dangthr commited on
Commit
381a6c0
·
verified ·
1 Parent(s): 5e8a249

Update remote_uploader.py

Browse files
Files changed (1) hide show
  1. remote_uploader.py +114 -89
remote_uploader.py CHANGED
@@ -1,97 +1,122 @@
1
- import asyncio
2
- import websockets
3
  import os
4
  import time
5
- import base64
6
- import logging
7
- import argparse
8
- import json
9
- import urllib.parse
10
-
11
- # Configure logging
12
- logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
13
- logger = logging.getLogger(__name__)
14
-
15
- async def upload_directory(space_id, api_key, upload_dir):
16
- # 使用查询参数传递 api_key
17
- encoded_secret = urllib.parse.quote(api_key)
18
- uri = f"wss://remote-terminal-worker.nianxi4563.workers.dev/terminal/{space_id}?secret={encoded_secret}"
19
- logger.info(f"Attempting to connect to {uri}")
20
-
21
- try:
22
- async with websockets.connect(uri, ping_interval=20, ping_timeout=60) as websocket:
23
- logger.info("Connected to WebSocket")
24
-
25
- # 发送机器注册信息(尽管去除 machine_id,但保持兼容)
26
- machine_info = {"type": "machine", "card_id": space_id}
27
- await websocket.send(json.dumps(machine_info))
28
- logger.debug(f"Sent machine registration: {machine_info}")
29
 
30
- # 不等待 machine_id,直接继续
31
-
32
- # 获取所有文件
33
- all_files = []
34
- for root, dirs, files in os.walk(upload_dir):
35
- for file in files:
36
- file_path = os.path.join(root, file)
37
- if os.path.isfile(file_path):
38
- all_files.append(file_path)
39
-
40
- if not all_files:
41
- logger.info("No files found in directory")
42
- return 0, 0
43
-
44
- logger.info(f"Found {len(all_files)} files, starting upload...")
45
-
46
- success_count = 0
47
- failed_count = 0
48
-
49
- for file_path in all_files:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  try:
51
- with open(file_path, 'rb') as f:
52
- file_content = f.read()
53
- file_b64 = base64.b64encode(file_content).decode('utf-8')
54
- file_msg = {
55
- "type": "file_upload",
56
- "filename": os.path.basename(file_path),
57
- "content": file_b64
58
- }
59
- await websocket.send(json.dumps(file_msg))
60
- logger.info(f"Uploaded file: {file_path}")
61
- success_count += 1
62
- except Exception as e:
63
- logger.error(f"Error uploading file {file_path}: {e}")
64
- failed_count += 1
65
- # 稍微延迟,避免服务器压力过大
66
- await asyncio.sleep(0.5)
67
-
68
- logger.info(f"Upload completed! Success: {success_count}, Failed: {failed_count}")
69
- return success_count, failed_count
70
-
71
- except Exception as e:
72
- logger.error(f"Failed to connect or upload: {e}")
73
- return 0, len(os.listdir(upload_dir)) if os.path.exists(upload_dir) else 0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
  if __name__ == "__main__":
76
- parser = argparse.ArgumentParser(description="一次性文件上传器 - 使用 WebSocket 扫描并上传指定文件夹中的所有文件")
77
- parser.add_argument("api_key", help="您的 API 密钥 (作为用户 token)")
78
- parser.add_argument("space_id", help="Space ID (作为 card_id)")
79
  parser.add_argument("--upload-dir", default="output", help="要上传的目录 (默认: output)")
80
-
81
  args = parser.parse_args()
82
-
83
- if not os.path.exists(args.upload_dir):
84
- print(f"目录不存在: {args.upload_dir}")
85
- exit(1)
86
-
87
- print(f"🔍 开始扫描目录: {args.upload_dir}")
88
- print(f"🔑 Space ID (card_id): {args.space_id}")
89
- print("-" * 50)
90
-
91
- success, failed = asyncio.run(upload_directory(args.space_id, args.api_key, args.upload_dir))
92
-
93
- print("-" * 50)
94
- print(f"📊 上传完成! 成功: {success}, 失败: {failed}")
95
-
96
- if success > 0:
97
- print("🎉 文件已成功上传到您的网盘!")
 
1
+ import requests
2
+ import argparse
3
  import os
4
  import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ class FileUploader:
7
+ def __init__(self, api_key, space_id):
8
+ self.server_url = "https://gkbtyo-rqvays-5001.preview.cloudstudio.work"
9
+ self.api_key = api_key
10
+ self.space_id = space_id
11
+
12
+ def upload_file(self, file_path):
13
+ """上传单个文件"""
14
+ if not os.path.exists(file_path):
15
+ print(f"文件不存在: {file_path}")
16
+ return False
17
+
18
+ filename = os.path.basename(file_path)
19
+ print(f"正在上传文件: {filename}")
20
+
21
+ # 构建完整的 API 端点 URL
22
+ upload_url = f"{self.server_url.rstrip('/')}/api/remote_upload"
23
+
24
+ # 准备请求头和数据
25
+ headers = {
26
+ 'X-API-Key': self.api_key
27
+ }
28
+ data = {
29
+ 'space_id': self.space_id
30
+ }
31
+
32
+ # 读取文件内容并上传
33
+ try:
34
+ with open(file_path, 'rb') as f:
35
+ files = {
36
+ 'file': (filename, f)
37
+ }
38
+
39
+ # 发送 POST 请求
40
+ response = requests.post(upload_url, headers=headers, data=data, files=files)
41
+
42
+ # 打印服务器响应
43
+ print(f"服务器响应 ({response.status_code}):")
44
  try:
45
+ result = response.json()
46
+ print(result)
47
+ if response.status_code == 200:
48
+ print(f"✅ 文件 '{filename}' 上传成功!")
49
+ return True
50
+ else:
51
+ print(f"❌ 上传失败: {result.get('error', '未知错误')}")
52
+ return False
53
+ except requests.exceptions.JSONDecodeError:
54
+ print(response.text)
55
+ return False
56
+
57
+ except IOError as e:
58
+ print(f"读取文件时出错: {e}")
59
+ return False
60
+ except requests.exceptions.RequestException as e:
61
+ print(f"请求时出错: {e}")
62
+ return False
63
+
64
+ def upload_directory_once(upload_dir, api_key, space_id):
65
+ """一次性扫描并上传目录中的所有文件"""
66
+ if not os.path.exists(upload_dir):
67
+ print(f"目录不存在: {upload_dir}")
68
+ return
69
+
70
+ print(f"🔍 开始扫描目录: {upload_dir}")
71
+ print(f"🔑 Space ID: {space_id}")
72
+ print("-" * 50)
73
+
74
+ uploader = FileUploader(api_key, space_id)
75
+
76
+ # 获取所有文件
77
+ all_files = []
78
+ for root, dirs, files in os.walk(upload_dir):
79
+ for file in files:
80
+ file_path = os.path.join(root, file)
81
+ if os.path.isfile(file_path):
82
+ all_files.append(file_path)
83
+
84
+ if not all_files:
85
+ print("📁 目录中没有找到任何文件")
86
+ return
87
+
88
+ print(f"📁 找到 {len(all_files)} 个文件,开始上传...")
89
+
90
+ success_count = 0
91
+ failed_count = 0
92
+
93
+ for file_path in all_files:
94
+ try:
95
+ if uploader.upload_file(file_path):
96
+ success_count += 1
97
+ else:
98
+ failed_count += 1
99
+ # 稍微延迟一下,避免服务器压力过大
100
+ time.sleep(0.5)
101
+ except Exception as e:
102
+ print(f"上传文件 {file_path} 时发生异常: {e}")
103
+ failed_count += 1
104
+
105
+ print("-" * 50)
106
+ print(f"📊 上传完成! 成功: {success_count}, 失败: {failed_count}")
107
+
108
+ if success_count > 0:
109
+ print("🎉 文件已成功上传到您的网盘!")
110
+
111
+ return success_count, failed_count
112
 
113
  if __name__ == "__main__":
114
+ parser = argparse.ArgumentParser(description="一次性文件上传器 - 扫描并上传指定文件夹中的所有文件")
115
+ parser.add_argument("api_key", help="您的 API 密钥")
116
+ parser.add_argument("space_id", help="Space ID")
117
  parser.add_argument("--upload-dir", default="output", help="要上传的目录 (默认: output)")
118
+
119
  args = parser.parse_args()
120
+
121
+ # 开始一次性上传
122
+ upload_directory_once(args.upload_dir, args.api_key, args.space_id)