forked from lumingya/universal-web-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.py
More file actions
1387 lines (1190 loc) · 49.3 KB
/
Copy pathstart.py
File metadata and controls
1387 lines (1190 loc) · 49.3 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
# -*- coding: utf-8 -*-
"""
跨平台启动入口。
设计目标:
- 与 start.bat 保持一致的核心启动行为
- 为 macOS / Linux 提供可运行的一键入口
- Windows 上也可使用,适合不想依赖批处理脚本的环境
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import shutil
import socket
import select
import socketserver
import subprocess
import sys
import tempfile
import threading
import time
import urllib.request
import venv
from pathlib import Path
from urllib.parse import urlsplit, urlunsplit
PROJECT_DIR = Path(__file__).resolve().parent
VENV_DIR = PROJECT_DIR / "venv"
REQ_HASH_FILE = VENV_DIR / ".req_hash"
REQUIREMENTS_FILE = PROJECT_DIR / "requirements.txt"
DEFAULT_PIP_MIRROR = "https://pypi.tuna.tsinghua.edu.cn/simple"
DEFAULT_GITHUB_REPO = "lumingya/universal-web-api"
DEFAULT_PYTHON_INSTALL_VERSION = "3.13.6"
_PYTHON_PROXY_SCHEMES = frozenset({
"http",
"https",
"socks4",
"socks4a",
"socks5",
"socks5h",
})
ENV_DEFAULTS = {
"APP_HOST": "127.0.0.1",
"APP_PORT": "8199",
"BROWSER_PORT": "9222",
"AUTO_UPDATE_ENABLED": "true",
"GITHUB_REPO": DEFAULT_GITHUB_REPO,
"PYTHON_INSTALL_VERSION": DEFAULT_PYTHON_INSTALL_VERSION,
"PROXY_ENABLED": "false",
"PROXY_ADDRESS": "",
"PROXY_BYPASS": "localhost,127.0.0.1",
"PIP_MIRROR_URL": DEFAULT_PIP_MIRROR,
"BROWSER_PROFILE_DIR": "",
"BROWSER_PROFILE_NAME": "",
# Opt-in because background freezing can delay site-specific periodic commands.
# Set BROWSER_MEMORY_SAVER=true after validating the target sites.
"BROWSER_MEMORY_SAVER": "false",
"PROFILE_CLEAN_ENABLED": "false",
"SCHEDULED_RESTART_ENABLED": "false",
"SCHEDULED_RESTART_INTERVAL_SECONDS": "10800",
"SCHEDULED_RESTART_DRAIN_TIMEOUT_SECONDS": "1800",
"SCHEDULED_RESTART_TAB_STATE_POLICY": "preserve",
"AUTO_OPEN_BROWSER": "true",
}
REQUIRED_PROJECT_FILES = [
Path("main.py"),
Path("app") / "core" / "browser.py",
Path("app") / "services" / "config_engine.py",
]
def _log(message: str = "") -> None:
print(message, flush=True)
def _section(title: str) -> None:
_log(f"[STEP] {title}")
_log("----------------------------------------")
def _env_flag(name: str, default: bool = False) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return str(raw).strip().lower() in ("1", "true", "yes", "on")
def _load_env_file(path: Path) -> None:
if not path.exists():
if path.name == ".env":
_log("[WARN] 未找到 .env 文件,使用默认配置")
return
_log(f"[INFO] 读取 {path.name} 配置文件...")
for raw_line in path.read_text(encoding="utf-8-sig").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
key = key.strip()
value = value.strip().strip('"').strip("'")
if key:
os.environ[key] = value
_log("[OK] 配置加载完成")
def _apply_env_defaults() -> None:
for key, value in ENV_DEFAULTS.items():
os.environ.setdefault(key, value)
def _normalize_python_proxy_url(value: str) -> str:
"""Convert a browser proxy value into a requests-compatible proxy URL."""
raw = str(value or "").strip()
if not raw:
return ""
if "://" not in raw:
raw = f"http://{raw}"
try:
parsed = urlsplit(raw)
scheme = str(parsed.scheme or "").lower()
if scheme not in _PYTHON_PROXY_SCHEMES or not parsed.hostname:
return ""
# Accessing .port validates malformed values such as :not-a-port.
_ = parsed.port
except (TypeError, ValueError):
return ""
# requests must resolve R2 hostnames through the SOCKS proxy. `socks5`
# resolves them locally, which reintroduces the fake-DNS/direct-DNS issue.
if scheme == "socks5":
scheme = "socks5h"
return urlunsplit((scheme, parsed.netloc, parsed.path, parsed.query, ""))
def _merged_no_proxy(*values: str) -> str:
entries = []
seen = set()
for raw_value in values:
for entry in str(raw_value or "").split(","):
normalized = entry.strip()
key = normalized.lower()
if normalized and key not in seen:
seen.add(key)
entries.append(normalized)
return ",".join(entries)
def _replace_env_value(env: dict[str, str], key: str, value: str) -> None:
"""Replace an environment key irrespective of its original casing."""
for existing_key in tuple(env):
if existing_key.lower() == key.lower():
env.pop(existing_key, None)
env[key] = value
def _build_service_env() -> dict[str, str]:
"""Build the child service environment without mutating the launcher shell."""
env = os.environ.copy()
if not _env_flag("PROXY_ENABLED"):
return env
proxy_url = _normalize_python_proxy_url(os.getenv("PROXY_ADDRESS", ""))
if not proxy_url:
return env
_replace_env_value(env, "HTTP_PROXY", proxy_url)
_replace_env_value(env, "HTTPS_PROXY", proxy_url)
existing_no_proxy = ",".join(
str(value or "")
for key, value in env.items()
if key.lower() == "no_proxy"
)
bypass = _merged_no_proxy(existing_no_proxy, os.getenv("PROXY_BYPASS", ""))
if bypass:
_replace_env_value(env, "NO_PROXY", bypass)
return env
def _display_current_config() -> None:
_log()
_log(" 当前配置:")
_log(f" APP_HOST : {os.getenv('APP_HOST')}")
_log(f" APP_PORT : {os.getenv('APP_PORT')}")
_log(f" BROWSER_PORT : {os.getenv('BROWSER_PORT')}")
_log(f" AUTO_UPDATE : {os.getenv('AUTO_UPDATE_ENABLED')}")
_log(f" PYTHON_FIXED : {os.getenv('PYTHON_INSTALL_VERSION')}")
profile_dir = _resolve_profile_dir()
_log(f" PROFILE_DIR : {profile_dir}")
profile_name = str(os.getenv("BROWSER_PROFILE_NAME", "") or "").strip()
if profile_name:
_log(f" PROFILE_NAME : {profile_name}")
_log(f" PROFILE_CLEAN: {os.getenv('PROFILE_CLEAN_ENABLED')}")
_log(f" MEMORY_SAVER : {os.getenv('BROWSER_MEMORY_SAVER', 'false')}")
if _env_flag("PROXY_ENABLED"):
_log(f" PROXY : {os.getenv('PROXY_ADDRESS', '')} (browser / Python downloads)")
else:
_log(" PROXY : 已禁用")
_log()
def _venv_python() -> Path:
if os.name == "nt":
return VENV_DIR / "Scripts" / "python.exe"
return VENV_DIR / "bin" / "python"
def _run(
cmd: list[str],
*,
check: bool = True,
capture: bool = False,
env: dict | None = None,
) -> subprocess.CompletedProcess:
kwargs = {
"cwd": str(PROJECT_DIR),
"check": check,
"text": True,
"env": env,
}
if capture:
kwargs["capture_output"] = True
kwargs["encoding"] = "utf-8"
kwargs["errors"] = "replace"
return subprocess.run(cmd, **kwargs)
def _run_project_python(args: list[str], *, check: bool = True, capture: bool = False) -> subprocess.CompletedProcess:
return _run(
[str(_venv_python()), *args],
check=check,
capture=capture,
env=_build_service_env(),
)
def _python_install_version() -> str:
return str(os.getenv("PYTHON_INSTALL_VERSION", DEFAULT_PYTHON_INSTALL_VERSION) or DEFAULT_PYTHON_INSTALL_VERSION).strip()
def _python_install_major_minor() -> str:
parts = _python_install_version().split(".")
if len(parts) >= 2:
return f"{parts[0]}.{parts[1]}"
return "3.13"
def _python_install_short() -> str:
return _python_install_major_minor().replace(".", "")
def _python_install_url() -> str:
version = _python_install_version()
return f"https://www.python.org/ftp/python/{version}/python-{version}-amd64.exe"
def _is_windows_store_python() -> bool:
if not sys.platform.startswith("win"):
return False
return "WindowsApps" in str(Path(sys.executable))
def _python_version_ok(python_path: Path) -> bool:
try:
result = subprocess.run(
[
str(python_path),
"-c",
"import sys; raise SystemExit(0 if sys.version_info >= (3, 8) else 1)",
],
check=False,
capture_output=True,
text=True,
timeout=10,
)
return result.returncode == 0
except Exception:
return False
def _find_installed_fixed_python() -> Path | None:
if not sys.platform.startswith("win"):
return None
short_version = _python_install_short()
major_minor = _python_install_major_minor()
local_app_data = os.getenv("LOCALAPPDATA", "")
program_files = os.getenv("ProgramFiles", r"C:\Program Files")
program_files_x86 = os.getenv("ProgramFiles(x86)", r"C:\Program Files (x86)")
candidates = [
Path(local_app_data) / "Programs" / "Python" / f"Python{short_version}" / "python.exe",
Path(program_files) / f"Python{short_version}" / "python.exe",
Path(program_files_x86) / f"Python{short_version}" / "python.exe",
]
for candidate in candidates:
if candidate.exists() and _python_version_ok(candidate):
return candidate
py_launcher = shutil.which("py")
if py_launcher:
try:
result = subprocess.run(
[py_launcher, f"-{major_minor}", "-c", "import sys; print(sys.executable)"],
check=False,
capture_output=True,
text=True,
timeout=10,
)
if result.returncode == 0:
candidate = Path(result.stdout.strip())
if candidate.exists() and _python_version_ok(candidate):
return candidate
except Exception:
pass
return None
def _download_and_install_fixed_python() -> Path:
version = _python_install_version()
url = _python_install_url()
installer = Path(tempfile.gettempdir()) / f"python-{version}-amd64.exe"
_log()
_log(f"[INFO] 正在下载 Python {version}...")
_log(f"[INFO] 下载来源: {url}")
try:
urllib.request.urlretrieve(url, installer)
except Exception as exc:
raise RuntimeError(f"Python 安装包下载失败: {exc}") from exc
if not installer.exists():
raise RuntimeError(f"Python 安装包不存在: {installer}")
_log(f"[INFO] 正在静默安装 Python {version}...")
result = subprocess.run(
[
str(installer),
"/quiet",
"InstallAllUsers=0",
"PrependPath=1",
"Include_launcher=1",
"Include_pip=1",
"Include_test=0",
"SimpleInstall=1",
],
check=False,
)
try:
installer.unlink(missing_ok=True)
except Exception:
pass
if result.returncode not in (0, 3010):
raise RuntimeError(f"Python 安装失败,安装器退出码: {result.returncode}")
installed = _find_installed_fixed_python()
if not installed:
raise RuntimeError("Python 安装完成后仍未找到可用解释器,请重新打开终端后再运行 start.py")
return installed
def _offer_python_install(reason: str) -> bool:
if not sys.platform.startswith("win"):
return False
version = _python_install_version()
_log()
_log(f"[INFO] {reason}")
_log()
_log(f" 可自动下载安装固定版本 Python {version} (64-bit)")
_log(f" 下载来源: {_python_install_url()}")
_log(" 安装范围: 当前用户")
_log()
choice = input(f"是否自动下载并安装 Python {version}?(Y/N): ").strip()
if choice.lower() != "y":
_log("[INFO] 已取消自动安装 Python")
return False
installed = _download_and_install_fixed_python()
if Path(sys.executable).resolve() == installed.resolve():
return True
_log(f"[OK] Python 已就绪: {installed}")
_log("[INFO] 正在使用新 Python 重新运行 start.py...")
os.execv(str(installed), [str(installed), str(Path(__file__).resolve()), *sys.argv[1:]])
return True
def _check_python_version() -> None:
_section("检查 Python 环境")
version = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
if _is_windows_store_python():
if _offer_python_install("检测到 Windows Store Python 占位符"):
return
raise RuntimeError("检测到 Windows Store Python 占位符,请关闭应用执行别名或安装完整版 Python")
if sys.version_info < (3, 8):
if _offer_python_install(f"Python 版本过低: {version},最低要求 Python 3.8+"):
return
raise RuntimeError(f"Python 版本过低: {version},最低要求 Python 3.8+")
_log(f"[OK] Python {version}")
_log(f" 路径: {sys.executable}")
_log()
def _run_auto_update() -> None:
if not _env_flag("AUTO_UPDATE_ENABLED", True):
_log("[INFO] 自动更新已禁用")
_log(" 本次不会自动应用更新;服务启动后仍会检查新版本并在设置图标提示")
_log(" 如需自动应用更新,请修改 .env 中的 AUTO_UPDATE_ENABLED=true")
_log()
return
_section("自动更新")
updater_script = PROJECT_DIR / "updater.py"
if not updater_script.exists():
_log("[WARN] 未找到 updater.py,跳过自动更新")
_log()
return
_log("[INFO] 检查 GitHub 最新版本...")
result = _run([sys.executable, "updater.py"], check=False)
if result.returncode == 0:
_log("[INFO] 自动更新已应用,继续启动服务...")
else:
_log("[WARN] 本次未应用更新,继续启动服务")
_log()
def _ensure_project_structure() -> None:
_section("检查项目结构")
missing = []
for rel_path in REQUIRED_PROJECT_FILES:
if not (PROJECT_DIR / rel_path).exists():
missing.append(str(rel_path))
sites_config = PROJECT_DIR / "config" / "sites.json"
if not sites_config.exists():
_log("[WARN] 缺失: config/sites.json,将自动创建")
sites_config.parent.mkdir(parents=True, exist_ok=True)
sites_config.write_text('{"_global": {"selector_definitions": []}}\n', encoding="utf-8")
_log("[INFO] 已创建空配置文件")
else:
_log("[OK] 找到: config/sites.json")
if missing:
for item in missing:
_log(f"[ERROR] 缺失: {item}")
raise RuntimeError("项目结构不完整,请检查文件是否齐全")
_log("[OK] 项目结构检查通过")
_log()
def _ensure_venv() -> None:
_section("准备虚拟环境")
python_path = _venv_python()
if python_path.exists():
_log("[OK] 虚拟环境已存在")
_log()
return
if VENV_DIR.exists():
raise RuntimeError("虚拟环境损坏,缺少 Python 解释器。请删除 venv 后重新运行。")
_log("[INFO] 创建虚拟环境...")
builder = venv.EnvBuilder(with_pip=True)
builder.create(str(VENV_DIR))
if not python_path.exists():
raise RuntimeError("虚拟环境创建失败,缺少 Python 解释器")
_log("[OK] 虚拟环境创建成功")
_log()
def _file_md5(path: Path) -> str:
digest = hashlib.md5()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _dependencies_ok() -> bool:
check_script = PROJECT_DIR / "check_deps.py"
if not check_script.exists():
return True
try:
result = _run_project_python([check_script.name], check=False, capture=True)
except Exception:
return False
return result.returncode == 0
def _ensure_dependencies() -> None:
_section("检查依赖")
if not REQUIREMENTS_FILE.exists():
raise FileNotFoundError("缺少 requirements.txt 文件")
current_hash = _file_md5(REQUIREMENTS_FILE)
old_hash = ""
if REQ_HASH_FILE.exists():
try:
old_hash = REQ_HASH_FILE.read_text(encoding="utf-8").strip()
except Exception:
old_hash = ""
if old_hash == current_hash and _dependencies_ok():
_log("[OK] 依赖已是最新")
_log()
return
_log("[INFO] 安装 Python 依赖包...")
pip_cmd = [str(_venv_python()), "-m", "pip", "install", "-r", str(REQUIREMENTS_FILE)]
install_source = "PyPI"
result = _run(pip_cmd, check=False)
if result.returncode != 0:
mirror = os.getenv("PIP_MIRROR_URL", DEFAULT_PIP_MIRROR).strip() or DEFAULT_PIP_MIRROR
install_source = mirror
_log(f"[WARN] 默认 PyPI 安装失败,尝试镜像: {mirror}")
result = _run(pip_cmd + ["-i", mirror], check=False)
if result.returncode != 0:
if REQ_HASH_FILE.exists():
REQ_HASH_FILE.unlink()
raise RuntimeError("依赖安装失败")
pip_check = _run([str(_venv_python()), "-m", "pip", "check"], check=False, capture=True)
if pip_check.returncode != 0:
_log("[WARN] pip check 报告依赖冲突,但不影响继续启动")
REQ_HASH_FILE.parent.mkdir(parents=True, exist_ok=True)
REQ_HASH_FILE.write_text(current_hash, encoding="utf-8")
_log("[OK] 依赖安装完成")
_log(f"[INFO] 安装来源: {install_source}")
_log()
def _maybe_apply_patch() -> None:
_section("应用 DrissionPage 补丁")
patch_script = PROJECT_DIR / "patch_drissionpage.py"
if not patch_script.exists():
_log("[WARN] 未找到 patch_drissionpage.py,跳过补丁")
_log()
return
result = _run_project_python([patch_script.name], check=False)
if result.returncode != 0:
_log("[WARN] 补丁应用失败,网络监听模式可能触发 CF 检测")
_log(" 项目仍可正常运行(DOM 模式不受影响)")
_log()
def _resolve_profile_dir() -> Path:
raw = str(os.getenv("BROWSER_PROFILE_DIR", "") or "").strip()
if raw:
profile_dir = Path(raw).expanduser()
if not profile_dir.is_absolute():
profile_dir = PROJECT_DIR / profile_dir
return profile_dir
return PROJECT_DIR / "chrome_profile"
def _maybe_clean_profile(profile_dir: Path) -> None:
_section("浏览器配置瘦身")
if not _env_flag("PROFILE_CLEAN_ENABLED"):
_log(f"[INFO] 已禁用配置瘦身(PROFILE_CLEAN_ENABLED={os.getenv('PROFILE_CLEAN_ENABLED')})")
_log()
return
clean_script = PROJECT_DIR / "clean_profile.py"
if not clean_script.exists():
_log("[WARN] 未找到 clean_profile.py,跳过清理")
_log()
return
_log("[INFO] 执行浏览器配置瘦身...")
_run_project_python([clean_script.name, str(profile_dir)], check=False)
_log()
def _debug_port_ready(port: int) -> bool:
try:
with socket.create_connection(("127.0.0.1", int(port)), timeout=0.4):
return True
except Exception:
return False
def _check_chromium_debug_endpoint(port: int, timeout: float = 0.5) -> tuple[bool, dict[str, Any]]:
"""
检查指定端口是否为可响应且合法的 Chromium 远程调试端点。
返回 (is_chromium, version_info)。
"""
version_url = f"http://127.0.0.1:{int(port)}/json/version"
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
try:
req = urllib.request.Request(version_url, headers={"User-Agent": "UWAPI-Diagnostics"})
with opener.open(req, timeout=timeout) as resp:
data = json.loads(resp.read().decode("utf-8", errors="ignore"))
if isinstance(data, dict) and ("Browser" in data or "webSocketDebuggerUrl" in data):
return True, data
except Exception:
pass
return False, {}
def _get_port_processes(port: int) -> list[dict[str, Any]]:
"""获取占用指定 TCP 端口(处于 LISTENING 状态)的进程信息列表。"""
port_int = int(port)
pids: set[int] = set()
# 1. 在 Windows 上优先使用 netstat -ano(支持 IPv4 与 IPv6 Dual-stack 监听)
if sys.platform == "win32":
try:
output = subprocess.check_output(
["netstat", "-ano"],
text=True,
errors="ignore",
stderr=subprocess.DEVNULL,
)
pattern = re.compile(
rf"^\s*TCP\s+\[?[\w\.:]+\]?:({port_int})\s+\S+\s+LISTENING\s+(\d+)",
re.IGNORECASE | re.MULTILINE,
)
for match in pattern.finditer(output):
try:
pids.add(int(match.group(2)))
except (ValueError, TypeError):
pass
except Exception:
pass
# 2. 尝试使用 psutil 获取连接
if not pids:
try:
import psutil
for conn in psutil.net_connections(kind="tcp"):
if conn.status == psutil.CONN_LISTEN and conn.laddr and conn.laddr.port == port_int:
if conn.pid:
pids.add(conn.pid)
except Exception:
pass
# 3. 获取进程详情
results = []
for pid in sorted(pids):
if pid <= 0:
continue
info = {"pid": pid, "name": f"PID:{pid}", "cmdline": ""}
try:
import psutil
proc = psutil.Process(pid)
info["name"] = proc.name()
try:
cmd = proc.cmdline()
info["cmdline"] = " ".join(cmd) if cmd else ""
except Exception:
pass
except Exception:
pass
results.append(info)
return results
def _terminate_port_processes(port: int, procs: list[dict[str, Any]]) -> bool:
"""终止占用指定端口的进程及其子进程树,并等待端口完全释放。"""
pids = [p["pid"] for p in procs if p.get("pid", 0) > 0]
if not pids:
return not _debug_port_ready(port)
for pid in pids:
if sys.platform == "win32":
try:
subprocess.run(
["taskkill", "/F", "/T", "/PID", str(pid)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
)
except Exception:
pass
else:
try:
import signal
os.kill(pid, getattr(signal, "SIGKILL", 9))
except Exception:
pass
try:
import psutil
proc = psutil.Process(pid)
for child in proc.children(recursive=True):
try:
child.kill()
except Exception:
pass
proc.kill()
except Exception:
pass
# 轮询等待端口释放(最多 5 秒)
for _ in range(10):
time.sleep(0.5)
if not _debug_port_ready(port):
return True
return False
def _is_interactive() -> bool:
"""安全检查当前环境是否为可交互终端(防御 sys.stdin 为 None)。"""
try:
return bool(sys.stdin and hasattr(sys.stdin, "isatty") and sys.stdin.isatty())
except Exception:
return False
def _ask_user_yes_no(prompt: str, default: bool = False) -> bool:
"""在交互式终端中询问用户 (y/n),返回 True 表示确认终止。"""
if not _is_interactive():
return default
try:
reply = input(prompt).strip().lower()
if not reply:
return default
return reply in ("y", "yes")
except EOFError:
_log()
return default
except KeyboardInterrupt:
_log()
raise
def _inspect_headless_or_windowless_browser(port: int, timeout: float = 0.5) -> Optional[dict[str, str]]:
"""
探测指定端口的 Chromium 浏览器是否处于无头(Headless)或无窗口/缺少页面标签页状态。
返回 None 表示不是无头(或者端口未开放/非 Chromium)。
"""
import json
import urllib.request
port_int = int(port)
# 显式使用空 ProxyHandler,避免系统或环境变量代理(如 HTTP_PROXY)拦截 loopback 探测
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
# 1. 检查进程启动参数 (若 psutil 可用,优先确认是否明确声明了 --headless 或 --no-startup-window)
cmd_has_headless = False
cmd_has_no_startup_window = False
try:
import psutil
target_arg = f"--remote-debugging-port={port_int}"
for proc in psutil.process_iter(["pid", "cmdline"]):
try:
cmdline_list = proc.info.get("cmdline") or []
# 过滤 Chromium 子进程(renderer/gpu/utility 等子进程必然包含 --type=,主进程不包含)
if any(str(arg).startswith("--type=") for arg in cmdline_list):
continue
cmdline = " ".join(cmdline_list)
if target_arg in cmdline:
cmd_lower = cmdline.lower()
if "--headless" in cmd_lower:
cmd_has_headless = True
if "--no-startup-window" in cmd_lower:
cmd_has_no_startup_window = True
if cmd_has_headless and cmd_has_no_startup_window:
break
except Exception:
continue
except Exception:
pass
if cmd_has_headless:
return {"reason": "headless_arg", "detail": "浏览器启动参数显式包含 --headless"}
# 2. 检查 /json/version
version_url = f"http://127.0.0.1:{port_int}/json/version"
try:
req = urllib.request.Request(version_url, headers={"User-Agent": "UWAPI-Diagnostics"})
with opener.open(req, timeout=timeout) as resp:
data = json.loads(resp.read().decode("utf-8", errors="ignore"))
except Exception:
return None
browser_desc = str(data.get("Browser", "") or "")
user_agent = str(data.get("User-Agent", "") or "")
if "headless" in browser_desc.lower() or "headless" in user_agent.lower():
return {
"reason": "headless",
"detail": f"检测到无头浏览器 ({browser_desc or user_agent})",
}
# 3. 检查 /json 目标列表 (targets)
targets_url = f"http://127.0.0.1:{port_int}/json"
try:
req = urllib.request.Request(targets_url, headers={"User-Agent": "UWAPI-Diagnostics"})
with opener.open(req, timeout=timeout) as resp:
targets = json.loads(resp.read().decode("utf-8", errors="ignore"))
if isinstance(targets, list):
pages = [
t for t in targets
if isinstance(t, dict) and str(t.get("type", "")).lower() == "page"
]
if not pages:
if cmd_has_no_startup_window:
return {
"reason": "no_startup_window",
"detail": "浏览器带有 --no-startup-window 参数且当前无前台可视页面",
}
other_types = sorted(list({
str(t.get("type", "unknown"))
for t in targets if isinstance(t, dict) and t.get("type")
}))
detail_types = ", ".join(other_types) if other_types else "无任何活动目标"
return {
"reason": "no_pages",
"detail": f"无可视标签页(当前后台目标: {detail_types})",
}
except Exception:
pass
return None
class _RestartHandoffProxy(socketserver.ThreadingTCPServer):
"""Small TCP relay which buffers a request while the child service restarts."""
allow_reuse_address = True
daemon_threads = True
def __init__(self, host: str, port: int, backend_port: int):
self.backend_port = int(backend_port)
super().__init__((host, int(port)), _RestartHandoffProxyHandler)
class _RestartHandoffProxyHandler(socketserver.BaseRequestHandler):
_BUFFER_SIZE = 64 * 1024
_MAX_REQUEST_BYTES = 64 * 1024 * 1024
def handle(self) -> None:
try:
payload = self._read_request()
if payload:
self._forward_when_backend_ready(payload)
except Exception:
return
def _read_request(self) -> bytes:
self.request.settimeout(60.0)
payload = bytearray()
while b"\r\n\r\n" not in payload:
chunk = self.request.recv(self._BUFFER_SIZE)
if not chunk:
return b""
payload.extend(chunk)
if len(payload) > self._MAX_REQUEST_BYTES:
return b""
header_end = payload.find(b"\r\n\r\n") + 4
headers = bytes(payload[:header_end]).decode("iso-8859-1", errors="replace")
content_length = 0
for line in headers.split("\r\n")[1:]:
if line.lower().startswith("content-length:"):
content_length = max(0, int(line.split(":", 1)[1].strip()))
break
target_size = header_end + content_length
if target_size > self._MAX_REQUEST_BYTES:
return b""
while len(payload) < target_size:
chunk = self.request.recv(min(self._BUFFER_SIZE, target_size - len(payload)))
if not chunk:
return b""
payload.extend(chunk)
# One request per client connection makes the restart boundary explicit
# and lets us safely replay a request that arrived while draining.
header_lines = [
line for line in headers.split("\r\n")
if not line.lower().startswith("connection:")
]
rewritten_headers = "\r\n".join(header_lines).rstrip("\r\n") + "\r\nConnection: close\r\n\r\n"
return rewritten_headers.encode("iso-8859-1") + bytes(payload[header_end:])
def _client_disconnected(self) -> bool:
# One HTTP request per connection. Never leave an old backend running
# merely because it has not produced its first response byte yet.
try:
readable, _, _ = select.select([self.request], [], [], 0)
if not readable:
return False
return not self.request.recv(1, socket.MSG_PEEK)
except OSError:
return True
def _forward_when_backend_ready(self, payload: bytes) -> None:
deadline = time.monotonic() + 120.0
while time.monotonic() < deadline:
if self._client_disconnected():
return
try:
backend = socket.create_connection(("127.0.0.1", self.server.backend_port), timeout=1.0)
except OSError:
# Connection not established: no request could have executed.
time.sleep(0.15)
continue
with backend:
try:
backend.settimeout(300.0)
if self._client_disconnected():
return
backend.sendall(payload)
if self._relay_response(backend):
return
except OSError:
# A partial send, backend reset, or CLIENT write error is
# ambiguous. Never replay a possibly executed POST.
return
# Only an explicit pre-admission handoff response permits replay.
time.sleep(0.15)
def _relay_response(self, backend: socket.socket) -> bool:
header = bytearray()
headers_sent = False
deadline = time.monotonic() + 300.0
while time.monotonic() < deadline:
if self._client_disconnected():
return True
readable, _, _ = select.select([backend], [], [], 0.1)
if not readable:
continue
chunk = backend.recv(self._BUFFER_SIZE)
if not chunk:
return True # EOF after dispatch is NOT permission to retry.
deadline = time.monotonic() + 300.0
if not headers_sent:
header.extend(chunk)
boundary = header.find(b"\r\n\r\n")
if boundary < 0:
if len(header) > self._BUFFER_SIZE:
return True
continue
lines = bytes(header[:boundary]).split(b"\r\n")
status = lines[0].split()
handoff = any(line.lower().strip() == b"x-uwa-restart-handoff: pending" for line in lines[1:])
if len(status) >= 2 and status[1] == b"503" and handoff:
return False
self.request.sendall(header)
headers_sent = True
else:
self.request.sendall(chunk)
return True
def _start_restart_handoff_proxy(host: str, public_port: int, backend_port: int):
try:
proxy = _RestartHandoffProxy(host, public_port, backend_port)
except OSError as exc:
raise RuntimeError(f"无法启动重启守护代理(端口 {public_port}):{exc}") from exc
threading.Thread(target=proxy.serve_forever, daemon=True, name="restart-handoff-proxy").start()
_log(f"[OK] 重启守护代理已监听 {host}:{public_port}(后端内部端口 {backend_port})")
return proxy
def _focus_browser_window_for_port(port: int) -> bool:
"""Best-effort Windows foreground restore for an already-running browser."""
if not sys.platform.startswith("win"):
return False
try:
import ctypes
from ctypes import wintypes
import psutil
except Exception as e:
_log(f"[DEBUG] 跳过浏览器唤起:{e}")
return False
target_arg = f"--remote-debugging-port={int(port)}"
target_pid = 0
for proc in psutil.process_iter(["pid", "cmdline"]):
try:
cmdline = " ".join(proc.info.get("cmdline") or [])
if target_arg in cmdline:
target_pid = int(proc.info["pid"])
break
except Exception:
continue
if not target_pid:
return False
user32 = ctypes.windll.user32
SW_RESTORE = 9