File size: 4,434 Bytes
fad568b
 
 
 
 
 
86913fe
6129265
fad568b
 
 
 
86913fe
6129265
 
86913fe
6129265
 
 
 
9d9567e
15bd9da
6129265
 
15bd9da
 
 
6129265
 
 
 
 
9d9567e
6129265
9d9567e
6129265
 
9d9567e
6129265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15bd9da
 
86913fe
6129265
15bd9da
6129265
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fad568b
6129265
15bd9da
6129265
15bd9da
86913fe
6129265
86913fe
6129265
 
86913fe
6129265
 
 
 
 
 
 
 
86913fe
6129265
 
 
86913fe
6129265
 
fad568b
 
6129265
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import asyncio
import websockets
import json
import logging
import sys
import base64
import os
import time

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

async def upload_files_via_websocket(space_id, user_token, website_url):
    """通过WebSocket上传output目录中的所有文件"""
    
    output_dir = "output"
    if not os.path.exists(output_dir):
        logger.error(f"输出目录不存在: {output_dir}")
        return False
    
    # 获取所有文件
    files_to_upload = []
    for root, dirs, files in os.walk(output_dir):
        for file in files:
            file_path = os.path.join(root, file)
            if os.path.isfile(file_path):
                files_to_upload.append(file_path)
    
    if not files_to_upload:
        logger.info("输出目录中没有找到任何文件")
        return True
    
    logger.info(f"找到 {len(files_to_upload)} 个文件需要上传")
    
    # 构建WebSocket URL
    ws_url = website_url.replace('http://', 'ws://').replace('https://', 'wss://') + '/socket.io/?EIO=4&transport=websocket'
    
    try:
        # 连接到WebSocket服务器
        logger.info(f"正在连接到 WebSocket 服务器: {ws_url}")
        
        # 使用socket.io客户端协议
        import socketio
        
        sio = socketio.AsyncClient()
        
        @sio.event
        async def connect():
            logger.info("WebSocket 连接成功")
            # 注册客户端
            await sio.emit('register_client', {
                'space_id': space_id,
                'user_token': user_token
            })
        
        @sio.event
        async def registered(data):
            logger.info(f"客户端注册成功: {data}")
            # 开始上传文件
            await upload_files(sio, files_to_upload, space_id, user_token)
        
        @sio.event
        async def upload_success(data):
            logger.info(f"文件上传成功: {data}")
        
        @sio.event
        async def upload_error(data):
            logger.error(f"文件上传失败: {data}")
        
        @sio.event
        async def error(data):
            logger.error(f"WebSocket 错误: {data}")
        
        @sio.event
        async def disconnect():
            logger.info("WebSocket 连接断开")
        
        # 连接到服务器
        await sio.connect(website_url)
        
        # 等待所有文件上传完成
        await sio.wait()
        
    except Exception as e:
        logger.error(f"WebSocket 连接或上传过程中发生错误: {e}")
        return False

async def upload_files(sio, files_to_upload, space_id, user_token):
    """上传文件列表"""
    success_count = 0
    failed_count = 0
    
    for file_path in files_to_upload:
        try:
            filename = os.path.basename(file_path)
            logger.info(f"正在上传文件: {filename}")
            
            # 读取文件内容并编码为base64
            with open(file_path, 'rb') as f:
                file_content = f.read()
                file_b64 = base64.b64encode(file_content).decode('utf-8')
            
            # 发送文件上传请求
            await sio.emit('file_upload', {
                'space_id': space_id,
                'user_token': user_token,
                'filename': filename,
                'content': file_b64
            })
            
            success_count += 1
            # 稍微延迟避免服务器压力过大
            await asyncio.sleep(0.5)
            
        except Exception as e:
            logger.error(f"上传文件 {file_path} 时发生错误: {e}")
            failed_count += 1
    
    logger.info(f"上传完成! 成功: {success_count}, 失败: {failed_count}")
    
    # 上传完成后断开连接
    await sio.disconnect()

def main():
    if len(sys.argv) != 4:
        print("用法: python3 websocket_uploader.py <space_id> <user_token> <website_url>")
        sys.exit(1)
    
    space_id = sys.argv[1]
    user_token = sys.argv[2] 
    website_url = sys.argv[3]
    
    logger.info(f"开始 WebSocket 文件上传")
    logger.info(f"Space ID: {space_id}")
    logger.info(f"Website URL: {website_url}")
    
    # 运行异步上传
    asyncio.run(upload_files_via_websocket(space_id, user_token, website_url))

if __name__ == "__main__":
    main()