-
Notifications
You must be signed in to change notification settings - Fork 2
/
Suya_Downloader.py
1982 lines (1671 loc) · 85.6 KB
/
Suya_Downloader.py
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 ctypes
import json
import os
import shutil
import sys
import threading
import tkinter as tk
from errno import EEXIST
from getpass import getuser
from queue import Queue
from socket import AF_INET
from tempfile import mkdtemp, NamedTemporaryFile
from time import time, sleep
from tkinter import scrolledtext, ttk, filedialog, messagebox as msgbox
from uuid import uuid4 as uuid
from webbrowser import open as webopen
from winreg import OpenKey, HKEY_CURRENT_USER, QueryValueEx
from zipfile import ZipFile, BadZipFile
import pygame
import requests
from PIL import Image, ImageTk
Suya_Downloader_Version = "1.0.3.6"
Dev_Version = ""
# 获取运行目录并设置默认API设置的文件目录
current_working_dir = os.getcwd()
suya_config_path = os.path.join(".", "suya_config.json")
default_api_setting_path = os.path.join(".", "default_api_setting.json")
def get_text(key):
if key == "lost_key":
try:
text = lang_json[key]
except:
try:
text = spare_lang_json[key]
except:
text = "Key lost,lost key: "
return text
else:
try:
text = lang_json[key]
except:
try:
text = spare_lang_json[key]
except:
text = get_text("lost_key") + key
return text
def check_folder(path):
if not os.path.exists(path):
os.makedirs(path)
print("已创建文件夹:", path)
def get_admin():
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
sys.exit()
# 打印运行目录以确认
print("运行目录:", current_working_dir)
def generate_time(tag):
# 使用strftime方法将当前时间格式化为指定的格式
from datetime import datetime
if tag == 0:
export_time = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
elif tag == 1:
local_tz = datetime.now().astimezone().tzinfo
formatted_time = datetime.now().strftime("%Y/%m/%d|%H:%M:%S")
tz_offset = local_tz.utcoffset(datetime.now()).total_seconds() / 3600
tz_str = f"|UTC{tz_offset:+.0f}"
export_time = f"{formatted_time}{tz_str}"
elif tag == 2:
export_time = time()
else:
export_time = "Unknown request"
return export_time
def export_system_info(msg_box):
import psutil
import platform
# 输出系统信息到文本框
msg_box.insert(tk.END, f"Report Export Time: {generate_time(1)}\n")
msg_box.insert(tk.END, f"Unix timestamp: {generate_time(2)}\n")
msg_box.insert(tk.END, f"Running Directory: {current_working_dir}\n")
msg_box.insert(tk.END, f"Suya Downloader Version: {Suya_Downloader_Version}")
if Dev_Version != "":
msg_box.insert(tk.END, f"-{Dev_Version}\n")
try:
msg_box.insert(tk.END, f"\nUpdater Version: {suya_config["Updater_Version"]}\n")
msg_box.insert(tk.END, "\n\n-------------Used Config Information-------------\n")
msg_box.insert(tk.END, f"\n{json.dumps(suya_config, ensure_ascii=False, indent=4)}\n")
msg_box.insert(tk.END, "\n-------------------------------------------------\n")
except:
msg_box.insert(tk.END, "\nSettings Information: Not initialized\n")
msg_box.insert(tk.END, "\n\n---------------System Information---------------\n")
msg_box.insert(tk.END, f"OS: {platform.platform(terse=True)}\n")
msg_box.insert(tk.END, f"OS Detailed: {platform.platform()}\n")
msg_box.insert(tk.END, f"Kernel Version: {platform.release()}\n")
msg_box.insert(tk.END, f"Architecture: {platform.machine()}\n")
# CPU Information
msg_box.insert(tk.END, "\n\n-----------------CPU Information-----------------\n")
msg_box.insert(tk.END, f"Model: {platform.processor()}\n")
msg_box.insert(tk.END, f"Physical Cores: {psutil.cpu_count(logical=False)}\n")
msg_box.insert(tk.END, f"Total Cores: {psutil.cpu_count(logical=True)}\n")
msg_box.insert(tk.END, f"Max Frequency: {psutil.cpu_freq().max:.2f} MHz\n")
msg_box.insert(tk.END, f"Current Frequency: {psutil.cpu_freq().current:.2f} MHz\n")
# Memory Information
msg_box.insert(tk.END, "\n\n---------------Memory Information---------------\n")
mem = psutil.virtual_memory()
msg_box.insert(tk.END, f"Total Memory: {mem.total / (1024 ** 3):.2f} GB\n")
msg_box.insert(tk.END, f"Available Memory: {mem.available / (1024 ** 3):.2f} GB\n")
msg_box.insert(tk.END, f"Used Memory: {mem.used / (1024 ** 3):.2f} GB\n")
msg_box.insert(tk.END, f"Memory Percent Used: {mem.percent}%\n")
# Disk Information
msg_box.insert(tk.END, "\n\n----------------Disk Information----------------\n")
try:
for part in psutil.disk_partitions(all=False):
if os.path.isdir(part.mountpoint): # 检查挂载点是否是一个有效的目录
try:
usage = psutil.disk_usage(part.mountpoint)
msg_box.insert(tk.END, f"Device: {part.device}\n")
msg_box.insert(tk.END, f"Mountpoint: {part.mountpoint}\n")
msg_box.insert(tk.END, f"File System Type: {part.fstype}\n")
msg_box.insert(tk.END, f"Total Size: {usage.total / (1024 ** 3):.2f}GB\n")
msg_box.insert(tk.END, f"Used: {usage.used / (1024 ** 3):.2f}GB\n")
msg_box.insert(tk.END, f"Free: {usage.free / (1024 ** 3):.2f}GB\n")
msg_box.insert(tk.END, f"Percent Used: {usage.percent}%\n\n")
except Exception as e:
msg_box.insert(tk.END, f"Error getting disk usage for {part.mountpoint}: {e}\n\n")
except Exception as e:
msg_box.insert(tk.END, f"Error iterating over disk partitions: {e}\n")
# Network Information
msg_box.insert(tk.END, "\n\n---------------Network Information---------------\n")
for interface, addrs in psutil.net_if_addrs().items():
msg_box.insert(tk.END, f"\n||||||||||||||{interface}||||||||||||||\n\n")
for addr in addrs:
if addr.family == AF_INET:
msg_box.insert(tk.END, f"Interface: {interface}\n")
msg_box.insert(tk.END, f"IP Address: {addr.address}\n")
msg_box.insert(tk.END, f"Netmask: {addr.netmask}\n")
msg_box.insert(tk.END, f"Broadcast IP: {addr.broadcast}\n\n")
# 将文本框内容写入文件的函数
def write_to_file(text_box, file_name):
# 获取文本框内容
info_text = text_box.get("1.0", tk.END)
# 确定下载文件夹路径
if os.name == "nt": # Windows
def get_download_folder():
try:
key = OpenKey(HKEY_CURRENT_USER,
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
print("从注册表获取到下载文件夹路径成功")
return QueryValueEx(key, "{374DE290-123F-4565-9164-39C4925E467B}")[0]
except FileNotFoundError:
# 如果上述方法失败,回退到默认路径
return os.path.join(os.getenv("USERPROFILE"), "Downloads")
download_folder = get_download_folder()
print("获取到下载文件夹路径:" + download_folder)
else: # Unix or Linux
download_folder = os.path.expanduser("~/Downloads")
# 写入文件
file_path = os.path.join(download_folder, file_name + ".txt")
with open(file_path, "w", encoding="utf-8") as file:
file.write(info_text)
return file_path
def open_directory(path):
"""在操作系统默认的文件管理器中打开指定路径的目录"""
if os.name == "nt": # Windows
os.startfile(os.path.dirname(path))
elif os.name == "posix": # Unix/Linux/MacOS
import subprocess
subprocess.run(["xdg-open", os.path.dirname(path)])
else:
print("Unsupported operating system")
def get_traceback_info():
"""获取当前线程的堆栈跟踪信息"""
import traceback
return traceback.format_exc()
def dupe_crash_report(error_message=None):
# 创建主窗口
crash_window = tk.Tk()
crash_window.title("Crash Report")
# 设置窗口图标
try:
window_main.iconbitmap("./Resources-Downloader/Pictures/Suya.ico") # 使用Suya作为窗口图标
except:
window_main.iconbitmap(ImageTk.PhotoImage(Image.new("RGB", (24, 24), color="red")))
print("丢失窗口图标")
# 创建一个滚动条和文本框
scrollbar = tk.Scrollbar(crash_window)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
msg_box = tk.Text(crash_window, yscrollcommand=scrollbar.set)
msg_box.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.config(command=msg_box.yview)
msg_box.insert(tk.END, "Crash Report\nOh, it seems like it crashed."
"\n\n--------------Crash Report--------------\n\n")
# 如果有错误消息,先输出错误消息
if error_message:
msg_box.insert(tk.END, f"Error:\n{error_message}\n\n")
# 输出堆栈跟踪信息
traceback_info = get_traceback_info()
msg_box.insert(tk.END, f"Traceback Info:\n{traceback_info}\n\n")
msg_box.insert(tk.END, "\n-------------------------------------------------\n\n")
# 输出系统信息并写入文件
export_system_info(msg_box)
file_name = generate_time(0) + "_CrashReport"
file_path = write_to_file(msg_box, file_name)
open_directory(file_path)
# 主事件循环
crash_window.mainloop()
def merge_jsons(default_json_or_path, file_or_json):
"""
合并两个 JSON 对象,优先使用文件中的数据。
:param default_json_or_path: 默认的 JSON 字典或对应文件路径
:param file_or_json: 文件路径或优先使用的 JSON 字典
:return: 合并后的 JSON 字典
"""
def load_json(data):
if isinstance(data, str): # 如果是字符串,判断是文件路径还是JSON文本
try:
with open(data, "r", encoding="utf-8") as file:
return json.load(file)
except FileNotFoundError:
try:
return json.loads(data) # 尝试将字符串作为JSON文本解析
except json.JSONDecodeError as e:
raise ValueError(f"Invalid JSON format: {e}")
elif isinstance(data, dict):
return data
else:
raise TypeError("Unsupported type for JSON input")
loaded_json = load_json(file_or_json)
default_json_loaded = load_json(default_json_or_path)
# 使用文件中的数据覆盖默认值
return {**default_json_loaded, **loaded_json}
def get_config(initialize_tag):
try:
with open(default_api_setting_path, "r", encoding="utf-8") as file:
default_suya_config = {"default_api_settings": json.load(file)}
print("读取到初始参数:", default_suya_config)
except:
get_admin()
if os.name == "nt":
try:
default_suya_config["initialize_path"] = os.path.join(
f"C:\\Users\\{getuser()}\\AppData\\Local\\Suya_Downloader",
default_suya_config["default_api_settings"]["Server_Name"])
except:
print("出现异常:" + str(Exception))
print("最终initialize_path:", default_suya_config["initialize_path"])
elif os.name == "posix":
try:
default_suya_config[
"initialize_path"] = fr"{os.getcwd()}\{default_suya_config["default_api_settings"]["Server_Name"]}"
except:
print("异常错误")
try:
final_suya_config = merge_jsons(suya_config_path, default_suya_config)
print("初次合并结果:", final_suya_config)
except:
final_suya_config = default_suya_config
print("出现异常:" + str(Exception))
try:
if final_suya_config["debug"]:
pass
except:
final_suya_config["debug"] = False
try:
if final_suya_config["cf_mirror_enabled"]:
print("使用CF镜像")
else:
print("使用Github镜像")
except:
try:
if final_suya_config["default_api_settings"]["cf_mirror_enabled"]:
final_suya_config["cf_mirror_enabled"] = final_suya_config["default_api_settings"]["cf_mirror_enabled"]
print("使用CF镜像")
else:
final_suya_config["cf_mirror_enabled"] = final_suya_config["default_api_settings"]["cf_mirror_enabled"]
print("使用Github镜像")
except:
final_suya_config["cf_mirror_enabled"] = True
try:
if initialize_tag:
try:
final_suya_config["Used_Server_url_get"]
except:
final_suya_config["Used_Server_url_get"] = {}
if final_suya_config["cf_mirror_enabled"]:
final_suya_config["Used_Server_url_get"]["latest_server_api_url"] = \
final_suya_config["default_api_settings"]["server_api_url"]
elif not final_suya_config["cf_mirror_enabled"]:
final_suya_config["Used_Server_url_get"]["latest_server_api_url"] = \
final_suya_config["default_api_settings"]["server_api_url_gh"]
else:
try:
api_content = requests.get(final_suya_config["Used_Server_url_get"]["latest_server_api_url"]).json()
print("获取到API信息: ", api_content)
api_content_new = {"All_Server_url_get": api_content}
final_suya_config = merge_jsons(final_suya_config, api_content_new)
print("合并全局配置:", final_suya_config)
except:
print("出现异常:" + str(Exception))
dupe_crash_report()
try:
final_suya_config["All_Server_url_get"]
except:
final_suya_config["All_Server_url_get"] = {}
if final_suya_config["cf_mirror_enabled"]:
final_suya_config["Used_Server_url_get"]["latest_api_url"] = \
final_suya_config["All_Server_url_get"]["api_url"]
final_suya_config["Used_Server_url_get"]["latest_update_url"] = \
final_suya_config["All_Server_url_get"]["update_url"]
final_suya_config["Used_Server_url_get"]["latest_announcement_url"] = \
final_suya_config["All_Server_url_get"]["announcement_url"]
final_suya_config["Used_Server_url_get"]["latest_important_notice_url"] = \
final_suya_config["All_Server_url_get"]["important_notice_url"]
elif not final_suya_config["cf_mirror_enabled"]:
final_suya_config["Used_Server_url_get"]["latest_api_url"] = \
final_suya_config["api_url_gh"]
final_suya_config["Used_Server_url_get"]["latest_update_url"] = \
final_suya_config["update_url_gh"]
final_suya_config["Used_Server_url_get"]["latest_announcement_url"] = \
final_suya_config["announcement_url_gh"]
final_suya_config["Used_Server_url_get"]["latest_important_notice_url"] = \
final_suya_config["important_notice_url_gh"]
except:
msgbox.showinfo("错误", str(Exception))
print("最终全局配置:", final_suya_config)
with open(suya_config_path, "w", encoding="utf-8") as file:
json.dump(final_suya_config, file, indent=4)
if final_suya_config["default_api_settings"]["server_api_url"] == "" and \
final_suya_config["default_api_settings"]["server_api_url_gh"] == "":
msgbox.showinfo(get_text("error"), get_text("no_api"))
dupe_crash_report()
return final_suya_config
try:
suya_config = get_config(True)
except:
get_admin()
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin() != 0
except:
return False
if suya_config["debug"]:
print("非管理员模式运行")
elif os.name == "nt" and not is_admin():
# 如果当前没有管理员权限且处于非调试模式,则重新启动脚本并请求管理员权限
get_admin()
def get_language():
global language
def set_lang(setting_json_inner):
choose_language()
setting_json_inner["language"] = global_selected_lang
final_language = global_selected_lang
if final_language is not None:
return final_language
else:
exit(1)
try:
language = suya_config["language"]
except:
language = set_lang(suya_config)
suya_config["language"] = language
with open(suya_config_path, "w", encoding="utf-8") as file_w:
json.dump(suya_config, file_w, ensure_ascii=False, indent=4)
def open_updater(window):
try:
if os.name == "nt":
updater_path = os.path.join(current_working_dir, "Updater.exe")
if os.name == "posix":
updater_path = os.path.join(current_working_dir, "Updater")
if os.path.isfile(updater_path):
import subprocess
subprocess.Popen([updater_path])
print("Updater已启动。")
if window is not None:
try:
window.destroy() # 关闭Tkinter窗口
except:
print("Tkinter窗口可能未开启或关闭失败。")
else:
print("Updater未找到。")
except:
msgbox.showerror(get_text("start_download_error"), get_text("start_download_error2") + f"{Exception}")
def pull_files(window, way):
if os.name == "nt":
global suya_config
suya_config["Updater_Method"] = way
if way == "Resources":
try:
suya_config["Pull_Resources_Count"] += 1
except:
suya_config["Pull_Resources_Count"] = 1
with open(suya_config_path, "w", encoding="utf-8") as file:
json.dump(suya_config, file, ensure_ascii=False, indent=4)
open_updater(window)
def choose_language():
# 初始化Tkinter窗口
language_choose_window = tk.Tk()
language_choose_window.title("Choose Your Language")
language_choose_window.geometry("300x250")
# 设置窗口图标
language_choose_window.iconbitmap("./Resources-Downloader/Pictures/Suya.ico") # 使用Suya作为窗口图标
center_window(language_choose_window)
# 加载图标并显示在窗口内
try:
try:
top_icon = Image.open("./Resources-Server/Pictures/Server-icon.png")
except:
top_icon = Image.open("./Resources-Downloader/Pictures/Suya.png")
except:
top_icon = ImageTk.PhotoImage(Image.new("RGB", (100, 100), color="red"))
top_icon = top_icon.resize((100, 100))
top_icon_image = ImageTk.PhotoImage(top_icon)
tk.Label(language_choose_window, image=top_icon_image).pack(side=tk.TOP) # 显示图标在顶部
# 定义一个变量来存储所选语言,并设置默认值为简体中文
selected_lang = tk.StringVar(value="zh_hans")
# 创建Radiobuttons并绑定到selected_lang
languages = [("简体中文", "zh_hans"), ("繁體中文", "zh_hant"), ("English", "en_us")]
for lang, value in languages:
tk.Radiobutton(language_choose_window, text=lang, variable=selected_lang, value=value).pack(anchor=tk.W)
# 定义一个函数来获取选择并关闭窗口,同时更新全局变量
def get_selection():
global global_selected_lang
global_selected_lang = selected_lang.get()
language_choose_window.destroy()
# 创建一个按钮来确认选择
confirm_button = ttk.Button(language_choose_window, text="Confirm", command=get_selection)
confirm_button.pack(pady=10)
# 运行Tkinter事件循环
language_choose_window.mainloop()
def initialize_languages(tag):
global lang_json, spare_lang_json
get_language()
lang = language
if tag is not None:
lang = tag
if lang == "zh_hans":
lang_path = os.path.join("./Resources-Downloader/Languages", "zh_hans.json")
elif lang == "zh_hant":
lang_path = os.path.join("./Resources-Downloader/Languages", "zh_hant.json")
elif lang == "en_us":
lang_path = os.path.join("./Resources-Downloader/Languages", "en_us.json")
else:
lang_path = os.path.join("./Resources-Downloader/Languages", "zh_hans.json")
suya_config["language"] = "zh_hans"
with open(suya_config_path, "w", encoding="utf-8") as file:
json.dump(suya_config_path, file, ensure_ascii=False, indent=4)
try:
with open(lang_path, "r", encoding="utf-8") as file:
lang_json = json.load(file)
with open(os.path.join("./Resources-Downloader/Languages", "zh_hans.json"), "r", encoding="utf-8") as file:
spare_lang_json = json.load(file)
except:
pull_files(None, "Resources")
sys.exit(0)
def export_info(event):
def show_ui():
# 导出按钮点击事件处理函数
def on_export_button_click():
try:
file_name = generate_time(0) + "_InfoExport"
file_path = write_to_file(system_info_box, file_name) # 返回文件的完整路径
msgbox.showinfo(get_text("export_information"),
get_text("export_information_success") + f"{file_path}")
# 打开文件所在目录
open_directory(file_path)
except:
msgbox.showerror(get_text("export_information"),
get_text("export_information_error") + f"{Exception}")
# 创建一个新的顶级窗口
export_info_window = tk.Toplevel()
export_info_window.title(get_text("export_information"))
# 设置窗口图标
export_info_window.iconbitmap("./Resources-Downloader/Pictures/Suya.ico") # 使用Suya作为窗口图标
# 创建一个框架来容纳文本框和滚动条
text_scroll_frame = tk.Frame(export_info_window)
text_scroll_frame.pack(fill="both", expand=True)
# 创建文本显示框
system_info_box = tk.Text(text_scroll_frame, width=50, height=10)
# 创建滚动条
scrollbar = tk.Scrollbar(text_scroll_frame, orient="vertical", command=system_info_box.yview)
# 将滚动条与文本框关联
system_info_box.config(yscrollcommand=scrollbar.set)
# 打包文本框和滚动条到text_scroll_frame中
system_info_box.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")
# 创建一个框架来容纳按钮
buttons_frame = tk.Frame(export_info_window)
buttons_frame.pack(fill="x", pady=(5, 0), side="bottom") # 明确指定side="bottom"
# 导出数据按钮
export_button = tk.Button(buttons_frame, text=get_text("export_data"), command=on_export_button_click)
export_button.pack(side="left", padx=5)
# 关闭窗口按钮
close_button = tk.Button(buttons_frame, text=get_text("close"), command=export_info_window.destroy)
close_button.pack(side="right", padx=5)
# 清空文本框内容
system_info_box.delete("1.0", tk.END)
system_info_box.insert(tk.END,
"Exported Information\nThis is not a crash report."
"\n\n---------------Exported Information--------------\n\n")
# 写入系统信息
export_system_info(system_info_box)
# 禁止编辑文本框
system_info_box.configure(state=tk.DISABLED)
# 创建并启动新线程
thread = threading.Thread(target=show_ui)
thread.daemon = True
thread.start()
def initialize_settings():
path_from_file = os.path.join(suya_config["initialize_path"], "Downloaded")
try:
path_from_file = suya_config["Client_dir"]
except:
suya_config["Client_dir"] = path_from_file
with open(suya_config_path, "w", encoding="utf-8") as file:
json.dump(suya_config, file, ensure_ascii=False, indent=4)
ensure_directory_exists(path_from_file)
print("格式化处理后的路径:" + path_from_file)
return path_from_file
def ensure_directory_exists(directory_path):
"""确保目录存在,如果不存在则尝试创建。"""
try:
check_folder(directory_path)
except OSError as e:
if e.errno != EEXIST:
raise ValueError(get_text("cant_make_dir") + f"{directory_path}") from e
def update_version_info(new_version):
"""
更新本地存储的版本信息。
:param new_version: 最新的版本号
"""
try:
with open(os.path.join(suya_config["initialize_path"], "client_version.txt"), "w", encoding="utf-8") as file:
file.write(new_version)
print(f"版本信息已更新至{new_version}")
except IOError as e:
print(f"写入版本信息时发生错误: {e}")
def read_client_version_from_file():
"""从本地文件读取客户端版本号,如文件不存在则创建并写入默认版本号。"""
file_path = os.path.join(suya_config["initialize_path"], "client_version.txt")
try:
with open(file_path, "r", encoding="utf-8") as file:
client_version_inner = file.read().strip()
return client_version_inner
except FileNotFoundError:
print("版本文件未找到,正在尝试创建并写入默认版本号...")
try:
with open(file_path, "w", encoding="utf-8") as file:
file.write("0.0.0.0") # 写入默认版本号
print("默认版本号已成功写入。")
return "0.0.0.0"
except IOError as io_err:
print(f"写入文件时发生IO错误: {io_err}")
return "写入错误"
except Exception as e:
print(f"处理文件时发生未知错误: {e}")
return "未知错误"
# 使用函数读取版本号
client_version = read_client_version_from_file()
print(f"当前客户端版本: {client_version}")
def center_window(window, width=None, height=None):
"""
使窗口居中显示。
:param window: Tkinter窗口实例
:param width: 窗口宽度,默认为None,表示使用当前窗口宽度
:param height: 窗口高度,默认为None,表示使用当前窗口高度
"""
window.update_idletasks() # 确保窗口尺寸是最新的
window_width = width if width is not None else window.winfo_width()
window_height = height if height is not None else window.winfo_height()
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
x_cordinate = int((screen_width / 2) - (window_width / 2))
y_cordinate = int((screen_height / 2) - (window_height / 2))
window.geometry(f"{window_width}x{window_height}+{x_cordinate}+{y_cordinate}")
class TkTransparentSplashScreen:
def __init__(self):
self.root = tk.Tk()
self.root.overrideredirect(True) # 移除标题栏和边框
self.root.wm_attributes("-topmost", True) # 置顶窗口
self.root.wm_attributes("-transparentcolor", "white") # 设置透明颜色为白色
# 获取屏幕尺寸以计算窗口大小,保持图片比例适应屏幕
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
# 尝试加载服务器提供的图片,如果不存在则加载下载器提供的图片,如果仍然不存在则使用纯白
try:
img = Image.open("./Resources-Server/Pictures/Server-icon.png")
pic_ratio = img.size[0] / img.size[1]
except:
try:
img = Image.open("./Resources-Downloader/Pictures/Suya.png")
pic_ratio = img.size[0] / img.size[1]
except:
img = Image.new("RGB", (200, 200), color="white")
pic_ratio = 1.0
window_width = min(int(screen_width * 0.8), int(screen_height * 0.6 * pic_ratio))
window_height = int(window_width / pic_ratio)
# 加载背景图像并按窗口大小调整,确保不失真且尽可能大
img = img.resize((window_width, window_height), Image.LANCZOS)
self.photo = ImageTk.PhotoImage(img)
# 创建一个 Canvas 用于显示图片
self.canvas = tk.Canvas(self.root, width=window_width, height=window_height, bg="white")
self.canvas.pack()
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.photo)
# 设置窗口居中显示
x = (screen_width - window_width) // 2
y = (screen_height - window_height) // 2
self.root.geometry(f"{window_width}x{window_height}+{x}+{y}")
# 模拟启动过程,2秒后关闭splash screen
self.root.after(2000, self.close_splash)
# 设置淡入定时器
self.alpha = 0
self.fade_in()
def fade_in(self):
"""淡入步骤函数,逐步增加窗口的透明度"""
self.alpha += 20 # 每次增加的透明度值
if self.alpha >= 255:
self.alpha = 255
return
# 更新透明度
self.root.wm_attributes("-alpha", self.alpha / 255.0)
# 每50毫秒执行一次淡入步骤
self.root.after(50, self.fade_in)
def close_splash(self):
self.root.destroy()
create_gui()
def language_unformatted():
if language == "zh_hans":
return "简体中文"
elif language == "zh_hant":
return "繁體中文"
elif language == "en_us":
return "English"
def language_formated(selected):
if selected == "简体中文":
return "zh_hans"
elif selected == "繁體中文":
return "zh_hant"
elif selected == "English":
return "en_us"
def create_setting_window(event):
"""在新窗口中创建设置界面。"""
def on_choose_path():
"""处理选择路径按钮点击的逻辑"""
rel_path = initialize_settings()
path_user = filedialog.askdirectory(initialdir=rel_path) # 设置默认打开的目录
print("用户输入路径:" + path_user)
if path_user:
entry.delete(0, tk.END) # 清除当前文本框内容
entry.insert(0, path_user) # 插入用户选择的路径
else:
if not entry.get(): # 如果文本框为空
path_user = suya_config["initialize_path"]
entry.delete(0, tk.END) # 如果没有选择,清除当前文本框内容
entry.insert(0, path_user) # 插入默认路径
else:
path_user = entry.get()
suya_config["Client_dir"] = path_user
with open(suya_config_path, "w", encoding="utf-8") as file:
json.dump(suya_config, file, ensure_ascii=False, indent=4)
ensure_directory_exists(path_user)
# 创建新窗口作为设置界面
setting_win = tk.Toplevel()
setting_win.title(get_text("settings"))
# 设置窗口图标
setting_win.iconbitmap("./Resources-Downloader/Pictures/Suya.ico") # 使用Suya作为窗口图标
# 添加说明标签
instruction_label = tk.Label(setting_win, text=get_text("direct_pull_path"), anchor="w")
instruction_label.pack(pady=(10, 0)) # 上方预留一些间距
# 添加一个文本框显示选择的路径
entry = tk.Entry(setting_win, width=50)
path = initialize_settings()
entry.insert(0, path) # 插入用户选择的路径
entry.pack(pady=5)
# 添加一个按钮用于打开文件夹选择对话框
choose_button = tk.Button(setting_win, text=get_text("choose_folders"), command=on_choose_path)
choose_button.pack(pady=10)
# 定义一个变量来追踪复选框的状态
cf_mirror_enabled = tk.BooleanVar(value=suya_config["cf_mirror_enabled"])
# 添加描述性标签
description_label = tk.Label(setting_win, text=get_text("cf_mirror_description"))
description_label.pack(pady=(10, 0))
# 在设置窗口的语言选项下方添加启用/禁用CF镜像源的复选框
cf_mirror_checkbox = tk.Checkbutton(setting_win, text=get_text("cf_mirror_enable"), variable=cf_mirror_enabled)
cf_mirror_checkbox.pack(pady=10)
# 更新保存设置的逻辑,确保新的设置被保存
def save_settings():
suya_config["cf_mirror_enabled"] = cf_mirror_enabled.get() # 保存复选框的状态
with open(suya_config_path, "w", encoding="utf-8") as file:
json.dump(suya_config, file, ensure_ascii=False, indent=4)
# 确保在关闭窗口前调用save_settings函数来保存所有设置
setting_win.protocol("WM_DELETE_WINDOW", lambda: [save_settings(), setting_win.destroy()])
# 语言选项部分
lang_frame = tk.Frame(setting_win)
lang_frame.pack(side=tk.LEFT, padx=(5, 0), fill=tk.Y) # 使用fill=tk.Y允许frame填充垂直空间
inner_frame = tk.Frame(lang_frame) # 新增内部框架用于垂直对齐
inner_frame.pack(fill=tk.Y, expand=True) # 允许内部框架填充并扩展以保持统一高度
lang_label = tk.Label(inner_frame, text="Languages: ", anchor="w")
lang_label.pack(side=tk.LEFT, padx=(0, 5), pady=(0, 5)) # 设置上下pad以增加间距
# 选项
lang_choice = ["简体中文", "繁體中文", "English"]
lang_selected = tk.StringVar(value=language_unformatted()) # 初始化
# 创建Combobox选择框,指定宽度
lang_combobox = ttk.Combobox(inner_frame, textvariable=lang_selected, values=lang_choice,
state="readonly", width=20) # 设定Combobox宽度为20字符宽
lang_combobox.pack(side=tk.LEFT, pady=(0, 5), fill=tk.X) # 增加上下pad以保持间距,fill=tk.X填充水平空间
# 添加按钮打开开源库地址
button_frame = tk.Frame(setting_win)
button_frame.pack(side=tk.LEFT, padx=(5, 0), fill=tk.Y)
def open_repo():
webopen("https://github.com/Suisuroru/Suya_Downloader")
open_repo_button = tk.Button(button_frame, text=get_text("open_repo"), command=open_repo)
open_repo_button.pack(pady=(0, 5), fill=tk.X)
def reload_with_confirm():
lang_old = language
lang_new = language_formated(lang_selected.get())
initialize_languages(lang_new)
if lang_new != language:
answer = msgbox.askyesno(get_text("tip"), get_text("reload_tip"))
if answer:
suya_config["language"] = lang_new
with open(suya_config_path, "w", encoding="utf-8") as file:
json.dump(suya_config, file, ensure_ascii=False, indent=4)
os.execl(sys.executable, sys.executable, *sys.argv)
else:
initialize_languages(lang_old)
# 创建确认按钮框架,确保与Combobox对齐
button_frame = tk.Frame(inner_frame)
button_frame.pack(side=tk.LEFT, pady=(0, 5), fill=tk.Y) # 填充垂直空间以保持高度一致
# 创建确定按钮并绑定到reload_with_confirm函数
confirm_button = tk.Button(button_frame, text=get_text("confirm"), command=reload_with_confirm)
confirm_button.pack(fill=tk.BOTH) # 让按钮填充button_frame的空间
setting_win.mainloop()
def update_progress_bar(progress_bar, value, max_value):
"""更新进度条的值"""
progress_bar["value"] = value
progress_bar["maximum"] = max_value
progress_bar.update()
def download_file_with_progress(url, save_path, chunk_size=1024, progress_callback=None):
"""带有进度显示的文件下载函数,直接保存到指定路径"""
response = requests.get(url, stream=True)
total_size = int(response.headers.get("content-length", 0))
downloaded_size = 0
with open(save_path, "wb", encoding="utf-8") as file:
for chunk in response.iter_content(chunk_size):
if chunk:
file.write(chunk)
downloaded_size += len(chunk)
if progress_callback:
progress_callback(downloaded_size, total_size)
response.raise_for_status()
def start_download_in_new_window(download_link):
def start_download_and_close(new_window):
# 添加进度文字标签
progress_text = tk.StringVar()
progress_label = ttk.Label(new_window, textvariable=progress_text)
progress_label.pack(anchor="w", pady=(10, 0)) # 上方添加进度文字,修正了语法错误
# 添加百分比标签
percentage_text = tk.StringVar()
percentage_label = ttk.Label(new_window, textvariable=percentage_text)
percentage_label.pack(anchor="center", pady=(0, 10)) # 下方添加百分比,这里原本就是正确的
# 添加速度相关变量和标签
speed_text = tk.StringVar()
speed_label = ttk.Label(new_window, textvariable=speed_text)
speed_label.pack(anchor="w", pady=(0, 10)) # 在百分比标签下方添加速度标签
def update_labels(downloaded, total, start_time=None):
"""更新进度文字、百分比和速度"""
current_time = time()
if start_time is None:
start_time = current_time
elapsed_time = current_time - start_time
percent = round((downloaded / total) * 100, 2) if total else 0
speed = round((downloaded / elapsed_time) / 1024, 2) if elapsed_time > 0 else 0 # 计算下载速度(KB/s)
progress_text.set(get_text("downloading_process") + f"{percent}%")
speed_text.set(get_text("downloading_speed") + f"{speed} kiB/s") # 更新速度文本
download_start_time = time() # 记录下载开始时间
download_complete_event = threading.Event()
temp_file = NamedTemporaryFile(delete=False) # 创建临时文件,delete=False表示手动管理文件生命周期
def start_download_client(download_link_client, file_zip):
file_zip.close() # 关闭文件,准备写入
def download_and_signal():
download_file_with_progress(download_link_client, file_zip.name,
progress_callback=lambda d, t: [update_progress_bar(progress_bar, d, t),
update_labels(d, t, download_start_time)])
download_complete_event.set() # 下载完成后设置事件
thread = threading.Thread(target=download_and_signal)
thread.daemon = True
thread.start()
start_download_client(download_link, temp_file)
# 使用after方法定期检查下载是否完成
def check_download_completion():
if download_complete_event.is_set(): # 如果下载完成
progress_text.set(get_text("download_finished"))
speed_text.set(get_text("unzip_tip"))
pull_dir = initialize_settings()
try:
with ZipFile(temp_file.name) as zip_file:
for member in zip_file.namelist():
member_path = os.path.abspath(os.path.join(pull_dir, member))
if member.endswith("/"):
check_folder(member)
print("成功创建文件夹", str(member_path))
else:
content = zip_file.read(member)
with open(member_path, "wb", encoding="utf-8") as f:
f.write(content)
print("成功写入文件", str(member_path))
progress_text.set(get_text("unzip_finished"))
speed_text.set(get_text("close_tip"))
msgbox.showinfo(get_text("tip"), get_text("unzip_finished_tip"))
new_window.destroy()
except BadZipFile as e:
progress_text.set(get_text("error_unzip"))
speed_text.set(str(e))
print("导出文件出错,相关文件/目录:", str(member))
msgbox.showerror(get_text("error"), str(e))
return
except Exception as e:
progress_text.set(get_text("unknown_error"))
speed_text.set(str(e))
msgbox.showerror(get_text("error"), str(e))
return
finally:
# 确保临时文件在操作完成后被删除
os.remove(temp_file.name)
else: # 如果下载未完成,则稍后再次检查
download_window.after(100, check_download_completion)
# 初始化检查
download_window.after(0, check_download_completion)
# 创建一个新的顶级窗口作为下载进度窗口
download_window = tk.Toplevel()
download_window.geometry("205x177") # 设置下载提示窗口大小
download_window.title(get_text("download_window"))
# 设置窗口图标
download_window.iconbitmap("./Resources-Downloader/Pictures/Suya.ico") # 使用Suya作为窗口图标
# 创建并配置进度条
progress_bar = ttk.Progressbar(download_window, orient="horizontal", length=200, mode="determinate")
progress_bar.pack(pady=20)
start_download_and_close(download_window)
def direct_download_client(download_link):
# 这里编写客户端直接拉取文件的逻辑