Spaces:
Runtime error
Runtime error
Update remote_uploader.py
Browse files- remote_uploader.py +114 -89
remote_uploader.py
CHANGED
@@ -1,97 +1,122 @@
|
|
1 |
-
import
|
2 |
-
import
|
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 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
try:
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
"
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
74 |
|
75 |
if __name__ == "__main__":
|
76 |
-
parser = argparse.ArgumentParser(description="一次性文件上传器 -
|
77 |
-
parser.add_argument("api_key", help="您的 API 密钥
|
78 |
-
parser.add_argument("space_id", help="Space ID
|
79 |
parser.add_argument("--upload-dir", default="output", help="要上传的目录 (默认: output)")
|
80 |
-
|
81 |
args = parser.parse_args()
|
82 |
-
|
83 |
-
|
84 |
-
|
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)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|