forked from CJackHwang/AIstudioProxyAPI
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgui_launcher.py
More file actions
2212 lines (1961 loc) · 127 KB
/
gui_launcher.py
File metadata and controls
2212 lines (1961 loc) · 127 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
#!/usr/bin/env python3
import re
import tkinter as tk
from tkinter import ttk, messagebox, simpledialog, scrolledtext
import subprocess
import os
import sys
import platform
import threading
import time
import socket
import signal
from typing import List, Dict, Any, Optional, Tuple
from urllib.parse import urlparse
import shlex
import logging
import json
import requests # 新增导入
from dotenv import load_dotenv
# 加载 .env 文件
load_dotenv()
# --- Configuration & Globals ---
PYTHON_EXECUTABLE = sys.executable
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
LAUNCH_CAMOUFOX_PY = os.path.join(SCRIPT_DIR, "launch_camoufox.py")
SERVER_PY_FILENAME = "server.py" # For context
AUTH_PROFILES_DIR = os.path.join(SCRIPT_DIR, "auth_profiles") # 确保这些目录存在
ACTIVE_AUTH_DIR = os.path.join(AUTH_PROFILES_DIR, "active")
SAVED_AUTH_DIR = os.path.join(AUTH_PROFILES_DIR, "saved")
DEFAULT_FASTAPI_PORT = int(os.environ.get('DEFAULT_FASTAPI_PORT', '2048'))
DEFAULT_CAMOUFOX_PORT_GUI = int(os.environ.get('DEFAULT_CAMOUFOX_PORT', '9222')) # 与 launch_camoufox.py 中的 DEFAULT_CAMOUFOX_PORT 一致
managed_process_info: Dict[str, Any] = {
"popen": None,
"service_name_key": None,
"monitor_thread": None,
"stdout_thread": None,
"stderr_thread": None,
"output_area": None,
"fully_detached": False # 新增:标记进程是否完全独立
}
# 添加按钮防抖机制
button_debounce_info: Dict[str, float] = {}
def debounce_button(func_name: str, delay_seconds: float = 2.0):
"""
按钮防抖装饰器,防止在指定时间内重复执行同一函数
"""
def decorator(func):
def wrapper(*args, **kwargs):
import time
current_time = time.time()
last_call_time = button_debounce_info.get(func_name, 0)
if current_time - last_call_time < delay_seconds:
logger.info(f"按钮防抖:忽略 {func_name} 的重复调用")
return
button_debounce_info[func_name] = current_time
return func(*args, **kwargs)
return wrapper
return decorator
# 添加全局logger定义
logger = logging.getLogger("GUILauncher")
logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(console_handler)
os.makedirs(os.path.join(SCRIPT_DIR, "logs"), exist_ok=True)
file_handler = logging.FileHandler(os.path.join(SCRIPT_DIR, "logs", "gui_launcher.log"), encoding='utf-8')
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(file_handler)
# 在LANG_TEXTS声明之前定义长文本
service_closing_guide_message_zh = """由于服务在独立终端中运行,您可以通过以下方式关闭服务:
1. 使用端口管理功能:
- 点击"查询端口进程"按钮
- 选择相关的Python进程
- 点击"停止选中进程"
2. 手动终止进程:
- Windows: 使用任务管理器
- macOS: 使用活动监视器或terminal
- Linux: 使用kill命令
3. 直接关闭服务运行的终端窗口"""
service_closing_guide_message_en = """Since the service runs in an independent terminal, you can close it using these methods:
1. Using port management in GUI:
- Click "Query Port Processes" button
- Select the relevant Python process
- Click "Stop Selected Process"
2. Manually terminate process:
- Windows: Use Task Manager
- macOS: Use Activity Monitor or terminal
- Linux: Use kill command
3. Directly close the terminal window running the service"""
# --- Internationalization (i18n) ---
LANG_TEXTS = {
"title": {"zh": "AI Studio Proxy API Launcher GUI", "en": "AI Studio Proxy API Launcher GUI"},
"status_idle": {"zh": "空闲,请选择操作。", "en": "Idle. Select an action."},
"port_section_label": {"zh": "服务端口配置", "en": "Service Port Configuration"},
"port_input_description_lbl": {"zh": "提示: 启动时将使用下方指定的FastAPI服务端口和Camoufox调试端口。", "en": "Note: The FastAPI service port and Camoufox debug port specified below will be used for launch."},
"fastapi_port_label": {"zh": "FastAPI 服务端口:", "en": "FastAPI Port:"},
"camoufox_debug_port_label": {"zh": "Camoufox 调试端口:", "en": "Camoufox Debug Port:"},
"query_pids_btn": {"zh": "查询端口进程", "en": "Query Port Processes"},
"stop_selected_pid_btn": {"zh": "停止选中进程", "en": "Stop Selected Process"},
"pids_on_port_label": {"zh": "端口占用情况 (PID - 名称):", "en": "Processes on Port (PID - Name):"}, # Static version for initialization
"pids_on_port_label_dynamic": {"zh": "端口 {port} 占用情况 (PID - 名称):", "en": "Processes on Port {port} (PID - Name):"}, # Dynamic version
"no_pids_found": {"zh": "未找到占用该端口的进程。", "en": "No processes found on this port."},
"static_pid_list_title": {"zh": "启动所需端口占用情况 (PID - 名称)", "en": "Required Ports Usage (PID - Name)"}, # 新增标题
"launch_options_label": {"zh": "启动选项", "en": "Launch Options"},
"launch_options_note_revised": {"zh": "提示:有头/无头模式均会在新的独立终端窗口中启动服务。\n有头模式用于调试和认证。无头模式需预先认证。\n关闭此GUI不会停止已独立启动的服务。",
"en": "Tip: Headed/Headless modes will launch the service in a new independent terminal window.\nHeaded mode is for debug and auth. Headless mode requires pre-auth.\nClosing this GUI will NOT stop independently launched services."},
"launch_headed_interactive_btn": {"zh": "启动有头模式 (新终端)", "en": "Launch Headed Mode (New Terminal)"},
"launch_headless_btn": {"zh": "启动无头模式 (新终端)", "en": "Launch Headless Mode (New Terminal)"},
"launch_virtual_display_btn": {"zh": "启动虚拟显示模式 (Linux)", "en": "Launch Virtual Display (Linux)"},
"stop_gui_service_btn": {"zh": "停止当前GUI管理的服务", "en": "Stop Current GUI-Managed Service"},
"status_label": {"zh": "状态", "en": "Status"},
"output_label": {"zh": "输出日志", "en": "Output Log"},
"menu_language_fixed": {"zh": "Language", "en": "Language"},
"menu_lang_zh_option": {"zh": "中文 (Chinese)", "en": "中文 (Chinese)"},
"menu_lang_en_option": {"zh": "英文 (English)", "en": "英文 (English)"},
"confirm_quit_title": {"zh": "确认退出", "en": "Confirm Quit"},
"confirm_quit_message": {"zh": "服务可能仍在独立终端中运行。确认退出GUI吗?", "en": "Services may still be running in independent terminals. Confirm quit GUI?"},
"confirm_quit_message_independent": {"zh": "独立后台服务 '{service_name}' 可能仍在运行。直接退出GUI吗 (服务将继续运行)?", "en": "Independent background service '{service_name}' may still be running. Quit GUI (service will continue to run)?"},
"error_title": {"zh": "错误", "en": "Error"},
"info_title": {"zh": "信息", "en": "Info"},
"warning_title": {"zh": "警告", "en": "Warning"},
"service_already_running": {"zh": "服务 ({service_name}) 已在运行。", "en": "A service ({service_name}) is already running."},
"proxy_config_title": {"zh": "代理配置", "en": "Proxy Configuration"},
"proxy_config_message_generic": {"zh": "是否为此启动启用 HTTP/HTTPS 代理?", "en": "Enable HTTP/HTTPS proxy for this launch?"},
"proxy_address_title": {"zh": "代理地址", "en": "Proxy Address"},
"proxy_address_prompt": {"zh": "输入代理地址 (例如 http://host:port)\n默认: {default_proxy}", "en": "Enter proxy address (e.g., http://host:port)\nDefault: {default_proxy}"},
"proxy_configured_status": {"zh": "代理已配置: {proxy_addr}", "en": "Proxy configured: {proxy_addr}"},
"proxy_skip_status": {"zh": "用户跳过代理设置。", "en": "Proxy setup skipped by user."},
"script_not_found_error_msgbox": {"zh": "启动失败: 未找到 Python 执行文件或脚本。\n命令: {cmd}", "en": "Failed to start: Python executable or script not found.\nCommand: {cmd}"},
"startup_error_title": {"zh": "启动错误", "en": "Startup Error"},
"startup_script_not_found_msgbox": {"zh": "必需的脚本 '{script}' 在当前目录未找到。\n请将此GUI启动器与 launch_camoufox.py 和 server.py 放在同一目录。", "en": "Required script '{script}' not found in the current directory.\nPlace this GUI launcher in the same directory as launch_camoufox.py and server.py."},
"service_starting_status": {"zh": "{service_name} 启动中... PID: {pid}", "en": "{service_name} starting... PID: {pid}"},
"service_stopped_gracefully_status": {"zh": "{service_name} 已平稳停止。", "en": "{service_name} stopped gracefully."},
"service_stopped_exit_code_status": {"zh": "{service_name} 已停止。退出码: {code}", "en": "{service_name} stopped. Exit code: {code}"},
"service_stop_fail_status": {"zh": "{service_name} (PID: {pid}) 未能平稳终止。正在强制停止...", "en": "{service_name} (PID: {pid}) did not terminate gracefully. Forcing kill..."},
"service_killed_status": {"zh": "{service_name} (PID: {pid}) 已被强制停止。", "en": "{service_name} (PID: {pid}) killed."},
"error_stopping_service_msgbox": {"zh": "停止 {service_name} (PID: {pid}) 时出错: {e}", "en": "Error stopping {service_name} (PID: {pid}): {e}"},
"no_service_running_status": {"zh": "当前没有GUI管理的服务在运行。", "en": "No GUI-managed service is currently running."},
"stopping_initiated_status": {"zh": "{service_name} (PID: {pid}) 停止已启动。最终状态待定。", "en": "{service_name} (PID: {pid}) stopping initiated. Final status pending."},
"service_name_headed_interactive": {"zh": "有头交互服务", "en": "Headed Interactive Service"},
"service_name_headless": {"zh": "无头服务", "en": "Headless Service"}, # Key 修改
"service_name_virtual_display": {"zh": "虚拟显示无头服务", "en": "Virtual Display Headless Service"},
"status_headed_launch": {"zh": "有头模式:启动中,请关注新控制台的提示...", "en": "Headed Mode: Launching, check new console for prompts..."},
"status_headless_launch": {"zh": "无头服务:启动中...新的独立终端将打开。", "en": "Headless Service: Launching... A new independent terminal will open."},
"status_virtual_display_launch": {"zh": "虚拟显示模式启动中...", "en": "Virtual Display Mode launching..."},
"info_service_is_independent": {"zh": "当前服务为独立后台进程,关闭GUI不会停止它。请使用系统工具或端口管理手动停止此服务。", "en": "The current service is an independent background process. Closing the GUI will not stop it. Please manage this service manually using system tools or port management."},
"info_service_new_terminal": {"zh": "服务已在新的独立终端启动。关闭此GUI不会影响该服务。", "en": "Service has been launched in a new independent terminal. Closing this GUI will not affect the service."},
"warn_cannot_stop_independent_service": {"zh": "通过此GUI启动的服务在独立终端中运行,无法通过此按钮停止。请直接管理其终端或使用系统工具。", "en": "Services launched via this GUI run in independent terminals and cannot be stopped by this button. Please manage their terminals directly or use system tools."},
"enter_valid_port_warn": {"zh": "请输入有效的端口号 (1024-65535)。", "en": "Please enter a valid port number (1024-65535)."},
"pid_list_empty_for_stop_warn": {"zh": "进程列表为空或未选择进程。", "en": "PID list is empty or no process selected."},
"confirm_stop_pid_title": {"zh": "确认停止进程", "en": "Confirm Stop Process"},
"confirm_stop_pid_message": {"zh": "确定要尝试停止 PID {pid} ({name}) 吗?", "en": "Are you sure you want to attempt to stop PID {pid} ({name})?"},
"confirm_stop_pid_admin_title": {"zh": "以管理员权限停止进程", "en": "Stop Process with Admin Privileges"},
"confirm_stop_pid_admin_message": {"zh": "以普通权限停止 PID {pid} ({name}) 可能失败。是否尝试使用管理员权限停止?", "en": "Stopping PID {pid} ({name}) with normal privileges may fail. Try with admin privileges?"},
"admin_stop_success": {"zh": "已成功使用管理员权限停止 PID {pid}", "en": "Successfully stopped PID {pid} with admin privileges"},
"admin_stop_failure": {"zh": "使用管理员权限停止 PID {pid} 失败: {error}", "en": "Failed to stop PID {pid} with admin privileges: {error}"},
"status_error_starting": {"zh": "启动 {service_name} 失败。", "en": "Error starting {service_name}"},
"status_script_not_found": {"zh": "错误: 未找到 {service_name} 的可执行文件/脚本。", "en": "Error: Executable/script not found for {service_name}."},
"error_getting_process_name": {"zh": "获取 PID {pid} 的进程名失败。", "en": "Failed to get process name for PID {pid}."},
"pid_info_format": {"zh": "PID: {pid} (端口: {port}) - 名称: {name}", "en": "PID: {pid} (Port: {port}) - Name: {name}"},
"status_stopping_service": {"zh": "正在停止 {service_name} (PID: {pid})...", "en": "Stopping {service_name} (PID: {pid})..."},
"error_title_invalid_selection": {"zh": "无效的选择格式: {selection}", "en": "Invalid selection format: {selection}"},
"error_parsing_pid": {"zh": "无法从 '{selection}' 解析PID。", "en": "Could not parse PID from '{selection}'."},
"terminate_request_sent": {"zh": "终止请求已发送。", "en": "Termination request sent."},
"terminate_attempt_failed": {"zh": "尝试终止 PID {pid} ({name}) 可能失败。", "en": "Attempt to terminate PID {pid} ({name}) may have failed."},
"unknown_process_name_placeholder": {"zh": "未知进程名", "en": "Unknown Process Name"},
"kill_custom_pid_label": {"zh": "或输入PID终止:", "en": "Or Enter PID to Kill:"},
"kill_custom_pid_btn": {"zh": "终止指定PID", "en": "Kill Specified PID"},
"pid_input_empty_warn": {"zh": "请输入要终止的PID。", "en": "Please enter a PID to kill."},
"pid_input_invalid_warn": {"zh": "输入的PID无效,请输入纯数字。", "en": "Invalid PID entered. Please enter numbers only."},
"confirm_kill_custom_pid_title": {"zh": "确认终止PID", "en": "Confirm Kill PID"},
"status_sending_sigint": {"zh": "正在向 {service_name} (PID: {pid}) 发送 SIGINT...", "en": "Sending SIGINT to {service_name} (PID: {pid})..."},
"status_waiting_after_sigint": {"zh": "{service_name} (PID: {pid}):SIGINT 已发送,等待 {timeout} 秒优雅退出...", "en": "{service_name} (PID: {pid}): SIGINT sent, waiting {timeout}s for graceful exit..."},
"status_sigint_effective": {"zh": "{service_name} (PID: {pid}) 已响应 SIGINT 并停止。", "en": "{service_name} (PID: {pid}) responded to SIGINT and stopped."},
"status_sending_sigterm": {"zh": "{service_name} (PID: {pid}):未在规定时间内响应 SIGINT,正在发送 SIGTERM...", "en": "{service_name} (PID: {pid}): Did not respond to SIGINT in time, sending SIGTERM..."},
"status_waiting_after_sigterm": {"zh": "{service_name} (PID: {pid}):SIGTERM 已发送,等待 {timeout} 秒优雅退出...", "en": "{service_name} (PID: {pid}): SIGTERM sent, waiting {timeout}s for graceful exit..."},
"status_sigterm_effective": {"zh": "{service_name} (PID: {pid}) 已响应 SIGTERM 并停止。", "en": "{service_name} (PID: {pid}) responded to SIGTERM and stopped."},
"status_forcing_kill": {"zh": "{service_name} (PID: {pid}):未在规定时间内响应 SIGTERM,正在强制终止 (SIGKILL)...", "en": "{service_name} (PID: {pid}): Did not respond to SIGTERM in time, forcing kill (SIGKILL)..."},
"enable_stream_proxy_label": {"zh": "启用流式代理服务", "en": "Enable Stream Proxy Service"},
"stream_proxy_port_label": {"zh": "流式代理端口:", "en": "Stream Proxy Port:"},
"enable_helper_label": {"zh": "启用外部Helper服务", "en": "Enable External Helper Service"},
"helper_endpoint_label": {"zh": "Helper端点URL:", "en": "Helper Endpoint URL:"},
"auth_manager_title": {"zh": "认证文件管理", "en": "Authentication File Manager"},
"saved_auth_files_label": {"zh": "已保存的认证文件:", "en": "Saved Authentication Files:"},
"no_file_selected": {"zh": "请选择一个认证文件", "en": "Please select an authentication file"},
"auth_file_activated": {"zh": "认证文件 '{file}' 已成功激活", "en": "Authentication file '{file}' has been activated successfully"},
"error_activating_file": {"zh": "激活文件 '{file}' 时出错: {error}", "en": "Error activating file '{file}': {error}"},
"activate_selected_btn": {"zh": "激活选中的文件", "en": "Activate Selected File"},
"cancel_btn": {"zh": "取消", "en": "Cancel"},
"auth_files_management": {"zh": "认证文件管理", "en": "Auth Files Management"},
"manage_auth_files_btn": {"zh": "管理认证文件", "en": "Manage Auth Files"},
"no_saved_auth_files": {"zh": "保存目录中没有认证文件", "en": "No authentication files in saved directory"},
"auth_dirs_missing": {"zh": "认证目录不存在,请确保目录结构正确", "en": "Authentication directories missing, please ensure correct directory structure"},
"confirm_kill_port_title": {"zh": "确认清理端口", "en": "Confirm Port Cleanup"},
"confirm_kill_port_message": {"zh": "端口 {port} 被以下PID占用: {pids}。是否尝试终止这些进程?", "en": "Port {port} is in use by PID(s): {pids}. Try to terminate them?"},
"port_cleared_success": {"zh": "端口 {port} 已成功清理", "en": "Port {port} has been cleared successfully"},
"port_still_in_use": {"zh": "端口 {port} 仍被占用,请手动处理", "en": "Port {port} is still in use, please handle manually"},
"port_in_use_no_pids": {"zh": "端口 {port} 被占用,但无法识别进程", "en": "Port {port} is in use, but processes cannot be identified"},
"error_removing_file": {"zh": "删除文件 '{file}' 时出错: {error}", "en": "Error removing file '{file}': {error}"},
"stream_port_out_of_range": {"zh": "流式代理端口必须为0(禁用)或1024-65535之间的值", "en": "Stream proxy port must be 0 (disabled) or a value between 1024-65535"},
"port_auto_check": {"zh": "启动前自动检查端口", "en": "Auto-check port before launch"},
"auto_port_check_enabled": {"zh": "已启用端口自动检查", "en": "Port auto-check enabled"},
"port_check_running": {"zh": "正在检查端口 {port}...", "en": "Checking port {port}..."},
"port_name_fastapi": {"zh": "FastAPI服务", "en": "FastAPI Service"},
"port_name_camoufox_debug": {"zh": "Camoufox调试", "en": "Camoufox Debug"},
"port_name_stream_proxy": {"zh": "流式代理", "en": "Stream Proxy"},
"checking_port_with_name": {"zh": "正在检查{port_name}端口 {port}...", "en": "Checking {port_name} port {port}..."},
"port_check_all_completed": {"zh": "所有端口检查完成", "en": "All port checks completed"},
"port_check_failed": {"zh": "{port_name}端口 {port} 检查失败,启动已中止", "en": "{port_name} port {port} check failed, launch aborted"},
"port_name_helper_service": {"zh": "Helper服务", "en": "Helper Service"},
"confirm_kill_multiple_ports_title": {"zh": "确认清理多个端口", "en": "Confirm Multiple Ports Cleanup"},
"confirm_kill_multiple_ports_message": {"zh": "以下端口被占用:\n{occupied_ports_details}\n是否尝试终止这些进程?", "en": "The following ports are in use:\n{occupied_ports_details}\nAttempt to terminate these processes?"},
"all_ports_cleared_success": {"zh": "所有选定端口已成功清理。", "en": "All selected ports have been cleared successfully."},
"some_ports_still_in_use": {"zh": "部分端口在清理后仍被占用,请手动处理。启动已中止。", "en": "Some ports are still in use after cleanup attempt. Please handle manually. Launch aborted."},
"port_check_user_declined_cleanup": {"zh": "用户选择不清理占用的端口,启动已中止。", "en": "User chose not to clean up occupied ports. Launch aborted."},
"reset_button": {"zh": "重置为默认设置", "en": "Reset to Defaults"},
"confirm_reset_title": {"zh": "确认重置", "en": "Confirm Reset"},
"confirm_reset_message": {"zh": "确定要重置所有设置为默认值吗?", "en": "Are you sure you want to reset all settings to default values?"},
"reset_success": {"zh": "已重置为默认设置", "en": "Reset to default settings successfully"},
"proxy_config_last_used": {"zh": "使用上次的代理: {proxy}", "en": "Using last proxy: {proxy}"},
"proxy_config_other": {"zh": "使用其他代理地址", "en": "Use a different proxy address"},
"service_closing_guide": {"zh": "关闭服务指南", "en": "Service Closing Guide"},
"service_closing_guide_btn": {"zh": "如何关闭服务?", "en": "How to Close Service?"},
"service_closing_guide_message": {"zh": service_closing_guide_message_zh, "en": service_closing_guide_message_en},
"enable_proxy_label": {"zh": "启用浏览器代理", "en": "Enable Browser Proxy"},
"proxy_address_label": {"zh": "代理地址:", "en": "Proxy Address:"},
"current_auth_file_display_label": {"zh": "当前认证: ", "en": "Current Auth: "},
"current_auth_file_none": {"zh": "无", "en": "None"},
"current_auth_file_selected_format": {"zh": "{file}", "en": "{file}"},
"test_proxy_btn": {"zh": "测试", "en": "Test"},
"proxy_section_label": {"zh": "代理配置", "en": "Proxy Configuration"},
"proxy_test_url_default": "http://httpbin.org/get", # 默认测试URL
"proxy_test_url_backup": "http://www.google.com", # 备用测试URL
"proxy_not_enabled_warn": {"zh": "代理未启用或地址为空,请先配置。", "en": "Proxy not enabled or address is empty. Please configure first."},
"proxy_test_success": {"zh": "代理连接成功 ({url})", "en": "Proxy connection successful ({url})"},
"proxy_test_failure": {"zh": "代理连接失败 ({url}):\n{error}", "en": "Proxy connection failed ({url}):\n{error}"},
"proxy_testing_status": {"zh": "正在测试代理 {proxy_addr}...", "en": "Testing proxy {proxy_addr}..."},
"proxy_test_success_status": {"zh": "代理测试成功 ({url})", "en": "Proxy test successful ({url})"},
"proxy_test_failure_status": {"zh": "代理测试失败: {error}", "en": "Proxy test failed: {error}"},
"proxy_test_retrying": {"zh": "代理测试失败,正在重试 ({attempt}/{max_attempts})...", "en": "Proxy test failed, retrying ({attempt}/{max_attempts})..."},
"proxy_test_backup_url": {"zh": "主测试URL失败,尝试备用URL...", "en": "Primary test URL failed, trying backup URL..."},
"proxy_test_all_failed": {"zh": "所有代理测试尝试均失败", "en": "All proxy test attempts failed"},
"querying_ports_status": {"zh": "正在查询端口: {ports_desc}...", "en": "Querying ports: {ports_desc}..."},
"port_query_result_format": {"zh": "[{port_type} - {port_num}] {pid_info}", "en": "[{port_type} - {port_num}] {pid_info}"},
"port_not_in_use_format": {"zh": "[{port_type} - {port_num}] 未被占用", "en": "[{port_type} - {port_num}] Not in use"},
"pids_on_multiple_ports_label": {"zh": "多端口占用情况:", "en": "Multi-Port Usage:"},
"launch_llm_service_btn": {"zh": "启动本地LLM模拟服务", "en": "Launch Local LLM Mock Service"},
"stop_llm_service_btn": {"zh": "停止本地LLM模拟服务", "en": "Stop Local LLM Mock Service"},
"llm_service_name_key": {"zh": "本地LLM模拟服务", "en": "Local LLM Mock Service"},
"status_llm_starting": {"zh": "本地LLM模拟服务启动中 (PID: {pid})...", "en": "Local LLM Mock Service starting (PID: {pid})..."},
"status_llm_stopped": {"zh": "本地LLM模拟服务已停止。", "en": "Local LLM Mock Service stopped."},
"status_llm_stop_error": {"zh": "停止本地LLM模拟服务时出错。", "en": "Error stopping Local LLM Mock Service."},
"status_llm_already_running": {"zh": "本地LLM模拟服务已在运行 (PID: {pid})。", "en": "Local LLM Mock Service is already running (PID: {pid})."},
"status_llm_not_running": {"zh": "本地LLM模拟服务未在运行。", "en": "Local LLM Mock Service is not running."},
"status_llm_backend_check": {"zh": "正在检查LLM后端服务 ...", "en": "Checking LLM backend service ..."},
"status_llm_backend_ok_starting": {"zh": "LLM后端服务 (localhost:{port}) 正常,正在启动模拟服务...", "en": "LLM backend service (localhost:{port}) OK, starting mock service..."},
"status_llm_backend_fail": {"zh": "LLM后端服务 (localhost:{port}) 未响应,无法启动模拟服务。", "en": "LLM backend service (localhost:{port}) not responding, cannot start mock service."},
"confirm_stop_llm_title": {"zh": "确认停止LLM服务", "en": "Confirm Stop LLM Service"},
"confirm_stop_llm_message": {"zh": "确定要停止本地LLM模拟服务吗?", "en": "Are you sure you want to stop the Local LLM Mock Service?"}
}
# 删除重复的定义
current_language = 'zh'
root_widget: Optional[tk.Tk] = None
process_status_text_var: Optional[tk.StringVar] = None
port_entry_var: Optional[tk.StringVar] = None # 将用于 FastAPI 端口
camoufox_debug_port_var: Optional[tk.StringVar] = None
pid_listbox_widget: Optional[tk.Listbox] = None
custom_pid_entry_var: Optional[tk.StringVar] = None
widgets_to_translate: List[Dict[str, Any]] = []
proxy_address_var: Optional[tk.StringVar] = None # 添加变量存储代理地址
proxy_enabled_var: Optional[tk.BooleanVar] = None # 添加变量标记代理是否启用
active_auth_file_display_var: Optional[tk.StringVar] = None # 用于显示当前认证文件
LLM_PY_FILENAME = "llm.py"
llm_service_process_info: Dict[str, Any] = {
"popen": None,
"monitor_thread": None,
"stdout_thread": None,
"stderr_thread": None,
"service_name_key": "llm_service_name_key" # Corresponds to a LANG_TEXTS key
}
# 将所有辅助函数定义移到 build_gui 之前
def get_text(key: str, **kwargs) -> str:
try:
text_template = LANG_TEXTS[key][current_language]
except KeyError:
text_template = LANG_TEXTS[key].get('en', f"<{key}_MISSING_{current_language}>")
return text_template.format(**kwargs) if kwargs else text_template
def update_status_bar(message_key: str, **kwargs):
message = get_text(message_key, **kwargs)
def _perform_gui_updates():
# Update the status bar label's text variable
if process_status_text_var:
process_status_text_var.set(message)
# Update the main log text area (if it exists)
if managed_process_info.get("output_area"):
# The 'message' variable is captured from the outer scope (closure)
if root_widget: # Ensure root_widget is still valid
output_area_widget = managed_process_info["output_area"]
output_area_widget.config(state=tk.NORMAL)
output_area_widget.insert(tk.END, f"[STATUS] {message}\n")
output_area_widget.see(tk.END)
output_area_widget.config(state=tk.DISABLED)
if root_widget:
root_widget.after_idle(_perform_gui_updates)
def is_port_in_use(port: int) -> bool:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(("0.0.0.0", port))
return False
except OSError: return True
except Exception: return True
def get_process_name_by_pid(pid: int) -> str:
system = platform.system()
name = get_text("unknown_process_name_placeholder")
cmd_args = []
try:
if system == "Windows":
cmd_args = ["tasklist", "/NH", "/FO", "CSV", "/FI", f"PID eq {pid}"]
process = subprocess.run(cmd_args, capture_output=True, text=True, check=True, timeout=3, creationflags=subprocess.CREATE_NO_WINDOW)
if process.stdout.strip():
parts = process.stdout.strip().split('","')
if len(parts) > 0: name = parts[0].strip('"')
elif system == "Linux":
cmd_args = ["ps", "-p", str(pid), "-o", "comm="]
process = subprocess.run(cmd_args, capture_output=True, text=True, check=True, timeout=3)
if process.stdout.strip(): name = process.stdout.strip()
elif system == "Darwin":
cmd_args = ["ps", "-p", str(pid), "-o", "comm="]
process = subprocess.run(cmd_args, capture_output=True, text=True, check=True, timeout=3)
raw_path = process.stdout.strip() if process.stdout.strip() else ""
cmd_args = ["ps", "-p", str(pid), "-o", "command="]
process = subprocess.run(cmd_args, capture_output=True, text=True, check=True, timeout=3)
if raw_path:
base_name = os.path.basename(raw_path)
name = f"{base_name} ({raw_path})"
except (subprocess.CalledProcessError, subprocess.TimeoutExpired, FileNotFoundError):
pass
except Exception:
pass
return name
def find_processes_on_port(port: int) -> List[Dict[str, Any]]:
process_details = []
pids_only: List[int] = []
system = platform.system()
command_pid = ""
try:
if system == "Linux" or system == "Darwin":
command_pid = f"lsof -ti tcp:{port} -sTCP:LISTEN"
process = subprocess.Popen(command_pid, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, universal_newlines=True, close_fds=True)
stdout_pid, _ = process.communicate(timeout=5)
if process.returncode == 0 and stdout_pid:
pids_only = [int(p) for p in stdout_pid.strip().splitlines() if p.isdigit()]
elif system == "Windows":
command_pid = 'netstat -ano -p TCP'
process = subprocess.Popen(command_pid, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, universal_newlines=True, creationflags=subprocess.CREATE_NO_WINDOW)
stdout_pid, _ = process.communicate(timeout=10)
if process.returncode == 0 and stdout_pid:
for line in stdout_pid.strip().splitlines():
parts = line.split()
if len(parts) >= 5 and parts[0].upper() == 'TCP':
if parts[3].upper() != 'LISTENING':
continue
local_address_full = parts[1]
try:
last_colon_idx = local_address_full.rfind(':')
if last_colon_idx == -1:
continue
extracted_port_str = local_address_full[last_colon_idx+1:]
if extracted_port_str.isdigit() and int(extracted_port_str) == port:
pid_str = parts[4]
if pid_str.isdigit():
pids_only.append(int(pid_str))
except (ValueError, IndexError):
continue
pids_only = list(set(pids_only))
except Exception:
pass
for pid_val in pids_only:
name = get_process_name_by_pid(pid_val)
process_details.append({"pid": pid_val, "name": name})
return process_details
def kill_process_pid(pid: int) -> bool:
system = platform.system()
success = False
logger.info(f"Attempting to kill PID {pid} with normal privileges on {system}")
try:
if system == "Linux" or system == "Darwin":
# 1. Attempt SIGTERM (best effort)
logger.debug(f"Sending SIGTERM to PID {pid}")
subprocess.run(["kill", "-TERM", str(pid)], capture_output=True, text=True, timeout=3) # check=False
time.sleep(0.5)
# 2. Check if process is gone (or if we lack permission to check)
try:
logger.debug(f"Checking PID {pid} with kill -0 after SIGTERM attempt")
# This will raise CalledProcessError if process is gone OR user lacks permission for kill -0
subprocess.run(["kill", "-0", str(pid)], check=True, capture_output=True, text=True, timeout=1)
# If kill -0 succeeded, process is still alive and we have permission to signal it.
# 3. Attempt SIGKILL
logger.info(f"PID {pid} still alive after SIGTERM attempt (kill -0 succeeded). Sending SIGKILL.")
subprocess.run(["kill", "-KILL", str(pid)], check=True, capture_output=True, text=True, timeout=3) # Raises on perm error for SIGKILL
# 4. Verify with kill -0 again that it's gone
time.sleep(0.1)
logger.debug(f"Verifying PID {pid} with kill -0 after SIGKILL attempt")
try:
subprocess.run(["kill", "-0", str(pid)], check=True, capture_output=True, text=True, timeout=1)
# If kill -0 still succeeds, SIGKILL failed to terminate it or it's unkillable
logger.warning(f"PID {pid} still alive even after SIGKILL was sent and did not error.")
success = False
except subprocess.CalledProcessError as e_final_check:
# kill -0 failed, means process is gone. Check stderr for "No such process".
if e_final_check.stderr and "no such process" in e_final_check.stderr.lower():
logger.info(f"PID {pid} successfully terminated with SIGKILL (confirmed by final kill -0).")
success = True
else:
# kill -0 failed for other reason (e.g. perms, though unlikely if SIGKILL 'succeeded')
logger.warning(f"Final kill -0 check for PID {pid} failed unexpectedly. Stderr: {e_final_check.stderr}")
success = False # Unsure, so treat as failure for normal kill
except subprocess.CalledProcessError as e:
# This block is reached if initial `kill -0` fails, or `kill -KILL` fails.
# `e` is the error from the *first* command that failed with check=True in the try block.
if e.stderr and "no such process" in e.stderr.lower():
logger.info(f"Process {pid} is gone (kill -0 or kill -KILL reported 'No such process'). SIGTERM might have worked or it was already gone.")
success = True
else:
# Failure was likely due to permissions (e.g., "Operation not permitted") or other reasons.
# This means normal kill attempt failed.
logger.warning(f"Normal kill attempt for PID {pid} failed or encountered permission issue. Stderr from failing cmd: {e.stderr}")
success = False
elif system == "Windows":
logger.debug(f"Using taskkill for PID {pid} on Windows.")
result = subprocess.run(["taskkill", "/PID", str(pid), "/T", "/F"], capture_output=True, text=True, check=False, timeout=5, creationflags=subprocess.CREATE_NO_WINDOW)
if result.returncode == 0:
logger.info(f"Taskkill for PID {pid} succeeded (rc=0).")
success = True
else:
# Check if process was not found
output_lower = (result.stdout + result.stderr).lower()
if "pid" in output_lower and ("not found" in output_lower or "no running instance" in output_lower or ("could not be terminated" in output_lower and "reason: there is no running instance" in output_lower)) :
logger.info(f"Taskkill for PID {pid} reported process not found or already terminated.")
success = True
else:
logger.warning(f"Taskkill for PID {pid} failed. RC: {result.returncode}. Output: {output_lower}")
success = False
except Exception as e_outer: # Catch any other unexpected exceptions
logger.error(f"Outer exception in kill_process_pid for PID {pid}: {e_outer}", exc_info=True)
success = False
logger.info(f"kill_process_pid for PID {pid} final result: {success}")
return success
def enhanced_port_check(port, port_name_key=""):
port_display_name = get_text(f"port_name_{port_name_key}") if port_name_key else ""
update_status_bar("checking_port_with_name", port_name=port_display_name, port=port)
if is_port_in_use(port):
pids_data = find_processes_on_port(port)
if pids_data:
pids_info_str_list = []
for proc_info in pids_data:
pids_info_str_list.append(f"{proc_info['pid']} ({proc_info['name']})")
return {"port": port, "name_key": port_name_key, "pids_data": pids_data, "pids_str": ", ".join(pids_info_str_list)}
else:
return {"port": port, "name_key": port_name_key, "pids_data": [], "pids_str": get_text("unknown_process_name_placeholder")}
return None
def check_all_required_ports(ports_to_check: List[Tuple[int, str]]) -> bool:
occupied_ports_info = []
for port, port_name_key in ports_to_check:
result = enhanced_port_check(port, port_name_key)
if result:
occupied_ports_info.append(result)
if not occupied_ports_info:
update_status_bar("port_check_all_completed")
return True
occupied_ports_details_for_msg = []
for info in occupied_ports_info:
port_display_name = get_text(f"port_name_{info['name_key']}") if info['name_key'] else ""
occupied_ports_details_for_msg.append(f" - {port_display_name} (端口 {info['port']}): 被 PID(s) {info['pids_str']} 占用")
details_str = "\n".join(occupied_ports_details_for_msg)
if messagebox.askyesno(
get_text("confirm_kill_multiple_ports_title"),
get_text("confirm_kill_multiple_ports_message", occupied_ports_details=details_str),
parent=root_widget
):
pids_processed_this_cycle = set() # Tracks PIDs for which kill attempts (normal or admin) have been made in this call
for info in occupied_ports_info:
if info['pids_data']:
for p_data in info['pids_data']:
pid = p_data['pid']
name = p_data['name']
if pid in pids_processed_this_cycle:
continue # Avoid reprocessing a PID if it appeared for multiple ports
logger.info(f"Port Check Cleanup: Attempting normal kill for PID {pid} ({name}) on port {info['port']}")
normal_kill_ok = kill_process_pid(pid)
if normal_kill_ok:
logger.info(f"Port Check Cleanup: Normal kill succeeded for PID {pid} ({name})")
pids_processed_this_cycle.add(pid)
else:
logger.warning(f"Port Check Cleanup: Normal kill FAILED for PID {pid} ({name}). Prompting for admin kill.")
if messagebox.askyesno(
get_text("confirm_stop_pid_admin_title"),
get_text("confirm_stop_pid_admin_message", pid=pid, name=name),
parent=root_widget
):
logger.info(f"Port Check Cleanup: User approved admin kill for PID {pid} ({name}). Attempting.")
admin_kill_initiated = kill_process_pid_admin(pid) # Optimistic for macOS
if admin_kill_initiated:
logger.info(f"Port Check Cleanup: Admin kill attempt for PID {pid} ({name}) initiated (result optimistic: {admin_kill_initiated}).")
# We still rely on the final port check, so no success message here.
else:
logger.warning(f"Port Check Cleanup: Admin kill attempt for PID {pid} ({name}) failed to initiate or was denied by user at OS level.")
else:
logger.info(f"Port Check Cleanup: User declined admin kill for PID {pid} ({name}).")
pids_processed_this_cycle.add(pid) # Mark as processed even if admin declined/failed, to avoid re-prompting in this cycle
logger.info("Port Check Cleanup: Waiting for 2 seconds for processes to terminate...")
time.sleep(2)
still_occupied_after_cleanup = False
for info in occupied_ports_info: # Re-check all originally occupied ports
if is_port_in_use(info['port']):
port_display_name = get_text(f"port_name_{info['name_key']}") if info['name_key'] else str(info['port'])
logger.warning(f"Port Check Cleanup: Port {port_display_name} ({info['port']}) is still in use after cleanup attempts.")
still_occupied_after_cleanup = True
break
if not still_occupied_after_cleanup:
messagebox.showinfo(get_text("info_title"), get_text("all_ports_cleared_success"), parent=root_widget)
update_status_bar("port_check_all_completed")
return True
else:
messagebox.showwarning(get_text("warning_title"), get_text("some_ports_still_in_use"), parent=root_widget)
return False
else:
update_status_bar("port_check_user_declined_cleanup")
return False
def _update_active_auth_display():
"""更新GUI中显示的当前活动认证文件"""
if not active_auth_file_display_var or not root_widget:
return
active_files = [f for f in os.listdir(ACTIVE_AUTH_DIR) if f.lower().endswith('.json')]
if active_files:
# 通常 active 目录只有一个文件,但以防万一,取第一个
active_file_name = sorted(active_files)[0]
active_auth_file_display_var.set(get_text("current_auth_file_selected_format", file=active_file_name))
else:
active_auth_file_display_var.set(get_text("current_auth_file_none"))
def manage_auth_files_gui():
if not os.path.exists(AUTH_PROFILES_DIR): # 检查根目录
messagebox.showerror(get_text("error_title"), get_text("auth_dirs_missing"), parent=root_widget)
return
# 确保 active 和 saved 目录存在,如果不存在则创建
os.makedirs(ACTIVE_AUTH_DIR, exist_ok=True)
os.makedirs(SAVED_AUTH_DIR, exist_ok=True)
all_auth_files = set()
# 扫描 auth_profiles/ 根目录
if os.path.exists(AUTH_PROFILES_DIR):
for f in os.listdir(AUTH_PROFILES_DIR):
if f.lower().endswith('.json') and os.path.isfile(os.path.join(AUTH_PROFILES_DIR, f)):
all_auth_files.add(f)
# 扫描 auth_profiles/active/ 子目录
if os.path.exists(ACTIVE_AUTH_DIR):
for f in os.listdir(ACTIVE_AUTH_DIR):
if f.lower().endswith('.json') and os.path.isfile(os.path.join(ACTIVE_AUTH_DIR, f)):
all_auth_files.add(f) # 通常 active 目录的文件也应该在 saved 或根目录有副本
# 扫描 auth_profiles/saved/ 子目录
if os.path.exists(SAVED_AUTH_DIR):
for f in os.listdir(SAVED_AUTH_DIR):
if f.lower().endswith('.json') and os.path.isfile(os.path.join(SAVED_AUTH_DIR, f)):
all_auth_files.add(f)
sorted_auth_files = sorted(list(all_auth_files))
if not sorted_auth_files:
messagebox.showinfo(get_text("info_title"), get_text("no_saved_auth_files"), parent=root_widget) # 可以复用这个文本
return
auth_window = tk.Toplevel(root_widget)
auth_window.title(get_text("auth_manager_title"))
auth_window.geometry("400x300")
auth_window.resizable(True, True)
ttk.Label(auth_window, text=get_text("saved_auth_files_label")).pack(pady=5)
files_frame = ttk.Frame(auth_window)
files_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
files_listbox = tk.Listbox(files_frame, selectmode=tk.SINGLE)
files_listbox.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
files_scrollbar = ttk.Scrollbar(files_frame, command=files_listbox.yview)
files_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
files_listbox.config(yscrollcommand=files_scrollbar.set)
for file_name in sorted_auth_files:
files_listbox.insert(tk.END, file_name)
def activate_selected_file():
if not files_listbox.curselection():
messagebox.showwarning(get_text("warning_title"), get_text("no_file_selected"), parent=auth_window)
return
selected_file_name = files_listbox.get(files_listbox.curselection()[0])
# 确定源文件路径,优先从 saved, 然后是根目录
source_path = None
potential_saved_path = os.path.join(SAVED_AUTH_DIR, selected_file_name)
potential_root_path = os.path.join(AUTH_PROFILES_DIR, selected_file_name)
if os.path.exists(potential_saved_path):
source_path = potential_saved_path
elif os.path.exists(potential_root_path):
source_path = potential_root_path
else:
# 如果文件在 active 目录但不在 saved 或根目录,也允许激活(理论上不应发生,但作为容错)
potential_active_path = os.path.join(ACTIVE_AUTH_DIR, selected_file_name)
if os.path.exists(potential_active_path):
source_path = potential_active_path
else:
messagebox.showerror(get_text("error_title"), f"源文件 {selected_file_name} 未找到!", parent=auth_window)
return
# 清空 active 目录
for existing_file in os.listdir(ACTIVE_AUTH_DIR):
if existing_file.lower().endswith('.json'):
try:
os.remove(os.path.join(ACTIVE_AUTH_DIR, existing_file))
except OSError as e:
messagebox.showerror(get_text("error_title"), get_text("error_removing_file", file=existing_file, error=str(e)), parent=auth_window)
return
try:
import shutil
dest_path = os.path.join(ACTIVE_AUTH_DIR, selected_file_name)
shutil.copy2(source_path, dest_path) # 将选中的文件复制到 active 目录
messagebox.showinfo(get_text("info_title"), get_text("auth_file_activated", file=selected_file_name), parent=auth_window)
_update_active_auth_display() # 更新主界面显示
auth_window.destroy()
except Exception as e:
messagebox.showerror(get_text("error_title"), get_text("error_activating_file", file=selected_file_name, error=str(e)), parent=auth_window)
_update_active_auth_display() # 即使失败也尝试更新显示
buttons_frame = ttk.Frame(auth_window)
buttons_frame.pack(fill=tk.X, padx=10, pady=10)
ttk.Button(buttons_frame, text=get_text("activate_selected_btn"), command=activate_selected_file).pack(side=tk.LEFT, padx=5)
ttk.Button(buttons_frame, text=get_text("cancel_btn"), command=auth_window.destroy).pack(side=tk.RIGHT, padx=5)
def get_active_auth_json_path_for_launch() -> Optional[str]:
"""获取用于启动命令的 --active-auth-json 参数值"""
active_files = [f for f in os.listdir(ACTIVE_AUTH_DIR) if f.lower().endswith('.json') and os.path.isfile(os.path.join(ACTIVE_AUTH_DIR, f))]
if active_files:
# 如果 active 目录有文件,总是使用它(按名称排序的第一个)
return os.path.join(ACTIVE_AUTH_DIR, sorted(active_files)[0])
return None
def build_launch_command(mode, fastapi_port, camoufox_debug_port, stream_port_enabled, stream_port, helper_enabled, helper_endpoint):
cmd = [PYTHON_EXECUTABLE, LAUNCH_CAMOUFOX_PY, f"--{mode}", "--server-port", str(fastapi_port), "--camoufox-debug-port", str(camoufox_debug_port)]
active_auth_path = get_active_auth_json_path_for_launch()
if active_auth_path:
cmd.extend(["--active-auth-json", active_auth_path])
logger.info(f"将使用认证文件: {active_auth_path}")
else:
logger.info("未找到活动的认证文件,不传递 --active-auth-json 参数。")
if stream_port_enabled:
cmd.extend(["--stream-port", str(stream_port)])
else:
cmd.extend(["--stream-port", "0"]) # 显式传递0表示禁用
if helper_enabled and helper_endpoint:
cmd.extend(["--helper", helper_endpoint])
else:
cmd.extend(["--helper", ""]) # 显式传递空字符串表示禁用
# 修复:添加统一代理配置参数传递
# 使用 --internal-camoufox-proxy 参数确保最高优先级,而不是仅依赖环境变量
if proxy_enabled_var.get():
proxy_addr = proxy_address_var.get().strip()
if proxy_addr:
cmd.extend(["--internal-camoufox-proxy", proxy_addr])
logger.info(f"将使用GUI配置的代理: {proxy_addr}")
else:
cmd.extend(["--internal-camoufox-proxy", ""])
logger.info("GUI代理已启用但地址为空,明确禁用代理")
else:
cmd.extend(["--internal-camoufox-proxy", ""])
logger.info("GUI代理未启用,明确禁用代理")
return cmd
# --- GUI构建与主逻辑区段的函数定义 ---
# (这些函数调用上面定义的辅助函数,所以它们的定义顺序很重要)
def enqueue_stream_output(stream, stream_name_prefix):
try:
for line_bytes in iter(stream.readline, b''):
if not line_bytes: break
line = line_bytes.decode(sys.stdout.encoding or 'utf-8', errors='replace')
if managed_process_info.get("output_area") and root_widget:
def _update_stream_output(line_to_insert):
current_line = line_to_insert
if managed_process_info.get("output_area"):
managed_process_info["output_area"].config(state=tk.NORMAL)
managed_process_info["output_area"].insert(tk.END, current_line)
managed_process_info["output_area"].see(tk.END)
managed_process_info["output_area"].config(state=tk.DISABLED)
root_widget.after_idle(_update_stream_output, f"[{stream_name_prefix}] {line}")
else: print(f"[{stream_name_prefix}] {line.strip()}", flush=True)
except ValueError: pass
except Exception: pass
finally:
if hasattr(stream, 'close') and not stream.closed: stream.close()
def is_service_running():
return managed_process_info.get("popen") and \
managed_process_info["popen"].poll() is None and \
not managed_process_info.get("fully_detached", False)
def is_any_service_known():
return managed_process_info.get("popen") is not None
def monitor_process_thread_target():
popen = managed_process_info.get("popen")
service_name_key = managed_process_info.get("service_name_key")
is_detached = managed_process_info.get("fully_detached", False)
if not popen or not service_name_key: return
stdout_thread = None; stderr_thread = None
if popen.stdout:
stdout_thread = threading.Thread(target=enqueue_stream_output, args=(popen.stdout, "stdout"), daemon=True)
managed_process_info["stdout_thread"] = stdout_thread
stdout_thread.start()
if popen.stderr:
stderr_thread = threading.Thread(target=enqueue_stream_output, args=(popen.stderr, "stderr"), daemon=True)
managed_process_info["stderr_thread"] = stderr_thread
stderr_thread.start()
popen.wait()
exit_code = popen.returncode
if stdout_thread and stdout_thread.is_alive(): stdout_thread.join(timeout=1)
if stderr_thread and stderr_thread.is_alive(): stderr_thread.join(timeout=1)
if managed_process_info.get("service_name_key") == service_name_key:
service_name = get_text(service_name_key)
if not is_detached:
if exit_code == 0: update_status_bar("service_stopped_gracefully_status", service_name=service_name)
else: update_status_bar("service_stopped_exit_code_status", service_name=service_name, code=exit_code)
managed_process_info["popen"] = None
managed_process_info["service_name_key"] = None
managed_process_info["fully_detached"] = False
def get_fastapi_port_from_gui() -> int:
try:
port_str = port_entry_var.get()
if not port_str: messagebox.showwarning(get_text("warning_title"), get_text("enter_valid_port_warn")); return DEFAULT_FASTAPI_PORT
port = int(port_str)
if not (1024 <= port <= 65535): raise ValueError("Port out of range")
return port
except ValueError:
messagebox.showwarning(get_text("warning_title"), get_text("enter_valid_port_warn"))
port_entry_var.set(str(DEFAULT_FASTAPI_PORT))
return DEFAULT_FASTAPI_PORT
def get_camoufox_debug_port_from_gui() -> int:
try:
port_str = camoufox_debug_port_var.get()
if not port_str:
camoufox_debug_port_var.set(str(DEFAULT_CAMOUFOX_PORT_GUI))
return DEFAULT_CAMOUFOX_PORT_GUI
port = int(port_str)
if not (1024 <= port <= 65535): raise ValueError("Port out of range")
return port
except ValueError:
messagebox.showwarning(get_text("warning_title"), get_text("enter_valid_port_warn"))
camoufox_debug_port_var.set(str(DEFAULT_CAMOUFOX_PORT_GUI))
return DEFAULT_CAMOUFOX_PORT_GUI
# 配置文件路径
CONFIG_FILE_PATH = os.path.join(SCRIPT_DIR, "gui_config.json")
# 默认配置 - 从环境变量读取,如果没有则使用硬编码默认值
DEFAULT_CONFIG = {
"fastapi_port": DEFAULT_FASTAPI_PORT,
"camoufox_debug_port": DEFAULT_CAMOUFOX_PORT_GUI,
"stream_port": int(os.environ.get('GUI_DEFAULT_STREAM_PORT', '3120')),
"stream_port_enabled": True,
"helper_endpoint": os.environ.get('GUI_DEFAULT_HELPER_ENDPOINT', ''),
"helper_enabled": False,
"proxy_address": os.environ.get('GUI_DEFAULT_PROXY_ADDRESS', 'http://127.0.0.1:7890'),
"proxy_enabled": False
}
# 加载配置
def load_config():
if os.path.exists(CONFIG_FILE_PATH):
try:
with open(CONFIG_FILE_PATH, 'r', encoding='utf-8') as f:
config = json.load(f)
logger.info(f"成功加载配置文件: {CONFIG_FILE_PATH}")
return config
except Exception as e:
logger.error(f"加载配置文件失败: {e}")
logger.info(f"使用默认配置")
return DEFAULT_CONFIG.copy()
# 保存配置
def save_config():
config = {
"fastapi_port": port_entry_var.get(),
"camoufox_debug_port": camoufox_debug_port_var.get(),
"stream_port": stream_port_var.get(),
"stream_port_enabled": stream_port_enabled_var.get(),
"helper_endpoint": helper_endpoint_var.get(),
"helper_enabled": helper_enabled_var.get(),
"proxy_address": proxy_address_var.get(),
"proxy_enabled": proxy_enabled_var.get()
}
try:
with open(CONFIG_FILE_PATH, 'w', encoding='utf-8') as f:
json.dump(config, f, ensure_ascii=False, indent=2)
logger.info(f"成功保存配置到: {CONFIG_FILE_PATH}")
except Exception as e:
logger.error(f"保存配置失败: {e}")
# 重置为默认配置,包含代理设置
def reset_to_defaults():
if messagebox.askyesno(get_text("confirm_reset_title"), get_text("confirm_reset_message"), parent=root_widget):
port_entry_var.set(str(DEFAULT_FASTAPI_PORT))
camoufox_debug_port_var.set(str(DEFAULT_CAMOUFOX_PORT_GUI))
stream_port_var.set("3120")
stream_port_enabled_var.set(True)
helper_endpoint_var.set("")
helper_enabled_var.set(False)
proxy_address_var.set("http://127.0.0.1:7890")
proxy_enabled_var.set(False)
messagebox.showinfo(get_text("info_title"), get_text("reset_success"), parent=root_widget)
def _configure_proxy_env_vars() -> Dict[str, str]:
"""
配置代理环境变量(已弃用,现在主要通过 --internal-camoufox-proxy 参数传递)
保留此函数以维持向后兼容性,但现在主要用于状态显示
"""
proxy_env = {}
if proxy_enabled_var.get():
proxy_addr = proxy_address_var.get().strip()
if proxy_addr:
# 注意:现在主要通过 --internal-camoufox-proxy 参数传递代理配置
# 环境变量作为备用方案,但优先级较低
update_status_bar("proxy_configured_status", proxy_addr=proxy_addr)
else:
update_status_bar("proxy_skip_status")
else:
update_status_bar("proxy_skip_status")
return proxy_env
def _launch_process_gui(cmd: List[str], service_name_key: str, env_vars: Optional[Dict[str, str]] = None):
global managed_process_info # managed_process_info is now informational for these launches
service_name = get_text(service_name_key)
# Clear previous output area for GUI messages, actual process output will be in the new terminal
if managed_process_info.get("output_area"):
managed_process_info["output_area"].config(state=tk.NORMAL)
managed_process_info["output_area"].delete('1.0', tk.END)
managed_process_info["output_area"].insert(tk.END, f"[INFO] Preparing to launch {service_name} in a new terminal...\\n")
managed_process_info["output_area"].config(state=tk.DISABLED)
effective_env = os.environ.copy()
if env_vars: effective_env.update(env_vars)
effective_env['PYTHONIOENCODING'] = 'utf-8'
popen_kwargs: Dict[str, Any] = {"env": effective_env}
system = platform.system()
launch_cmd_for_terminal: Optional[List[str]] = None
# Prepare command string for terminals that take a single command string
# Ensure correct quoting for arguments with spaces
cmd_parts_for_string = []
for part in cmd:
if " " in part and not (part.startswith('"') and part.endswith('"')):
cmd_parts_for_string.append(f'"{part}"')
else:
cmd_parts_for_string.append(part)
cmd_str_for_terminal_execution = " ".join(cmd_parts_for_string)
if system == "Windows":
# CREATE_NEW_CONSOLE opens a new window.
# The new process will be a child of this GUI initially, but if python.exe
# itself handles its lifecycle well, closing GUI might not kill it.
# To be more robust for independence, one might use 'start' cmd,
# but simple CREATE_NEW_CONSOLE often works for python scripts.
# For true independence and GUI not waiting, Popen should be on python.exe directly.
popen_kwargs["creationflags"] = subprocess.CREATE_NEW_CONSOLE
launch_cmd_for_terminal = cmd # Direct command
elif system == "Darwin": # macOS
# import shlex # Ensure shlex is imported (should be at top of file)
# Build the shell command string with proper quoting for each argument.
# The command will first change to SCRIPT_DIR, then execute the python script.
script_dir_quoted = shlex.quote(SCRIPT_DIR)
python_executable_quoted = shlex.quote(cmd[0])
script_path_quoted = shlex.quote(cmd[1])
args_for_script_quoted = [shlex.quote(arg) for arg in cmd[2:]]
# 构建环境变量设置字符串
env_prefix_parts = []
if env_vars: # env_vars 应该是从 _configure_proxy_env_vars() 来的 proxy_env
for key, value in env_vars.items():
if value is not None: # 确保值存在且不为空字符串
env_prefix_parts.append(f"{shlex.quote(key)}={shlex.quote(str(value))}")
env_prefix_str = " ".join(env_prefix_parts)
# Construct the full shell command to be executed in the new terminal
shell_command_parts = [
f"cd {script_dir_quoted}",
"&&" # Ensure command separation
]
if env_prefix_str:
shell_command_parts.append(env_prefix_str)
shell_command_parts.extend([
python_executable_quoted,
script_path_quoted
])
shell_command_parts.extend(args_for_script_quoted)
shell_command_str = " ".join(shell_command_parts)
# Now, escape this shell_command_str for embedding within an AppleScript double-quoted string.
# In AppleScript strings, backslash `\\` and double quote `\"` are special and need to be escaped.
applescript_arg_escaped = shell_command_str.replace('\\\\', '\\\\\\\\').replace('\"', '\\\\\"')
# Construct the AppleScript command
# 修复:使用简化的AppleScript命令避免AppleEvent处理程序失败
# 直接创建新窗口并执行命令,避免复杂的条件判断
applescript_command = f'''
tell application "Terminal"
do script "{applescript_arg_escaped}"
activate
end tell
'''
launch_cmd_for_terminal = ["osascript", "-e", applescript_command.strip()]
elif system == "Linux":
import shutil
terminal_emulator = shutil.which("x-terminal-emulator") or shutil.which("gnome-terminal") or shutil.which("konsole") or shutil.which("xfce4-terminal") or shutil.which("xterm")
if terminal_emulator:
# Construct command ensuring SCRIPT_DIR is CWD for the launched script
# Some terminals might need `sh -c "cd ... && python ..."`
# For simplicity, let's try to pass the command directly if possible or via sh -c
cd_command = f"cd '{SCRIPT_DIR}' && "
full_command_to_run = cd_command + cmd_str_for_terminal_execution
if "gnome-terminal" in terminal_emulator or "mate-terminal" in terminal_emulator:
launch_cmd_for_terminal = [terminal_emulator, "--", "bash", "-c", full_command_to_run + "; exec bash"]
elif "konsole" in terminal_emulator or "xfce4-terminal" in terminal_emulator or "lxterminal" in terminal_emulator:
launch_cmd_for_terminal = [terminal_emulator, "-e", f"bash -c '{full_command_to_run}; exec bash'"]