-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwss.py
More file actions
2083 lines (1792 loc) · 79.4 KB
/
wss.py
File metadata and controls
2083 lines (1792 loc) · 79.4 KB
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import base64
import concurrent.futures
import hashlib
import json
import os
import signal
import sys
import time
import traceback
from concurrent.futures import ThreadPoolExecutor
import tarfile
import random
import logging
import threading
from threading import Lock
import base58
import requests
from Cryptodome.Cipher import DES
from Cryptodome.Util import Padding
# 全局变量用于控制上传中断
upload_interrupted = False
interrupt_count = 0
current_operation = None # 'upload' 或 'download'
resume_enabled = False # 是否启用了断点续传
# 多线程下载相关全局变量
download_lock = Lock() # 用于线程安全的进度更新
total_downloaded = 0 # 总下载字节数
chunk_download_status = {} # 分块下载状态
active_connections = {} # 活跃连接状态
download_speed_history = [] # 下载速度历史
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
_apiBaseUrl = 'https://www.wenshushu.cn'
def signal_handler(signum, frame):
"""处理Ctrl+C中断信号"""
global upload_interrupted, interrupt_count, current_operation, resume_enabled
interrupt_count += 1
if interrupt_count == 1:
upload_interrupted = True
# 根据当前操作显示相应的中断消息
if current_operation == 'download':
print(f"\n{_('download_interrupted')}")
else:
print(f"\n{_('upload_interrupted')}")
# 只在启用断点续传时显示保存信息
if resume_enabled:
print(_('saving_resume_info'))
# 第一次Ctrl+C,优雅退出
elif interrupt_count >= 2:
# 第二次Ctrl+C,强制退出
print(f"\n{_('force_exit')}")
import os
os._exit(1)
# 注册信号处理器
signal.signal(signal.SIGINT, signal_handler)
# 断点续传信息存储
# 语言系统
LANG = 'zh' # 默认语言
TRANSLATIONS = {
'zh': {
'file_expires': '文件过期时间:{}天{}时{}分{}秒',
'file_size': '文件大小:{} MB',
'file_name': '文件名:{}',
'detected_resume_with_progress': '检测到断点续传,已下载: {} ({}%)',
'detected_resume': '检测到断点续传,已下载: {}',
'starting_download': '开始下载!',
'download_complete': '下载完成!',
'download_error': '下载出错: {}',
'download_cancelled': '下载已取消,断点续传信息已保存',
'download_cancelled_no_resume': '下载已取消',
'download_interrupted': '检测到中断信号,正在停止下载...',
'resume_info_saved': '已保存断点续传信息,下次可使用 -c 参数继续下载',
'share_traffic_insufficient': '对方的分享流量不足',
'used_space': '当前已用空间:{}GB,剩余空间:{}GB,总空间:{}GB',
'too_fast': '操作太快啦!请{}秒后重试',
'need_verification': '需要滑动验证码',
'personal_link': '个人管理链接:{}',
'public_link': '公共链接:{}',
'instant_transfer': '文件{}可以被秒传!',
'file_chunked_upload': '文件正在被分块上传!',
'upload_complete': '上传完成!',
'upload_error': '上传出错: {}',
'file_single_upload': '文件被整块上传!',
'upload_complete_100': '上传完成:100%',
'upload_interrupted': '检测到中断信号,正在停止上传...',
'saving_resume_info': '正在保存断点续传信息...',
'upload_cancelled': '上传已取消',
'force_exit': '强制退出程序...',
'days': '天',
'hours': '时',
'minutes': '分',
'seconds': '秒',
'trying_saved_token': '尝试使用已保存的token登录',
'logged_in': '已登录 "{}"',
'saved_token_invalid': '已保存的token无效,使用匿名登录',
'no_saved_token': '未找到已保存的token,使用匿名登录',
'using_anonymous': '使用匿名登录',
'parameter_error': '参数错误,使用 -h 查看帮助',
'login_success_saved': '登录成功并已保存!',
'login_failed': '登录失败,请检查token是否正确',
'current_login_status': '=== 当前登录状态 ===',
'currently_logged_user': '当前已登录用户',
'username': '用户名',
'email': '邮箱',
'phone': '手机号',
'current_token_invalid': '当前token无效',
'token_cleaned': '已自动清理无效token',
'not_logged_in': '当前未登录',
'login_options': '=== 登录选项 ===',
'enter_new_token': '1. 输入新的TOKEN登录',
'select_saved_account': '2. 从已保存账户中选择',
'view_tutorial': '3. 查看TOKEN获取教程',
'cancel': '0. 取消',
'please_choose': '请选择',
'enter_token': '请输入X-TOKEN',
'no_saved_accounts': '没有保存的账户信息',
'choose_option1_or_3': '请选择选项1输入新TOKEN,或选择选项3查看获取教程',
'switch_login_success': '切换登录成功!',
'account_token_expired': '该账户token已失效',
'cancelled': '已取消',
'invalid_choice': '无效选择',
'operation_failed': '操作失败',
'current_user_info': '=== 当前登录用户信息 ===',
'token_invalid_expired': '当前token无效或已过期',
'confirm_logout': '确定要退出当前账户吗?(y/N)',
'logout_success': '已成功退出账户',
'logout_cancelled': '已取消退出',
'no_account_logged': '当前未登录任何账户',
'error_provide_command': '错误: 请提供命令 (upload/download/login/unlogin)',
'use_help': '使用 -h 查看帮助',
'error_target_required': '错误: {} 命令需要提供目标参数',
'using_proxy': '使用代理',
'using_pickup_code': '使用取件码',
'random_pickup_code': '随机生成取件码',
'no_saved_user_tokens': '没有保存的用户token',
'saved_user_accounts': '已保存的用户账户',
'last_login': '最后登录',
'select_account_number': '请选择账户编号 (0=取消)',
'invalid_input': '无效输入',
'removed_invalid_account': '已删除无效账户',
'multithread_download': '多线程下载模式 ({}线程)',
'single_thread_download': '单线程下载模式',
'server_no_range_support': '服务器不支持多线程下载,使用单线程模式',
'file_too_small': '文件较小,使用单线程下载',
'multithread_resume_detected': '检测到多线程断点续传,已完成 {}/{} 个分块',
'multithread_complete': '多线程下载完成!',
'multithread_failed': '多线程下载失败',
'chunk_download_failed': '分块下载失败',
'fallback_single_thread': '多线程下载失败,尝试单线程下载...',
'invalid_thread_count': '错误: 线程数必须在1-16之间',
'idm_style_download': 'IDM风格多连接下载: {} 个并行连接',
'connection_status': '活跃连接状态',
'download_stream_mode': '无法获取文件大小,使用流式下载',
'file_already_complete': '文件已经下载完成',
'download_incomplete': '下载不完整: {}/{}',
'multiconnection_failed': '多连接下载失败,尝试单线程下载...',
'active_connections': '活跃',
'chunk_status': '块状态',
'chunk': '块',
'server_range_support_yes': '服务器Range支持: 是',
'server_range_support_no': '服务器Range支持: 否',
'starting_threads': '启动 {} 个线程...',
'merging_chunks': '开始合并 {} 个块...',
'merge_complete': '合并完成! 文件大小: {}',
'integrity_verified': '✓ 文件完整性验证通过',
'temp_files_cleaned': '✓ 临时文件已清理',
'temp_files_clean_failed': '注意: 临时文件清理失败',
'file_size_mismatch': '⚠ 文件大小不匹配: 期望{},实际{}',
'download_interrupted': '下载已中断',
'partial_chunks_incomplete': '警告: 部分块未完成下载',
'chunk_file_missing': ' 警告: 块{}文件不存在',
'merge_error': '合并文件时出错: {}',
'resume_detected': '断点续传',
'downloaded_so_far': '已下载'
},
'en': {
'file_expires': 'File expires in: {} days {} hours {} minutes {} seconds',
'file_size': 'File size: {} MB',
'file_name': 'File name: {}',
'detected_resume_with_progress': 'Detected resume, downloaded: {} ({}%)',
'detected_resume': 'Detected resume, downloaded: {}',
'starting_download': 'Starting download!',
'download_complete': 'Download complete!',
'download_error': 'Download error: {}',
'download_cancelled': 'Download interrupted, saving resume info...',
'download_cancelled_no_resume': 'Download cancelled',
'download_interrupted': 'Download interrupted, stopping download...',
'resume_info_saved': 'Resume info saved, you can continue with -c parameter',
'share_traffic_insufficient': 'Share traffic insufficient',
'used_space': 'Current used space: {} GB, remaining space: {} GB, total space: {} GB',
'too_fast': 'Too fast! Please try again after {} seconds',
'need_verification': 'Need to slide verification code',
'personal_link': 'Personal management link: {}',
'public_link': 'Public link: {}',
'instant_transfer': 'File {} can be transferred instantly!',
'file_chunked_upload': 'File is being chunked up!',
'upload_complete': 'Upload complete!',
'upload_error': 'Upload error: {}',
'file_single_upload': 'File is being uploaded in one go!',
'upload_complete_100': 'Upload complete: 100%',
'upload_interrupted': 'Upload interrupted, saving resume info...',
'saving_resume_info': 'Saving resume info...',
'upload_cancelled': 'Upload cancelled',
'force_exit': 'Force exit program...',
'days': 'days',
'hours': 'hours',
'minutes': 'minutes',
'seconds': 'seconds',
'trying_saved_token': 'Trying to login with saved token',
'logged_in': 'Logged in "{}"',
'saved_token_invalid': 'Saved token invalid, using anonymous login',
'no_saved_token': 'No saved token found, using anonymous login',
'using_anonymous': 'Using anonymous login',
'parameter_error': 'Parameter error, use -h for help',
'login_success_saved': 'Login successful and saved!',
'login_failed': 'Login failed, please check if token is correct',
'current_login_status': '=== Current Login Status ===',
'currently_logged_user': 'Currently logged in user',
'username': 'Username',
'email': 'Email',
'phone': 'Phone',
'current_token_invalid': 'Current token is invalid',
'token_cleaned': 'Invalid token has been automatically cleaned',
'not_logged_in': 'Not logged in',
'login_options': '=== Login Options ===',
'enter_new_token': '1. Enter new TOKEN to login',
'select_saved_account': '2. Select from saved accounts',
'view_tutorial': '3. View TOKEN tutorial',
'cancel': '0. Cancel',
'please_choose': 'Please choose (0-3)',
'enter_token': 'Please enter X-TOKEN',
'no_saved_accounts': 'No saved account information',
'choose_option1_or_3': 'Please choose option 1 to enter new TOKEN, or option 3 to view tutorial',
'switch_login_success': 'Switch login successful!',
'account_token_expired': 'This account token has expired',
'cancelled': 'Cancelled',
'invalid_choice': 'Invalid choice',
'operation_failed': 'Operation failed',
'current_user_info': '=== Current User Info ===',
'token_invalid_expired': 'Current token is invalid or expired',
'confirm_logout': 'Are you sure to logout? (y/N)',
'logout_success': 'Successfully logged out',
'logout_cancelled': 'Logout cancelled',
'no_account_logged': 'No account currently logged in',
'error_provide_command': 'Error: Please provide a command (upload/download/login/unlogin)',
'use_help': 'Use -h for help',
'error_target_required': 'Error: {} command requires target parameter',
'using_proxy': 'Using proxy',
'using_pickup_code': 'Using pickup code',
'random_pickup_code': 'Random pickup code',
'no_saved_user_tokens': 'No saved user tokens',
'saved_user_accounts': 'Saved user accounts',
'last_login': 'Last login',
'select_account_number': 'Please select account number (0=cancel)',
'invalid_input': 'Invalid input',
'removed_invalid_account': 'Removed invalid account',
'multithread_download': 'Multi-thread download mode ({} threads)',
'single_thread_download': 'Single-thread download mode',
'server_no_range_support': 'Server does not support multi-thread download, using single-thread mode',
'file_too_small': 'File is too small, using single-thread download',
'multithread_resume_detected': 'Detected multi-thread resume, completed {}/{} chunks',
'multithread_complete': 'Multi-thread download complete!',
'multithread_failed': 'Multi-thread download failed',
'chunk_download_failed': 'Chunk download failed',
'fallback_single_thread': 'Multi-thread download failed, trying single-thread download...',
'invalid_thread_count': 'Error: Thread count must be between 1-16',
'idm_style_download': 'IDM-style multi-connection download: {} parallel connections',
'connection_status': 'Active connection status',
'download_stream_mode': 'Unable to get file size, using streaming download',
'file_already_complete': 'File already downloaded',
'download_incomplete': 'Download incomplete: {}/{}',
'multiconnection_failed': 'Multi-connection download failed, trying single-thread download...',
'active_connections': 'Active',
'chunk_status': 'Chunk status',
'chunk': 'Chunk',
'server_range_support_yes': 'Server Range support: Yes',
'server_range_support_no': 'Server Range support: No',
'starting_threads': 'Starting {} threads...',
'merging_chunks': 'Merging {} chunks...',
'merge_complete': 'Merge complete! File size: {}',
'integrity_verified': '✓ File integrity verified',
'temp_files_cleaned': '✓ Temporary files cleaned',
'temp_files_clean_failed': 'Note: Temporary files cleanup failed',
'file_size_mismatch': '⚠ File size mismatch: Expected {}, actual {}',
'download_interrupted': 'Download interrupted',
'partial_chunks_incomplete': 'Warning: Partial chunks incomplete',
'chunk_file_missing': ' Warning: Chunk {} file not found',
'merge_error': 'Merge error: {}',
'resume_detected': 'Resume detected',
'downloaded_so_far': 'Downloaded so far'
}
}
def _(key, *args):
"""翻译函数"""
global LANG
text = TRANSLATIONS.get(LANG, TRANSLATIONS['zh']).get(key, key)
if args:
return text.format(*args)
return text
def format_size(size_bytes):
"""格式化文件大小显示"""
if size_bytes == 0:
return "0 B"
units = ['B', 'KB', 'MB', 'GB', 'TB']
unit_index = 0
size = float(size_bytes)
while size >= 1024 and unit_index < len(units) - 1:
size /= 1024
unit_index += 1
if unit_index == 0: # 字节
return f"{int(size)} {units[unit_index]}"
else:
return f"{size:.2f} {units[unit_index]}"
def format_speed(bytes_per_second):
"""格式化速度显示"""
return f"{format_size(bytes_per_second)}/s"
def draw_progress_bar(current, total, width=30, start_time=None):
"""绘制进度条"""
if total == 0:
return "0.0% [" + " " * width + "] 0 B/0 B 0 B/s"
# 计算百分比
percentage = min(100.0, (current / total) * 100)
# 计算进度条填充
filled_width = int(width * current // total)
bar = "█" * filled_width + "░" * (width - filled_width)
# 计算速度
speed_str = ""
if start_time is not None:
elapsed_time = time.time() - start_time
if elapsed_time > 0:
speed = current / elapsed_time
speed_str = f" {format_speed(speed)}"
# 格式化大小
current_str = format_size(current)
total_str = format_size(total)
return f"{percentage:5.1f}% [{bar}] {current_str}/{total_str}{speed_str}"
def save_resume_info(filename, info):
"""保存断点续传信息"""
resume_file = f"{filename}.resume"
with open(resume_file, 'w', encoding='utf-8') as f:
json.dump(info, f)
def load_resume_info(filename):
"""加载断点续传信息"""
resume_file = f"{filename}.resume"
if os.path.exists(resume_file):
try:
with open(resume_file, 'r', encoding='utf-8') as f:
return json.load(f)
except:
return None
return None
def remove_resume_info(filename):
"""删除断点续传信息"""
resume_file = f"{filename}.resume"
if os.path.exists(resume_file):
os.remove(resume_file)
def get_file_size(filename):
"""获取已下载文件大小"""
if os.path.exists(filename):
return os.path.getsize(filename)
return 0
def save_multithread_resume_info(filename, info):
"""保存多线程断点续传信息"""
resume_file = f"{filename}.mtresume"
with open(resume_file, 'w', encoding='utf-8') as f:
json.dump(info, f, indent=2)
def load_multithread_resume_info(filename):
"""加载多线程断点续传信息"""
resume_file = f"{filename}.mtresume"
if os.path.exists(resume_file):
try:
with open(resume_file, 'r', encoding='utf-8') as f:
return json.load(f)
except:
return None
return None
def remove_multithread_resume_info(filename):
"""删除多线程断点续传信息"""
resume_file = f"{filename}.mtresume"
if os.path.exists(resume_file):
os.remove(resume_file)
def check_server_support_range(url, session):
"""检查服务器是否支持Range请求"""
try:
headers = {'Range': 'bytes=0-0'}
response = session.head(url, headers=headers, timeout=10)
return response.status_code == 206 or 'Accept-Ranges' in response.headers
except:
return False
def get_file_total_size(url, session):
"""获取文件总大小"""
try:
response = session.head(url, timeout=10)
content_length = response.headers.get('Content-Length')
if content_length:
return int(content_length)
else:
# 如果HEAD请求不返回Content-Length,尝试GET请求
response = session.get(url, stream=True, timeout=10)
content_length = response.headers.get('Content-Length')
response.close()
return int(content_length) if content_length else 0
except:
return 0
def single_thread_download(url, filename, session, enable_resume=True):
"""单线程下载(原有逻辑的简化版本)"""
global upload_interrupted
# 首先检查文件是否已经完全下载(不管是否启用断点续传)
if os.path.exists(filename):
existing_size = get_file_size(filename)
if existing_size > 0:
# 获取文件总大小来检查是否已完全下载
try:
head_response = session.head(url, timeout=10)
total_size = int(head_response.headers.get('Content-Length', 0))
if total_size > 0 and existing_size >= total_size:
print(_('file_already_complete'))
# 如果启用了断点续传,清理断点续传信息
if enable_resume:
remove_resume_info(filename)
return True
except Exception:
# 如果获取文件大小失败,继续正常的下载流程
pass
# 检查断点续传
downloaded_size = 0
mode = 'wb'
headers = {}
if enable_resume and os.path.exists(filename):
downloaded_size = get_file_size(filename)
if downloaded_size > 0:
headers['Range'] = f'bytes={downloaded_size}-'
mode = 'ab'
print(_('detected_resume', format_size(downloaded_size)))
print(_('single_thread_download'))
try:
response = session.get(url, stream=True, headers=headers, timeout=30)
response.raise_for_status()
# 获取总大小
if 'Content-Range' in response.headers:
total_size = int(response.headers['Content-Range'].split('/')[-1])
else:
total_size = int(response.headers.get('Content-Length', 0)) + downloaded_size
block_size = 2097152 # 2MB
dl_count = downloaded_size
start_time = time.time()
last_update_time = start_time
with open(filename, mode) as f:
for chunk in response.iter_content(chunk_size=block_size):
if upload_interrupted:
print(f"\n{_('download_interrupted')}")
return False
f.write(chunk)
dl_count += len(chunk)
# 更新进度条
current_time = time.time()
if current_time - last_update_time >= 0.1:
progress_bar = draw_progress_bar(dl_count, total_size, start_time=start_time)
print(f'\r{progress_bar}', end='', flush=True)
last_update_time = current_time
if not upload_interrupted:
progress_bar = draw_progress_bar(total_size, total_size, start_time=start_time)
print(f'\r{progress_bar}')
print(f"\n{_('download_complete')}")
# 下载完成,清理断点续传信息
if enable_resume:
remove_resume_info(filename)
return True
except Exception as e:
print(f"\n{_('download_error', e)}")
return False
return False
def login_anonymous(session):
try:
r = session.post(
url='https://www.wenshushu.cn/ap/login/anonymous',
json={
"dev_info": "{}"
},
timeout=30
)
r.raise_for_status() # 检查HTTP状态码
# 检查响应内容
if not r.text.strip():
raise Exception("服务器返回空响应")
try:
response_data = r.json()
except ValueError as e:
logging.error(f"JSON解析失败,响应内容: {r.text[:200]}")
raise Exception(f"无法解析服务器响应: {e}")
if 'data' not in response_data or 'token' not in response_data.get('data', {}):
logging.error(f"响应格式错误: {response_data}")
raise Exception("服务器响应格式错误,缺少token字段")
return response_data['data']['token']
except requests.exceptions.RequestException as e:
logging.error(f"网络请求失败: {e}")
raise Exception(f"匿名登录失败: 网络错误 - {e}")
except Exception as e:
logging.error(f"匿名登录失败: {e}")
raise Exception(f"匿名登录失败: {e}")
def api_overseashow(session):
"""调用海外显示API"""
try:
r = session.post(
url=_apiBaseUrl + '/ap/user/overseashow',
json={
"lang": "zh"
},
timeout=30
)
r.raise_for_status()
except Exception as e:
# 海外显示API失败不影响主要功能,记录日志即可
logging.warning(f"海外显示API调用失败: {e}")
pass
def display_login_instructions():
"""显示登录指导"""
instructions = """获取X-TOKEN以便登录你自己的账号:
1. 打开浏览器,访问 https://www.wenshushu.cn
2. 登录你的账号
3. 按F12打开开发者工具
4. 切换到Network(网络)标签
5. 刷新页面或进行任意操作
6. 找到任意一个请求(打开过滤器(Filter)从Fetch/XHR类型中找,例如userinfo或storage或msg或current或ad等)
7. 查看Request Headers(请求标头),找到最下方的X-TOKEN字段
8. 复制X-TOKEN字段(大概率为27位,30或31开头的字符串)
9. 使用`python wss.py login "30xxxxxxxxxxxxxxxxxxxxxxxxx"`登录
10.使用账户上传或下载时不建议关闭获取token的浏览器,可能会被清除缓存导致token失效
Get X-TOKEN to log in to your own account:
1.Open the browser and visit https://www.wenshushu.cn
2.Log in to your account
3.Press F12 to open Developer Tools
4.Switch to the Network tab
5.Refresh the page or perform any action
6.Find any request (Open the Filter and look for it from the Fetch/XHR type, such as userinfo or storage or msg or current or ad)
7.Check the Request Headers and find the X-TOKEN field at the bottom
8.Copy the X-TOKEN field (highly probable strings starting with 27 bits, 30 or 31)
9.使用`python wss.py登录" 30xxxxxxxxxxxxxxxxxxxxxxxxxxxxx x"
10.When uploading or downloading an account, it is not recommended to close the browser to obtain the token. The cache may be cleared and the token is invalidated.
"""
print(instructions)
def write_token(token):
"""保存token到文件"""
script_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(script_dir, 'token.txt'), 'w') as f:
f.write(token)
print(f"尝试使用 X-TOKEN: {token} 登录")
return token
def save_user_token(token, user_info):
"""保存用户token到多用户文件"""
script_dir = os.path.dirname(os.path.abspath(__file__))
tokens_file = os.path.join(script_dir, 'user_tokens.json')
# 读取现有tokens
if os.path.exists(tokens_file):
try:
with open(tokens_file, 'r', encoding='utf-8') as f:
tokens_data = json.load(f)
except:
tokens_data = {}
else:
tokens_data = {}
# 保存新token
user_key = f"{user_info.get('name', '无名')}_{user_info.get('tel', user_info.get('email', 'unknown'))}"
tokens_data[user_key] = {
'token': token,
'user_info': user_info,
'last_login': time.time()
}
# 保存到文件
with open(tokens_file, 'w', encoding='utf-8') as f:
json.dump(tokens_data, f, ensure_ascii=False, indent=2)
# 同时保存到单用户文件(兼容性)
with open(os.path.join(script_dir, 'token.txt'), 'w') as f:
f.write(token)
return user_key
def load_user_tokens():
"""加载所有用户tokens"""
script_dir = os.path.dirname(os.path.abspath(__file__))
tokens_file = os.path.join(script_dir, 'user_tokens.json')
if os.path.exists(tokens_file):
try:
with open(tokens_file, 'r', encoding='utf-8') as f:
return json.load(f)
except:
return {}
return {}
def get_current_user_info(session):
"""获取当前用户信息"""
try:
r = session.post(
url=_apiBaseUrl + '/ap/user/userinfo',
json={"plat": "pcweb"}
)
if r.json()["code"] == 0:
return r.json()['data']
except:
pass
return None
def display_user_tokens():
"""显示所有保存的用户tokens"""
tokens_data = load_user_tokens()
if not tokens_data:
print(_('no_saved_user_tokens'))
return False
print(f"\n{_('saved_user_accounts')}:")
print("-" * 50)
for i, (user_key, data) in enumerate(tokens_data.items(), 1):
user_info = data['user_info']
last_login = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(data['last_login']))
print(f"{i}. {user_info.get('name', '无名')} ({user_info.get('tel', user_info.get('email', 'unknown'))})")
print(f" {_('last_login')}: {last_login}")
print("-" * 50)
return True
def select_user_token():
"""让用户选择一个token"""
tokens_data = load_user_tokens()
if not tokens_data:
return None
display_user_tokens()
try:
choice = input(f"\n{_('select_account_number')}: ").strip()
if choice == '0':
return None
choice_num = int(choice)
user_keys = list(tokens_data.keys())
if 1 <= choice_num <= len(user_keys):
selected_key = user_keys[choice_num - 1]
return tokens_data[selected_key]['token']
else:
print(_('invalid_choice'))
return None
except:
print(_('invalid_input'))
return None
def remove_invalid_token(token_to_remove):
"""从user_tokens.json中删除无效的token"""
script_dir = os.path.dirname(os.path.abspath(__file__))
tokens_file = os.path.join(script_dir, 'user_tokens.json')
if not os.path.exists(tokens_file):
return False
try:
with open(tokens_file, 'r', encoding='utf-8') as f:
tokens_data = json.load(f)
# 查找并删除匹配的token
user_key_to_remove = None
for user_key, data in tokens_data.items():
if data['token'] == token_to_remove:
user_key_to_remove = user_key
break
if user_key_to_remove:
user_info = tokens_data[user_key_to_remove]['user_info']
del tokens_data[user_key_to_remove]
# 保存更新后的数据
with open(tokens_file, 'w', encoding='utf-8') as f:
json.dump(tokens_data, f, ensure_ascii=False, indent=2)
print(f"{_('removed_invalid_account')}: {user_info.get('name', '无名')}")
return True
except Exception as e:
print(f"{_('operation_failed')}: {e}")
return False
def try_login(session):
"""尝试登录"""
script_dir = os.path.dirname(os.path.abspath(__file__))
token_file = os.path.join(script_dir, 'token.txt')
if os.path.exists(token_file):
with open(token_file, 'r') as f:
token = f.read().strip()
print(f"尝试使用已保存的 X-TOKEN: {token} 登录")
session.headers['X-TOKEN'] = token
if get_current_user_info(session):
print()
return True
print("未找到有效token,使用匿名登录")
try:
session.headers['X-TOKEN'] = login_anonymous(session)
api_overseashow(session)
except Exception as e:
logging.error(f"匿名登录失败: {e}")
raise
return False
def patch_session_headers(session):
"""设置session headers"""
user_agents = [
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0'
]
ua = random.choice(user_agents)
common_headers = {
"Origin": "https://www.wenshushu.cn",
"Priority": "u=1, i",
"Prod": "com.wenshushu.web.pc",
"Referer": "https://www.wenshushu.cn/",
"Sec-Ch-Ua": '"Microsoft Edge";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
"Sec-Ch-Ua-Mobile": "?0",
"Sec-Ch-Ua-Platform": '"Windows"',
"Sec-Fetch-Dest": 'empty',
"Sec-Fetch-Mode": 'cors',
"Sec-Fetch-Site": 'same-origin',
"User-Agent": ua,
"Accept-Language": "zh-CN, en-um;q=0.9"
}
session.headers.update(common_headers)
def download(url, enable_resume=False, session=None, num_threads=1):
global LANG
if session is None:
raise ValueError("Session is required")
s = session
def get_tid(token):
r = s.post(
url='https://www.wenshushu.cn/ap/task/token',
json={
'token': token
}
)
return r.json()['data']['tid']
def mgrtask(tid):
global LANG
r = s.post(
url='https://www.wenshushu.cn/ap/task/mgrtask',
json={
'tid': tid,
'password': ''
}
)
rsp = r.json()
expire = rsp['data']['expire']
days, remainder = divmod(int(float(expire)), 3600*24)
hours, remainder = divmod(remainder, 3600)
minutes, seconds = divmod(remainder, 60)
print(_('file_expires', days, hours, minutes, seconds))
file_size = rsp['data']['file_size']
print(_('file_size', round(int(file_size)/1024**2,2)))
return rsp['data']['boxid'], rsp['data']['ufileid'] # pid
def list_file(tid):
global LANG
bid, pid = mgrtask(tid)
r = s.post(
url='https://www.wenshushu.cn/ap/ufile/list',
json={
"start": 0,
"sort": {
"name": "asc"
},
"bid": bid,
"pid": pid,
"type": 1,
"options": {
"uploader": "true"
},
"size": 50
}
)
rsp = r.json()
filelist = rsp['data']['fileList']
# 支持多文件下载
for i, file_info in enumerate(filelist):
filename = file_info['fname']
fid = file_info['fid']
print(f'[{i + 1}/{len(filelist)}] {_("file_name", filename)}')
sign(bid, fid, filename)
def down_handle(url, filename):
global LANG
# 根据线程数选择下载方式
if num_threads > 1:
# 使用智能多线程下载
success = smart_multithread_download(url, filename, s, num_threads, enable_resume)
if not success and not upload_interrupted:
print("多连接下载失败,尝试单线程下载...")
return single_thread_download(url, filename, s, enable_resume)
return success
else:
# 使用单线程下载
return single_thread_download(url, filename, s, enable_resume)
def sign(bid, fid, filename):
global LANG
r = s.post(
url='https://www.wenshushu.cn/ap/dl/sign',
json={
'consumeCode': 0,
'type': 1,
'ufileid': fid
}
)
if r.json()['data']['url'] == "" and \
r.json()['data']['ttNeed'] != 0:
print(_('share_traffic_insufficient'))
sys.exit(0)
url = r.json()['data']['url']
down_handle(url, filename)
if len(url.split('/')[-1]) == 16:
token = url.split('/')[-1]
tid = get_tid(token)
elif len(url.split('/')[-1]) == 11:
tid = url.split('/')[-1]
list_file(tid)
def upload(filePath, pwd="", session=None):
global LANG
if session is None:
raise ValueError("Session is required")
s = session
# 目录处理相关函数
def make_tar_gz(output_filename, source_dir):
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir))
def get_readable_size(file_path):
size = os.path.getsize(file_path)
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024:
return f"{size:.2f} {unit}"
size /= 1024
return f"{size:.2f} PB"
# 处理目录上传
need_del_file = False
original_path = filePath
if not os.path.exists(filePath):
logging.error(f'{filePath} 不存在')
return
if os.path.isdir(filePath):
filePath = os.path.normpath(filePath)
new_filename = os.path.basename(filePath) + '.tar.gz'
start_time = time.time()
logging.warning(f'{filePath} 是一个目录,自动压缩为: {new_filename}')
make_tar_gz(new_filename, filePath)
end_time = time.time()
logging.info(f"压缩耗时: {end_time - start_time:.4f} 秒,大小: {get_readable_size(new_filename)}")
filePath = new_filename
need_del_file = True
elif os.path.isfile(filePath):
need_del_file = False
chunk_size = 2097152
file_size = os.path.getsize(filePath)
ispart = True if file_size > chunk_size else False
def read_file(block_size=chunk_size):
partnu = 0
with open(filePath, "rb") as f:
while True:
block = f.read(block_size)
partnu += 1
if block:
yield block, partnu
else:
return
def sha1_str(s):
cm = hashlib.sha1(s.encode()).hexdigest()
return cm
def calc_file_hash(hashtype, block=None):
read_size = chunk_size if ispart else None
if not block:
with open(filePath, 'rb') as f:
block = f.read(read_size)
if hashtype == "MD5":
hash_code = hashlib.md5(block).hexdigest()
elif hashtype == "SHA1":
hash_code = hashlib.sha1(block).hexdigest()
return hash_code
def get_epochtime():
global LANG
r = s.get(
url='https://www.wenshushu.cn/ag/time',
headers={
"Prod": "com.wenshushu.web.pc",
"Referer": "https://www.wenshushu.cn/"
}
)
rsp = r.json()
return rsp["data"]["time"] # epochtime expires in 60s
def get_cipherheader(epochtime, token, data):
global LANG
# cipherMethod: DES/CBC/PKCS7Padding
json_dumps = json.dumps(data, ensure_ascii=False)