letterm commited on
Commit
feddd9e
·
verified ·
1 Parent(s): 60a25d2

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -563
app.py DELETED
@@ -1,563 +0,0 @@
1
- # Generated from trimmed zed.proto
2
- from google.protobuf import descriptor as _descriptor
3
- from google.protobuf import descriptor_pool as _descriptor_pool
4
- from google.protobuf import runtime_version as _runtime_version
5
- from google.protobuf import symbol_database as _symbol_database
6
- from google.protobuf.internal import builder as _builder
7
- _runtime_version.ValidateProtobufRuntimeVersion(
8
- _runtime_version.Domain.PUBLIC,
9
- 5,
10
- 29,
11
- 0,
12
- '',
13
- 'zed.proto'
14
- )
15
- # @@protoc_insertion_point(imports)
16
-
17
- _sym_db = _symbol_database.Default()
18
-
19
- DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tzed.proto\x12\x0czed.messages\"&\n\x06PeerId\x12\x10\n\x08owner_id\x18\x01 \x01(\r\x12\n\n\x02id\x18\x02 \x01(\r\"\xe2\x05\n\x08\x45nvelope\x12\n\n\x02id\x18\x01 \x01(\r\x12\x1a\n\rresponding_to\x18\x02 \x01(\rH\x01\x88\x01\x01\x12\x35\n\x12original_sender_id\x18\x03 \x01(\x0b\x32\x14.zed.messages.PeerIdH\x02\x88\x01\x01\x12\x14\n\x06\x61\x63k_id\x18\x8a\x02 \x01(\rH\x03\x88\x01\x01\x12$\n\x05hello\x18\x04 \x01(\x0b\x32\x13.zed.messages.HelloH\x00\x12 \n\x03\x61\x63k\x18\x05 \x01(\x0b\x32\x11.zed.messages.AckH\x00\x12$\n\x05\x65rror\x18\x06 \x01(\x0b\x32\x13.zed.messages.ErrorH\x00\x12\"\n\x04ping\x18\x07 \x01(\x0b\x32\x12.zed.messages.PingH\x00\x12\x46\n\x17\x61\x63\x63\x65pt_terms_of_service\x18\xef\x01 \x01(\x0b\x32".zed.messages.AcceptTermsOfServiceH\x00\x12W\n accept_terms_of_service_response\x18\xf0\x01 \x01(\x0b\x32*.zed.messages.AcceptTermsOfServiceResponseH\x00\x12\x33\n\rget_llm_token\x18\xeb\x01 \x01(\x0b\x32\x19.zed.messages.GetLlmTokenH\x00\x12\x44\n\x16get_llm_token_response\x18\xec\x01 \x01(\x0b\x32!.zed.messages.GetLlmTokenResponseH\x00\x42\t\n\x07payloadB\x10\n\x0e_responding_toB\x15\n\x13_original_sender_idB\t\n\x07_ack_idJ\x04\x08W\x10YJ\x06\x08\x9e\x01\x10\xa2\x01J\x06\x08\xa4\x01\x10\xa5\x01J\x06\x08\xa6\x01\x10\xaa\x01J\x06\x08\xb1\x01\x10\xba\x01J\x06\x08\xbc\x01\x10\xbd\x01J\x06\x08\xc1\x01\x10\xc4\x01J\x06\x08\xc5\x01\x10\xc6\x01J\x06\x08\xc8\x01\x10\xcb\x01J\x06\x08\xcd\x01\x10\xcf\x01J\x06\x08\xdd\x01\x10\xde\x01J\x06\x08\xe0\x01\x10\xe6\x01J\x06\x08\xf6\x01\x10\xf7\x01J\x06\x08\xf7\x01\x10\xff\x01J\x06\x08\xff\x01\x10\x81\x02\".\n\x05Hello\x12%\n\x07peer_id\x18\x01 \x01(\x0b\x32\x14.zed.messages.PeerId\"\x06\n\x04Ping\"\x05\n\x03\x41\x63k\"M\n\x05\x45rror\x12\x0f\n\x07message\x18\x01 \x01(\t\x12%\n\x04\x63ode\x18\x02 \x01(\x0e\x32\x17.zed.messages.ErrorCode\x12\x0c\n\x04tags\x18\x03 \x03(\t\"\x16\n\x14\x41\x63\x63\x65ptTermsOfService\"7\n\x1c\x41\x63\x63\x65ptTermsOfServiceResponse\x12\x17\n\x0f\x61\x63\x63\x65pted_tos_at\x18\x01 \x01(\x04\"\r\n\x0bGetLlmToken\"$\n\x13GetLlmTokenResponse\x12\r\n\x05token\x18\x01 \x01(\t*\xef\x02\n\tErrorCode\x12\x0c\n\x08Internal\x10\x00\x12\x11\n\rNoSuchChannel\x10\x01\x12\x10\n\x0c\x44isconnected\x10\x02\x12\r\n\tSignedOut\x10\x03\x12\x13\n\x0fUpgradeRequired\x10\x04\x12\r\n\tForbidden\x10\x05\x12\x0c\n\x08NeedsCla\x10\x07\x12\x13\n\x0fNotARootChannel\x10\x08\x12\x14\n\x10\x42\x61\x64PublicNesting\x10\t\x12\x13\n\x0f\x43ircularNesting\x10\n\x12\x13\n\x0fWrongMoveTarget\x10\x0b\x12\x10\n\x0cUnsharedItem\x10\x0c\x12\x11\n\rNoSuchProject\x10\r\x12$\n DevServerProjectPathDoesNotExist\x10\x10\x12\x19\n\x15RemoteUpgradeRequired\x10\x11\x12\x15\n\x11RateLimitExceeded\x10\x12\x12\x10\n\x0c\x43ommitFailed\x10\x13\"\x04\x08\x06\x10\x06\"\x04\x08\x0e\x10\x0f\x62\x06proto3')
20
-
21
- _globals = globals()
22
- _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
23
- _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'zed_pb2', _globals)
24
- if not _descriptor._USE_C_DESCRIPTORS:
25
- DESCRIPTOR._loaded_options = None
26
- _globals['_ERRORCODE']._serialized_start=1085
27
- _globals['_ERRORCODE']._serialized_end=1452
28
- _globals['_PEERID']._serialized_start=27
29
- _globals['_PEERID']._serialized_end=65
30
- _globals['_ENVELOPE']._serialized_start=68
31
- _globals['_ENVELOPE']._serialized_end=806
32
- _globals['_HELLO']._serialized_start=808
33
- _globals['_HELLO']._serialized_end=854
34
- _globals['_PING']._serialized_start=856
35
- _globals['_PING']._serialized_end=862
36
- _globals['_ACK']._serialized_start=864
37
- _globals['_ACK']._serialized_end=869
38
- _globals['_ERROR']._serialized_start=871
39
- _globals['_ERROR']._serialized_end=948
40
- _globals['_ACCEPTTERMSOFSERVICE']._serialized_start=950
41
- _globals['_ACCEPTTERMSOFSERVICE']._serialized_end=972
42
- _globals['_ACCEPTTERMSOFSERVICERESPONSE']._serialized_start=974
43
- _globals['_ACCEPTTERMSOFSERVICERESPONSE']._serialized_end=1029
44
- _globals['_GETLLMTOKEN']._serialized_start=1031
45
- _globals['_GETLLMTOKEN']._serialized_end=1044
46
- _globals['_GETLLMTOKENRESPONSE']._serialized_start=1046
47
- _globals['_GETLLMTOKENRESPONSE']._serialized_end=1082
48
-
49
- # Start of the actual script
50
- import os
51
- import json
52
- import ssl
53
- import time
54
- import asyncio
55
- import logging
56
- import aiohttp
57
- from aiohttp import web
58
- import zstandard as zstd
59
- from dotenv import load_dotenv
60
- from websockets.asyncio.client import connect
61
- from websockets.exceptions import ConnectionClosed
62
- import uuid
63
-
64
- from google.protobuf.json_format import MessageToDict
65
-
66
- Envelope = _sym_db.GetSymbol('zed.messages.Envelope')
67
-
68
- logging.basicConfig(
69
- level=logging.INFO,
70
- format='%(levelname)s: %(message)s'
71
- )
72
- logger = logging.getLogger(__name__)
73
-
74
- current_dir = os.path.dirname(os.path.abspath(__file__))
75
- env_path = os.path.join(current_dir, '.env')
76
-
77
- load_dotenv(env_path)
78
-
79
- CONFIG = {
80
- "API":{
81
- "BASE_URL": "https://zed.dev",
82
- "API_KEY": os.getenv("API_KEY","sk-123456"),
83
- "BASE_API_URL": "https://collab.zed.dev",
84
- "WS_URL": "wss://collab.zed.dev/rpc",
85
- "LLM_API_URL": "https://llm.zed.dev/completion",
86
- },
87
- "LOGIN":{
88
- "USER_ID": os.getenv("ZED_USER_ID"),
89
- "AUTH": os.getenv("ZED_AUTH_TOKEN")
90
- },
91
- "SERVER":{
92
- "PORT": os.getenv("PORT",7860),
93
- "TOKEN_EXPIRY_WARNING_MINUTES": 50
94
- },
95
- "MODELS":{
96
- "claude-3-5-sonnet-20241022":"claude-3-5-sonnet-latest",
97
- "claude-3-7-sonnet-20250219":"claude-3-7-sonnet-20250219"
98
- }
99
- }
100
-
101
- highest_message_id = 0
102
- llm_token = None
103
- token_timestamp = None
104
- server_peer_id = None
105
- active_websocket = None
106
- proxy_server_running = False
107
-
108
- class MessageProcessor:
109
- @staticmethod
110
- def create_chat_response(message, model, is_stream=False):
111
- base_response = {
112
- "id": f"chatcmpl-{uuid.uuid4()}",
113
- "created": int(time.time()),
114
- "model": model
115
- }
116
-
117
- if is_stream:
118
- return {
119
- **base_response,
120
- "object": "chat.completion.chunk",
121
- "choices": [{
122
- "index": 0,
123
- "delta": {
124
- "content": message
125
- }
126
- }]
127
- }
128
-
129
- return {
130
- **base_response,
131
- "object": "chat.completion",
132
- "choices": [{
133
- "index": 0,
134
- "message": {
135
- "role": "assistant",
136
- "content": message
137
- },
138
- "finish_reason": "stop"
139
- }],
140
- "usage": None
141
- }
142
-
143
- def decode_envelope(data):
144
- try:
145
- dctx = zstd.ZstdDecompressor()
146
- decompressed_data = b''
147
- with dctx.stream_reader(data) as reader:
148
- while True:
149
- chunk = reader.read(8192)
150
- if not chunk:
151
- break
152
- decompressed_data += chunk
153
- envelope = Envelope()
154
- envelope.ParseFromString(decompressed_data)
155
- return MessageToDict(envelope, preserving_proto_field_name=True)
156
- except Exception as e:
157
- hex_preview = ' '.join(f'{byte:02x}' for byte in data[:20]) + ('...' if len(data) > 20 else '')
158
- logger.error(f"无法解码消息: {e}; 数据预览: {hex_preview}")
159
- return {"error": f"无法解码消息: {e}"}
160
-
161
- def compress_protobuf(data):
162
- return zstd.ZstdCompressor(level=-7).compress(data)
163
-
164
- def create_message(message_type):
165
- global highest_message_id
166
- highest_message_id += 1
167
- message_id = highest_message_id
168
- envelope = Envelope(id=highest_message_id)
169
-
170
- getattr(envelope, message_type).SetInParent()
171
- return compress_protobuf(envelope.SerializeToString()), message_id
172
-
173
- async def ping_periodically(websocket):
174
- while True:
175
- try:
176
- await websocket.ping()
177
- await asyncio.sleep(1)
178
- except Exception as e:
179
- logger.error(f"发送ping错误: {e}")
180
- break
181
-
182
- async def handle_messages(websocket):
183
- global server_peer_id, llm_token, token_timestamp, active_websocket
184
- active_websocket = websocket
185
- try:
186
- async for message in websocket:
187
- message_bytes = message.encode('utf-8') if isinstance(message, str) else message
188
- decoded = decode_envelope(message_bytes)
189
- if "hello" in decoded:
190
- server_peer_id = decoded.get('hello', {}).get('peer_id')
191
- elif "accept_terms_of_service_response" in decoded:
192
- await request_llm_token(websocket)
193
- elif ("get_llm_token_response" in decoded and
194
- 'token' in decoded.get('get_llm_token_response', {})):
195
- llm_token = decoded['get_llm_token_response']['token']
196
- token_timestamp = time.time()
197
- logger.info(f"LLM令牌收到 {time.ctime(token_timestamp)}")
198
- if not proxy_server_running:
199
- asyncio.create_task(start_proxy_server())
200
- asyncio.create_task(monitor_token_expiration())
201
- logger.info("关闭WebSocket连接,直到需要刷新令牌")
202
- await websocket.close()
203
- active_websocket = None
204
- return
205
- except ConnectionClosed:
206
- logger.info("连接已关闭")
207
- active_websocket = None
208
-
209
- async def request_llm_token(websocket):
210
- message, _ = create_message('get_llm_token')
211
- logger.info("请求LLM令牌")
212
- await websocket.send(message)
213
-
214
- async def request_accept_terms_of_service(websocket):
215
- message, _ = create_message('accept_terms_of_service')
216
- logger.info("发送同意Zed服务条款")
217
- await websocket.send(message)
218
-
219
- def format_content(content):
220
- if isinstance(content, str):
221
- return [{"type": "text", "text": content}]
222
- return content
223
-
224
-
225
-
226
- async def process_message_content(content):
227
- """
228
- 处理消息内容,将不同类型的内容转换为字符串
229
- """
230
- if isinstance(content, str):
231
- return content
232
-
233
- if isinstance(content, list):
234
- return '\n'.join([item.get('text', '') for item in content])
235
-
236
- if isinstance(content, dict):
237
- return content.get('text', None)
238
-
239
- return None
240
-
241
- async def transform_messages(request):
242
- """
243
- 转换消息格式,合并系统消息并处理消息结构
244
- """
245
- system_message = '' # 存储系统消息的变量
246
- is_collecting_system_message = False # 是否正在收集系统消息
247
- has_processed_system_messages = False # 是否已处理初始系统消息
248
-
249
- converted_messages = []
250
-
251
- for current in request.get('messages', []):
252
- role = current.get('role')
253
- current_content = await process_message_content(current.get('content'))
254
-
255
- if current_content is None:
256
- converted_messages.append(current)
257
- continue
258
-
259
- if role == 'system' and not has_processed_system_messages:
260
- if not is_collecting_system_message:
261
- # 第一次遇到system,开启收集
262
- system_message = current_content
263
- is_collecting_system_message = True
264
- else:
265
- # 继续遇到system,合并system消息
266
- system_message += '\n' + current_content
267
- continue
268
-
269
- # 遇到非system消息
270
- if is_collecting_system_message:
271
- # 结束系统消息收集
272
- is_collecting_system_message = False
273
- has_processed_system_messages = True
274
-
275
- # 如果已处理初始消息序列且再次遇到system,则转换role为user
276
- if has_processed_system_messages and role == 'system':
277
- role = 'user'
278
-
279
- # 检查是否可以合并消息
280
- if converted_messages and converted_messages[-1].get('role') == role:
281
- converted_messages[-1]['content'][0]['text'] += '\r\n' + current_content
282
- else:
283
- converted_messages.append({
284
- 'role': role,
285
- 'content': [{'type': 'text', 'text': current_content}]
286
- })
287
-
288
- return {
289
- 'messages': converted_messages,
290
- 'system': system_message,
291
- 'model': CONFIG['MODELS'].get(request.get('model'), "claude-3-5-sonnet-latest"),
292
- 'max_tokens': request.get('max_tokens',8192),
293
- 'temperature': max(0, min(request.get('temperature', 0), 1)),
294
- 'top_p': max(0, min(request.get('top_p', 1), 1)),
295
- 'top_k': max(0, min(request.get('top_k', 0), 500)),
296
- 'stream': request.get('stream', False)
297
- }
298
-
299
- @web.middleware
300
- async def auth_middleware(request, handler):
301
- if CONFIG['API']['API_KEY']:
302
- auth_header = request.headers.get('Authorization')
303
- xapi_key_header = request.headers.get('x-api-key')
304
-
305
- auth_password = None
306
- if auth_header and auth_header.startswith('Bearer '):
307
- auth_password = auth_header[7:]
308
-
309
- if auth_password == CONFIG['API']['API_KEY'] or xapi_key_header == CONFIG['API']['API_KEY']:
310
- return await handler(request)
311
- else:
312
- return web.json_response(
313
- {"error": "Unauthorized"},
314
- status=401
315
- )
316
-
317
- return await handler(request)
318
-
319
- async def handle_models_request(request):
320
- return web.json_response({
321
- "object": "list",
322
- "data": [
323
- {
324
- "id": model,
325
- "object": "model",
326
- "created": int(time.time()),
327
- "owned_by": "zed"
328
- }
329
- for model in CONFIG["MODELS"].keys()
330
- ]
331
- })
332
-
333
- async def handle_message_request(request):
334
- global llm_token
335
- if not llm_token:
336
- return web.json_response({"error": "LLM令牌不可用"}, status=500)
337
- try:
338
- body = await request.json()
339
- isClaudeAI = False
340
- if request.path == '/v1/messages':
341
- isClaudeAI = True
342
- if "messages" in body:
343
- for msg in body["messages"]:
344
- if "content" in msg:
345
- msg["content"] = format_content(msg["content"])
346
- if "system" in body:
347
- if isinstance(body["system"], list):
348
- body["system"] = "\n".join([item["text"] for item in body["system"]])
349
- if "model" in body:
350
- body["model"] = CONFIG['MODELS'].get(body["model"], "claude-3-5-sonnet-latest")
351
- else:
352
- body = await transform_messages(body)
353
-
354
- headers = {"Content-Type": "application/json", "Authorization": f"Bearer {llm_token}"}
355
- payload = {
356
- "provider": "anthropic",
357
- "model": body.get("model", "claude-3-5-sonnet-latest"),
358
- "provider_request": body
359
- }
360
- # with open('ceshi.txt', 'w', encoding='utf-8') as f:
361
- # f.write(json.dumps(body,ensure_ascii=False) + '\n')
362
- if body.get("stream", False):
363
- return await handle_streaming_request(request, headers, payload, isClaudeAI)
364
- else:
365
- return await handle_non_streaming_request(headers, payload, isClaudeAI)
366
- except Exception as e:
367
- logger.error(f"处理请求时发生错误: {e}")
368
- return web.json_response({"error": str(e)}, status=500)
369
-
370
- async def handle_non_streaming_request(headers, payload, isClaudeAI=False):
371
- async with aiohttp.ClientSession() as session:
372
- async with session.post(CONFIG['API']['LLM_API_URL'], headers=headers, json=payload) as r:
373
- if r.status != 200:
374
- text = await r.text()
375
- logger.error(f"LLM API错误: {text}")
376
- return web.json_response({"error": text}, status=r.status)
377
- full_content, message_data = "", {}
378
- async for line in r.content:
379
- if not line:
380
- continue
381
- try:
382
- event = json.loads(line.decode('utf-8').strip())
383
- et = event.get('type')
384
- if et == "message_start":
385
- message_data = event.get('message', {})
386
- elif et == "content_block_delta" and event.get('delta', {}).get('type') == "text_delta":
387
- full_content += event['delta'].get('text', '')
388
- elif et == "message_delta" and 'usage' in event:
389
- message_data['usage'] = event.get('usage')
390
- elif et == "message_stop":
391
- break
392
- except Exception as e:
393
- logger.error(f"Error processing line: {e}")
394
- if isClaudeAI:
395
- message_data['content'] = [{"type": "text", "text": full_content}]
396
- else:
397
- message_data = MessageProcessor.create_chat_response(full_content, payload.get("model"), False)
398
- return web.json_response(message_data)
399
-
400
- async def handle_streaming_request(request, headers, payload, isClaudeAI=False):
401
- response = web.StreamResponse()
402
- response.headers['Content-Type'] = 'text/event-stream'
403
- response.headers['Cache-Control'] = 'no-cache'
404
- response.headers['Connection'] = 'keep-alive'
405
- await response.prepare(request)
406
- logger.info(f"开始处理流请求")
407
- async with aiohttp.ClientSession() as session:
408
- async with session.post(CONFIG['API']['LLM_API_URL'], headers=headers, json=payload) as api_response:
409
- if api_response.status != 200:
410
- error_text = await api_response.text()
411
- logger.error(f"LLM API (stream)错误: {error_text}")
412
- await response.write(f"data: {json.dumps({'error': error_text})}\n\n".encode())
413
- await response.write(b"data: [DONE]\n\n")
414
- return response
415
- async for line in api_response.content:
416
- try:
417
- if line:
418
- if isClaudeAI:
419
- await response.write(f"data: {line.decode('utf-8')}\n\n".encode())
420
- else:
421
- try:
422
- data = json.loads(line.decode('utf-8').strip())
423
- print(data)
424
- if data.get('type') == "content_block_delta" and data.get('delta', {}).get('type') == "text_delta":
425
- text = data['delta'].get('text', '')
426
- message = MessageProcessor.create_chat_response(text, payload.get("model"), True)
427
- await response.write(f"data: {json.dumps(message)}\n\n".encode())
428
- except Exception as e:
429
- logger.error(f"Error processing line: {e}")
430
- except Exception as e:
431
- logger.error(f"Error processing line: {e}")
432
- await response.write(b"data: [DONE]\n\n")
433
- return response
434
-
435
-
436
- async def start_proxy_server():
437
- global proxy_server_running
438
- if proxy_server_running:
439
- logger.info("代理服务器已运行,跳过启动")
440
- return
441
-
442
- proxy_server_running = True
443
- app = web.Application(middlewares=[auth_middleware])
444
- app.router.add_post('/v1/messages', handle_message_request)
445
- app.router.add_post('/v1/chat/completions', handle_message_request)
446
- app.router.add_get('/v1/models', handle_models_request)
447
-
448
- async def health_check():
449
- return web.json_response({
450
- "status": "ok",
451
- "message": "Zed LLM proxy is running"
452
- })
453
-
454
- app.router.add_get('/', health_check)
455
-
456
- runner = web.AppRunner(app)
457
- await runner.setup()
458
- site = web.TCPSite(runner, '0.0.0.0', CONFIG['SERVER']['PORT'])
459
- await site.start()
460
- logger.info(f"代理服务器启动 http://0.0.0.0:{CONFIG['SERVER']['PORT']}")
461
- while True:
462
- await asyncio.sleep(3600)
463
-
464
- def is_token_expiring():
465
- if not token_timestamp:
466
- return False
467
- return (time.time() - token_timestamp) / 60 >= CONFIG['SERVER']['TOKEN_EXPIRY_WARNING_MINUTES']
468
-
469
- async def monitor_token_expiration():
470
- while True:
471
- await asyncio.sleep(60)
472
- if is_token_expiring():
473
- elapsed = int((time.time() - token_timestamp) / 60)
474
- logger.warning(f"LLM令牌接近过期 (收到 {elapsed} 分钟前)")
475
- if active_websocket is None:
476
- logger.info("重新连接WebSocket以刷新令牌")
477
- asyncio.create_task(reconnect_for_token_refresh())
478
- return
479
-
480
- async def reconnect_for_token_refresh():
481
- try:
482
- if not CONFIG['LOGIN']['USER_ID'] or not CONFIG['LOGIN']['AUTH']:
483
- logger.error("用户ID或授权令牌未设置")
484
- return
485
- headers = {
486
- "authorization": f"{CONFIG['LOGIN']['USER_ID']} {CONFIG['LOGIN']['AUTH']}",
487
- "x-zed-protocol-version": "68",
488
- "x-zed-app-version": "0.178.0",
489
- "x-zed-release-channel": "stable"
490
- }
491
- ssl_context = ssl.create_default_context()
492
- ssl_context.check_hostname = False
493
- ssl_context.verify_mode = ssl.CERT_NONE
494
-
495
- async for websocket in connect(CONFIG['API']['WS_URL'], additional_headers=headers, ssl=ssl_context):
496
- try:
497
- ping_task = asyncio.create_task(ping_periodically(websocket))
498
- await asyncio.sleep(2)
499
- await request_accept_terms_of_service(websocket)
500
- await handle_messages(websocket)
501
- break
502
- except ConnectionClosed:
503
- continue
504
- except Exception as e:
505
- logger.error(f"令牌刷新期间发生错误: {e}")
506
- await asyncio.sleep(1)
507
- continue
508
- finally:
509
- ping_task.cancel()
510
- try:
511
- await ping_task
512
- except asyncio.CancelledError:
513
- pass
514
- except Exception as e:
515
- logger.error(f"令牌刷新失败: {e}")
516
-
517
- async def async_main():
518
- if not CONFIG['LOGIN']['USER_ID'] or not CONFIG['LOGIN']['AUTH']:
519
- logger.error("用户ID或授权令牌未设置")
520
- return
521
- headers = {
522
- "authorization": f"{CONFIG['LOGIN']['USER_ID']} {CONFIG['LOGIN']['AUTH']}",
523
- "x-zed-protocol-version": "68",
524
- "x-zed-app-version": "0.178.0",
525
- "x-zed-release-channel": "stable"
526
- }
527
- ssl_context = ssl.create_default_context()
528
- ssl_context.check_hostname = False
529
- ssl_context.verify_mode = ssl.CERT_NONE
530
- logger.info("连接到Websocket服务器")
531
- async for websocket in connect(CONFIG['API']['WS_URL'], additional_headers=headers, ssl=ssl_context):
532
- try:
533
- ping_task = asyncio.create_task(ping_periodically(websocket))
534
- token_request_task = asyncio.create_task(delayed_token_request(websocket, delay=2))
535
- await handle_messages(websocket)
536
- break
537
- except ConnectionClosed:
538
- continue
539
- except Exception as e:
540
- logger.error(f"意外错误: {e}")
541
- await asyncio.sleep(1)
542
- continue
543
- finally:
544
- ping_task.cancel()
545
- try:
546
- await ping_task
547
- except asyncio.CancelledError:
548
- pass
549
- token_request_task.cancel()
550
- try:
551
- await token_request_task
552
- except asyncio.CancelledError:
553
- pass
554
-
555
- while True:
556
- await asyncio.sleep(3600)
557
-
558
- async def delayed_token_request(websocket, delay=2):
559
- await asyncio.sleep(delay)
560
- await request_accept_terms_of_service(websocket)
561
-
562
- if __name__ == "__main__":
563
- asyncio.run(async_main())