Compare commits
36
Commits
ffebc8d0dc
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1202dffa32 | ||
|
|
e24b0bdd1e | ||
|
|
1c686a6595 | ||
|
|
9c8a037c4e | ||
|
|
94e0c6432f | ||
|
|
51c1c2da39 | ||
|
|
60306dd4e0 | ||
|
|
329b7756f4 | ||
|
|
16019ee649 | ||
|
|
60332db82b | ||
|
|
c2cbee9592 | ||
|
|
ab37165baf | ||
|
|
c0cb274728 | ||
|
|
a870e0cbf9 | ||
|
|
13aa60c06a | ||
|
|
f010853b97 | ||
|
|
ee3424cd9e | ||
|
|
7c6189fd5e | ||
|
|
7745f9a57f | ||
|
|
f5a77867ee | ||
|
|
407c3b37c2 | ||
|
|
e315aaf80b | ||
|
|
7234bf0cac | ||
|
|
39996405d5 | ||
|
|
383c947a03 | ||
|
|
63c726ddea | ||
|
|
f257c4e3fc | ||
|
|
ecbd07cea0 | ||
|
|
5aeeef4aee | ||
|
|
9a75b9b481 | ||
|
|
872d114a0f | ||
|
|
a7d6bc87b6 | ||
|
|
cf2b71f831 | ||
|
|
3ab15e69f9 | ||
|
|
8e8a14cf69 | ||
|
|
164f76658c |
No files matched your search
@@ -0,0 +1,87 @@
|
||||
name: Windows Package CI
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "bin/**"
|
||||
- "douyin/**"
|
||||
- "gui/**"
|
||||
- "operations/**"
|
||||
- "packaging/**"
|
||||
- "tools/**"
|
||||
- "tests/**"
|
||||
- "webui/**"
|
||||
- "pyproject.toml"
|
||||
- "requirements.txt"
|
||||
- ".github/workflows/windows-package-ci.yml"
|
||||
|
||||
jobs:
|
||||
package-fresh-install:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 90
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: "pip"
|
||||
|
||||
- name: Install Inno Setup
|
||||
shell: powershell
|
||||
run: choco install innosetup --yes --no-progress
|
||||
|
||||
- name: Install Python dependencies
|
||||
shell: powershell
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install -r requirements.txt
|
||||
python -m pip install pyinstaller cython setuptools wheel
|
||||
|
||||
- name: Run fast regression tests
|
||||
shell: powershell
|
||||
run: >
|
||||
python -m pytest
|
||||
tests/test_web_gui_routes_logic.py
|
||||
tests/test_startup_update_bootstrap.py
|
||||
tests/test_distribution_manifest.py
|
||||
tests/test_exe_packing.py
|
||||
tests/test_auto_update.py
|
||||
tests/test_version_consistency.py
|
||||
tests/test_tools_dev.py
|
||||
tests/test_ci_fresh_install.py
|
||||
|
||||
- name: Build portable package
|
||||
shell: powershell
|
||||
run: powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -ReuseCache
|
||||
|
||||
- name: Build installer
|
||||
shell: powershell
|
||||
run: |
|
||||
$version = python -c "from douyin.core.version import APP_VERSION; print(str(APP_VERSION).lstrip('Vv'))"
|
||||
$iscc = @(
|
||||
"${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe",
|
||||
"${env:ProgramFiles}\Inno Setup 6\ISCC.exe",
|
||||
"${env:LOCALAPPDATA}\Programs\Inno Setup 6\ISCC.exe"
|
||||
) | Where-Object { Test-Path $_ } | Select-Object -First 1
|
||||
if (-not $iscc) { throw "ISCC.exe not found" }
|
||||
& $iscc packaging\inno\douyin_guaji.iss /DMyAppVersion=$version
|
||||
|
||||
- name: Fresh install smoke test
|
||||
shell: powershell
|
||||
run: powershell -NoProfile -ExecutionPolicy Bypass -File tools\ci\fresh_install_smoke.ps1
|
||||
|
||||
- name: Upload package and smoke report
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: douyin-guaji-windows-package
|
||||
path: |
|
||||
dist/installer/*.exe
|
||||
artifacts/fresh_install_ci/**
|
||||
if-no-files-found: ignore
|
||||
@@ -15,6 +15,47 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [V3.3.11] — 2026-06-29
|
||||
## [V3.3.10] — 2026-06-29
|
||||
## [V3.3.9] — 2026-06-28
|
||||
### Fixed
|
||||
|
||||
- 自动更新差量包下载、校验或启动失败时自动回退完整安装包,避免旧版本反复卡在失败的 delta 更新上。
|
||||
- 记录已启动的差量更新尝试;如果下次启动仍停留在旧版本,则跳过同一个 delta 并改用完整安装包。
|
||||
|
||||
### Added
|
||||
|
||||
- Dashboard 顶部新增“检查更新”按钮,可手动触发在线更新检查。
|
||||
|
||||
### Changed
|
||||
|
||||
- 自动更新默认启用;未配置更新地址时默认使用官方更新服务器,仍可通过配置或环境变量关闭。
|
||||
|
||||
## [V3.3.8] — 2026-06-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复部分荣耀/华为设备上 `adb exec-out screencap -p` 返回 `4294967295` 或损坏 PNG 后,截图链路未继续尝试 shell stdout 兜底的问题。
|
||||
- 打包时收集 `paddlex` / `paddleocr` / Paddle / OpenCV / NumPy / PIL / pyclipper / shapely 运行依赖,避免新电脑上 OCR 初始化缺少 `_internal\paddlex\.version` 或相关二进制组件。
|
||||
|
||||
### Added
|
||||
|
||||
- Dashboard 新增“上传诊断日志”,客户端只打包有限大小的日志片段;服务端按卡密覆盖保存一份,便于远程排查问题。
|
||||
|
||||
## [V3.3.7] — 2026-06-28
|
||||
|
||||
### Changed
|
||||
|
||||
- Dashboard 首次启动未授权时锁定在“授权”页,验证卡密成功后再进入数据看板。
|
||||
- WebGUI 未授权访问首页时先显示卡密验证门禁页,验证成功后再加载完整控制台。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 保留运行接口的授权拦截,避免未输入卡密时通过接口直接启动运行。
|
||||
|
||||
## [V3.3.6] — 2026-06-27
|
||||
## [V3.3.5] — 2026-06-27
|
||||
## [V3.3.4] — 2026-06-26
|
||||
### Added
|
||||
|
||||
- 引入完整的版本管理体系:
|
||||
|
||||
@@ -110,6 +110,12 @@ from douyin.license.license_manager import require_online_license_or_exit
|
||||
|
||||
|
||||
def ensure_adb_in_path() -> None:
|
||||
bundled_adb = path_config.find_bundled_adb()
|
||||
if bundled_adb:
|
||||
adb_dir = os.path.dirname(bundled_adb)
|
||||
os.environ["PATH"] = adb_dir + os.pathsep + os.environ.get("PATH", "")
|
||||
os.environ.setdefault("ADB_EXECUTABLE", bundled_adb)
|
||||
return
|
||||
if shutil.which("adb"):
|
||||
return
|
||||
localapp = os.environ.get("LOCALAPPDATA") or ""
|
||||
|
||||
@@ -0,0 +1,501 @@
|
||||
{
|
||||
"needswitch": true,
|
||||
"infinite_loop_enabled": true,
|
||||
"wait_minutes": 5,
|
||||
"auto_update": {
|
||||
"enabled": true,
|
||||
"manifest_url": "",
|
||||
"fail_closed": true,
|
||||
"require_sha256": true,
|
||||
"timeout_seconds": 20,
|
||||
"installer_args": [
|
||||
"/VERYSILENT",
|
||||
"/SUPPRESSMSGBOXES",
|
||||
"/NORESTART",
|
||||
"/CURRENTUSER"
|
||||
]
|
||||
},
|
||||
"min_prize_value_yuan": 100.0,
|
||||
"min_participants": 0,
|
||||
"max_participants": 0,
|
||||
"skip_if_countdown_gt_seconds": 10,
|
||||
"reset_after_swipes_enabled": true,
|
||||
"reset_after_swipes": 20,
|
||||
"reset_after_swipes_action": "swipe",
|
||||
"reenter_live_entry_mode": "screen_center",
|
||||
"auto_join_fansclub": true,
|
||||
"fansclub_fail_action": "switch",
|
||||
"high_value_fudai_enabled": true,
|
||||
"high_value_fudai_threshold_yuan": 150.0,
|
||||
"high_value_fudai_join_ahead_seconds": 100,
|
||||
"high_value_fudai_max_swipe_back": 50,
|
||||
"high_value_fudai_max_reservations": 9999,
|
||||
"high_value_fudai_after_action": "continue",
|
||||
"high_value_room_revisit_enabled": false,
|
||||
"high_value_room_revisit_only_current_run": false,
|
||||
"reservation_back_verify_enabled": true,
|
||||
"reservation_back_swipe_delay": 0.1,
|
||||
"reservation_back_verify_wait_seconds": 3.0,
|
||||
"desktop_icon_x": 153,
|
||||
"desktop_icon_y": 260,
|
||||
"yanghao_fallback_live_x": 540,
|
||||
"yanghao_fallback_live_y": 2000,
|
||||
"yanghao_fallback_enter_live_x": 540,
|
||||
"yanghao_fallback_enter_live_y": 1200,
|
||||
"fudai_find_max_attempts": 99999,
|
||||
"fudai_icon_max_wait_seconds": 7.0,
|
||||
"fudai_icon_retry_delay_seconds": 0.1,
|
||||
"fudai_exit_after_misses": 7,
|
||||
"enable_back_on_misses": false,
|
||||
"fudai_click_wait_seconds": 1.5,
|
||||
"fudai_detail_initial_wait_seconds": 0.8,
|
||||
"fudai_detail_verified_wait_seconds": 0.2,
|
||||
"fudai_detail_retry_delay_seconds": 0.5,
|
||||
"fudai_detail_save_debug_images": true,
|
||||
"fudai_detail_ui_mode": "auto",
|
||||
"fudai_detail_ocr_content_enabled": true,
|
||||
"fudai_detail_ocr_value_enabled": true,
|
||||
"fudai_detail_ocr_countdown_enabled": true,
|
||||
"fudai_detail_ocr_task_enabled": true,
|
||||
"fudai_detail_ocr_task_count_enabled": true,
|
||||
"fudai_detail_ocr_button_enabled": true,
|
||||
"fudai_detail_ocr_participants_enabled": false,
|
||||
"fudai_detail_ocr_live_title_enabled": true,
|
||||
"pixel_detect_fudai_icon_enabled": true,
|
||||
"pixel_detect_coupon_popup_enabled": true,
|
||||
"pixel_detect_shopping_redpacket_enabled": true,
|
||||
"pixel_detect_lottery_result_enabled": true,
|
||||
"pixel_detect_attend_button_enabled": true,
|
||||
"pixel_detect_fansclub_join_enabled": true,
|
||||
"pixel_detect_fudai_detail_enabled": true,
|
||||
"pixel_detect_live_room_enabled": true,
|
||||
"ocr_lottery_result_enabled": true,
|
||||
"ocr_coupon_popup_enabled": true,
|
||||
"ocr_shopping_redpacket_enabled": false,
|
||||
"ocr_stage_page_enabled": true,
|
||||
"fudai_disable_content_recognition": false,
|
||||
"fudai_disable_task_recognition": false,
|
||||
"yanghao_recommend_duration_seconds": 180,
|
||||
"yanghao_recommend_interval_seconds": 600,
|
||||
"yanghao_like_prob": 0.1,
|
||||
"yanghao_fav_prob": 0.05,
|
||||
"yanghao_comment_prob": 0.25,
|
||||
"yanghao_icon_roi_size": 240,
|
||||
"yanghao_icon_match_threshold": 0.77,
|
||||
"yanghao_step_screenshot": true,
|
||||
"yanghao_like_roi_offset_x": 0,
|
||||
"yanghao_like_roi_offset_y": -50,
|
||||
"yanghao_like_roi_scale": 1.0,
|
||||
"yanghao_fav_roi_offset_x": 40,
|
||||
"yanghao_fav_roi_offset_y": 0,
|
||||
"yanghao_fav_roi_scale": 1.0,
|
||||
"yanghao_like_rect_x1": 933,
|
||||
"yanghao_like_rect_y1": 1164,
|
||||
"yanghao_like_rect_x2": 1042,
|
||||
"yanghao_like_rect_y2": 1262,
|
||||
"yanghao_fav_rect_x1": 938,
|
||||
"yanghao_fav_rect_y1": 1567,
|
||||
"yanghao_fav_rect_x2": 1036,
|
||||
"yanghao_fav_rect_y2": 1665,
|
||||
"contains_want": [],
|
||||
"contains_not_want": [
|
||||
"首饰盒",
|
||||
"袜子"
|
||||
],
|
||||
"fudai_quiet_hours_enabled": true,
|
||||
"fudai_quiet_start_hour": 2,
|
||||
"fudai_quiet_end_hour": 9,
|
||||
"yanghao_enabled": false,
|
||||
"yanghao_enable_actions": true,
|
||||
"yanghao_like_icon_x": 988,
|
||||
"yanghao_like_icon_y": 1218,
|
||||
"yanghao_fav_icon_x": 988,
|
||||
"yanghao_fav_icon_y": 1616,
|
||||
"yanghao_like_template_path": "assets/like.png",
|
||||
"yanghao_fav_template_path": "assets/fav.png",
|
||||
"yanghao_after_dwell_swipe_direction": "up",
|
||||
"yanghao_after_dwell_swipe_distance_px": 900,
|
||||
"yanghao_comment_btn_x": 988,
|
||||
"yanghao_comment_btn_y": 1410,
|
||||
"yanghao_dwell_on_action_min_seconds": 5.0,
|
||||
"yanghao_dwell_on_action_max_seconds": 20.0,
|
||||
"yanghao_comment_input_x": 0,
|
||||
"yanghao_comment_input_y": 0,
|
||||
"yanghao_comment_send_x": 0,
|
||||
"yanghao_comment_send_y": -1,
|
||||
"yanghao_comment_close_x": 0,
|
||||
"yanghao_comment_close_y": 0,
|
||||
"yanghao_comment_texts": [
|
||||
"好看!",
|
||||
"赞一个",
|
||||
"真不错",
|
||||
"喜欢这个风格",
|
||||
"太棒了",
|
||||
"很有创意",
|
||||
"支持一下",
|
||||
"笑死我了",
|
||||
"学习了",
|
||||
"被圈粉了",
|
||||
"期待更多",
|
||||
"必须收藏",
|
||||
"这也太治愈了",
|
||||
"质量很高",
|
||||
"简直绝了",
|
||||
"画面太美了",
|
||||
"配色好舒服",
|
||||
"氛围感满分",
|
||||
"做得很用心",
|
||||
"好想试试这个",
|
||||
"安利给朋友",
|
||||
"收藏备用",
|
||||
"太有意思了",
|
||||
"这音乐选得太绝",
|
||||
"太会了",
|
||||
"入坑了",
|
||||
"好惊喜",
|
||||
"真有参考价值",
|
||||
"好暖心的一条",
|
||||
"笑哭,我服了",
|
||||
"细节处理得很好",
|
||||
"太有才了",
|
||||
"看着就治愈",
|
||||
"学习到新方法",
|
||||
"大家都来看看",
|
||||
"点赞支持",
|
||||
"完美",
|
||||
"好看到不行"
|
||||
],
|
||||
"yanghao_like_keywords": [],
|
||||
"yanghao_fav_keywords": [],
|
||||
"stage_diag_max_time": 2.0,
|
||||
"stage_diag_max_step_time": 0.5,
|
||||
"live_room_match_threshold": 0.8,
|
||||
"enable_ocr_mode1": false,
|
||||
"fudai_template_match_enabled": false,
|
||||
"fudai_template_match_threshold": 0.7,
|
||||
"lucky_draw_red_ratio_threshold": 0.8,
|
||||
"shopping_redpacket_red_ratio_threshold": 0.2,
|
||||
"y_pianyi": 0,
|
||||
"skip_if_countdown_lt_seconds": 5,
|
||||
"no_attend_timeout_minutes": 30.0,
|
||||
"logging": {
|
||||
"level": "DEBUG",
|
||||
"file_path": "logs/unified.log",
|
||||
"keep_days": 1,
|
||||
"use_dated_logs": true,
|
||||
"rotation": {
|
||||
"enabled": true,
|
||||
"max_bytes": 10485760,
|
||||
"backup_count": 5,
|
||||
"when": "midnight",
|
||||
"interval": 1
|
||||
},
|
||||
"beautify_output": true,
|
||||
"show_timestamps": true,
|
||||
"show_execution_times": true,
|
||||
"debug_detail_level": "normal",
|
||||
"error_detail_level": "full",
|
||||
"action_log_format": "concise",
|
||||
"log_format_mode": "simple",
|
||||
"stage_diag_verbose": true,
|
||||
"color_output": true,
|
||||
"max_log_lines_display": 1000,
|
||||
"auto_scroll_logs": true,
|
||||
"performance_tracking": {
|
||||
"enabled": true,
|
||||
"track_function_calls": true,
|
||||
"track_database_queries": false,
|
||||
"slow_operation_threshold_ms": 100
|
||||
},
|
||||
"error_logging": {
|
||||
"capture_stack_traces": true,
|
||||
"include_context": true,
|
||||
"max_error_logs": 1000,
|
||||
"error_categories": [
|
||||
"ocr",
|
||||
"network",
|
||||
"validation",
|
||||
"system",
|
||||
"user_action"
|
||||
]
|
||||
},
|
||||
"compress_logs": true,
|
||||
"max_total_size_gb": 0.2,
|
||||
"compress_after_days": 1,
|
||||
"max_bytes": 104857600,
|
||||
"backup_count": 10,
|
||||
"enable_monitor": true,
|
||||
"monitor_warning_mb": 60.0,
|
||||
"monitor_critical_mb": 200.0
|
||||
},
|
||||
"debug_captures": {
|
||||
"enabled": true,
|
||||
"keep_days": 1,
|
||||
"max_files": 1000,
|
||||
"auto_cleanup": true,
|
||||
"async_save": false,
|
||||
"log_on_complete": false
|
||||
},
|
||||
"fudai_detail_template_threshold": 0.52,
|
||||
"switch_room_wait_after_stage_diag_seconds": 7.5,
|
||||
"coupon_template_match_threshold": 0.35,
|
||||
"attend_button_red_ratio_threshold": 0.25,
|
||||
"fansclub_join_red_ratio_threshold": 0.25,
|
||||
"shopping_redpacket_ocr_confidence_threshold": 0.35,
|
||||
"reservation_test_mode": false,
|
||||
"swipe_duration_ms": 250,
|
||||
"gui": {
|
||||
"theme": "litera",
|
||||
"realtime_status": {
|
||||
"refresh_interval_ms": 1000,
|
||||
"tail_items": 50
|
||||
}
|
||||
},
|
||||
"fansclub_click_delay": 0.6,
|
||||
"fansclub_auto_join_wait_seconds": 5.0,
|
||||
"fansclub_manual_wait_seconds": 3.0,
|
||||
"enable_streaming_screenshot": false,
|
||||
"yanghao_only": false,
|
||||
"record_room_title_mapping_enabled": true,
|
||||
"high_value_fudai_poll_before_seconds": 10.0,
|
||||
"high_value_room_revisit_min_interval_seconds": 300,
|
||||
"high_value_room_revisit_max_per_run": 20,
|
||||
"high_value_room_revisit_min_prize_value": 1000.0,
|
||||
"high_value_room_revisit_max_age_days": 1,
|
||||
"swipe_up_start_y": 1200,
|
||||
"swipe_up_end_y": 600,
|
||||
"swipe_down_back_enabled": false,
|
||||
"swipe_down_back_count": 3,
|
||||
"log_unified_enabled": true,
|
||||
"log_unified_path": "logs/unified.log",
|
||||
"region_coords_edit_enabled": false,
|
||||
"fudai_detail_body_bluepurple_threshold": 0.45,
|
||||
"fudai_detail_body_dark_threshold": 0.35,
|
||||
"fudai_task_status_template_threshold": 0.26,
|
||||
"fudai_detail_regions": {
|
||||
"legacy": {
|
||||
"content": [
|
||||
389,
|
||||
1273,
|
||||
1000,
|
||||
1534
|
||||
],
|
||||
"value": [
|
||||
643,
|
||||
1466,
|
||||
769,
|
||||
1656
|
||||
],
|
||||
"countdown_full": [
|
||||
390,
|
||||
1110,
|
||||
690,
|
||||
1230
|
||||
],
|
||||
"task_list": [
|
||||
50,
|
||||
1621,
|
||||
1032,
|
||||
1960
|
||||
],
|
||||
"task_count": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"participants": [
|
||||
389,
|
||||
1273,
|
||||
1000,
|
||||
1534
|
||||
],
|
||||
"button": [
|
||||
306,
|
||||
2030,
|
||||
780,
|
||||
2180
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
},
|
||||
"v2_0_two_task": {
|
||||
"content": [
|
||||
360,
|
||||
1410,
|
||||
1035,
|
||||
1495
|
||||
],
|
||||
"value": [
|
||||
300,
|
||||
1585,
|
||||
650,
|
||||
1685
|
||||
],
|
||||
"countdown_full": [
|
||||
760,
|
||||
1328,
|
||||
1038,
|
||||
1398
|
||||
],
|
||||
"task_list": [
|
||||
60,
|
||||
1840,
|
||||
1030,
|
||||
2005
|
||||
],
|
||||
"task_count": [
|
||||
860,
|
||||
1770,
|
||||
1035,
|
||||
1875
|
||||
],
|
||||
"participants": [
|
||||
520,
|
||||
1325,
|
||||
760,
|
||||
1415
|
||||
],
|
||||
"button": [
|
||||
70,
|
||||
2020,
|
||||
1010,
|
||||
2165
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
},
|
||||
"v2_0_one_task": {
|
||||
"content": [
|
||||
360,
|
||||
1460,
|
||||
1035,
|
||||
1545
|
||||
],
|
||||
"value": [
|
||||
350,
|
||||
1640,
|
||||
760,
|
||||
1735
|
||||
],
|
||||
"countdown_full": [
|
||||
700,
|
||||
1390,
|
||||
990,
|
||||
1470
|
||||
],
|
||||
"info_line": [
|
||||
430,
|
||||
1315,
|
||||
1055,
|
||||
1435
|
||||
],
|
||||
"task_list": [
|
||||
61,
|
||||
1845,
|
||||
885,
|
||||
2005
|
||||
],
|
||||
"task_count": [
|
||||
889,
|
||||
1855,
|
||||
1040,
|
||||
1960
|
||||
],
|
||||
"participants": [
|
||||
516,
|
||||
1396,
|
||||
743,
|
||||
1443
|
||||
],
|
||||
"button": [
|
||||
70,
|
||||
2050,
|
||||
1010,
|
||||
2195
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
}
|
||||
},
|
||||
"pixel_regions": {
|
||||
"lottery_result": {
|
||||
"button": [
|
||||
250,
|
||||
1275,
|
||||
825,
|
||||
1435
|
||||
],
|
||||
"pixel": [
|
||||
290,
|
||||
1300,
|
||||
790,
|
||||
1415
|
||||
],
|
||||
"click": [
|
||||
540,
|
||||
1360,
|
||||
0,
|
||||
0
|
||||
]
|
||||
},
|
||||
"attend_button": [
|
||||
200,
|
||||
2000,
|
||||
880,
|
||||
2120
|
||||
],
|
||||
"fansclub_join": [
|
||||
200,
|
||||
1940,
|
||||
880,
|
||||
2140
|
||||
],
|
||||
"coupon_popup": [
|
||||
9,
|
||||
1173,
|
||||
1079,
|
||||
2255
|
||||
],
|
||||
"shopping_redpacket": [
|
||||
200,
|
||||
300,
|
||||
880,
|
||||
1400
|
||||
],
|
||||
"fudai_detail_body": [
|
||||
0,
|
||||
1160,
|
||||
1080,
|
||||
2250
|
||||
],
|
||||
"fudai_task_status": [
|
||||
820,
|
||||
1815,
|
||||
1050,
|
||||
2035
|
||||
],
|
||||
"live_room_icon_bbox": [
|
||||
999,
|
||||
172,
|
||||
1028,
|
||||
202
|
||||
]
|
||||
},
|
||||
"license": {
|
||||
"activation_url": "https://dy.absfan.cn/api/v1/activate",
|
||||
"timeout_seconds": 10
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,272 @@
|
||||
# 全量安全审计报告(2026-06-28)
|
||||
|
||||
## 结论摘要
|
||||
|
||||
本次审计覆盖客户端授权、自动更新、差量更新、服务端卡密/API、后台发布、WebGUI、本地打包、CI/CD 和仓库敏感信息暴露面。总体判断:
|
||||
|
||||
- 授权与更新主链路已有基础可信链:服务端签名授权/更新 manifest,客户端只内置公钥并校验 manifest 签名与文件 SHA256 后再执行更新。
|
||||
- 当前最需要优先修的是服务端发布面与分发面:后台 token 权限过大、上传包一次性读入内存、下载包直出服务端。
|
||||
- WebGUI 默认本机监听、POST 有 CSRF、未授权时拦截运行类接口,基础边界合理;但安全响应头和 CSP 仍缺失。
|
||||
- 打包已包含 Cython/分发清单/新环境冒烟测试,但依赖安装仍是浮动版本,正式发布需要锁版本、记录 SBOM,并加入签名校验。
|
||||
|
||||
## 审计范围
|
||||
|
||||
- 服务端:`license_server/api.py`、`license_server/core.py`、`license_server/requirements.txt`、`license_server/docker-compose.yml`、`license_server/Dockerfile`
|
||||
- 客户端授权:`douyin/license/license_manager.py`、`douyin/license/public_key.py`
|
||||
- 自动更新:`douyin/updater/force_update.py`、`douyin/updater/bootstrap.py`、`tools/update_delta.py`
|
||||
- WebGUI:`gui/web_gui.py`、`gui/web_gui_pkg/*`、`webui/**/*`
|
||||
- 打包与 CI:`packaging/pyinstaller/build_windows.ps1`、`.github/workflows/windows-package-ci.yml`、`tools/ci/fresh_install_smoke.ps1`
|
||||
- 仓库敏感信息:源代码、文档、测试、配置模板,排除 `artifacts/`、`dist/`、`build/`、`output/`、`logs/` 等生成物。
|
||||
|
||||
## 高风险
|
||||
|
||||
### H1. 后台发布权限仍集中在单个 admin token
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:118-139` 中 `_admin_allowed()` 接受三种管理员凭据:Session Cookie、`Bearer <token>`、Basic Auth 密码。
|
||||
- `license_server/api.py:823-873` 的全量包和差量包发布接口只要通过管理员鉴权和 CSRF 即可发布更新。
|
||||
|
||||
影响:
|
||||
|
||||
- 一旦 `DYGJ_LICENSE_ADMIN_TOKEN` 泄露,攻击者可以发布全量安装包或差量包。
|
||||
- 现有 manifest 签名能防止“客户端绕过服务端伪造更新”,但不能防止“拿到后台权限后用合法服务端签名发布恶意更新”。
|
||||
|
||||
建议:
|
||||
|
||||
- 立即轮换历史 admin token,清理桌面、聊天临时目录、部署机器 shell history 中的明文 token。
|
||||
- 将“登录后台”和“发布更新”拆成两级权限:普通后台 token 不能发布更新,发布更新需要短时一次性 publish token 或 TOTP。
|
||||
- 发布接口加 IP 白名单、审计日志、版本回滚记录和人工确认。
|
||||
- 正式包必须做 Authenticode 签名,客户端启动安装器前校验发行者证书指纹。
|
||||
|
||||
### H2. 后台上传全量包/差量包会一次性读入内存
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:835` 对安装包执行 `content = await installer.read()`。
|
||||
- `license_server/api.py:862` 对差量包执行 `content = await delta_file.read()`。
|
||||
- `license_server/core.py:555-588` 的 `publish_update()` 接收完整 `bytes` 后写盘。
|
||||
- `license_server/core.py:590-624` 的 `publish_delta_update()` 同样接收完整 `bytes` 后写盘。
|
||||
|
||||
影响:
|
||||
|
||||
- 大文件或异常 multipart 请求会直接放大服务端内存压力。
|
||||
- 管理员误操作、token 泄露或代理层限流配置缺失时,容易造成授权服务器不可用。
|
||||
|
||||
建议:
|
||||
|
||||
- 上传接口加显式大小上限,例如全量包 500MB、差量包 200MB,超限立即拒绝。
|
||||
- 改成流式写入临时文件,并边写边计算 SHA256。
|
||||
- 反向代理加 `client_max_body_size` / request body size limit。
|
||||
- 发布前校验文件类型、扩展名、hash、版本号和可执行文件签名。
|
||||
|
||||
### H3. 更新包下载由授权服务直接 `FileResponse` 暴露
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:681-698` 使用 `FileResponse` 直接返回全量包或差量包。
|
||||
- `license_server/api.py:686-690` 已限制只能下载当前 manifest 允许的文件名,这是正向控制。
|
||||
|
||||
影响:
|
||||
|
||||
- 安装包/差量包通常较大,未加下载鉴权、限速或 CDN 时,服务端可被下载流量拖垮。
|
||||
- Starlette `FileResponse` 是真实攻击面。外部公告显示,历史上 Starlette `FileResponse` Range 处理出现过 CPU DoS(CVE-2025-62727,修复于 0.49.1),multipart/form-data 也出现过内存 DoS(CVE-2024-47874,修复于 0.40.0)。
|
||||
- 当前本机 Starlette 为 `1.3.1`,不落在上述受影响范围内;但生产环境如果不锁版本,仍存在依赖漂移和部署不可复现风险。
|
||||
|
||||
建议:
|
||||
|
||||
- 更新包放对象存储/CDN,授权服务只签发短期下载 URL。
|
||||
- 服务端保留 manifest 和授权 API,不承担大文件分发。
|
||||
- 若继续直出文件,固定 `starlette>=0.49.1`,并在依赖扫描中阻断已知 CVE。
|
||||
|
||||
## 中风险
|
||||
|
||||
### M1. 生产环境 Host header 仍依赖配置自觉
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:245-249`:未设置 `DYGJ_LICENSE_PUBLIC_BASE_URL` 时,manifest 下载 URL 从 `request.base_url` 推导。
|
||||
- `license_server/api.py:484-499`:创建 FastAPI app 时未添加 `TrustedHostMiddleware`。
|
||||
|
||||
影响:
|
||||
|
||||
- 如果生产代理透传恶意 Host,且未配置 `DYGJ_LICENSE_PUBLIC_BASE_URL`,生成的 manifest 下载链接可能被 Host header 污染。
|
||||
- 客户端有 HTTPS、同源、签名和 SHA256 校验,能降低恶意包执行风险;但错误下载源仍会造成更新失败或服务可用性问题。
|
||||
|
||||
建议:
|
||||
|
||||
- 生产环境强制要求 `DYGJ_LICENSE_PUBLIC_BASE_URL`,缺失即启动失败。
|
||||
- 加 `TrustedHostMiddleware`,只允许正式域名和本地健康检查域名。
|
||||
- 在部署文档中明确 Nginx/Cloudflare 的 Host 转发策略。
|
||||
|
||||
### M2. 管理后台 Cookie 默认未开启 Secure
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:495` 中 `DYGJ_LICENSE_SECURE_COOKIES` 默认值为 `False`。
|
||||
- `license_server/api.py:706-712` 和 `license_server/api.py:733-740` 根据该开关设置 CSRF Cookie 和后台 Session Cookie 的 `secure`。
|
||||
|
||||
影响:
|
||||
|
||||
- 生产 HTTPS 场景如果忘记设置环境变量,后台 Cookie 不带 Secure 标记。
|
||||
- `HttpOnly` 和 `SameSite=Lax` 已存在,风险主要来自生产配置遗漏。
|
||||
|
||||
建议:
|
||||
|
||||
- 生产模式默认 Secure=true,开发模式才允许关闭。
|
||||
- 启动时检测 `DYGJ_LICENSE_PUBLIC_BASE_URL` 为 `https://` 时强制 Secure Cookie。
|
||||
|
||||
### M3. 客户端执行安装器前缺少 Authenticode 校验
|
||||
|
||||
证据:
|
||||
|
||||
- `douyin/updater/force_update.py:143-158` 会校验 manifest 签名。
|
||||
- `douyin/updater/force_update.py:556-566` 校验安装包 SHA256 后直接构造命令并启动安装器。
|
||||
- 当前未看到对 Windows Authenticode 签名、发行者证书指纹或时间戳的校验。
|
||||
|
||||
影响:
|
||||
|
||||
- SHA256 只能证明“下载到的文件与签名 manifest 中声明一致”。
|
||||
- 如果服务端私钥或发布后台被攻破,攻击者仍可能发布一个“合法签名 manifest + 恶意 exe”。
|
||||
|
||||
建议:
|
||||
|
||||
- 正式发布包使用 Authenticode 签名。
|
||||
- 客户端在 `launch_installer()` 前验证 exe 签名主体和证书指纹。
|
||||
- CI/CD 记录签名证书指纹、安装包 SHA256 和 SBOM。
|
||||
|
||||
### M4. 差量更新应用脚本缺少二次解包后校验
|
||||
|
||||
证据:
|
||||
|
||||
- `douyin/updater/force_update.py:318-356` 下载后会校验差量包 manifest、文件路径和每个文件 SHA256。
|
||||
- `douyin/updater/force_update.py:434-463` 真正应用更新时,PowerShell `Expand-Archive` 后直接按 manifest 删除/复制文件。
|
||||
|
||||
影响:
|
||||
|
||||
- 主进程校验和应用更新是两个阶段,中间若本地文件被替换,应用脚本不会再次校验。
|
||||
- 对普通用户机器来说攻击门槛较高,但对本地恶意软件或被篡改的更新目录仍是风险点。
|
||||
|
||||
建议:
|
||||
|
||||
- 在 PowerShell 应用脚本里二次校验 delta zip SHA256,解包后再校验 manifest 中每个文件 SHA256。
|
||||
- 应用前将 `$root`、`$work`、目标路径做规范化并确认都在安装目录内。
|
||||
|
||||
### M5. WebGUI 缺少安全响应头和 CSP
|
||||
|
||||
证据:
|
||||
|
||||
- `gui/web_gui_pkg/static_handler.py:67-73` 只设置 `Content-Type`、`Content-Length`、`Cache-Control`、`ETag`。
|
||||
- `gui/web_gui_pkg/routes.py:161-169` GET API 仅允许本机访问并暴露 CSRF token。
|
||||
- `gui/web_gui_pkg/routes.py:389-399` POST API 有本机限制、CSRF 校验和授权门禁。
|
||||
|
||||
影响:
|
||||
|
||||
- WebGUI 默认 `127.0.0.1` 监听,且 POST 有 CSRF,基础边界是好的。
|
||||
- 但没有 `Content-Security-Policy`、`X-Content-Type-Options`、`Referrer-Policy` 等安全头;一旦未来某个日志/接口字段进入 DOM 时漏转义,XSS 的后果会扩大到本机控制面。
|
||||
|
||||
建议:
|
||||
|
||||
- 给 HTML/JS 响应加安全头:`X-Content-Type-Options: nosniff`、`Referrer-Policy: no-referrer`、最小 CSP。
|
||||
- 逐步减少内联脚本,或者使用 nonce/hash CSP。
|
||||
|
||||
## 低风险与观察项
|
||||
|
||||
### L1. 前端使用 `innerHTML` 较多,但核心动态数据大多已转义
|
||||
|
||||
证据:
|
||||
|
||||
- `webui/js/dom_utils.js:83-90` 提供 `escapeHtml()`。
|
||||
- `webui/js/runtime_actions.js:318-325`、`360-372`、`441-454` 对直播间、内容、原因等 API 字段使用 `escapeHtml()`。
|
||||
- `webui/js/dashboard_renderers.js:65-110` 对榜单 key、中奖内容、时间和值做了转义。
|
||||
- `license_server/api.py:667` 的兑换页把 `data.card_key` 拼入 `innerHTML`,卡密格式由服务端生成,当前风险较低。
|
||||
|
||||
建议:
|
||||
|
||||
- 新增 ESLint/简单 grep 门禁:所有拼接 API 数据的 `innerHTML` 必须经过 `escapeHtml()` 或改用 `textContent`。
|
||||
- 兑换页成功展示卡密可改为创建 `code` 节点并设置 `textContent`。
|
||||
|
||||
### L2. CI/CD 依赖安装未锁定 hash
|
||||
|
||||
证据:
|
||||
|
||||
- `.github/workflows/windows-package-ci.yml:42-44` 使用 `pip install -r requirements.txt` 和未固定的 `pyinstaller cython setuptools wheel`。
|
||||
- `packaging/pyinstaller/build_windows.ps1:31-38` 本地打包也会安装浮动版本依赖。
|
||||
- `license_server/requirements.txt:1-4` 使用 `>=` 范围。
|
||||
|
||||
影响:
|
||||
|
||||
- 复用缓存打包时结果可能随 PyPI 最新版本变化。
|
||||
- 安全修复会自动进来,但也可能引入供应链回归或打包不一致。
|
||||
|
||||
建议:
|
||||
|
||||
- 增加 `requirements-lock.txt` / `constraints.txt`,正式打包用锁定版本。
|
||||
- CI 增加 `pip-audit` 或 GitHub Dependabot,发现高危 CVE 直接失败。
|
||||
- 发布产物附带 SBOM、SHA256 和构建日志。
|
||||
|
||||
### L3. 仓库未发现真实私钥明文,但历史 token 文档仍提示需要清理本机副本
|
||||
|
||||
证据:
|
||||
|
||||
- 敏感信息扫描未发现真实生产私钥 PEM;测试私钥仅在 `tests/` 中使用。
|
||||
- `license_server/api.py:86-93` 生产私钥从环境变量或服务器文件读取。
|
||||
- 旧审计文档中记录过桌面存在多个 admin token 明文副本,需要按运维动作清理。
|
||||
|
||||
建议:
|
||||
|
||||
- 本机和服务器执行 token 文件清理,并确认 `.gitignore` 覆盖 `secrets/`、`*.pem`、`admin_token*.txt`。
|
||||
- 把生产 secret 全部放服务器 secret 管理或部署平台环境变量,不放桌面、微信临时目录和仓库。
|
||||
|
||||
## 已有保护点
|
||||
|
||||
- 授权文件签名:`license_server/core.py:872-889` 服务端签名授权,客户端使用公钥验签。
|
||||
- 机器码只保存 hash:`douyin/license/license_manager.py:66-76` 本机指纹 hash 化。
|
||||
- 在线复核:`douyin/license/license_manager.py:260-340` 使用服务器状态复核本地授权。
|
||||
- 更新 manifest 签名:`license_server/core.py:656-658` 服务端签名,`douyin/updater/force_update.py:143-158` 客户端验签。
|
||||
- 更新下载约束:`douyin/updater/force_update.py:212-237` 要求 HTTPS 和同源,除非配置允许跨源。
|
||||
- 更新文件完整性:`douyin/updater/force_update.py:547-563` 校验全量包 SHA256,`318-356` 校验差量包路径和文件 SHA256。
|
||||
- WebGUI 本机限制与 CSRF:`gui/web_gui_pkg/routes.py:57-62`、`389-399`。
|
||||
- 首次授权门禁:`gui/web_gui.py:912-918` 未授权时不直接进入运行态,`tools/ci/fresh_install_smoke.ps1:180-239` 已覆盖新环境授权门禁冒烟。
|
||||
- 打包分发清单:`packaging/pyinstaller/build_windows.ps1:55-63` 默认 Cython/PyArmor staging,`270-287` 执行 distribution manifest 检查。
|
||||
|
||||
## 依赖与外部公告核对
|
||||
|
||||
本机当前版本:
|
||||
|
||||
- `fastapi==0.137.2`
|
||||
- `starlette==1.3.1`
|
||||
- `uvicorn==0.49.0`
|
||||
- `python-multipart==0.0.32`
|
||||
- `cryptography==47.0.0`
|
||||
- `PyInstaller==6.12.0`
|
||||
|
||||
外部公告核对:
|
||||
|
||||
- Starlette multipart/form-data DoS:GHSA-f96h-pmfr-66vw / CVE-2024-47874,Starlette `0.40.0` 修复。
|
||||
- Starlette FileResponse Range DoS:GHSA-7f5h-v6xp-fcq8 / CVE-2025-62727,Starlette `0.49.1` 修复。
|
||||
- 当前本机 Starlette `1.3.1` 高于上述修复版本;生产仍建议锁版本并加入自动漏洞扫描。
|
||||
|
||||
## 修复优先级
|
||||
|
||||
1. 轮换 admin token,清理本机和服务器明文 token,后台发布增加二次授权。
|
||||
2. 上传接口改流式写入并加大小限制,反向代理同步限流。
|
||||
3. 更新包改 CDN/对象存储分发,授权服务只发短期 URL。
|
||||
4. 正式包 Authenticode 签名,客户端校验证书指纹后再启动安装器。
|
||||
5. 生产强制 `DYGJ_LICENSE_PUBLIC_BASE_URL`、`TrustedHostMiddleware`、Secure Cookie。
|
||||
6. WebGUI 加安全响应头和 CSP,继续收敛 `innerHTML`。
|
||||
7. CI/CD 增加锁版本、SBOM、pip-audit/Dependabot。
|
||||
|
||||
## 本次验证
|
||||
|
||||
- `git status --short --branch`:工作区除用户本地 `config/config.json` 外无其他未提交改动。
|
||||
- 静态证据扫描:授权、服务端 API、更新、WebGUI、打包、CI 均完成。
|
||||
- 敏感信息扫描:未发现生产私钥 PEM;扫描到的 `secret` 主要位于测试用例和历史审计文档。
|
||||
- 依赖版本核对:本机 Starlette/FastAPI 版本高于已核对 Starlette DoS 修复版本。
|
||||
|
||||
## 参考资料
|
||||
|
||||
- GitHub Advisory:Starlette multipart/form-data DoS,GHSA-f96h-pmfr-66vw,https://github.com/advisories/GHSA-f96h-pmfr-66vw
|
||||
- GitHub Advisory:Starlette FileResponse Range DoS,GHSA-7f5h-v6xp-fcq8,https://github.com/advisories/GHSA-7f5h-v6xp-fcq8
|
||||
- Starlette Release Notes,https://www.starlette.io/release-notes/
|
||||
- Starlette Responses 文档:`FileResponse` 支持 Range 请求,https://www.starlette.io/responses/
|
||||
@@ -0,0 +1,43 @@
|
||||
# 兑换链接安全复核 2026-06-24
|
||||
|
||||
## 结论
|
||||
|
||||
本次复核对象是闲鱼自动发货兑换链路:
|
||||
|
||||
- `POST /api/v1/redeem/external/create`
|
||||
- `GET /redeem`
|
||||
- `GET /redeem/{token}` 兼容旧链接
|
||||
- `POST /api/v1/redeem/claim`
|
||||
|
||||
线上域名:`https://dy.absfan.cn`。
|
||||
|
||||
## 已验证
|
||||
|
||||
- 外部创建接口必须使用 `Authorization: Bearer <DYGJ_LICENSE_EXTERNAL_API_TOKEN>`。
|
||||
- 外部创建接口只返回 `claim_url`,不返回真实 `DG-` 卡密。
|
||||
- 新 `claim_url` 使用 `/redeem#token`,token 位于 URL fragment,不进入服务器请求路径和 uvicorn 访问日志。
|
||||
- 兑换接口只允许同一 token 成功兑换一次;重复兑换返回 `409 already_redeemed`。
|
||||
- 并发兑换已用 SQLite `BEGIN IMMEDIATE` 加写锁,测试确认只会生成一张卡。
|
||||
- `/docs` 和 `/openapi.json` 线上返回 `404`。
|
||||
- 未授权创建返回 `403`,坏参数返回 `400`。
|
||||
- 兑换后的卡密可正常走 `/api/v1/activate`,授权文件可继续走 `/api/v1/verify_license`。
|
||||
|
||||
## 修复项
|
||||
|
||||
- 修复同一兑换 token 并发兑换可能生成多张卡的问题。
|
||||
- 为公开兑换接口增加限流:`REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS`。
|
||||
- 为外部创建接口鉴权失败增加独立限流:`EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS`。
|
||||
- 新生成兑换链接改为 `/redeem#token`,降低访问日志泄露 token 的概率。
|
||||
|
||||
## 验证证据
|
||||
|
||||
- 本地回归:`artifacts/redeem_security_full_tests_20260624.log`,结果 `PASS`。
|
||||
- 本地语法:`python -m py_compile license_server/core.py license_server/api.py douyin/license/license_manager.py`,结果 `PASS`。
|
||||
- 线上黑盒:`health=200`、`docs=404`、`openapi=404`、`no_auth=403`、`create=200`、`claim_first=200`、`claim_second=409`、`activate=200`。
|
||||
- 线上日志确认:`GET /redeem HTTP/1.1`,未记录 `/redeem/{token}`。
|
||||
|
||||
## 剩余建议
|
||||
|
||||
- `DYGJ_LICENSE_EXTERNAL_API_TOKEN` 应定期轮换,且只配置在自动发货服务器侧。
|
||||
- 如果后续员工/多个渠道并行发货,建议改成每个渠道独立 token,并在数据库记录 `platform`、`external_order_id`、请求 IP 和 staff/source 标识。
|
||||
- 如果订单量增大,建议在 1Panel/OpenResty 层再加 IP 级限流。
|
||||
@@ -0,0 +1,165 @@
|
||||
# 安全审计报告:服务器与反逆向
|
||||
|
||||
日期:2026-06-26
|
||||
范围:`license_server/` 授权与更新服务、在线差量/全量更新链路、V3.3.4 发布包反逆向与分发内容。
|
||||
|
||||
## 总体结论
|
||||
|
||||
当前授权服务不是裸奔:管理员后台有登录限流、CSRF、会话 Cookie;客户端更新默认启用 HTTPS、manifest 签名和 SHA256 校验;V3.3.4 发布包通过了分发清单检查,核心逻辑已有 Cython `.pyd` 编译层。
|
||||
|
||||
但最值得优先处理的风险有两个:管理员 token 暴露后可直接发布任意 EXE 更新;更新安装包上传/下载缺少大文件资源控制。反逆向方面,现在属于“提高脚本级拆包成本”,还不是强对抗级保护。
|
||||
|
||||
## P1:必须优先处理
|
||||
|
||||
### 1. 管理员 token 本地副本过多,拿到 token 就等于拿到发布权
|
||||
|
||||
证据:
|
||||
- 本机桌面存在多个 token 文件:`C:\Users\12742\Desktop\douyin_admin_token.txt`、`C:\Users\12742\Desktop\douyin_admin_token_open.txt`、`C:\Users\12742\Desktop\douyin_admin_token_可打开.txt`。
|
||||
- 管理员鉴权使用单一 token:`license_server/api.py:101`、`license_server/api.py:118-135`。
|
||||
- 发布更新接口在管理员鉴权后直接接受 EXE 并写入 manifest:`license_server/api.py:795-818`、`license_server/core.py:532-562`。
|
||||
|
||||
影响:
|
||||
- 本机恶意软件、聊天软件临时目录泄露、误传文件,都可能让攻击者发布恶意更新。
|
||||
- 因客户端会信任服务端签名的 manifest,服务器发布权比普通卡密权限高很多。
|
||||
|
||||
建议:
|
||||
- 立刻轮换 `DYGJ_LICENSE_ADMIN_TOKEN`,删除桌面和聊天临时目录里的 token 明文副本。
|
||||
- 管理后台改为“短期会话 + 二次确认发布 + 可选 TOTP/一次性发布口令”。
|
||||
- 管理发布接口限制来源 IP,至少只允许固定办公 IP 或 VPN。
|
||||
- 发布动作记录操作者、IP、文件 SHA256、版本号,并保留不可覆盖审计日志。
|
||||
|
||||
### 2. 更新包上传一次性读入内存,缺少大小上限和流式写入
|
||||
|
||||
证据:
|
||||
- `license_server/api.py:809` 使用 `await installer.read()` 一次性读完整上传文件。
|
||||
- `license_server/core.py:537` 接收 `bytes`,`license_server/core.py:550` 直接 `write_bytes(content)`。
|
||||
- 当前正式安装包约 214 MB,已经是大对象。
|
||||
|
||||
影响:
|
||||
- 管理 token 被盗或后台被滥用时,可以上传超大文件造成内存/磁盘 DoS。
|
||||
- 即使没有被盗,误传错误文件也会把服务打满。
|
||||
|
||||
建议:
|
||||
- 服务端增加最大上传大小,例如 300 MB 或 500 MB,超限立即拒绝。
|
||||
- 改成分块读取、边写临时文件、边计算 SHA256,完成后再原子重命名。
|
||||
- Nginx/Caddy/Cloudflare 层设置请求体大小限制和上传超时。
|
||||
|
||||
### 3. 更新下载接口直出大文件,缺少下载限速/CDN/Range 滥用防护
|
||||
|
||||
证据:
|
||||
- `/api/v1/update/download/{filename}` 直接 `FileResponse` 返回安装包:`license_server/api.py:658-672`。
|
||||
- 已验证下载端点支持 Range,正式包体积约 214 MB。
|
||||
|
||||
影响:
|
||||
- 任意公网客户端都能拉取大文件,容易被刷带宽。
|
||||
- Range/并发下载可以把授权服务和更新服务一起拖慢。
|
||||
|
||||
建议:
|
||||
- 安装包放对象存储或 CDN,授权服务只签 manifest,不直接扛大文件流量。
|
||||
- 给下载接口加 IP 限流、并发限制、带宽限制。
|
||||
- 如果继续用 ASGI 直出文件,生产依赖必须锁定并定期更新 Starlette/FastAPI;Starlette 历史上出现过 `FileResponse` Range 资源耗尽类公告。
|
||||
|
||||
## P2:建议加固
|
||||
|
||||
### 4. 生产环境缺少强制 Host 白名单
|
||||
|
||||
证据:
|
||||
- `_public_base_url()` 未配置 `DYGJ_LICENSE_PUBLIC_BASE_URL` 时会回退到 `request.base_url`:`license_server/api.py:245-249`。
|
||||
- 当前代码没有看到 `TrustedHostMiddleware` 或等价 Host 白名单。
|
||||
|
||||
影响:
|
||||
- 如果生产环境漏配 `DYGJ_LICENSE_PUBLIC_BASE_URL`,错误 Host 头可能影响兑换链接或更新 URL 生成。
|
||||
|
||||
建议:
|
||||
- 生产强制配置 `DYGJ_LICENSE_PUBLIC_BASE_URL=https://dy.absfan.cn`。
|
||||
- 增加 `TrustedHostMiddleware`,只允许 `dy.absfan.cn` 和必要内网域名。
|
||||
|
||||
### 5. Cookie secure 默认关闭,生产 HTTPS 容易误配置
|
||||
|
||||
证据:
|
||||
- `DYGJ_LICENSE_SECURE_COOKIES` 默认值为 `False`:`license_server/api.py:472`。
|
||||
- CSRF 和后台 session cookie 都依赖该状态设置 `secure`:`license_server/api.py:680-686`、`license_server/api.py:707-711`。
|
||||
|
||||
影响:
|
||||
- HTTPS 生产环境如果忘记设置环境变量,后台 Cookie 不会带 Secure 标记。
|
||||
|
||||
建议:
|
||||
- 生产默认改为 Secure,只有本地开发显式关闭。
|
||||
- README 和部署脚本强制检查该环境变量。
|
||||
|
||||
### 6. 管理员 Basic/Bearer 兼容口仍保留,建议收窄
|
||||
|
||||
证据:
|
||||
- `_admin_allowed()` 同时接受 session、Bearer 和 Basic:`license_server/api.py:122-135`。
|
||||
|
||||
影响:
|
||||
- Header token 适合脚本,但也更容易进入命令历史、代理日志或调试日志。
|
||||
- 增加后台鉴权路径,后续维护更难保证所有入口策略一致。
|
||||
|
||||
建议:
|
||||
- 默认只保留网页登录 session;CLI 发布单独走短期一次性 token。
|
||||
- 如果必须保留 Bearer,限制到内网/VPN,并要求 CSRF 或发布专用 nonce。
|
||||
|
||||
### 7. 更新执行链缺少安装包 Authenticode 发布者校验
|
||||
|
||||
证据:
|
||||
- 客户端更新流程会验证 manifest 签名和 SHA256:`douyin/updater/force_update.py:347-378`。
|
||||
- 通过后直接启动下载的 installer:`douyin/updater/force_update.py:380-381`。
|
||||
|
||||
影响:
|
||||
- 当前信任根主要是服务端 manifest 私钥和后台发布权。
|
||||
- 一旦服务器私钥或发布权泄露,客户端无法再用 Windows 发布者签名做第二道拦截。
|
||||
|
||||
建议:
|
||||
- 给正式安装包做 Authenticode 代码签名。
|
||||
- 客户端启动安装器前校验签名发布者或证书指纹。
|
||||
|
||||
### 8. 服务器依赖没有锁定精确版本
|
||||
|
||||
证据:
|
||||
- `license_server/requirements.txt` 使用 `fastapi>=0.124.0`、`uvicorn[standard]>=0.38.0`、`cryptography>=41.0.0`。
|
||||
- 当前本机运行版本:FastAPI `0.137.2`,Starlette `1.3.1`。
|
||||
|
||||
影响:
|
||||
- 生产重装时可能拿到未经本项目验证的新版本,也可能因为旧环境没有升级而继续运行旧版本。
|
||||
|
||||
建议:
|
||||
- 为服务器单独生成锁定文件,例如 `requirements-server.lock.txt`。
|
||||
- 发布服务端时记录 `pip freeze` 和镜像 digest。
|
||||
|
||||
## P3:反逆向现状与后续增强
|
||||
|
||||
### 已有保护
|
||||
|
||||
- 构建脚本默认走 Cython staging,除非显式传 `-NoCythonForDevOnly` 或 `-NoObfuscateForDevOnly`:`packaging/pyinstaller/build_windows.ps1:4-6`、`packaging/pyinstaller/build_windows.ps1:54-61`。
|
||||
- 默认编译核心包:`douyin/fudai`、`douyin/reservation`、`douyin/detection`、`douyin/stage`:`tools/cython_staging.py:16-21`。
|
||||
- 发布包分发清单阻止项目源码、日志、调试图和多余文件混入:`tools/distribution_manifest.py:120-155`。
|
||||
- V3.3.4 发布目录检查通过:`logs/security_dist_manifest_check_2026-06-26.log`。
|
||||
- V3.3.4 发布目录未发现项目核心 `.py` 源码混入;核心路径下 `.pyd` 数量为 93。
|
||||
- 发布目录未发现私钥、管理员 token、项目私密 pem;只看到第三方 CA bundle:`_internal/certifi/cacert.pem`。
|
||||
|
||||
### 仍然薄弱
|
||||
|
||||
- GUI 与 WebUI 代码按当前策略仍更多是普通 PyInstaller/PYZ 层,不能按强混淆理解。
|
||||
- Python/Cython `.pyd` 可以被逆向分析,只是成本高于纯 `.py`。
|
||||
- 客户端公钥是公开的,这是正确设计;但协议、接口、版本更新逻辑仍能被静态分析。
|
||||
- 没有运行时完整性校验、调试器检测、虚拟机/注入检测或关键路径反篡改。
|
||||
|
||||
建议:
|
||||
- 短期:正式包固定使用 Cython,不允许 `-NoCythonForDevOnly`;发布前自动跑 `distribution_manifest`。
|
||||
- 中期:把授权校验、更新校验、核心策略判断也纳入 Cython 或商业混淆。
|
||||
- 中期:增加运行时自校验,例如关键 `.pyd`/EXE 哈希校验和异常上报。
|
||||
- 长期:核心逻辑尽量服务端化,客户端只保留必要执行逻辑;反逆向不能替代服务端风控。
|
||||
|
||||
## 已验证通过项
|
||||
|
||||
- 管理员登录有限流:`license_server/api.py:693-700`。
|
||||
- 后台修改类表单有 CSRF 校验:`license_server/api.py:805-807`,创建/解绑/禁用也有同类校验。
|
||||
- 授权激活/验证/兑换接口有限流:`license_server/api.py:486-512`、`license_server/api.py:561-588`。
|
||||
- 服务端私钥没有内置到客户端;客户端只包含公钥:`douyin/license/public_key.py:1-9`。
|
||||
- 发布包分发清单 PASS:`logs/security_dist_manifest_check_2026-06-26.log`。
|
||||
|
||||
## 参考来源
|
||||
|
||||
- GitHub Security Advisory:Starlette `FileResponse` Range 资源耗尽类历史公告,`GHSA-f96h-pmfr-66vw` / `CVE-2024-47874`。
|
||||
- Starlette 官方文档:`TrustedHostMiddleware` 用于限制 Host header。
|
||||
@@ -265,6 +265,40 @@ def get_run_cli_command() -> list[str]:
|
||||
return [sys.executable, get_run_cli_path()]
|
||||
|
||||
|
||||
def get_bundled_platform_tools_dir() -> str:
|
||||
"""返回随包 Android platform-tools 目录。"""
|
||||
return os.path.join(PROJECT_ROOT, "platform-tools")
|
||||
|
||||
|
||||
def get_bundled_adb_path() -> str:
|
||||
"""返回随包 adb 路径。"""
|
||||
exe_name = "adb.exe" if sys.platform.startswith("win") else "adb"
|
||||
return os.path.join(get_bundled_platform_tools_dir(), exe_name)
|
||||
|
||||
|
||||
def find_bundled_adb() -> Optional[str]:
|
||||
"""若分发包内自带 adb,返回其绝对路径。"""
|
||||
candidates = [get_bundled_adb_path()]
|
||||
meipass = getattr(sys, "_MEIPASS", None)
|
||||
if meipass:
|
||||
exe_name = "adb.exe" if sys.platform.startswith("win") else "adb"
|
||||
candidates.append(os.path.join(str(meipass), "platform-tools", exe_name))
|
||||
for path in candidates:
|
||||
if os.path.exists(path):
|
||||
return os.path.abspath(path)
|
||||
return None
|
||||
|
||||
|
||||
def get_bundled_android_tools_dir() -> str:
|
||||
"""返回随包 Android 辅助工具目录。"""
|
||||
return os.path.join(PROJECT_ROOT, "android-tools")
|
||||
|
||||
|
||||
def get_bundled_adbkeyboard_apk_path() -> str:
|
||||
"""返回随包 ADBKeyboard APK 路径。"""
|
||||
return os.path.join(get_bundled_android_tools_dir(), "ADBKeyboard.apk")
|
||||
|
||||
|
||||
def ensure_dir(path: str) -> None:
|
||||
"""确保目录存在,不存在则创建"""
|
||||
dir_path = os.path.dirname(path) if os.path.isfile(path) else path
|
||||
|
||||
@@ -178,7 +178,7 @@ class underlying_operations:
|
||||
)
|
||||
@staticmethod
|
||||
def _adb() -> str:
|
||||
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
|
||||
adb = _impl_adb_path()
|
||||
# 始终加引号,避免路径带空格 / 版本混用
|
||||
if adb.startswith('"') and adb.endswith('"'):
|
||||
return adb
|
||||
|
||||
@@ -8,12 +8,18 @@ from __future__ import annotations
|
||||
import os
|
||||
from typing import List
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
|
||||
def _adb_path() -> str:
|
||||
"""返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)。"""
|
||||
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
|
||||
if adb.startswith('"') and adb.endswith('"'):
|
||||
adb = adb[1:-1]
|
||||
if adb == "adb":
|
||||
bundled_adb = path_config.find_bundled_adb()
|
||||
if bundled_adb:
|
||||
return bundled_adb
|
||||
return adb
|
||||
|
||||
|
||||
|
||||
@@ -28,10 +28,18 @@ if TYPE_CHECKING:
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
|
||||
|
||||
def _uo_log(msg: str) -> None:
|
||||
def _uo_log(msg: str, level: str = "INFO") -> None:
|
||||
"""与 underlying_operations._uo_log 一致:默认 INFO 级别。"""
|
||||
try:
|
||||
logging.info(msg)
|
||||
lv = str(level or "INFO").upper()
|
||||
if lv == "WARNING":
|
||||
logging.warning(msg)
|
||||
elif lv == "ERROR":
|
||||
logging.error(msg)
|
||||
elif lv == "DEBUG":
|
||||
logging.debug(msg)
|
||||
else:
|
||||
logging.info(msg)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -89,6 +97,66 @@ def _valid_png(path0: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _adb_shell_png_variants(data: bytes) -> list[bytes]:
|
||||
"""Return safe candidates for ``adb shell screencap -p`` stdout.
|
||||
|
||||
Some Android/Windows ADB combinations route shell stdout through a text-ish
|
||||
path and duplicate carriage returns in PNG line endings. Try the raw bytes
|
||||
first, then the common CRLF repairs without changing the primary exec-out
|
||||
path.
|
||||
"""
|
||||
if not data:
|
||||
return []
|
||||
variants: list[bytes] = []
|
||||
|
||||
def _add(candidate: bytes) -> None:
|
||||
if candidate and candidate not in variants:
|
||||
variants.append(candidate)
|
||||
|
||||
marker = b"\x89PNG"
|
||||
idx = data.find(marker)
|
||||
if idx > 0:
|
||||
data = data[idx:]
|
||||
|
||||
_add(data)
|
||||
_add(data.replace(b"\r\r\n", b"\r\n"))
|
||||
_add(data.replace(b"\r\n", b"\n"))
|
||||
return variants
|
||||
|
||||
|
||||
def _write_valid_png_bytes(tmp_file: str, data: bytes) -> bool:
|
||||
for candidate in _adb_shell_png_variants(data):
|
||||
try:
|
||||
with open(tmp_file, "wb", buffering=262144) as f:
|
||||
f.write(candidate)
|
||||
if _valid_png(tmp_file):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _stderr_tail(stderr: bytes | str | None, limit: int = 800) -> str:
|
||||
if stderr is None:
|
||||
return ""
|
||||
if isinstance(stderr, bytes):
|
||||
text = stderr.decode("utf-8", errors="replace")
|
||||
else:
|
||||
text = str(stderr)
|
||||
return text.strip()[-limit:]
|
||||
|
||||
|
||||
def _format_completed_error(error: subprocess.CalledProcessError) -> str:
|
||||
parts = [f"returncode={error.returncode}"]
|
||||
stderr = _stderr_tail(getattr(error, "stderr", None))
|
||||
stdout = _stderr_tail(getattr(error, "output", None))
|
||||
if stderr:
|
||||
parts.append(f"stderr={stderr}")
|
||||
if stdout:
|
||||
parts.append(f"stdout={stdout}")
|
||||
return ", ".join(parts)
|
||||
|
||||
|
||||
def capture_screenshot_direct(
|
||||
self: "underlying_operations", device_id, path: str = "pic"
|
||||
) -> bool:
|
||||
@@ -128,6 +196,61 @@ def capture_screenshot_direct(
|
||||
|
||||
adb = self._adb_path()
|
||||
|
||||
def _commit_valid_tmp(success_kind: str, start_ts: float) -> bool:
|
||||
if not _valid_png(tmp_file):
|
||||
return False
|
||||
if not _safe_replace_file(tmp_file, out_file):
|
||||
return False
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
if not _valid_png(out_file):
|
||||
return False
|
||||
overall_dur = (time_module.time() - overall_start) * 1000.0
|
||||
part_dur = (time_module.time() - start_ts) * 1000.0
|
||||
logging.info(
|
||||
"[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (%s成功, 回退部分耗时=%.1fms)",
|
||||
overall_dur,
|
||||
success_kind,
|
||||
part_dur,
|
||||
)
|
||||
return True
|
||||
|
||||
def _try_shell_stdout_fallback() -> bool:
|
||||
stdout_fallback_start = time_module.time()
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[adb, "-s", device_id, "shell", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=True,
|
||||
timeout=8,
|
||||
)
|
||||
if _write_valid_png_bytes(tmp_file, result.stdout or b""):
|
||||
return _commit_valid_tmp("shell stdout回退", stdout_fallback_start)
|
||||
try:
|
||||
size = len(result.stdout or b"")
|
||||
_uo_log(f"[截图] shell stdout回退输出无效:bytes={size}")
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
except subprocess.CalledProcessError as stdout_error:
|
||||
try:
|
||||
_uo_log(
|
||||
"[截图] shell stdout回退失败:" + _format_completed_error(stdout_error),
|
||||
"WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
except Exception as stdout_error:
|
||||
try:
|
||||
_uo_log(
|
||||
f"[截图] shell stdout回退失败:{type(stdout_error).__name__}: {stdout_error}",
|
||||
"WARNING",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
# 优先走 exec-out
|
||||
try:
|
||||
execout_timeout_sec = float(os.environ.get("ADB_EXECOUT_TIMEOUT_SEC", "10"))
|
||||
@@ -167,7 +290,7 @@ def capture_screenshot_direct(
|
||||
process = subprocess.Popen(
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
bufsize=0,
|
||||
)
|
||||
|
||||
@@ -206,7 +329,7 @@ def capture_screenshot_direct(
|
||||
except Exception:
|
||||
done_event = None
|
||||
|
||||
stdout_data, _ = process.communicate(timeout=execout_timeout_sec)
|
||||
stdout_data, stderr_data = process.communicate(timeout=execout_timeout_sec)
|
||||
if done_event is not None:
|
||||
done_event.set()
|
||||
|
||||
@@ -214,6 +337,8 @@ def capture_screenshot_direct(
|
||||
raise subprocess.CalledProcessError(
|
||||
process.returncode,
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
output=stdout_data,
|
||||
stderr=stderr_data,
|
||||
)
|
||||
|
||||
with open(tmp_file, "wb", buffering=262144) as f:
|
||||
@@ -334,7 +459,10 @@ def capture_screenshot_direct(
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
_uo_log(f"[截图] exec-out 异常:{e}")
|
||||
if isinstance(e, subprocess.CalledProcessError):
|
||||
_uo_log(f"[截图] exec-out 异常:{_format_completed_error(e)}")
|
||||
else:
|
||||
_uo_log(f"[截图] exec-out 异常:{e}")
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
@@ -347,7 +475,7 @@ def capture_screenshot_direct(
|
||||
shell_screencap_start = time_module.time()
|
||||
remote_shot = path_config.get_android_screenshot_path()
|
||||
remote_shot_alt = path_config.get_android_screenshot_alt_path()
|
||||
subprocess.run(
|
||||
shell_result = subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
@@ -358,10 +486,13 @@ def capture_screenshot_direct(
|
||||
remote_shot,
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
check=True,
|
||||
timeout=10,
|
||||
)
|
||||
shell_stderr = _stderr_tail(getattr(shell_result, "stderr", None))
|
||||
if shell_stderr:
|
||||
logging.info("[截图] 回退方案-shell screencap stderr=%s", shell_stderr)
|
||||
shell_screencap_dur = (time_module.time() - shell_screencap_start) * 1000.0
|
||||
logging.info(
|
||||
"[截图] 回退方案-shell screencap耗时(ms)=%.1f device=%s",
|
||||
@@ -370,13 +501,16 @@ def capture_screenshot_direct(
|
||||
)
|
||||
|
||||
pull_start = time_module.time()
|
||||
subprocess.run(
|
||||
pull_result = subprocess.run(
|
||||
[adb, "-s", device_id, "pull", remote_shot, tmp_file],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
check=True,
|
||||
timeout=10,
|
||||
)
|
||||
pull_stderr = _stderr_tail(getattr(pull_result, "stderr", None))
|
||||
if pull_stderr:
|
||||
logging.info("[截图] 回退方案-adb pull stderr=%s", pull_stderr)
|
||||
pull_dur = (time_module.time() - pull_start) * 1000.0
|
||||
logging.info(
|
||||
"[截图] 回退方案-adb pull耗时(ms)=%.1f device=%s", pull_dur, device_id
|
||||
@@ -466,70 +600,64 @@ def capture_screenshot_direct(
|
||||
except Exception:
|
||||
_uo_log(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}")
|
||||
return True
|
||||
return False
|
||||
except Exception:
|
||||
try:
|
||||
stdout_fallback_start = time_module.time()
|
||||
result = subprocess.run(
|
||||
[adb, "-s", device_id, "shell", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=True,
|
||||
timeout=8,
|
||||
)
|
||||
with open(tmp_file, "wb", buffering=262144) as f:
|
||||
f.write(result.stdout or b"")
|
||||
if _valid_png(tmp_file) and _safe_replace_file(tmp_file, out_file):
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
if _valid_png(out_file):
|
||||
overall_dur = (time_module.time() - overall_start) * 1000.0
|
||||
fallback_total_dur = (
|
||||
time_module.time() - stdout_fallback_start
|
||||
) * 1000.0
|
||||
logging.info(
|
||||
"[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (shell stdout回退成功, 回退部分耗时=%.1fms)",
|
||||
overall_dur,
|
||||
fallback_total_dur,
|
||||
)
|
||||
return True
|
||||
except Exception as stdout_error:
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
st = os.stat(tmp_file)
|
||||
_uo_log(
|
||||
f"[截图] shell stdout回退失败:{type(stdout_error).__name__}: {stdout_error}",
|
||||
"WARNING",
|
||||
f"[截图] 回退方案截图无效,继续尝试 shell stdout 回退: size={st.st_size}"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
# 再次回退:尝试用 screenshot1.png 覆盖 screenshot.png
|
||||
try:
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"screencap",
|
||||
"-p",
|
||||
remote_shot_alt,
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"mv",
|
||||
remote_shot_alt,
|
||||
remote_shot,
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
return self.get_screenshot(device_id, path)
|
||||
except Exception:
|
||||
return False
|
||||
pass
|
||||
except subprocess.CalledProcessError as fallback_error:
|
||||
try:
|
||||
_uo_log(
|
||||
"[截图] 回退方案失败,继续尝试 shell stdout 回退:"
|
||||
+ _format_completed_error(fallback_error)
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as fallback_error:
|
||||
try:
|
||||
_uo_log(f"[截图] 回退方案失败,继续尝试 shell stdout 回退:{fallback_error}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if _try_shell_stdout_fallback():
|
||||
return True
|
||||
|
||||
# 再次回退:尝试用 screenshot1.png 覆盖 screenshot.png
|
||||
try:
|
||||
if "remote_shot" not in locals():
|
||||
remote_shot = path_config.get_android_screenshot_path()
|
||||
remote_shot_alt = path_config.get_android_screenshot_alt_path()
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"screencap",
|
||||
"-p",
|
||||
remote_shot_alt,
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
adb,
|
||||
"-s",
|
||||
device_id,
|
||||
"shell",
|
||||
"mv",
|
||||
remote_shot_alt,
|
||||
remote_shot,
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
check=True,
|
||||
)
|
||||
return self.get_screenshot(device_id, path)
|
||||
except Exception:
|
||||
return False
|
||||
@@ -3,6 +3,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import time as time_module
|
||||
@@ -116,6 +117,20 @@ def ensure_adbkeyboard_ime(
|
||||
return True, prev, prev
|
||||
|
||||
imes = self.list_imes(device_id)
|
||||
if not self._pick_adbkeyboard_ime(imes):
|
||||
apk_path = path_config.get_bundled_adbkeyboard_apk_path()
|
||||
if os.path.exists(apk_path):
|
||||
try:
|
||||
subprocess.run(
|
||||
[self._adb_path(), "-s", str(device_id), "install", "-r", apk_path],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=20.0,
|
||||
check=False,
|
||||
)
|
||||
imes = self.list_imes(device_id)
|
||||
except Exception:
|
||||
pass
|
||||
adb_ime = ""
|
||||
|
||||
pref = str(preferred_ime or "").strip()
|
||||
|
||||
@@ -10,8 +10,8 @@
|
||||
from typing import Optional
|
||||
|
||||
APP_NAME = "douyin_guaji"
|
||||
APP_VERSION = "V3.3.3"
|
||||
APP_BUILD_DATE = "2025-12-28"
|
||||
APP_VERSION = "V3.3.11"
|
||||
APP_BUILD_DATE = "2026-06-29"
|
||||
|
||||
# 兼容旧代码与测试:提供 VERSION / RELEASE_DATE 别名
|
||||
# tests 期望: from version import VERSION, RELEASE_DATE, print_version_banner
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Diagnostic helpers for packaged clients."""
|
||||
@@ -0,0 +1,346 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
import time
|
||||
import zipfile
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib import request
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.license.license_manager import get_default_license_path, get_default_verify_url
|
||||
|
||||
DEFAULT_MAX_ARCHIVE_BYTES = 500 * 1024 * 1024
|
||||
DEFAULT_MAX_SOURCE_BYTES = 64 * 1024 * 1024
|
||||
DEFAULT_MAX_FILES = 32
|
||||
DEFAULT_MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
||||
SENSITIVE_KEY_PARTS = ("key", "token", "secret", "password", "license", "card")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LogUploadResult:
|
||||
ok: bool
|
||||
message: str
|
||||
reason: str = ""
|
||||
archive_path: str = ""
|
||||
size: int = 0
|
||||
|
||||
|
||||
def get_default_log_upload_url() -> str:
|
||||
raw = str(os.environ.get("DOUYIN_LOG_UPLOAD_URL") or "").strip()
|
||||
if raw:
|
||||
return raw
|
||||
verify_url = get_default_verify_url()
|
||||
if verify_url.endswith("/verify_license"):
|
||||
return verify_url[: -len("/verify_license")] + "/logs/upload"
|
||||
return verify_url.rstrip("/") + "/logs/upload"
|
||||
|
||||
|
||||
def _candidate_log_files(logs_dir: Path) -> list[Path]:
|
||||
suffixes = {".log", ".jsonl", ".txt"}
|
||||
if not logs_dir.exists():
|
||||
return []
|
||||
files = [
|
||||
p
|
||||
for p in logs_dir.rglob("*")
|
||||
if p.is_file() and p.suffix.lower() in suffixes and p.name != ".keep"
|
||||
]
|
||||
return sorted(files, key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
|
||||
|
||||
def _tail_bytes(path: Path, limit: int) -> bytes:
|
||||
size = path.stat().st_size
|
||||
with path.open("rb") as f:
|
||||
if size > limit:
|
||||
f.seek(size - limit)
|
||||
return f.read(limit)
|
||||
|
||||
|
||||
def _safe_rel(path: Path, base: Path) -> str:
|
||||
try:
|
||||
return path.relative_to(base).as_posix()
|
||||
except Exception:
|
||||
return path.name
|
||||
|
||||
|
||||
def _redact_value(key: str, value: Any) -> Any:
|
||||
key_l = str(key or "").lower()
|
||||
if isinstance(value, dict):
|
||||
return {str(k): _redact_value(str(k), v) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_redact_value(key, item) for item in value]
|
||||
if any(part in key_l for part in SENSITIVE_KEY_PARTS):
|
||||
return "<redacted>"
|
||||
return value
|
||||
|
||||
|
||||
def _read_redacted_config() -> dict[str, Any] | None:
|
||||
try:
|
||||
path = Path(path_config.get_config_path())
|
||||
obj = json.loads(path.read_text(encoding="utf-8-sig"))
|
||||
if not isinstance(obj, dict):
|
||||
return None
|
||||
return {str(k): _redact_value(str(k), v) for k, v in obj.items()}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _candidate_state_files(state_dir: Path) -> list[Path]:
|
||||
if not state_dir.exists():
|
||||
return []
|
||||
names = {
|
||||
"reservations.json",
|
||||
"room_pos_map.json",
|
||||
"high_value_rooms.json",
|
||||
"runtime_stats.json",
|
||||
"dashboard_stats.json",
|
||||
}
|
||||
files = [p for p in state_dir.rglob("*.json") if p.is_file() and p.name in names]
|
||||
return sorted(files, key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
|
||||
|
||||
def _candidate_pic_files(pic_dir: Path) -> list[Path]:
|
||||
if not pic_dir.exists():
|
||||
return []
|
||||
preferred = []
|
||||
for name in (
|
||||
"screenshot.png",
|
||||
"screenshot.png.tmp",
|
||||
"screenshot.jpg",
|
||||
"latest.png",
|
||||
"last_match.png",
|
||||
):
|
||||
p = pic_dir / name
|
||||
if p.is_file():
|
||||
preferred.append(p)
|
||||
|
||||
def _is_diagnostic_pic(path: Path) -> bool:
|
||||
suffix = path.suffix.lower()
|
||||
if suffix in {".png", ".jpg", ".jpeg"}:
|
||||
return True
|
||||
return path.name.lower().endswith(".png.tmp")
|
||||
|
||||
recent = sorted(
|
||||
[p for p in pic_dir.rglob("*") if p.is_file() and _is_diagnostic_pic(p)],
|
||||
key=lambda p: p.stat().st_mtime,
|
||||
reverse=True,
|
||||
)
|
||||
result: list[Path] = []
|
||||
for item in [*preferred, *recent]:
|
||||
if item not in result:
|
||||
result.append(item)
|
||||
if len(result) >= 12:
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def _run_command(cmd: list[str], timeout: int = 5) -> dict[str, Any]:
|
||||
try:
|
||||
proc = subprocess.run(cmd, text=True, capture_output=True, timeout=timeout)
|
||||
return {
|
||||
"cmd": cmd,
|
||||
"returncode": proc.returncode,
|
||||
"stdout": (proc.stdout or "")[-4000:],
|
||||
"stderr": (proc.stderr or "")[-2000:],
|
||||
}
|
||||
except Exception as exc:
|
||||
return {"cmd": cmd, "error": f"{type(exc).__name__}: {exc}"}
|
||||
|
||||
|
||||
def _diagnostic_environment() -> dict[str, Any]:
|
||||
payload: dict[str, Any] = {
|
||||
"created_at": int(time.time()),
|
||||
"platform": platform.platform(),
|
||||
"python": platform.python_version(),
|
||||
"cwd": os.getcwd(),
|
||||
"project_root": path_config.get_project_root(),
|
||||
"logs_dir": path_config.get_logs_dir(),
|
||||
"pic_dir": path_config.get_pic_dir(),
|
||||
"state_dir": path_config.get_state_dir(),
|
||||
}
|
||||
adb = ""
|
||||
try:
|
||||
from gui.gui_core import find_adb_executable
|
||||
|
||||
adb = str(find_adb_executable() or "")
|
||||
except Exception:
|
||||
adb = str(os.environ.get("ADB") or "adb")
|
||||
payload["adb"] = adb
|
||||
payload["adb_version"] = _run_command([adb, "version"]) if adb else {"error": "adb not found"}
|
||||
payload["adb_devices"] = _run_command([adb, "devices", "-l"]) if adb else {"error": "adb not found"}
|
||||
return payload
|
||||
|
||||
|
||||
def build_diagnostic_log_archive(
|
||||
*,
|
||||
output_dir: str | os.PathLike[str] | None = None,
|
||||
max_archive_bytes: int = DEFAULT_MAX_ARCHIVE_BYTES,
|
||||
max_source_bytes: int = DEFAULT_MAX_SOURCE_BYTES,
|
||||
max_files: int = DEFAULT_MAX_FILES,
|
||||
) -> Path:
|
||||
logs_dir = Path(path_config.get_logs_dir())
|
||||
out_dir = Path(output_dir) if output_dir is not None else logs_dir
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
archive = out_dir / f"diagnostic_logs_{int(time.time())}.zip"
|
||||
files = _candidate_log_files(logs_dir)[: max(1, int(max_files))]
|
||||
if not files:
|
||||
raise FileNotFoundError("没有找到可上传的日志文件")
|
||||
|
||||
with zipfile.ZipFile(archive, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as zf:
|
||||
manifest: dict[str, Any] = {
|
||||
"created_at": int(time.time()),
|
||||
"source": "douyin_guaji",
|
||||
"truncated_each_file_bytes": int(max_source_bytes),
|
||||
"files": [],
|
||||
}
|
||||
for file in files:
|
||||
rel = _safe_rel(file, logs_dir)
|
||||
data = _tail_bytes(file, max_source_bytes)
|
||||
zf.writestr(f"logs/{rel}", data)
|
||||
manifest["files"].append(
|
||||
{
|
||||
"path": f"logs/{rel}",
|
||||
"original_size": file.stat().st_size,
|
||||
"included_size": len(data),
|
||||
"mtime": int(file.stat().st_mtime),
|
||||
}
|
||||
)
|
||||
try:
|
||||
pic_dir = Path(path_config.get_pic_dir())
|
||||
for file in _candidate_pic_files(pic_dir):
|
||||
if file.stat().st_size > DEFAULT_MAX_IMAGE_BYTES:
|
||||
continue
|
||||
rel = _safe_rel(file, pic_dir)
|
||||
zf.write(file, f"pic/{rel}")
|
||||
manifest["files"].append(
|
||||
{
|
||||
"path": f"pic/{rel}",
|
||||
"original_size": file.stat().st_size,
|
||||
"included_size": file.stat().st_size,
|
||||
"mtime": int(file.stat().st_mtime),
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
manifest["pic_error"] = str(exc)
|
||||
try:
|
||||
state_dir = Path(path_config.get_state_dir())
|
||||
for file in _candidate_state_files(state_dir):
|
||||
rel = _safe_rel(file, state_dir)
|
||||
data = _tail_bytes(file, max_source_bytes)
|
||||
zf.writestr(f"state/{rel}", data)
|
||||
manifest["files"].append(
|
||||
{
|
||||
"path": f"state/{rel}",
|
||||
"original_size": file.stat().st_size,
|
||||
"included_size": len(data),
|
||||
"mtime": int(file.stat().st_mtime),
|
||||
}
|
||||
)
|
||||
except Exception as exc:
|
||||
manifest["state_error"] = str(exc)
|
||||
redacted_cfg = _read_redacted_config()
|
||||
if redacted_cfg is not None:
|
||||
zf.writestr(
|
||||
"config/config.redacted.json",
|
||||
json.dumps(redacted_cfg, ensure_ascii=False, indent=2),
|
||||
)
|
||||
zf.writestr(
|
||||
"diagnostics/environment.json",
|
||||
json.dumps(_diagnostic_environment(), ensure_ascii=False, indent=2),
|
||||
)
|
||||
zf.writestr("manifest.json", json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
|
||||
if archive.stat().st_size > max_archive_bytes:
|
||||
try:
|
||||
archive.unlink()
|
||||
finally:
|
||||
raise ValueError(f"诊断日志包超过大小限制(最大 {max_archive_bytes // (1024 * 1024)} MB)")
|
||||
return archive
|
||||
|
||||
|
||||
def upload_diagnostic_logs(
|
||||
*,
|
||||
upload_url: str = "",
|
||||
timeout_seconds: int = 120,
|
||||
http_post_file=None,
|
||||
) -> LogUploadResult:
|
||||
license_path = get_default_license_path()
|
||||
if not license_path.exists():
|
||||
return LogUploadResult(False, "缺少授权文件,无法上传日志", "missing_license")
|
||||
try:
|
||||
license_doc = json.loads(license_path.read_text(encoding="utf-8"))
|
||||
except Exception as exc:
|
||||
return LogUploadResult(False, f"授权文件读取失败: {exc}", "invalid_license")
|
||||
|
||||
try:
|
||||
archive = build_diagnostic_log_archive()
|
||||
except Exception as exc:
|
||||
return LogUploadResult(False, str(exc), "archive_failed")
|
||||
|
||||
url = str(upload_url or "").strip() or get_default_log_upload_url()
|
||||
try:
|
||||
post = http_post_file or _default_http_post_file
|
||||
data = post(
|
||||
url,
|
||||
license_doc=license_doc,
|
||||
file_path=archive,
|
||||
timeout_seconds=timeout_seconds,
|
||||
)
|
||||
except Exception as exc:
|
||||
return LogUploadResult(False, f"上传失败: {exc}", "upload_failed", str(archive), archive.stat().st_size)
|
||||
if not bool(data.get("ok")):
|
||||
return LogUploadResult(
|
||||
False,
|
||||
str(data.get("message") or data.get("error") or "上传失败"),
|
||||
str(data.get("reason") or "rejected"),
|
||||
str(archive),
|
||||
archive.stat().st_size,
|
||||
)
|
||||
return LogUploadResult(True, "日志上传成功", "ok", str(archive), archive.stat().st_size)
|
||||
|
||||
|
||||
def _default_http_post_file(
|
||||
url: str,
|
||||
*,
|
||||
license_doc: dict[str, Any],
|
||||
file_path: Path,
|
||||
timeout_seconds: int = 20,
|
||||
) -> dict[str, Any]:
|
||||
boundary = f"----DYGJ{int(time.time() * 1000)}"
|
||||
payload = json.dumps(license_doc, ensure_ascii=False).encode("utf-8")
|
||||
file_data = file_path.read_bytes()
|
||||
body = bytearray()
|
||||
|
||||
def add_field(name: str, value: bytes, content_type: str = "text/plain") -> None:
|
||||
body.extend(f"--{boundary}\r\n".encode("ascii"))
|
||||
body.extend(f'Content-Disposition: form-data; name="{name}"\r\n'.encode("ascii"))
|
||||
body.extend(f"Content-Type: {content_type}\r\n\r\n".encode("ascii"))
|
||||
body.extend(value)
|
||||
body.extend(b"\r\n")
|
||||
|
||||
add_field("license", payload, "application/json")
|
||||
body.extend(f"--{boundary}\r\n".encode("ascii"))
|
||||
body.extend(
|
||||
f'Content-Disposition: form-data; name="log_file"; filename="{file_path.name}"\r\n'.encode("ascii")
|
||||
)
|
||||
body.extend(b"Content-Type: application/zip\r\n\r\n")
|
||||
body.extend(file_data)
|
||||
body.extend(b"\r\n")
|
||||
body.extend(f"--{boundary}--\r\n".encode("ascii"))
|
||||
|
||||
req = request.Request(
|
||||
url,
|
||||
data=bytes(body),
|
||||
headers={"Content-Type": f"multipart/form-data; boundary={boundary}"},
|
||||
method="POST",
|
||||
)
|
||||
with request.urlopen(req, timeout=max(1, int(timeout_seconds))) as resp:
|
||||
raw = resp.read().decode("utf-8")
|
||||
obj = json.loads(raw)
|
||||
if not isinstance(obj, dict):
|
||||
raise ValueError("server response is not an object")
|
||||
return obj
|
||||
@@ -315,5 +315,5 @@ DIAG_SHOPPING_REDPACKET = (200, 300, 880, 1000)
|
||||
|
||||
DETAIL_OUTSIDE_CLICK = (500, 470)
|
||||
PARTICIPATE_BTN_CLICK = (543, 2070)
|
||||
FANSCLUB_JOIN_CLICK = (540, 2006)
|
||||
FANSCLUB_JOIN_FALLBACK_CLICK = (500, 2060)
|
||||
FANSCLUB_JOIN_CLICK = (550, 2050)
|
||||
FANSCLUB_JOIN_FALLBACK_CLICK = (540, 2006)
|
||||
@@ -30,12 +30,21 @@ def _scaled_point(analyser: Any, point: tuple[int, int]) -> tuple[int, int]:
|
||||
return int(point[0] * rx // 1080), int(point[1] * ry // 2400)
|
||||
|
||||
|
||||
def _fast_delay(analyser: Any, attr_name: str, default_seconds: float) -> None:
|
||||
def _fast_delay(
|
||||
analyser: Any,
|
||||
attr_name: str,
|
||||
default_seconds: float,
|
||||
*,
|
||||
min_seconds: float = 0.0,
|
||||
) -> None:
|
||||
try:
|
||||
seconds = float(getattr(analyser, attr_name, default_seconds) or default_seconds)
|
||||
raw = getattr(analyser, attr_name, default_seconds)
|
||||
if not isinstance(raw, (int, float, str)):
|
||||
raw = default_seconds
|
||||
seconds = float(raw or default_seconds)
|
||||
except Exception:
|
||||
seconds = default_seconds
|
||||
seconds = max(0.0, min(seconds, 1.2))
|
||||
seconds = max(float(min_seconds or 0.0), min(seconds, 3.0))
|
||||
try:
|
||||
analyser.operation.delay(seconds)
|
||||
except Exception:
|
||||
@@ -74,7 +83,12 @@ def handle_reservation_prejoin_fansclub(
|
||||
pass
|
||||
return False
|
||||
|
||||
_fast_delay(analyser, "reservation_prejoin_fansclub_participate_wait_seconds", 0.6)
|
||||
_fast_delay(
|
||||
analyser,
|
||||
"reservation_prejoin_fansclub_participate_wait_seconds",
|
||||
1.2,
|
||||
min_seconds=0.8,
|
||||
)
|
||||
|
||||
click_point = FANSCLUB_JOIN_CLICK
|
||||
click_x, click_y = _scaled_point(analyser, click_point)
|
||||
@@ -118,7 +132,12 @@ def handle_reservation_prejoin_fansclub(
|
||||
pass
|
||||
return False
|
||||
|
||||
_fast_delay(analyser, "reservation_prejoin_fansclub_confirm_wait_seconds", 0.8)
|
||||
_fast_delay(
|
||||
analyser,
|
||||
"reservation_prejoin_fansclub_confirm_wait_seconds",
|
||||
1.6,
|
||||
min_seconds=1.2,
|
||||
)
|
||||
|
||||
try:
|
||||
analyser.click(*DETAIL_OUTSIDE_CLICK)
|
||||
|
||||
@@ -33,6 +33,10 @@ _DIRECT_ATTEND_ACTIONABLE_BUTTON_TEXT_SNIPPETS = (
|
||||
"发表",
|
||||
"一键",
|
||||
)
|
||||
_DIRECT_ATTEND_FANSCLUB_TEXT_SNIPPETS = (
|
||||
"粉丝团",
|
||||
"关注主播",
|
||||
)
|
||||
|
||||
# 错误处理工具占位(与原文件保持兼容降级)
|
||||
try:
|
||||
@@ -321,6 +325,33 @@ def _reservation_button_fallback_is_actionable(analyser: Any, item: Dict[str, An
|
||||
return False, button_text, button_status
|
||||
|
||||
|
||||
def _normalize_direct_button_text(text: str) -> str:
|
||||
return "".join(ch for ch in str(text or "") if ch not in " \t\r\n·。.,,、::||-_")
|
||||
|
||||
|
||||
def _looks_like_fansclub_button_text(button_text: str, button_status: str = "") -> bool:
|
||||
joined = _normalize_direct_button_text(button_text) + _normalize_direct_button_text(
|
||||
button_status
|
||||
)
|
||||
if not joined:
|
||||
return False
|
||||
if "粉丝团" in joined:
|
||||
return True
|
||||
if "关注主播" in joined and ("加入" in joined or "加人" in joined):
|
||||
return True
|
||||
if "需要加入粉丝" in joined:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _reservation_may_need_fansclub_flow(item: Dict[str, Any]) -> bool:
|
||||
button_text = str(item.get("button_text") or item.get("button_text_raw") or "")
|
||||
button_status = str(item.get("button_status") or "")
|
||||
if bool(item.get("prejoined_fansclub_before_reservation")):
|
||||
return True
|
||||
return _looks_like_fansclub_button_text(button_text, button_status)
|
||||
|
||||
|
||||
def _ocr_current_attend_button_if_actionable(analyser: Any, item: Dict[str, Any]) -> tuple[bool, str, str]:
|
||||
try:
|
||||
from douyin.fudai.core.coords import get_fudai_detail_profile
|
||||
@@ -817,6 +848,29 @@ def handle_reservation_direct_attend(analyser: Any) -> None:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if has_button and _reservation_may_need_fansclub_flow(first_reservation):
|
||||
current_ok, current_button_text, current_button_status = (
|
||||
_ocr_current_attend_button_if_actionable(analyser, first_reservation)
|
||||
)
|
||||
if current_button_text and _looks_like_fansclub_button_text(
|
||||
current_button_text,
|
||||
current_button_status,
|
||||
):
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"预约",
|
||||
"[预约] 预约直参检测到当前仍是粉丝团任务按钮,交给详情页正常流程",
|
||||
button_info=button_info,
|
||||
button_text=current_button_text[:80],
|
||||
button_status=current_button_status,
|
||||
ocr_actionable=bool(current_ok),
|
||||
reason="direct_attend_fansclub_button_semantic_guard",
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
analyser._handle_in_fudai_detail() # type: ignore[attr-defined]
|
||||
return
|
||||
|
||||
if not has_button:
|
||||
fallback_ok, fallback_button_text, fallback_button_status = (
|
||||
_reservation_button_fallback_is_actionable(analyser, first_reservation)
|
||||
|
||||
@@ -71,6 +71,7 @@ def run_startup_update_check_early(
|
||||
app_name: str,
|
||||
*,
|
||||
update_check: Callable[..., object] | None = None,
|
||||
progress_callback: Callable[[dict[str, object]], None] | None = None,
|
||||
) -> None:
|
||||
"""Run the updater before importing the heavier app modules."""
|
||||
try:
|
||||
@@ -80,7 +81,10 @@ def run_startup_update_check_early(
|
||||
check = run_startup_update_check
|
||||
else:
|
||||
check = update_check
|
||||
check(app_name=app_name)
|
||||
if progress_callback is None:
|
||||
check(app_name=app_name)
|
||||
else:
|
||||
check(app_name=app_name, progress_callback=progress_callback)
|
||||
except SystemExit:
|
||||
raise
|
||||
except Exception as exc:
|
||||
|
||||
+454
-37
@@ -8,7 +8,9 @@ import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
import zipfile
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urljoin, urlparse
|
||||
@@ -23,8 +25,6 @@ from douyin.license.public_key import PUBLIC_KEY_PEM
|
||||
|
||||
|
||||
DEFAULT_INSTALLER_ARGS = (
|
||||
"/VERYSILENT",
|
||||
"/SUPPRESSMSGBOXES",
|
||||
"/NORESTART",
|
||||
"/CURRENTUSER",
|
||||
)
|
||||
@@ -47,6 +47,7 @@ class UpdateSettings:
|
||||
require_https: bool = True
|
||||
allow_cross_origin: bool = False
|
||||
require_signed_manifest: bool = False
|
||||
allow_delta: bool = False
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -56,11 +57,14 @@ class UpdateResult:
|
||||
exit_required: bool = False
|
||||
version: str = ""
|
||||
installer_path: Path | None = None
|
||||
delta_path: Path | None = None
|
||||
|
||||
|
||||
FetchManifest = Callable[[str, float], dict[str, Any]]
|
||||
DownloadFile = Callable[[str, Path, float], None]
|
||||
LaunchInstaller = Callable[[list[str]], None]
|
||||
LaunchDeltaUpdate = Callable[[Path, str], None]
|
||||
ProgressCallback = Callable[[dict[str, Any]], None]
|
||||
|
||||
|
||||
def _to_bool(value: Any, default: bool = False) -> bool:
|
||||
@@ -165,15 +169,13 @@ def load_update_settings() -> UpdateSettings:
|
||||
).strip()
|
||||
env_enabled = os.environ.get("DOUYIN_AUTO_UPDATE_ENABLED")
|
||||
using_default_manifest = False
|
||||
if not manifest_url and getattr(sys, "frozen", False):
|
||||
if not manifest_url:
|
||||
manifest_url = DEFAULT_UPDATE_MANIFEST_URL
|
||||
using_default_manifest = True
|
||||
enabled_default = True if using_default_manifest else _to_bool(section.get("enabled"), False)
|
||||
enabled_default = _to_bool(section.get("enabled"), True)
|
||||
enabled = _to_bool(env_enabled, default=enabled_default)
|
||||
if os.environ.get("DOUYIN_DISABLE_AUTO_UPDATE", "").strip() == "1":
|
||||
enabled = False
|
||||
if not manifest_url:
|
||||
enabled = False
|
||||
|
||||
default_download_dir = Path(path_config.get_state_dir()) / "updates"
|
||||
timeout_raw = section.get("timeout_seconds", 20.0)
|
||||
@@ -193,9 +195,23 @@ def load_update_settings() -> UpdateSettings:
|
||||
require_https=_to_bool(section.get("require_https"), not using_default_manifest),
|
||||
allow_cross_origin=_to_bool(section.get("allow_cross_origin"), False),
|
||||
require_signed_manifest=_to_bool(section.get("require_signed_manifest"), using_default_manifest),
|
||||
allow_delta=_to_bool(
|
||||
os.environ.get("DOUYIN_UPDATE_ALLOW_DELTA", section.get("allow_delta")),
|
||||
False,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def load_manual_update_settings() -> UpdateSettings:
|
||||
"""Load settings for an explicit user-triggered update check.
|
||||
|
||||
The manual button should report errors in the UI instead of exiting the
|
||||
process through the startup fail-closed path.
|
||||
"""
|
||||
settings = load_update_settings()
|
||||
return replace(settings, enabled=True, fail_closed=False)
|
||||
|
||||
|
||||
def _origin(value: str) -> tuple[str, str, int]:
|
||||
parsed = urlparse(value)
|
||||
scheme = (parsed.scheme or "").lower()
|
||||
@@ -224,6 +240,16 @@ def _validate_installer_url(settings: UpdateSettings, download_url: str) -> None
|
||||
raise UpdateError("安装包 URL 必须与 manifest 同源")
|
||||
|
||||
|
||||
def _validate_download_url(settings: UpdateSettings, download_url: str, label: str) -> None:
|
||||
parsed = urlparse(download_url)
|
||||
if settings.require_https and parsed.scheme.lower() != "https":
|
||||
raise UpdateError(f"{label} URL 必须使用 HTTPS")
|
||||
if not parsed.scheme or not parsed.netloc:
|
||||
raise UpdateError(f"{label} URL 必须是完整 URL")
|
||||
if not settings.allow_cross_origin and _origin(download_url) != _origin(settings.manifest_url):
|
||||
raise UpdateError(f"{label} URL 必须与 manifest 同源")
|
||||
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict[str, Any]:
|
||||
req = Request(url, headers={"User-Agent": f"douyin-guaji-updater/{VERSION}"})
|
||||
with urlopen(req, timeout=timeout) as resp:
|
||||
@@ -234,18 +260,35 @@ def fetch_manifest(url: str, timeout: float) -> dict[str, Any]:
|
||||
return obj
|
||||
|
||||
|
||||
def download_file(url: str, dest: Path, timeout: float) -> None:
|
||||
def download_file(
|
||||
url: str,
|
||||
dest: Path,
|
||||
timeout: float,
|
||||
progress_callback: Callable[[int, int], None] | None = None,
|
||||
) -> None:
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = dest.with_name(dest.name + ".download")
|
||||
if tmp.exists():
|
||||
tmp.unlink()
|
||||
req = Request(url, headers={"User-Agent": f"douyin-guaji-updater/{VERSION}"})
|
||||
with urlopen(req, timeout=timeout) as resp, tmp.open("wb") as f:
|
||||
total = 0
|
||||
try:
|
||||
total = int(resp.headers.get("Content-Length") or 0)
|
||||
except Exception:
|
||||
total = 0
|
||||
done = 0
|
||||
while True:
|
||||
chunk = resp.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
done += len(chunk)
|
||||
if progress_callback:
|
||||
try:
|
||||
progress_callback(done, total)
|
||||
except Exception:
|
||||
pass
|
||||
if dest.exists():
|
||||
dest.unlink()
|
||||
tmp.replace(dest)
|
||||
@@ -266,6 +309,153 @@ def _safe_installer_name(manifest: dict[str, Any], download_url: str, version: s
|
||||
return re.sub(r'[<>:"/\\|?*]+', "_", raw)
|
||||
|
||||
|
||||
def _safe_delta_name(delta: dict[str, Any], download_url: str, version: str) -> str:
|
||||
raw = str(delta.get("filename") or Path(urlparse(download_url).path).name or "").strip()
|
||||
if not raw.lower().endswith(".zip"):
|
||||
raw = f"DouyinGuaji-delta-{version}.zip"
|
||||
return re.sub(r'[<>:"/\\|?*]+', "_", raw)
|
||||
|
||||
|
||||
def _delta_attempt_state_path(settings: UpdateSettings) -> Path:
|
||||
return settings.download_dir / "delta_attempt_state.json"
|
||||
|
||||
|
||||
def _delta_attempt_key(delta: dict[str, Any], current_version: str, latest_version: str) -> str:
|
||||
filename = str(delta.get("filename") or delta.get("url") or "").strip()
|
||||
sha = str(delta.get("sha256") or "").strip().lower()
|
||||
return "|".join([str(current_version), str(latest_version), filename, sha])
|
||||
|
||||
|
||||
def _read_delta_attempt_state(settings: UpdateSettings) -> dict[str, Any]:
|
||||
path = _delta_attempt_state_path(settings)
|
||||
try:
|
||||
obj = json.loads(path.read_text(encoding="utf-8-sig"))
|
||||
return obj if isinstance(obj, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _write_delta_attempt_state(settings: UpdateSettings, payload: dict[str, Any]) -> None:
|
||||
path = _delta_attempt_state_path(settings)
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _clear_delta_attempt_state(settings: UpdateSettings) -> None:
|
||||
try:
|
||||
_delta_attempt_state_path(settings).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _should_skip_delta_after_previous_attempt(
|
||||
settings: UpdateSettings,
|
||||
delta: dict[str, Any],
|
||||
current_version: str,
|
||||
latest_version: str,
|
||||
) -> bool:
|
||||
state = _read_delta_attempt_state(settings)
|
||||
if state.get("status") != "started":
|
||||
return False
|
||||
if state.get("key") != _delta_attempt_key(delta, current_version, latest_version):
|
||||
return False
|
||||
return compare_versions(current_version, latest_version) < 0
|
||||
|
||||
|
||||
def _mark_delta_attempt_started(
|
||||
settings: UpdateSettings,
|
||||
delta: dict[str, Any],
|
||||
current_version: str,
|
||||
latest_version: str,
|
||||
delta_path: Path,
|
||||
) -> None:
|
||||
_write_delta_attempt_state(
|
||||
settings,
|
||||
{
|
||||
"status": "started",
|
||||
"key": _delta_attempt_key(delta, current_version, latest_version),
|
||||
"from_version": current_version,
|
||||
"to_version": latest_version,
|
||||
"filename": delta_path.name,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _safe_delta_path(raw_path: Any) -> str:
|
||||
rel = str(raw_path or "").replace("\\", "/").strip("/")
|
||||
parts = [part for part in rel.split("/") if part]
|
||||
if not parts or any(part in {".", ".."} for part in parts):
|
||||
raise UpdateError(f"差量包包含非法路径:{raw_path}")
|
||||
if Path(rel).is_absolute() or ":" in parts[0]:
|
||||
raise UpdateError(f"差量包包含非法路径:{raw_path}")
|
||||
return "/".join(parts)
|
||||
|
||||
|
||||
def _matching_delta(manifest: dict[str, Any], current_version: str, latest_version: str) -> dict[str, Any] | None:
|
||||
raw = manifest.get("delta")
|
||||
candidates: list[Any]
|
||||
if isinstance(raw, list):
|
||||
candidates = raw
|
||||
elif isinstance(raw, dict):
|
||||
candidates = [raw]
|
||||
else:
|
||||
return None
|
||||
for item in candidates:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
from_version = str(item.get("from_version") or "").strip().lstrip("Vv")
|
||||
to_version = str(item.get("to_version") or latest_version).strip().lstrip("Vv")
|
||||
if compare_versions(from_version, current_version) == 0 and compare_versions(to_version, latest_version) == 0:
|
||||
return dict(item)
|
||||
return None
|
||||
|
||||
|
||||
def validate_delta_package(delta_path: Path, *, current_version: str, latest_version: str) -> dict[str, Any]:
|
||||
try:
|
||||
with zipfile.ZipFile(delta_path) as zf:
|
||||
for info in zf.infolist():
|
||||
name = info.filename.replace("\\", "/")
|
||||
if name.endswith("/"):
|
||||
continue
|
||||
if name != "manifest.json" and not name.startswith("files/"):
|
||||
raise UpdateError(f"差量包包含未知条目:{info.filename}")
|
||||
if name.startswith("files/"):
|
||||
_safe_delta_path(name[len("files/"):])
|
||||
try:
|
||||
manifest = json.loads(zf.read("manifest.json").decode("utf-8-sig"))
|
||||
except KeyError as exc:
|
||||
raise UpdateError("差量包缺少 manifest.json") from exc
|
||||
except Exception as exc:
|
||||
raise UpdateError(f"差量包 manifest 读取失败:{exc}") from exc
|
||||
if not isinstance(manifest, dict):
|
||||
raise UpdateError("差量包 manifest 格式错误")
|
||||
if compare_versions(str(manifest.get("from_version") or ""), current_version) != 0:
|
||||
raise UpdateError("差量包来源版本不匹配")
|
||||
if compare_versions(str(manifest.get("to_version") or ""), latest_version) != 0:
|
||||
raise UpdateError("差量包目标版本不匹配")
|
||||
for item in manifest.get("files") or []:
|
||||
if not isinstance(item, dict):
|
||||
raise UpdateError("差量包文件列表格式错误")
|
||||
rel = _safe_delta_path(item.get("path"))
|
||||
zip_name = f"files/{rel}"
|
||||
if zip_name not in zf.namelist():
|
||||
raise UpdateError(f"差量包缺少文件:{rel}")
|
||||
expected = str(item.get("sha256") or "").strip().lower()
|
||||
if not re.fullmatch(r"[0-9a-fA-F]{64}", expected):
|
||||
raise UpdateError(f"差量包文件缺少有效 sha256:{rel}")
|
||||
actual = hashlib.sha256(zf.read(zip_name)).hexdigest()
|
||||
if actual.lower() != expected:
|
||||
raise UpdateError(f"差量包文件校验失败:{rel}")
|
||||
for rel in manifest.get("delete") or []:
|
||||
_safe_delta_path(rel)
|
||||
return manifest
|
||||
except zipfile.BadZipFile as exc:
|
||||
raise UpdateError("差量包不是有效 zip") from exc
|
||||
|
||||
|
||||
def _installer_log_arg(version: str) -> str:
|
||||
safe_version = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(version or "unknown"))
|
||||
log_dir = Path(path_config.get_logs_dir()) / "updates"
|
||||
@@ -326,6 +516,96 @@ def launch_installer(cmd: list[str]) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _install_root() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).resolve().parent
|
||||
return Path(path_config.get_project_root()).resolve()
|
||||
|
||||
|
||||
def _delta_log_path(version: str) -> Path:
|
||||
safe_version = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(version or "unknown"))
|
||||
log_dir = Path(path_config.get_logs_dir()) / "updates"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
return log_dir / f"delta-{safe_version}.log"
|
||||
|
||||
|
||||
def _update_client_log_path() -> Path:
|
||||
log_dir = Path(path_config.get_logs_dir()) / "updates"
|
||||
log_dir.mkdir(parents=True, exist_ok=True)
|
||||
return log_dir / "update-client.log"
|
||||
|
||||
|
||||
def _append_update_log(event: str, **fields: Any) -> None:
|
||||
try:
|
||||
payload = {
|
||||
"time": datetime.now(timezone.utc).isoformat(),
|
||||
"event": event,
|
||||
**fields,
|
||||
}
|
||||
with _update_client_log_path().open("a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(payload, ensure_ascii=False, default=str) + "\n")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def launch_delta_update(delta_path: Path, version: str) -> None:
|
||||
install_root = _install_root()
|
||||
work_dir = delta_path.parent / f"{delta_path.stem}.apply"
|
||||
log_path = _delta_log_path(version)
|
||||
parent_pid = os.getpid()
|
||||
script = (
|
||||
"$ErrorActionPreference = 'Stop'; "
|
||||
f"Wait-Process -Id {parent_pid} -ErrorAction SilentlyContinue; "
|
||||
f"$zip = {_ps_quote(str(delta_path))}; "
|
||||
f"$root = {_ps_quote(str(install_root))}; "
|
||||
f"$work = {_ps_quote(str(work_dir))}; "
|
||||
f"$log = {_ps_quote(str(log_path))}; "
|
||||
"New-Item -ItemType Directory -Force -Path (Split-Path $log) | Out-Null; "
|
||||
"try { "
|
||||
" ('delta update started ' + (Get-Date -Format o) + ' zip=' + $zip + ' root=' + $root) | Out-File -LiteralPath $log -Encoding utf8 -Append; "
|
||||
" if (Test-Path $work) { Remove-Item -LiteralPath $work -Recurse -Force }; "
|
||||
" New-Item -ItemType Directory -Force -Path $work | Out-Null; "
|
||||
" Expand-Archive -LiteralPath $zip -DestinationPath $work -Force; "
|
||||
" $manifest = Get-Content -LiteralPath (Join-Path $work 'manifest.json') -Raw | ConvertFrom-Json; "
|
||||
" foreach ($rel in $manifest.delete) { "
|
||||
" $target = Join-Path $root $rel; "
|
||||
" if (Test-Path -LiteralPath $target) { Remove-Item -LiteralPath $target -Recurse -Force } "
|
||||
" }; "
|
||||
" foreach ($file in $manifest.files) { "
|
||||
" $src = Join-Path (Join-Path $work 'files') $file.path; "
|
||||
" $dst = Join-Path $root $file.path; "
|
||||
" New-Item -ItemType Directory -Force -Path (Split-Path $dst) | Out-Null; "
|
||||
" Copy-Item -LiteralPath $src -Destination $dst -Force "
|
||||
" }; "
|
||||
" 'delta update applied' | Out-File -LiteralPath $log -Encoding utf8 -Append; "
|
||||
" Remove-Item -LiteralPath $work -Recurse -Force; "
|
||||
" exit 0 "
|
||||
"} catch { "
|
||||
" ('delta update failed ' + (Get-Date -Format o) + ' error=' + $_.Exception.Message) | Out-File -LiteralPath $log -Encoding utf8 -Append; "
|
||||
" if ($_.ScriptStackTrace) { $_.ScriptStackTrace | Out-File -LiteralPath $log -Encoding utf8 -Append }; "
|
||||
" exit 1 "
|
||||
"}"
|
||||
)
|
||||
subprocess.Popen(
|
||||
[
|
||||
"powershell",
|
||||
"-NoProfile",
|
||||
"-ExecutionPolicy",
|
||||
"Bypass",
|
||||
"-WindowStyle",
|
||||
"Hidden",
|
||||
"-Command",
|
||||
script,
|
||||
],
|
||||
cwd=str(install_root),
|
||||
stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
close_fds=True,
|
||||
creationflags=getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0),
|
||||
)
|
||||
|
||||
|
||||
def _ps_quote(value: str) -> str:
|
||||
text = str(value)
|
||||
if sys.platform.startswith("win"):
|
||||
@@ -340,52 +620,181 @@ def perform_forced_update(
|
||||
fetch_manifest: FetchManifest = fetch_manifest,
|
||||
download_file: DownloadFile = download_file,
|
||||
launch_installer: LaunchInstaller = launch_installer,
|
||||
launch_delta_update: LaunchDeltaUpdate = launch_delta_update,
|
||||
progress_callback: ProgressCallback | None = None,
|
||||
) -> UpdateResult:
|
||||
def emit_progress(stage: str, **fields: Any) -> None:
|
||||
if progress_callback:
|
||||
try:
|
||||
progress_callback({"stage": stage, **fields})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def call_download_file(
|
||||
url: str,
|
||||
dest: Path,
|
||||
timeout: float,
|
||||
*,
|
||||
kind: str,
|
||||
) -> None:
|
||||
def on_bytes(done: int, total: int) -> None:
|
||||
emit_progress("download_progress", kind=kind, done=done, total=total, path=str(dest), url=url)
|
||||
|
||||
try:
|
||||
download_file(url, dest, timeout, on_bytes) # type: ignore[misc]
|
||||
except TypeError:
|
||||
download_file(url, dest, timeout)
|
||||
|
||||
if not settings.enabled:
|
||||
return UpdateResult("disabled", "未配置更新服务器")
|
||||
|
||||
_validate_manifest_url(settings)
|
||||
emit_progress("manifest_fetch", message="正在连接更新服务器")
|
||||
manifest = fetch_manifest(settings.manifest_url, settings.timeout_seconds)
|
||||
if settings.require_signed_manifest:
|
||||
emit_progress("manifest_verify", message="正在校验更新签名")
|
||||
_verify_manifest_signature(manifest)
|
||||
latest_version = str(manifest.get("version", "") or "").strip()
|
||||
if not latest_version:
|
||||
raise UpdateError("manifest 缺少 version")
|
||||
if compare_versions(latest_version, current_version) <= 0:
|
||||
_clear_delta_attempt_state(settings)
|
||||
return UpdateResult("up_to_date", "已是最新版本", version=latest_version)
|
||||
|
||||
raw_url = str(manifest.get("url") or manifest.get("installer_url") or "").strip()
|
||||
if not raw_url:
|
||||
raise UpdateError("manifest 缺少 url")
|
||||
download_url = urljoin(settings.manifest_url, raw_url)
|
||||
_validate_installer_url(settings, download_url)
|
||||
expected_sha = str(manifest.get("sha256") or "").strip().lower()
|
||||
if settings.require_sha256 and not re.fullmatch(r"[0-9a-fA-F]{64}", expected_sha):
|
||||
raise UpdateError("manifest 缺少有效 sha256")
|
||||
def launch_full_installer() -> UpdateResult:
|
||||
emit_progress("full_prepare", message="准备下载完整安装包")
|
||||
raw_url = str(manifest.get("url") or manifest.get("installer_url") or "").strip()
|
||||
if not raw_url:
|
||||
raise UpdateError("manifest 缺少 url")
|
||||
download_url = urljoin(settings.manifest_url, raw_url)
|
||||
_validate_installer_url(settings, download_url)
|
||||
expected_sha = str(manifest.get("sha256") or "").strip().lower()
|
||||
if settings.require_sha256 and not re.fullmatch(r"[0-9a-fA-F]{64}", expected_sha):
|
||||
raise UpdateError("manifest 缺少有效 sha256")
|
||||
|
||||
installer_name = _safe_installer_name(manifest, download_url, latest_version)
|
||||
installer_path = settings.download_dir / installer_name
|
||||
installer_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
download_file(download_url, installer_path, settings.timeout_seconds)
|
||||
installer_name = _safe_installer_name(manifest, download_url, latest_version)
|
||||
installer_path = settings.download_dir / installer_name
|
||||
installer_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
emit_progress("full_download_start", kind="full", message=f"正在下载完整安装包 {installer_name}", path=str(installer_path), url=download_url)
|
||||
call_download_file(download_url, installer_path, settings.timeout_seconds, kind="full")
|
||||
|
||||
if expected_sha:
|
||||
actual_sha = _sha256(installer_path)
|
||||
if actual_sha.lower() != expected_sha.lower():
|
||||
if expected_sha:
|
||||
emit_progress("full_verify", message="正在校验完整安装包")
|
||||
actual_sha = _sha256(installer_path)
|
||||
if actual_sha.lower() != expected_sha.lower():
|
||||
try:
|
||||
installer_path.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
raise UpdateError(f"sha256 校验失败: expected={expected_sha} actual={actual_sha}")
|
||||
|
||||
cmd = _build_installer_cmd(installer_path, settings.installer_args, latest_version)
|
||||
emit_progress("full_launch", message="正在启动安装器")
|
||||
launch_installer(cmd)
|
||||
_clear_delta_attempt_state(settings)
|
||||
return UpdateResult(
|
||||
"update_started",
|
||||
f"发现新版本 {latest_version},已启动安装器",
|
||||
exit_required=True,
|
||||
version=latest_version,
|
||||
installer_path=installer_path,
|
||||
)
|
||||
|
||||
delta = _matching_delta(manifest, current_version, latest_version) if settings.allow_delta else None
|
||||
if not delta:
|
||||
unavailable_message = (
|
||||
"未找到当前版本可用的差量包,准备下载完整安装包"
|
||||
if settings.allow_delta
|
||||
else "准备下载完整安装包"
|
||||
)
|
||||
emit_progress(
|
||||
"delta_unavailable",
|
||||
message=unavailable_message,
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
)
|
||||
skip_delta = bool(delta and _should_skip_delta_after_previous_attempt(settings, delta, current_version, latest_version))
|
||||
if delta and skip_delta:
|
||||
emit_progress(
|
||||
"delta_skipped",
|
||||
message="上次差量更新未完成,准备回退完整安装包",
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
)
|
||||
_append_update_log(
|
||||
"delta_skip_after_previous_started_attempt",
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
delta_filename=delta.get("filename") or delta.get("url"),
|
||||
)
|
||||
if delta and not skip_delta:
|
||||
raw_delta_url = str(delta.get("url") or "").strip()
|
||||
delta_sha = str(delta.get("sha256") or "").strip().lower()
|
||||
if raw_delta_url and (not settings.require_sha256 or re.fullmatch(r"[0-9a-fA-F]{64}", delta_sha)):
|
||||
try:
|
||||
installer_path.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
raise UpdateError(f"sha256 校验失败: expected={expected_sha} actual={actual_sha}")
|
||||
delta_url = urljoin(settings.manifest_url, raw_delta_url)
|
||||
_validate_download_url(settings, delta_url, "差量包")
|
||||
delta_name = _safe_delta_name(delta, delta_url, latest_version)
|
||||
delta_path = settings.download_dir / delta_name
|
||||
delta_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
emit_progress("delta_download_start", kind="delta", message=f"正在下载差量包 {delta_name}", path=str(delta_path), url=delta_url)
|
||||
_append_update_log(
|
||||
"delta_download_start",
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
url=delta_url,
|
||||
path=str(delta_path),
|
||||
)
|
||||
call_download_file(delta_url, delta_path, settings.timeout_seconds, kind="delta")
|
||||
if delta_sha:
|
||||
emit_progress("delta_verify", message="正在校验差量包")
|
||||
actual_sha = _sha256(delta_path)
|
||||
if actual_sha.lower() != delta_sha:
|
||||
try:
|
||||
delta_path.unlink()
|
||||
except Exception:
|
||||
pass
|
||||
raise UpdateError(f"差量包 sha256 校验失败: expected={delta_sha} actual={actual_sha}")
|
||||
emit_progress("delta_validate", message="正在检查差量包内容")
|
||||
validate_delta_package(delta_path, current_version=current_version, latest_version=latest_version)
|
||||
_mark_delta_attempt_started(settings, delta, current_version, latest_version, delta_path)
|
||||
_append_update_log(
|
||||
"delta_launch_start",
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
path=str(delta_path),
|
||||
sha256=delta_sha,
|
||||
)
|
||||
emit_progress("delta_launch", message="正在应用差量更新")
|
||||
launch_delta_update(delta_path, latest_version)
|
||||
return UpdateResult(
|
||||
"delta_update_started",
|
||||
f"发现新版本 {latest_version},已启动差量更新",
|
||||
exit_required=True,
|
||||
version=latest_version,
|
||||
delta_path=delta_path,
|
||||
)
|
||||
except Exception as exc:
|
||||
emit_progress("delta_failed", message="差量更新失败,准备回退完整安装包", error=f"{type(exc).__name__}: {exc}")
|
||||
_append_update_log(
|
||||
"delta_failed_fallback_full",
|
||||
current_version=current_version,
|
||||
latest_version=latest_version,
|
||||
delta_filename=delta.get("filename") or delta.get("url"),
|
||||
error=f"{type(exc).__name__}: {exc}",
|
||||
)
|
||||
_write_delta_attempt_state(
|
||||
settings,
|
||||
{
|
||||
"status": "failed",
|
||||
"key": _delta_attempt_key(delta, current_version, latest_version),
|
||||
"from_version": current_version,
|
||||
"to_version": latest_version,
|
||||
"error": f"{type(exc).__name__}: {exc}",
|
||||
},
|
||||
)
|
||||
|
||||
cmd = _build_installer_cmd(installer_path, settings.installer_args, latest_version)
|
||||
launch_installer(cmd)
|
||||
return UpdateResult(
|
||||
"update_started",
|
||||
f"发现新版本 {latest_version},已启动安装器",
|
||||
exit_required=True,
|
||||
version=latest_version,
|
||||
installer_path=installer_path,
|
||||
)
|
||||
return launch_full_installer()
|
||||
|
||||
|
||||
def run_startup_update_check(
|
||||
@@ -393,10 +802,18 @@ def run_startup_update_check(
|
||||
app_name: str,
|
||||
current_version: str = VERSION,
|
||||
perform_update: Callable[..., UpdateResult] = perform_forced_update,
|
||||
progress_callback: ProgressCallback | None = None,
|
||||
) -> UpdateResult:
|
||||
settings = load_update_settings()
|
||||
try:
|
||||
result = perform_update(settings=settings, current_version=current_version)
|
||||
if progress_callback is None:
|
||||
result = perform_update(settings=settings, current_version=current_version)
|
||||
else:
|
||||
result = perform_update(
|
||||
settings=settings,
|
||||
current_version=current_version,
|
||||
progress_callback=progress_callback,
|
||||
)
|
||||
except UpdateError as exc:
|
||||
message = f"[更新] {app_name} 强制更新失败:{exc}"
|
||||
print(message, file=sys.stderr)
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from typing import Any, Callable
|
||||
|
||||
from douyin.updater.bootstrap import load_update_settings, run_startup_update_check_early
|
||||
from gui.dashboard_app import theme
|
||||
from gui.dashboard_app.widgets import rounded_surface
|
||||
|
||||
|
||||
class UpdateProgressWindow:
|
||||
"""Small standalone update progress window used before the main GUI exists."""
|
||||
|
||||
def __init__(self, title: str = "软件更新") -> None:
|
||||
self.root = tk.Tk()
|
||||
self.root.title(title)
|
||||
self.root.resizable(False, False)
|
||||
self.root.configure(bg=theme.BG)
|
||||
theme.setup_styles(self.root)
|
||||
self.root.protocol("WM_DELETE_WINDOW", lambda: None)
|
||||
|
||||
frame = tk.Frame(self.root, bg=theme.BG, padx=28, pady=26)
|
||||
frame.pack(fill="both", expand=True)
|
||||
card = rounded_surface(frame, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
card.pack(fill="both", expand=True)
|
||||
inner = tk.Frame(card, bg=theme.SURFACE, padx=26, pady=24)
|
||||
inner.pack(fill="both", expand=True)
|
||||
|
||||
top = tk.Frame(inner, bg=theme.SURFACE)
|
||||
top.pack(fill="x")
|
||||
tk.Label(
|
||||
top,
|
||||
text="正在更新",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEXT,
|
||||
font=("Microsoft YaHei UI", 19, "bold"),
|
||||
).pack(side="left")
|
||||
self.mode = tk.Label(
|
||||
top,
|
||||
text="检查中",
|
||||
bg=theme.BLUE_SOFT,
|
||||
fg=theme.BLUE,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
padx=12,
|
||||
pady=5,
|
||||
)
|
||||
self.mode.pack(side="right")
|
||||
|
||||
self.stage = tk.Label(
|
||||
inner,
|
||||
text="正在连接更新服务器",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEXT,
|
||||
font=("Microsoft YaHei UI", 14, "bold"),
|
||||
)
|
||||
self.stage.pack(anchor="w", pady=(20, 5))
|
||||
self.detail = tk.Label(
|
||||
inner,
|
||||
text="优先尝试差量更新,失败后才回退完整安装包",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=theme.FONT_SMALL,
|
||||
)
|
||||
self.detail.pack(anchor="w", pady=(0, 14))
|
||||
self.percent = tk.Label(
|
||||
inner,
|
||||
text="0%",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEAL_DARK,
|
||||
font=("Microsoft YaHei UI", 24, "bold"),
|
||||
)
|
||||
self.percent.pack(anchor="e")
|
||||
self.bar = ttk.Progressbar(inner, mode="determinate", length=460, maximum=100)
|
||||
self.bar.pack(fill="x", pady=(3, 10), ipady=4)
|
||||
self.sub = tk.Label(
|
||||
inner,
|
||||
text="准备中",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.SUBTLE,
|
||||
font=("Microsoft YaHei UI", 11),
|
||||
)
|
||||
self.sub.pack(anchor="w")
|
||||
|
||||
self.root.update_idletasks()
|
||||
w, h = self.root.winfo_width(), self.root.winfo_height()
|
||||
sw, sh = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
|
||||
self.root.geometry(f"+{max(0, (sw - w) // 2)}+{max(0, (sh - h) // 2)}")
|
||||
|
||||
def callback(self) -> Callable[[dict[str, Any]], None]:
|
||||
return lambda event: self.root.after(0, lambda event=event: self.update(event))
|
||||
|
||||
def update(self, event: dict[str, Any]) -> None:
|
||||
apply_update_progress_event(
|
||||
event,
|
||||
mode_label=self.mode,
|
||||
stage_label=self.stage,
|
||||
detail_label=self.detail,
|
||||
percent_label=self.percent,
|
||||
bar=self.bar,
|
||||
sub_label=self.sub,
|
||||
)
|
||||
self.root.update_idletasks()
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
self.root.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def run_gui_startup_update_check_early(app_name: str) -> None:
|
||||
"""Run startup updater with a visible GUI progress window when enabled."""
|
||||
try:
|
||||
settings = load_update_settings()
|
||||
except Exception:
|
||||
settings = None
|
||||
if settings is None or not settings.enabled:
|
||||
run_startup_update_check_early(app_name=app_name)
|
||||
return
|
||||
|
||||
progress = UpdateProgressWindow()
|
||||
try:
|
||||
run_startup_update_check_early(
|
||||
app_name=app_name,
|
||||
progress_callback=progress.callback(),
|
||||
)
|
||||
finally:
|
||||
progress.close()
|
||||
|
||||
|
||||
def apply_update_progress_event(
|
||||
event: dict[str, Any],
|
||||
*,
|
||||
mode_label: tk.Label,
|
||||
stage_label: tk.Label,
|
||||
detail_label: tk.Label,
|
||||
percent_label: tk.Label,
|
||||
bar: ttk.Progressbar,
|
||||
sub_label: tk.Label,
|
||||
) -> None:
|
||||
stage = str(event.get("stage") or "")
|
||||
message = str(event.get("message") or "")
|
||||
kind = str(event.get("kind") or "")
|
||||
stage_text = message or {
|
||||
"manifest_fetch": "正在连接更新服务器",
|
||||
"manifest_verify": "正在校验更新签名",
|
||||
"delta_download_start": "正在下载差量包",
|
||||
"delta_verify": "正在校验差量包",
|
||||
"delta_validate": "正在检查差量包内容",
|
||||
"delta_launch": "正在应用差量更新",
|
||||
"delta_failed": "差量更新失败,准备回退完整安装包",
|
||||
"delta_unavailable": "未找到当前版本可用的差量包",
|
||||
"delta_skipped": "上次差量更新未完成",
|
||||
"full_prepare": "准备下载完整安装包",
|
||||
"full_download_start": "正在下载完整安装包",
|
||||
"full_verify": "正在校验完整安装包",
|
||||
"full_launch": "正在启动安装器",
|
||||
}.get(stage, "正在处理更新")
|
||||
|
||||
if kind == "delta" or stage.startswith("delta_"):
|
||||
mode_text = "差量更新"
|
||||
mode_bg, mode_fg = theme.TEAL_SOFT, theme.TEAL_DARK
|
||||
elif kind == "full" or stage.startswith("full_"):
|
||||
mode_text = "完整安装包"
|
||||
mode_bg, mode_fg = theme.AMBER_SOFT, theme.AMBER
|
||||
else:
|
||||
mode_text = "检查中"
|
||||
mode_bg, mode_fg = theme.BLUE_SOFT, theme.BLUE
|
||||
|
||||
mode_label.config(text=mode_text, bg=mode_bg, fg=mode_fg)
|
||||
stage_label.config(text=stage_text)
|
||||
|
||||
done = int(event.get("done") or 0)
|
||||
total = int(event.get("total") or 0)
|
||||
if stage == "download_progress" and total > 0:
|
||||
percent = max(0, min(100, round(done * 100 / total)))
|
||||
bar.config(value=percent)
|
||||
percent_label.config(text=f"{percent}%")
|
||||
detail_label.config(text=f"已下载 {done // (1024 * 1024)} MB / {max(1, total // (1024 * 1024))} MB")
|
||||
elif stage.endswith("_start"):
|
||||
bar.config(value=5)
|
||||
percent_label.config(text="0%")
|
||||
detail_label.config(text="正在建立下载任务")
|
||||
elif stage in {"delta_verify", "delta_validate", "full_verify"}:
|
||||
bar.config(value=92)
|
||||
percent_label.config(text="92%")
|
||||
detail_label.config(text="下载完成,正在校验完整性")
|
||||
elif stage in {"delta_launch", "full_launch"}:
|
||||
bar.config(value=100)
|
||||
percent_label.config(text="100%")
|
||||
detail_label.config(text="校验完成,正在启动更新器")
|
||||
elif stage in {"delta_failed", "delta_unavailable", "delta_skipped"}:
|
||||
bar.config(value=0)
|
||||
percent_label.config(text="回退")
|
||||
detail_label.config(text=str(event.get("error") or "将下载完整安装包"))
|
||||
else:
|
||||
bar.config(value=max(8, int(float(bar["value"] or 0))))
|
||||
percent_label.config(text="")
|
||||
|
||||
sub_label.config(text=str(event.get("path") or event.get("url") or ""))
|
||||
@@ -17,6 +17,8 @@ from tkinter import ttk
|
||||
from tkinter.constants import LEFT, W, X
|
||||
from typing import Callable
|
||||
|
||||
from gui.dashboard_app import theme
|
||||
from gui.dashboard_app.widgets import button, rounded_surface
|
||||
from gui.gui_core import (
|
||||
auto_connect_wifi_adb,
|
||||
connect_wifi_adb,
|
||||
@@ -35,6 +37,64 @@ from gui.gui_core_pkg.wifi_adb_scan import query_device_model
|
||||
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
|
||||
|
||||
|
||||
TITLE_FONT = ("Microsoft YaHei UI", 20, "bold")
|
||||
SUBTITLE_FONT = ("Microsoft YaHei UI", 12)
|
||||
LABEL_FONT = ("Microsoft YaHei UI", 13, "bold")
|
||||
BODY_FONT = ("Microsoft YaHei UI", 13)
|
||||
HELP_FONT = ("Microsoft YaHei UI", 12)
|
||||
|
||||
|
||||
def _setup_wifi_dialog_styles(dialog: tk.Toplevel) -> None:
|
||||
try:
|
||||
style = ttk.Style(dialog)
|
||||
style.configure("WifiADB.TCombobox", padding=(10, 8), font=BODY_FONT)
|
||||
style.configure("WifiADB.TEntry", padding=(10, 8), font=BODY_FONT)
|
||||
except Exception:
|
||||
# Headless tests may provide a lightweight fake Toplevel without a tk handle.
|
||||
return
|
||||
|
||||
|
||||
def _card(parent: tk.Misc, title: str, subtitle: str = "") -> tuple[tk.Frame, tk.Frame]:
|
||||
outer = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
head = tk.Frame(outer, bg=theme.SURFACE)
|
||||
head.pack(fill="x", padx=22, pady=(18, 10))
|
||||
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 15, "bold")).pack(side="left")
|
||||
if subtitle:
|
||||
tk.Label(head, text=subtitle, bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(side="left", padx=(12, 0))
|
||||
body = tk.Frame(outer, bg=theme.SURFACE)
|
||||
body.pack(fill="both", expand=True, padx=22, pady=(0, 20))
|
||||
return outer, body
|
||||
|
||||
|
||||
def _status_pill(parent: tk.Misc, text: str, *, ok: bool, active: bool = True) -> tk.Label:
|
||||
if ok:
|
||||
fg, bg = theme.GREEN, theme.GREEN_SOFT
|
||||
elif active:
|
||||
fg, bg = theme.AMBER, theme.AMBER_SOFT
|
||||
else:
|
||||
fg, bg = theme.MUTED, theme.SURFACE_ALT
|
||||
return tk.Label(parent, text=text, bg=bg, fg=fg, font=("Microsoft YaHei UI", 12, "bold"), padx=12, pady=5)
|
||||
|
||||
|
||||
def _field_group(parent: tk.Misc, title: str) -> tk.Frame:
|
||||
box = tk.Frame(parent, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
|
||||
tk.Label(box, text=title, bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor="w", padx=14, pady=(12, 8))
|
||||
return box
|
||||
|
||||
|
||||
def _action_grid(parent: tk.Misc, actions: tuple[tuple[str, Callable[[], None], str, int], ...], *, columns: int = 3) -> None:
|
||||
for col in range(columns):
|
||||
parent.grid_columnconfigure(col, weight=1, uniform="action")
|
||||
for idx, (text, command, kind, width) in enumerate(actions):
|
||||
button(parent, text, command, kind=kind, width=width).grid(
|
||||
row=idx // columns,
|
||||
column=idx % columns,
|
||||
sticky="ew",
|
||||
padx=(0 if idx % columns == 0 else 10, 0),
|
||||
pady=4,
|
||||
)
|
||||
|
||||
|
||||
def open_wifi_adb_dialog(
|
||||
parent: tk.Misc,
|
||||
*,
|
||||
@@ -45,36 +105,70 @@ def open_wifi_adb_dialog(
|
||||
"""打开WiFi ADB设置对话框"""
|
||||
dialog = tk.Toplevel(parent)
|
||||
dialog.title("WiFi ADB 设置")
|
||||
dialog.geometry("500x450")
|
||||
dialog.geometry("900x820")
|
||||
dialog.configure(bg=theme.BG)
|
||||
_setup_wifi_dialog_styles(dialog)
|
||||
# 允许用户调整对话框大小,避免窗口内容被裁剪
|
||||
dialog.resizable(True, True)
|
||||
dialog.minsize(420, 320)
|
||||
dialog.minsize(780, 640)
|
||||
|
||||
if not hasattr(dialog, "tk"):
|
||||
ttk.Button(dialog, text="放大/恢复", command=lambda: None)
|
||||
return
|
||||
|
||||
# 获取设备列表并分类
|
||||
current_devices = list_adb_devices(adb_exe)
|
||||
wifi_devices = get_connected_wifi_devices(adb_exe)
|
||||
usb_devices = [d for d in current_devices if d not in wifi_devices]
|
||||
|
||||
canvas = tk.Canvas(dialog, bg=theme.BG, highlightthickness=0, bd=0)
|
||||
scroll = ttk.Scrollbar(dialog, orient="vertical", command=canvas.yview)
|
||||
canvas.configure(yscrollcommand=scroll.set)
|
||||
canvas.pack(side="left", fill="both", expand=True)
|
||||
scroll.pack(side="right", fill="y")
|
||||
shell = tk.Frame(canvas, bg=theme.BG)
|
||||
shell_window = canvas.create_window((0, 0), window=shell, anchor="nw")
|
||||
shell.bind("<Configure>", lambda _e: canvas.configure(scrollregion=canvas.bbox("all")))
|
||||
canvas.bind("<Configure>", lambda e: canvas.itemconfigure(shell_window, width=e.width))
|
||||
|
||||
content = tk.Frame(shell, bg=theme.BG)
|
||||
content.pack(fill="both", expand=True, padx=22, pady=18)
|
||||
|
||||
header = tk.Frame(content, bg=theme.BG)
|
||||
header.pack(fill="x", pady=(0, 14))
|
||||
title_box = tk.Frame(header, bg=theme.BG)
|
||||
title_box.pack(side="left", fill="x", expand=True)
|
||||
tk.Label(title_box, text="WiFi ADB 设置", bg=theme.BG, fg=theme.TEXT, font=TITLE_FONT).pack(anchor="w")
|
||||
tk.Label(
|
||||
title_box,
|
||||
text="保留原有连接流程,优化设备选择与操作可读性",
|
||||
bg=theme.BG,
|
||||
fg=theme.MUTED,
|
||||
font=SUBTITLE_FONT,
|
||||
).pack(anchor="w", pady=(3, 0))
|
||||
_status_pill(header, f"USB {len(usb_devices)}", ok=bool(usb_devices)).pack(side="right", padx=(8, 0))
|
||||
_status_pill(header, f"WiFi {len(wifi_devices)}", ok=bool(wifi_devices), active=False).pack(side="right", padx=(8, 0))
|
||||
|
||||
# 创建设备选择区域
|
||||
device_frame = ttk.LabelFrame(dialog, text="设备选择", padding=10)
|
||||
device_frame.pack(fill=X, padx=10, pady=10)
|
||||
# 使内部 grid 列随窗口宽度伸缩
|
||||
device_frame.grid_columnconfigure(0, weight=3)
|
||||
device_frame.grid_columnconfigure(1, weight=1)
|
||||
device_card, device_frame = _card(content, "设备选择", "首次启用需要 USB,日常可直接选择 WiFi 设备")
|
||||
device_card.pack(fill="x", pady=(0, 14))
|
||||
device_frame.grid_columnconfigure(0, weight=1, uniform="device")
|
||||
device_frame.grid_columnconfigure(1, weight=1, uniform="device")
|
||||
|
||||
# USB设备选择
|
||||
ttk.Label(device_frame, text="USB设备(用于首次启用):").grid(
|
||||
row=0, column=0, sticky=W, pady=(0, 5)
|
||||
)
|
||||
usb_group = _field_group(device_frame, "USB设备(用于首次启用)")
|
||||
usb_group.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
|
||||
usb_device_var = tk.StringVar(value=(usb_devices[0] if usb_devices else ""))
|
||||
usb_combo = ttk.Combobox(
|
||||
device_frame,
|
||||
usb_group,
|
||||
textvariable=usb_device_var,
|
||||
values=usb_devices,
|
||||
width=25,
|
||||
width=34,
|
||||
state="readonly" if not usb_devices else "normal",
|
||||
style="WifiADB.TCombobox",
|
||||
font=BODY_FONT,
|
||||
)
|
||||
usb_combo.grid(row=1, column=0, padx=(0, 10), pady=(0, 10), sticky="we")
|
||||
usb_combo.pack(fill="x", padx=14, pady=(0, 10), ipady=5)
|
||||
|
||||
# 显示USB设备状态
|
||||
usb_status_text = (
|
||||
@@ -82,27 +176,23 @@ def open_wifi_adb_dialog(
|
||||
if usb_devices
|
||||
else "未检测到USB设备,请确保设备已连接并授权"
|
||||
)
|
||||
usb_status_label = ttk.Label(
|
||||
device_frame,
|
||||
text=usb_status_text,
|
||||
font=("Arial", 8),
|
||||
foreground="red" if not usb_devices else "green",
|
||||
)
|
||||
usb_status_label.grid(row=2, column=0, sticky=W, pady=(0, 10))
|
||||
usb_status_label = _status_pill(usb_group, usb_status_text, ok=bool(usb_devices))
|
||||
usb_status_label.pack(anchor="w", padx=14, pady=(0, 14))
|
||||
|
||||
# WiFi设备选择
|
||||
ttk.Label(device_frame, text="WiFi设备(已连接):").grid(
|
||||
row=0, column=1, sticky=W, pady=(0, 5)
|
||||
)
|
||||
wifi_group = _field_group(device_frame, "WiFi设备(已连接)")
|
||||
wifi_group.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
|
||||
wifi_device_var = tk.StringVar(value=(wifi_devices[0] if wifi_devices else ""))
|
||||
wifi_combo = ttk.Combobox(
|
||||
device_frame,
|
||||
wifi_group,
|
||||
textvariable=wifi_device_var,
|
||||
values=wifi_devices,
|
||||
width=25,
|
||||
width=34,
|
||||
state="readonly" if not wifi_devices else "normal",
|
||||
style="WifiADB.TCombobox",
|
||||
font=BODY_FONT,
|
||||
)
|
||||
wifi_combo.grid(row=1, column=1, pady=(0, 10), sticky="we")
|
||||
wifi_combo.pack(fill="x", padx=14, pady=(0, 10), ipady=5)
|
||||
|
||||
# 显示WiFi设备状态
|
||||
wifi_status_text = (
|
||||
@@ -110,38 +200,32 @@ def open_wifi_adb_dialog(
|
||||
if wifi_devices
|
||||
else "无WiFi设备连接"
|
||||
)
|
||||
wifi_status_label = ttk.Label(
|
||||
device_frame,
|
||||
text=wifi_status_text,
|
||||
font=("Arial", 8),
|
||||
foreground="blue" if wifi_devices else "gray",
|
||||
)
|
||||
wifi_status_label.grid(row=2, column=1, sticky=W, pady=(0, 10))
|
||||
wifi_status_label = _status_pill(wifi_group, wifi_status_text, ok=bool(wifi_devices), active=False)
|
||||
wifi_status_label.pack(anchor="w", padx=14, pady=(0, 14))
|
||||
|
||||
# IP地址输入区域
|
||||
ip_frame = ttk.LabelFrame(dialog, text="连接信息", padding=10)
|
||||
ip_frame.pack(fill=X, padx=10, pady=(0, 10))
|
||||
# 使 IP/端口 输入框随窗口宽度伸缩
|
||||
ip_card, ip_frame = _card(content, "连接信息", "手动连接时填写设备 IP 与端口")
|
||||
ip_card.pack(fill=X, pady=(0, 14))
|
||||
ip_frame.grid_columnconfigure(0, weight=3)
|
||||
ip_frame.grid_columnconfigure(1, weight=1)
|
||||
|
||||
ttk.Label(ip_frame, text="设备IP地址:").grid(
|
||||
row=0, column=0, sticky=W, pady=(0, 5)
|
||||
tk.Label(ip_frame, text="设备IP地址", bg=theme.SURFACE, fg=theme.TEXT, font=LABEL_FONT).grid(
|
||||
row=0, column=0, sticky=W, pady=(0, 8)
|
||||
)
|
||||
ip_var = tk.StringVar()
|
||||
ip_entry = ttk.Entry(ip_frame, textvariable=ip_var, width=25)
|
||||
ip_entry.grid(row=1, column=0, padx=(0, 10), pady=(0, 10), sticky="we")
|
||||
ip_entry = ttk.Entry(ip_frame, textvariable=ip_var, width=30, style="WifiADB.TEntry", font=BODY_FONT)
|
||||
ip_entry.grid(row=1, column=0, padx=(0, 14), pady=(0, 2), sticky="we", ipady=7)
|
||||
|
||||
ttk.Label(ip_frame, text="端口(默认5555):").grid(
|
||||
row=0, column=1, sticky=W, pady=(0, 5)
|
||||
tk.Label(ip_frame, text="端口(默认5555)", bg=theme.SURFACE, fg=theme.TEXT, font=LABEL_FONT).grid(
|
||||
row=0, column=1, sticky=W, pady=(0, 8)
|
||||
)
|
||||
port_var = tk.StringVar(value="5555")
|
||||
port_entry = ttk.Entry(ip_frame, textvariable=port_var, width=25)
|
||||
port_entry.grid(row=1, column=1, pady=(0, 10), sticky="we")
|
||||
port_entry = ttk.Entry(ip_frame, textvariable=port_var, width=16, style="WifiADB.TEntry", font=BODY_FONT)
|
||||
port_entry.grid(row=1, column=1, pady=(0, 2), sticky="we", ipady=7)
|
||||
|
||||
# 按钮区域
|
||||
button_frame = ttk.Frame(dialog)
|
||||
button_frame.pack(fill=X, padx=10, pady=10)
|
||||
action_card, button_frame = _card(content, "设备操作", "按当前连接方式选择对应动作")
|
||||
action_card.pack(fill=X, pady=(0, 14))
|
||||
|
||||
# 放大/恢复窗口支持(当系统边框无法调整窗口时提供备用按钮)
|
||||
is_maximized = False
|
||||
@@ -214,13 +298,14 @@ def open_wifi_adb_dialog(
|
||||
if not device_id:
|
||||
on_line("[WiFi ADB] 请先选择WiFi设备")
|
||||
return
|
||||
# 从设备ID中提取IP地址
|
||||
ip_match = re.search(r"(\d+\.\d+\.\d+\.\d+)", device_id)
|
||||
if not ip_match:
|
||||
# WiFi 设备通常是 ip:port。保留端口,避免随机无线调试端口被误断成 5555。
|
||||
target_match = re.search(r"(\d+\.\d+\.\d+\.\d+)(?::(\d{1,5}))?", device_id)
|
||||
if not target_match:
|
||||
on_line("[WiFi ADB] 无法从设备ID中提取IP地址")
|
||||
return
|
||||
ip = ip_match.group(1)
|
||||
success, msg = disconnect_wifi_adb(adb_exe, ip, "5555")
|
||||
ip = target_match.group(1)
|
||||
port = target_match.group(2) or "5555"
|
||||
success, msg = disconnect_wifi_adb(adb_exe, ip, port)
|
||||
on_line(f"[WiFi ADB] {msg}")
|
||||
if success:
|
||||
# 如果断开的就是上次记住的设备,清掉记录避免下次启动徒劳重试
|
||||
@@ -350,63 +435,83 @@ def open_wifi_adb_dialog(
|
||||
on_line("[WiFi ADB] 设备列表已刷新")
|
||||
|
||||
# USB设备操作按钮
|
||||
usb_button_frame = ttk.Frame(button_frame)
|
||||
usb_button_frame.pack(fill=X, pady=(0, 10))
|
||||
button_frame.grid_columnconfigure(0, weight=1, uniform="actions")
|
||||
button_frame.grid_columnconfigure(1, weight=1, uniform="actions")
|
||||
button_frame.grid_columnconfigure(2, weight=1, uniform="actions")
|
||||
usb_button_frame = tk.Frame(button_frame, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
|
||||
usb_button_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
|
||||
|
||||
ttk.Label(usb_button_frame, text="USB设备操作:").pack(anchor=W)
|
||||
usb_buttons_frame = ttk.Frame(usb_button_frame)
|
||||
usb_buttons_frame.pack(fill=X, pady=(5, 0))
|
||||
tk.Label(usb_button_frame, text="USB首次启用", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(13, 8))
|
||||
usb_buttons_frame = tk.Frame(usb_button_frame, bg=theme.SURFACE_ALT)
|
||||
usb_buttons_frame.pack(fill=X, padx=14, pady=(0, 14))
|
||||
|
||||
ttk.Button(usb_buttons_frame, text="自动连接", command=auto_connect_wifi).pack(
|
||||
side=LEFT, padx=(0, 10)
|
||||
)
|
||||
ttk.Button(usb_buttons_frame, text="启用WiFi ADB", command=enable_wifi).pack(
|
||||
side=LEFT, padx=(0, 10)
|
||||
)
|
||||
ttk.Button(usb_buttons_frame, text="连接", command=connect_wifi).pack(
|
||||
side=LEFT, padx=(0, 10)
|
||||
)
|
||||
ttk.Button(
|
||||
usb_buttons_frame, text="刷新设备", command=refresh_device_lists
|
||||
).pack(side=LEFT)
|
||||
# 如果窗口无法通过边框调整,提供放大/恢复按钮作为备用
|
||||
ttk.Button(usb_buttons_frame, text="放大/恢复", command=toggle_maximize).pack(
|
||||
side=LEFT, padx=(8, 0)
|
||||
_action_grid(
|
||||
usb_buttons_frame,
|
||||
(
|
||||
("自动连接", auto_connect_wifi, "primary", 150),
|
||||
("启用WiFi ADB", enable_wifi, "soft", 170),
|
||||
),
|
||||
columns=1,
|
||||
)
|
||||
|
||||
# WiFi设备操作按钮
|
||||
wifi_button_frame = ttk.Frame(button_frame)
|
||||
wifi_button_frame.pack(fill=X, pady=(10, 0))
|
||||
wifi_button_frame = tk.Frame(button_frame, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
|
||||
wifi_button_frame.grid(row=0, column=1, sticky="nsew", padx=(10, 10))
|
||||
|
||||
ttk.Label(wifi_button_frame, text="WiFi设备操作:").pack(anchor=W)
|
||||
wifi_buttons_frame = ttk.Frame(wifi_button_frame)
|
||||
wifi_buttons_frame.pack(fill=X, pady=(5, 0))
|
||||
tk.Label(wifi_button_frame, text="WiFi连接操作", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(13, 8))
|
||||
wifi_buttons_frame = tk.Frame(wifi_button_frame, bg=theme.SURFACE_ALT)
|
||||
wifi_buttons_frame.pack(fill=X, padx=14, pady=(0, 14))
|
||||
|
||||
ttk.Button(wifi_buttons_frame, text="断开连接", command=disconnect_wifi).pack(
|
||||
side=LEFT
|
||||
)
|
||||
ttk.Button(
|
||||
_action_grid(
|
||||
wifi_buttons_frame,
|
||||
text="扫描局域网",
|
||||
command=lambda: open_scan_dialog(
|
||||
dialog, adb_exe, ip_var, on_line, refresh_device_lists
|
||||
(
|
||||
("连接", connect_wifi, "primary", 124),
|
||||
("断开连接", disconnect_wifi, "soft", 132),
|
||||
("扫描局域网", lambda: open_scan_dialog(dialog, adb_exe, ip_var, on_line, refresh_device_lists, port_var), "soft", 142),
|
||||
),
|
||||
).pack(side=LEFT, padx=(10, 0))
|
||||
columns=1,
|
||||
)
|
||||
|
||||
# 通用工具
|
||||
tools_button_frame = tk.Frame(button_frame, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
|
||||
tools_button_frame.grid(row=0, column=2, sticky="nsew", padx=(10, 0))
|
||||
tk.Label(tools_button_frame, text="通用工具", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(13, 8))
|
||||
tools_buttons_frame = tk.Frame(tools_button_frame, bg=theme.SURFACE_ALT)
|
||||
tools_buttons_frame.pack(fill=X, padx=14, pady=(0, 14))
|
||||
_action_grid(
|
||||
tools_buttons_frame,
|
||||
(
|
||||
("刷新设备", refresh_device_lists, "soft", 132),
|
||||
("放大/恢复", toggle_maximize, "soft", 132),
|
||||
),
|
||||
columns=1,
|
||||
)
|
||||
|
||||
# 说明文本
|
||||
info_text = """重要说明:
|
||||
• Android系统安全要求:首次启用WiFi ADB必须通过USB连接
|
||||
• 工作流程:USB连接 → 启用WiFi ADB → 设备重启 → WiFi连接
|
||||
• 设置完成后,设备会出现在"WiFi设备"列表中,无需再次USB连接
|
||||
• 设备重启后WiFi ADB模式会保持,可直接通过WiFi连接使用
|
||||
help_card, help_body = _card(content, "重要说明", "为什么首次必须接 USB")
|
||||
help_card.pack(fill="both", expand=True)
|
||||
help_body.grid_columnconfigure(0, weight=1)
|
||||
help_body.grid_columnconfigure(1, weight=1)
|
||||
|
||||
使用方法:
|
||||
1. 连接Android设备到电脑(USB)
|
||||
2. 点击"刷新设备"确保设备被检测到
|
||||
3. 选择USB设备,点击"自动连接"或手动操作
|
||||
4. 等待设备重启后即可通过WiFi使用"""
|
||||
notes = tk.Frame(help_body, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
|
||||
notes.grid(row=0, column=0, sticky="nsew", padx=(0, 10))
|
||||
steps = tk.Frame(help_body, bg=theme.SURFACE_ALT, highlightthickness=1, highlightbackground=theme.BORDER)
|
||||
steps.grid(row=0, column=1, sticky="nsew", padx=(10, 0))
|
||||
|
||||
info_label = ttk.Label(
|
||||
dialog, text=info_text, justify=LEFT, font=("Arial", 9), wraplength=460
|
||||
)
|
||||
info_label.pack(pady=(10, 0), padx=20, anchor="w")
|
||||
tk.Label(notes, text="连接规则", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(12, 6))
|
||||
for line in (
|
||||
"Android 首次启用 WiFi ADB 必须通过 USB 连接",
|
||||
"流程:USB连接 -> 启用WiFi ADB -> 设备重启 -> WiFi连接",
|
||||
"设置完成后,设备会出现在 WiFi 设备列表中",
|
||||
"设备重启后 WiFi ADB 模式会保持,可继续通过 WiFi 使用",
|
||||
):
|
||||
tk.Label(notes, text=f"• {line}", bg=theme.SURFACE_ALT, fg=theme.MUTED, font=HELP_FONT, anchor=W, justify=LEFT, wraplength=360).pack(fill=X, padx=14, pady=2)
|
||||
|
||||
tk.Label(steps, text="使用方法", bg=theme.SURFACE_ALT, fg=theme.TEXT, font=LABEL_FONT).pack(anchor=W, padx=14, pady=(12, 6))
|
||||
for line in (
|
||||
"1. 连接 Android 设备到电脑(USB)",
|
||||
"2. 点击“刷新设备”确保设备被检测到",
|
||||
"3. 选择 USB 设备,点击“自动连接”或手动操作",
|
||||
"4. 等待设备重启后即可通过 WiFi 使用",
|
||||
):
|
||||
tk.Label(steps, text=line, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=HELP_FONT, anchor=W, justify=LEFT, wraplength=360).pack(fill=X, padx=14, pady=2)
|
||||
@@ -27,6 +27,7 @@ def open_scan_dialog(
|
||||
ip_var: tk.StringVar,
|
||||
on_line_local: Callable[[str], None],
|
||||
refresh_cb: Callable[[], None],
|
||||
port_var: tk.StringVar | None = None,
|
||||
) -> None:
|
||||
"""打开"扫描局域网"对话框:自动推子网或手动输入 → 后台扫描 → 列表展示。"""
|
||||
scan_dlg = tk.Toplevel(parent)
|
||||
@@ -130,9 +131,12 @@ def open_scan_dialog(
|
||||
f"[扫描] {target} 未授权,请先在手机上确认 ADB 调试授权再选"
|
||||
)
|
||||
return
|
||||
# 把 IP 部分填回主对话框
|
||||
ip_part = str(target).split(":")[0]
|
||||
# 把 IP 和端口填回主对话框。Android 11+ 无线调试常用随机端口,
|
||||
# 丢掉端口会导致用户选中后仍按默认 5555 连接失败。
|
||||
ip_part, port_part = split_target_for_fields(target)
|
||||
ip_var.set(ip_part)
|
||||
if port_var is not None and port_part:
|
||||
port_var.set(port_part)
|
||||
on_line_local(f"[扫描] 已选中 {target},可在主对话框点'连接'或它已在 adb devices 中")
|
||||
try:
|
||||
refresh_cb()
|
||||
@@ -229,3 +233,16 @@ def open_scan_dialog(
|
||||
threading.Thread(target=worker, daemon=True).start()
|
||||
|
||||
scan_btn.config(command=do_scan)
|
||||
|
||||
|
||||
def split_target_for_fields(target: object) -> tuple[str, str]:
|
||||
"""Return (host, port) for an adb target string, preserving random WiFi ports."""
|
||||
text = str(target or "").strip()
|
||||
if not text:
|
||||
return "", ""
|
||||
if ":" not in text:
|
||||
return text, ""
|
||||
host, port = text.rsplit(":", 1)
|
||||
if host and port.isdigit():
|
||||
return host, port
|
||||
return text, ""
|
||||
+469
-42
@@ -1,14 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import threading
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter import messagebox, ttk
|
||||
|
||||
from douyin.core.version import print_version_banner
|
||||
from douyin.diagnostics.log_upload import upload_diagnostic_logs
|
||||
from douyin.license.license_manager import (
|
||||
check_license,
|
||||
get_default_activation_url,
|
||||
install_license_or_activate,
|
||||
require_online_license_or_exit,
|
||||
start_online_license_monitor,
|
||||
)
|
||||
from douyin.updater.force_update import (
|
||||
UpdateError,
|
||||
load_manual_update_settings,
|
||||
perform_forced_update,
|
||||
)
|
||||
from gui.components.config_io import save_ui_to_config
|
||||
from gui.components.config_vars import build_config_vars
|
||||
from gui.components.mousewheel_guard import disable_spinbox_mousewheel
|
||||
from gui.components.run_params_builder import get_params as build_run_params
|
||||
from gui.components.screenshot_action import do_screenshot
|
||||
from gui.components.update_progress import apply_update_progress_event
|
||||
from gui.components.wifi_adb_dialog import open_wifi_adb_dialog
|
||||
from gui.components.wifi_adb_one_click_scan import on_scan_one_click
|
||||
from gui.components.wifi_adb_pick_dialog import open_scan_pick_dialog
|
||||
@@ -19,19 +35,23 @@ from . import theme
|
||||
from .data import load_dashboard_data
|
||||
from .page_context import PageContext
|
||||
from .page_registry import PAGES
|
||||
from .widgets import ScrollFrame, button, clear, nav_button, rounded_surface, status_pill
|
||||
from .widgets import ScrollFrame, SlimScrollbar, button, clear, nav_button, rounded_surface, status_pill
|
||||
|
||||
|
||||
def enforce_dashboard_license_required() -> None:
|
||||
os.environ["DOUYIN_LICENSE_REQUIRED"] = "1"
|
||||
|
||||
|
||||
class DashboardApp:
|
||||
def __init__(self) -> None:
|
||||
def __init__(self, *, initial_page: str = "数据看板", license_locked: bool = False) -> None:
|
||||
self.root = tk.Tk()
|
||||
try:
|
||||
self.root.tk.call("tk", "scaling", 1.12)
|
||||
except Exception:
|
||||
pass
|
||||
self.root.title("抖音自动化助手 - 数据看板")
|
||||
self.root.geometry("1280x860")
|
||||
self.root.minsize(1080, 720)
|
||||
self.root.geometry("1360x900")
|
||||
self.root.minsize(1160, 760)
|
||||
theme.setup_styles(self.root)
|
||||
disable_spinbox_mousewheel(self.root)
|
||||
|
||||
@@ -46,8 +66,10 @@ class DashboardApp:
|
||||
"yg_like_keywords_text": self.data.cfg.get("yanghao_like_keywords", []) or [],
|
||||
"yg_fav_keywords_text": self.data.cfg.get("yanghao_fav_keywords", []) or [],
|
||||
}
|
||||
self.current_page = "数据看板"
|
||||
self.status_var = tk.StringVar(value="就绪")
|
||||
self.license_locked = bool(license_locked)
|
||||
self.current_page = "授权" if self.license_locked else (initial_page if initial_page in PAGES else "数据看板")
|
||||
self._license_monitor_started = False
|
||||
self.status_var = tk.StringVar(value="请先验证卡密" if self.license_locked else "就绪")
|
||||
self.adb_exe = find_adb_executable()
|
||||
self.device_var = tk.StringVar(value="")
|
||||
self.y_var = self.config_vars.get("y_var", tk.IntVar(value=0))
|
||||
@@ -55,6 +77,7 @@ class DashboardApp:
|
||||
self.ocr_results: list = []
|
||||
self._scan_busy = {"flag": False}
|
||||
self.nav_buttons: dict[str, tk.Widget] = {}
|
||||
self._startup_progress: tk.Toplevel | None = None
|
||||
|
||||
self._build_shell()
|
||||
self.status_var.trace_add("write", lambda *_: self._sync_status_pill())
|
||||
@@ -62,53 +85,130 @@ class DashboardApp:
|
||||
self.root.after(300, self._try_reconnect_last_wifi)
|
||||
self.show_page(self.current_page)
|
||||
|
||||
def _ensure_license_ready(self) -> bool:
|
||||
if not self.license_locked:
|
||||
return True
|
||||
self.status_var.set("请先验证卡密")
|
||||
try:
|
||||
self.show_page("授权")
|
||||
except Exception:
|
||||
pass
|
||||
messagebox.showwarning("需要授权", "请先在“授权”页面输入卡密并验证成功。", parent=self.root)
|
||||
return False
|
||||
|
||||
def _start_license_monitor_once(self) -> None:
|
||||
if self._license_monitor_started:
|
||||
return
|
||||
start_online_license_monitor(on_line=self._on_runner_line)
|
||||
self._license_monitor_started = True
|
||||
|
||||
def _build_shell(self) -> None:
|
||||
shell = ttk.Frame(self.root, style="Dashboard.TFrame")
|
||||
shell.pack(fill="both", expand=True)
|
||||
|
||||
top = rounded_surface(shell, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
top.pack(fill="x", padx=18, pady=(14, 8))
|
||||
top = rounded_surface(shell, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_LG)
|
||||
top.pack(fill="x", padx=20, pady=(12, 6))
|
||||
brand = tk.Frame(top, bg=theme.SURFACE)
|
||||
brand.pack(fill="x", padx=18, pady=(12, 5))
|
||||
brand.pack(fill="x", padx=20, pady=(10, 4))
|
||||
brand.grid_columnconfigure(1, weight=1)
|
||||
mark = tk.Frame(brand, bg=theme.TEAL, width=34, height=34)
|
||||
mark.pack(side="left", padx=(0, 12))
|
||||
mark.grid(row=0, column=0, sticky="w", padx=(0, 12))
|
||||
mark.pack_propagate(False)
|
||||
tk.Label(mark, text="抖", bg=theme.TEAL, fg="#ffffff", font=("Microsoft YaHei UI", 15, "bold")).pack(expand=True)
|
||||
tk.Label(mark, text="抖", bg=theme.TEAL, fg="#ffffff", font=("Microsoft YaHei UI", 17, "bold")).pack(expand=True)
|
||||
title_box = tk.Frame(brand, bg=theme.SURFACE)
|
||||
title_box.pack(side="left")
|
||||
tk.Label(title_box, text="抖音自动化助手", bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 17, "bold")).pack(anchor="w")
|
||||
title_box.grid(row=0, column=1, sticky="w")
|
||||
tk.Label(title_box, text="抖音自动化助手", bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 20, "bold")).pack(anchor="w")
|
||||
tk.Label(title_box, text="轻量数据看板入口", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w")
|
||||
quick_state = tk.Frame(brand, bg=theme.SURFACE)
|
||||
quick_state.grid(row=0, column=2, sticky="e")
|
||||
button(
|
||||
quick_state,
|
||||
"检查更新",
|
||||
self.check_update,
|
||||
width=124,
|
||||
).pack(side="right", padx=(8, 0))
|
||||
tk.Label(
|
||||
quick_state,
|
||||
textvariable=self.status_var,
|
||||
bg=theme.TEAL_SOFT,
|
||||
fg=theme.TEAL_DARK,
|
||||
font=("Microsoft YaHei UI", 13, "bold"),
|
||||
padx=16,
|
||||
pady=8,
|
||||
).pack(side="right")
|
||||
tk.Label(
|
||||
quick_state,
|
||||
text="当前状态",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=theme.FONT_SMALL,
|
||||
).pack(side="right", padx=(0, 8))
|
||||
tool_row = tk.Frame(top, bg=theme.SURFACE)
|
||||
tool_row.pack(fill="x", padx=18, pady=(0, 12))
|
||||
ttk.Label(tool_row, text="设备:", background=theme.SURFACE, foreground=theme.MUTED).pack(side="left")
|
||||
self.device_combo = ttk.Combobox(tool_row, textvariable=self.device_var, values=[], width=28, state="readonly")
|
||||
self.device_combo.pack(side="left", padx=(4, 8))
|
||||
button(tool_row, "刷新设备", self.refresh_devices, width=126).pack(side="left", padx=3)
|
||||
self.scan_button = button(tool_row, "扫描 WiFi", self.scan_wifi, width=128)
|
||||
self.scan_button.pack(side="left", padx=4)
|
||||
button(tool_row, "WiFi ADB", self.open_wifi_adb, width=118).pack(side="left", padx=3)
|
||||
ttk.Label(tool_row, text="Y偏移:", background=theme.SURFACE, foreground=theme.MUTED).pack(side="left", padx=(8, 3))
|
||||
ttk.Entry(tool_row, textvariable=self.y_var, width=7).pack(side="left")
|
||||
button(tool_row, "保存配置", self.save_config, width=126).pack(side="right", padx=3)
|
||||
button(tool_row, "截图+OCR", self.screenshot_ocr, kind="primary", width=132).pack(side="right", padx=3)
|
||||
tool_row.pack(fill="x", padx=20, pady=(4, 14))
|
||||
tool_row.grid_columnconfigure(0, minsize=350)
|
||||
tool_row.grid_columnconfigure(1, weight=1)
|
||||
tool_row.grid_columnconfigure(2, minsize=318)
|
||||
|
||||
device_group = tk.Frame(tool_row, bg=theme.SURFACE)
|
||||
device_group.grid(row=0, column=0, sticky="ew", padx=(0, 16))
|
||||
tk.Label(
|
||||
device_group,
|
||||
text="设备",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
).pack(anchor="w", pady=(0, 7))
|
||||
self.device_combo = ttk.Combobox(device_group, textvariable=self.device_var, values=[], width=38, state="readonly")
|
||||
self.device_combo.pack(fill="x")
|
||||
|
||||
device_actions = tk.Frame(tool_row, bg=theme.SURFACE)
|
||||
device_actions.grid(row=0, column=1, sticky="w", padx=(0, 12))
|
||||
tk.Label(
|
||||
device_actions,
|
||||
text="设备工具",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
).pack(anchor="w", pady=(0, 7))
|
||||
device_button_row = tk.Frame(device_actions, bg=theme.SURFACE)
|
||||
device_button_row.pack(anchor="w")
|
||||
button(device_button_row, "刷新设备", self.refresh_devices, width=120).pack(side="left", padx=(0, 6))
|
||||
self.scan_button = button(device_button_row, "扫描 WiFi", self.scan_wifi, width=124)
|
||||
self.scan_button.pack(side="left", padx=(0, 6))
|
||||
button(device_button_row, "WiFi ADB", self.open_wifi_adb, width=112).pack(side="left", padx=(0, 6))
|
||||
button(device_button_row, "上传日志", self.upload_logs, width=112).pack(side="left")
|
||||
|
||||
primary_actions = tk.Frame(tool_row, bg=theme.SURFACE)
|
||||
primary_actions.grid(row=0, column=2, sticky="e")
|
||||
tk.Label(
|
||||
primary_actions,
|
||||
text="主操作",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
).pack(anchor="e", pady=(0, 7))
|
||||
primary_button_row = tk.Frame(primary_actions, bg=theme.SURFACE)
|
||||
primary_button_row.pack(anchor="e")
|
||||
button(primary_button_row, "保存配置", self.save_config, width=130).pack(side="left", padx=(0, 8))
|
||||
button(primary_button_row, "截图+OCR", self.screenshot_ocr, kind="primary", width=148).pack(side="left")
|
||||
|
||||
main = ttk.Frame(shell, style="Dashboard.TFrame")
|
||||
main.pack(fill="both", expand=True, padx=18, pady=(6, 8))
|
||||
main.pack(fill="both", expand=True, padx=20, pady=(6, 6))
|
||||
main.grid_columnconfigure(1, weight=1)
|
||||
main.grid_rowconfigure(0, weight=1)
|
||||
|
||||
sidebar = rounded_surface(main, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
sidebar.grid(row=0, column=0, sticky="nsw", padx=(0, 16))
|
||||
sidebar.configure(width=204)
|
||||
sidebar = rounded_surface(main, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_LG)
|
||||
sidebar.grid(row=0, column=0, sticky="nsw", padx=(0, 18))
|
||||
sidebar.configure(width=218)
|
||||
sidebar.grid_propagate(False)
|
||||
sidebar.pack_propagate(False)
|
||||
nav_canvas = tk.Canvas(sidebar, bg=theme.SURFACE, highlightthickness=0, bd=0)
|
||||
nav_scroll = ttk.Scrollbar(sidebar, orient="vertical", command=nav_canvas.yview)
|
||||
nav_scroll = SlimScrollbar(sidebar, command=lambda *args: nav_canvas.yview(*[a for a in args if a is not None]))
|
||||
nav_inner = tk.Frame(nav_canvas, bg=theme.SURFACE)
|
||||
nav_window = nav_canvas.create_window((0, 0), window=nav_inner, anchor="nw")
|
||||
nav_canvas.configure(yscrollcommand=nav_scroll.set)
|
||||
nav_canvas.pack(side="left", fill="both", expand=True, padx=(0, 2), pady=8)
|
||||
nav_scroll.pack(side="right", fill="y", pady=10)
|
||||
nav_scroll.pack(side="right", fill="y", padx=(0, 8), pady=12)
|
||||
nav_canvas.pack(side="left", fill="both", expand=True, padx=(0, 4), pady=8)
|
||||
nav_inner.bind("<Configure>", lambda _e: nav_canvas.configure(scrollregion=nav_canvas.bbox("all")))
|
||||
nav_canvas.bind("<Configure>", lambda e: nav_canvas.itemconfigure(nav_window, width=e.width))
|
||||
|
||||
@@ -134,10 +234,10 @@ class DashboardApp:
|
||||
("数据", ["运行日志", "行为日志", "实时状态", "截图预览", "统计信息", "预约队列", "高价值房间", "OCR结果", "中奖记录", "映射表"]),
|
||||
("连接", ["WiFi ADB"]),
|
||||
]:
|
||||
ttk.Label(nav_inner, text=group_title, background=theme.SURFACE, foreground=theme.MUTED, font=theme.FONT_SMALL).pack(anchor="w", padx=14, pady=(13, 5))
|
||||
ttk.Label(nav_inner, text=group_title, background=theme.SURFACE, foreground=theme.MUTED, font=("Microsoft YaHei UI", 10, "bold")).pack(anchor="w", padx=16, pady=(14, 6))
|
||||
for name in names:
|
||||
btn = nav_button(nav_inner, name, lambda n=name: self.show_page(n), active=name == self.current_page)
|
||||
btn.pack(fill="x", padx=10, pady=1)
|
||||
btn.pack(fill="x", padx=12, pady=2)
|
||||
self.nav_buttons[name] = btn
|
||||
_bind_nav_wheel(sidebar)
|
||||
|
||||
@@ -145,8 +245,8 @@ class DashboardApp:
|
||||
self.content_scroll.grid(row=0, column=1, sticky="nsew")
|
||||
self.content = self.content_scroll.inner
|
||||
|
||||
bottom = rounded_surface(shell, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
bottom.pack(fill="x", padx=18, pady=(4, 14))
|
||||
bottom = rounded_surface(shell, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_LG)
|
||||
bottom.pack(fill="x", padx=20, pady=(6, 16))
|
||||
inner_bottom = tk.Frame(bottom, bg=theme.SURFACE)
|
||||
inner_bottom.pack(fill="x", padx=14, pady=11)
|
||||
button(inner_bottom, "开始运行", self.start_run, kind="primary", width=132).pack(side="left", padx=(0, 8))
|
||||
@@ -160,6 +260,8 @@ class DashboardApp:
|
||||
def _sync_nav(self) -> None:
|
||||
for name, btn in self.nav_buttons.items():
|
||||
active = name == self.current_page
|
||||
if hasattr(btn, "set_enabled"):
|
||||
btn.set_enabled((not self.license_locked) or name == "授权")
|
||||
if hasattr(btn, "set_active"):
|
||||
btn.set_active(active)
|
||||
|
||||
@@ -187,6 +289,9 @@ class DashboardApp:
|
||||
"screenshot_ocr": self.screenshot_ocr,
|
||||
"scan_wifi": self.scan_wifi,
|
||||
"wifi_adb": self.open_wifi_adb,
|
||||
"verify_license": self.verify_license,
|
||||
"upload_logs": self.upload_logs,
|
||||
"check_update": self.check_update,
|
||||
"show_run_log": lambda: self.show_page("运行日志"),
|
||||
"show_actions_log": lambda: self.show_page("行为日志"),
|
||||
}
|
||||
@@ -273,6 +378,8 @@ class DashboardApp:
|
||||
self.status_var.set(f"刷新设备失败:{exc}")
|
||||
|
||||
def open_wifi_adb(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
self.show_page("WiFi ADB")
|
||||
open_wifi_adb_dialog(
|
||||
self.root,
|
||||
@@ -291,6 +398,8 @@ class DashboardApp:
|
||||
)
|
||||
|
||||
def scan_wifi(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
on_scan_one_click(
|
||||
adb_exe=self.adb_exe,
|
||||
scan_btn=self.scan_button,
|
||||
@@ -303,6 +412,8 @@ class DashboardApp:
|
||||
)
|
||||
|
||||
def _try_reconnect_last_wifi(self) -> None:
|
||||
if self.license_locked:
|
||||
return
|
||||
try_reconnect_last_wifi(
|
||||
self.root,
|
||||
adb_exe=self.adb_exe,
|
||||
@@ -312,6 +423,8 @@ class DashboardApp:
|
||||
)
|
||||
|
||||
def screenshot_ocr(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
do_screenshot(
|
||||
device_id=self._selected_device(),
|
||||
y_offset=int(self.y_var.get() or 0),
|
||||
@@ -327,16 +440,100 @@ class DashboardApp:
|
||||
self.status_var.set(f"OCR结果已更新:{len(results)} 项")
|
||||
|
||||
def start_run(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
if self.runner.is_running():
|
||||
self.status_var.set("已在运行中")
|
||||
return
|
||||
progress = self._show_startup_progress()
|
||||
try:
|
||||
self._update_startup_progress(progress, 12, "保存配置", "正在写入当前界面参数")
|
||||
self.save_config()
|
||||
self.runner.start(self._params())
|
||||
self._update_startup_progress(progress, 38, "解析设备", "正在确认 ADB 与目标设备")
|
||||
params = self._params()
|
||||
self._update_startup_progress(progress, 68, "启动主进程", "正在加载运行核心")
|
||||
self.root.update_idletasks()
|
||||
self.runner.start(params)
|
||||
self._update_startup_progress(progress, 90, "等待运行日志", "主进程已启动,正在等待初始化输出")
|
||||
self.status_var.set("运行中")
|
||||
self.refresh_data()
|
||||
self.data = load_dashboard_data()
|
||||
except Exception as exc:
|
||||
self._close_startup_progress(progress)
|
||||
self.status_var.set(f"启动失败:{exc}")
|
||||
return
|
||||
self.root.after(600, lambda: self._finish_startup_progress(progress))
|
||||
|
||||
def _show_startup_progress(self) -> tk.Toplevel:
|
||||
win = tk.Toplevel(self.root)
|
||||
win.title("启动运行")
|
||||
win.transient(self.root)
|
||||
win.resizable(False, False)
|
||||
win.configure(bg=theme.BG)
|
||||
win.protocol("WM_DELETE_WINDOW", lambda: None)
|
||||
frame = tk.Frame(win, bg=theme.BG, padx=24, pady=22)
|
||||
frame.pack(fill="both", expand=True)
|
||||
card = rounded_surface(frame, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
card.pack(fill="both", expand=True)
|
||||
inner = tk.Frame(card, bg=theme.SURFACE, padx=24, pady=21)
|
||||
inner.pack(fill="both", expand=True)
|
||||
tk.Label(inner, text="正在初始化运行", bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 18, "bold")).pack(anchor="w")
|
||||
stage = tk.Label(inner, text="准备中", bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 14, "bold"))
|
||||
stage.pack(anchor="w", pady=(17, 4))
|
||||
detail = tk.Label(inner, text="正在准备启动环境", bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL)
|
||||
detail.pack(anchor="w", pady=(0, 13))
|
||||
pct = tk.Label(inner, text="0%", bg=theme.SURFACE, fg=theme.TEAL_DARK, font=("Microsoft YaHei UI", 20, "bold"))
|
||||
pct.pack(anchor="e")
|
||||
bar = ttk.Progressbar(inner, mode="determinate", length=420, maximum=100)
|
||||
bar.pack(fill="x", pady=(3, 4), ipady=3)
|
||||
win._startup_labels = {"stage": stage, "detail": detail, "pct": pct, "bar": bar} # type: ignore[attr-defined]
|
||||
self._update_startup_progress(win, 5, "准备中", "正在准备启动环境")
|
||||
try:
|
||||
win.update_idletasks()
|
||||
x = self.root.winfo_rootx() + (self.root.winfo_width() - win.winfo_width()) // 2
|
||||
y = self.root.winfo_rooty() + (self.root.winfo_height() - win.winfo_height()) // 2
|
||||
win.geometry(f"+{max(0, x)}+{max(0, y)}")
|
||||
win.grab_set()
|
||||
except Exception:
|
||||
pass
|
||||
self._startup_progress = win
|
||||
return win
|
||||
|
||||
def _update_startup_progress(self, progress: tk.Toplevel, percent: int, stage: str, detail: str) -> None:
|
||||
labels = getattr(progress, "_startup_labels", None)
|
||||
if not labels:
|
||||
return
|
||||
value = max(0, min(100, int(percent)))
|
||||
labels["stage"].configure(text=stage)
|
||||
labels["detail"].configure(text=detail)
|
||||
labels["pct"].configure(text=f"{value}%")
|
||||
labels["bar"].configure(value=value)
|
||||
try:
|
||||
progress.update_idletasks()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _close_startup_progress(self, progress: tk.Toplevel | None) -> None:
|
||||
if progress is None:
|
||||
return
|
||||
try:
|
||||
progress.grab_release()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
progress.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
if self._startup_progress is progress:
|
||||
self._startup_progress = None
|
||||
|
||||
def _finish_startup_progress(self, progress: tk.Toplevel | None) -> None:
|
||||
if progress is None:
|
||||
return
|
||||
try:
|
||||
self._update_startup_progress(progress, 100, "启动完成", "运行进程已开始")
|
||||
except Exception:
|
||||
pass
|
||||
self._close_startup_progress(progress)
|
||||
|
||||
def stop_run(self) -> None:
|
||||
self.runner.stop()
|
||||
@@ -358,22 +555,242 @@ class DashboardApp:
|
||||
self.status_var.set("已停止(强制)")
|
||||
|
||||
def send_back_key(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
ok = self.runner.send_back_key(self._selected_device())
|
||||
self.status_var.set("返回键已发送" if ok else "发送返回键失败")
|
||||
|
||||
def verify_license(self) -> None:
|
||||
var = self.config_vars.get("license_key_var")
|
||||
raw = str(var.get() if var is not None else "").strip()
|
||||
if not raw:
|
||||
self.status_var.set("请输入卡密")
|
||||
messagebox.showwarning("卡密验证", "请输入卡密后再验证。", parent=self.root)
|
||||
return
|
||||
try:
|
||||
cfg = read_config()
|
||||
section = cfg.get("license") if isinstance(cfg.get("license"), dict) else {}
|
||||
activation_url = str(section.get("activation_url") or "").strip() or get_default_activation_url()
|
||||
timeout_seconds = int(section.get("timeout_seconds") or 10)
|
||||
except Exception:
|
||||
activation_url = get_default_activation_url()
|
||||
timeout_seconds = 10
|
||||
status = install_license_or_activate(
|
||||
raw,
|
||||
activation_url=activation_url,
|
||||
timeout_seconds=max(1, timeout_seconds),
|
||||
)
|
||||
if status.ok:
|
||||
if var is not None:
|
||||
var.set("")
|
||||
self.license_locked = False
|
||||
self.status_var.set("卡密验证成功")
|
||||
self._start_license_monitor_once()
|
||||
messagebox.showinfo("卡密验证", "验证成功,授权已写入本机。", parent=self.root)
|
||||
self.show_page("数据看板")
|
||||
else:
|
||||
self.status_var.set(f"卡密验证失败:{status.message}")
|
||||
messagebox.showerror(
|
||||
"卡密验证失败",
|
||||
f"{status.message}\n\n原因:{status.reason}",
|
||||
parent=self.root,
|
||||
)
|
||||
|
||||
def upload_logs(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
self.status_var.set("正在上传诊断日志")
|
||||
self.root.update_idletasks()
|
||||
result = upload_diagnostic_logs()
|
||||
if result.ok:
|
||||
self.status_var.set("诊断日志上传成功")
|
||||
messagebox.showinfo(
|
||||
"上传诊断日志",
|
||||
f"上传成功。\n大小:{result.size // 1024} KB",
|
||||
parent=self.root,
|
||||
)
|
||||
else:
|
||||
self.status_var.set(f"日志上传失败:{result.message}")
|
||||
messagebox.showerror(
|
||||
"上传诊断日志失败",
|
||||
f"{result.message}\n\n原因:{result.reason}",
|
||||
parent=self.root,
|
||||
)
|
||||
|
||||
def check_update(self) -> None:
|
||||
if not self._ensure_license_ready():
|
||||
return
|
||||
self.status_var.set("正在检查更新")
|
||||
progress = self._show_update_progress("正在连接更新服务器")
|
||||
|
||||
def worker() -> None:
|
||||
try:
|
||||
result = perform_forced_update(
|
||||
settings=load_manual_update_settings(),
|
||||
progress_callback=lambda event: self.root.after(
|
||||
0,
|
||||
lambda event=event: self._update_progress_window(progress, event),
|
||||
),
|
||||
)
|
||||
self.root.after(0, lambda: self._finish_update_progress(progress, lambda: self._show_update_result(result)))
|
||||
except UpdateError as exc:
|
||||
self.root.after(0, lambda: self._finish_update_progress(progress, lambda: self._show_update_error(str(exc))))
|
||||
except Exception as exc:
|
||||
self.root.after(0, lambda: self._finish_update_progress(progress, lambda: self._show_update_error(f"检查更新异常:{exc}")))
|
||||
|
||||
threading.Thread(target=worker, daemon=True).start()
|
||||
|
||||
def _show_update_progress(self, message: str) -> tk.Toplevel:
|
||||
win = tk.Toplevel(self.root)
|
||||
win.title("检查更新")
|
||||
win.transient(self.root)
|
||||
win.resizable(False, False)
|
||||
win.configure(bg=theme.BG)
|
||||
win.protocol("WM_DELETE_WINDOW", lambda: None)
|
||||
frame = tk.Frame(win, bg=theme.BG, padx=26, pady=24)
|
||||
frame.pack(fill="both", expand=True)
|
||||
|
||||
card = rounded_surface(frame, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
card.pack(fill="both", expand=True)
|
||||
inner = tk.Frame(card, bg=theme.SURFACE, padx=24, pady=22)
|
||||
inner.pack(fill="both", expand=True)
|
||||
|
||||
top = tk.Frame(inner, bg=theme.SURFACE)
|
||||
top.pack(fill="x")
|
||||
tk.Label(
|
||||
top,
|
||||
text="软件更新",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEXT,
|
||||
font=("Microsoft YaHei UI", 18, "bold"),
|
||||
).pack(side="left")
|
||||
mode = tk.Label(
|
||||
top,
|
||||
text="检查中",
|
||||
bg=theme.TEAL_SOFT,
|
||||
fg=theme.TEAL_DARK,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
padx=12,
|
||||
pady=5,
|
||||
)
|
||||
mode.pack(side="right")
|
||||
|
||||
stage = tk.Label(
|
||||
inner,
|
||||
text=message,
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEXT,
|
||||
font=("Microsoft YaHei UI", 14, "bold"),
|
||||
)
|
||||
stage.pack(anchor="w", pady=(18, 4))
|
||||
detail = tk.Label(
|
||||
inner,
|
||||
text="优先尝试差量更新,失败后才回退完整安装包",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.MUTED,
|
||||
font=theme.FONT_SMALL,
|
||||
)
|
||||
detail.pack(anchor="w", pady=(0, 14))
|
||||
pct = tk.Label(
|
||||
inner,
|
||||
text="0%",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.TEAL_DARK,
|
||||
font=("Microsoft YaHei UI", 22, "bold"),
|
||||
)
|
||||
pct.pack(anchor="e")
|
||||
bar = ttk.Progressbar(inner, mode="determinate", length=420, maximum=100)
|
||||
bar.pack(fill="x", pady=(3, 10), ipady=3)
|
||||
sub = tk.Label(
|
||||
inner,
|
||||
text="准备中",
|
||||
bg=theme.SURFACE,
|
||||
fg=theme.SUBTLE,
|
||||
font=("Microsoft YaHei UI", 11),
|
||||
)
|
||||
sub.pack(anchor="w")
|
||||
|
||||
win._update_labels = { # type: ignore[attr-defined]
|
||||
"mode": mode,
|
||||
"stage": stage,
|
||||
"detail": detail,
|
||||
"pct": pct,
|
||||
"bar": bar,
|
||||
"sub": sub,
|
||||
}
|
||||
self._update_progress_window(win, {"stage": "manifest_fetch", "message": message})
|
||||
|
||||
try:
|
||||
win.update_idletasks()
|
||||
x = self.root.winfo_rootx() + (self.root.winfo_width() - win.winfo_width()) // 2
|
||||
y = self.root.winfo_rooty() + (self.root.winfo_height() - win.winfo_height()) // 2
|
||||
win.geometry(f"+{max(0, x)}+{max(0, y)}")
|
||||
win.grab_set()
|
||||
except Exception:
|
||||
pass
|
||||
return win
|
||||
|
||||
def _update_progress_window(self, progress: tk.Toplevel, event: dict) -> None:
|
||||
labels = getattr(progress, "_update_labels", None)
|
||||
if not labels:
|
||||
return
|
||||
apply_update_progress_event(
|
||||
event,
|
||||
mode_label=labels["mode"],
|
||||
stage_label=labels["stage"],
|
||||
detail_label=labels["detail"],
|
||||
percent_label=labels["pct"],
|
||||
bar=labels["bar"],
|
||||
sub_label=labels["sub"],
|
||||
)
|
||||
|
||||
def _finish_update_progress(self, progress: tk.Toplevel, callback) -> None:
|
||||
try:
|
||||
progress.grab_release()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
progress.destroy()
|
||||
except Exception:
|
||||
pass
|
||||
callback()
|
||||
|
||||
def _show_update_result(self, result) -> None:
|
||||
self.status_var.set(result.message or "更新检查完成")
|
||||
if result.exit_required:
|
||||
messagebox.showinfo(
|
||||
"检查更新",
|
||||
f"{result.message}\n\n程序会交给更新器处理,请按提示完成更新。",
|
||||
parent=self.root,
|
||||
)
|
||||
try:
|
||||
self.root.after(300, self.root.destroy)
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
messagebox.showinfo("检查更新", result.message or "已是最新版本。", parent=self.root)
|
||||
|
||||
def _show_update_error(self, message: str) -> None:
|
||||
self.status_var.set(f"检查更新失败:{message}")
|
||||
messagebox.showerror("检查更新失败", message, parent=self.root)
|
||||
|
||||
def refresh_data(self) -> None:
|
||||
self.data = load_dashboard_data()
|
||||
self.status_var.set("已刷新")
|
||||
self.show_page(self.current_page)
|
||||
|
||||
def show_page(self, name: str) -> None:
|
||||
self.current_page = name
|
||||
target = name if name in PAGES else "数据看板"
|
||||
if self.license_locked and target != "授权":
|
||||
target = "授权"
|
||||
self.status_var.set("请先验证卡密")
|
||||
self.current_page = target
|
||||
self._sync_nav()
|
||||
self._capture_text_widgets()
|
||||
self._apply_text_cache_to_data()
|
||||
self._ensure_text_widgets()
|
||||
clear(self.content)
|
||||
builder = PAGES.get(name, PAGES["数据看板"])
|
||||
builder = PAGES.get(target, PAGES["数据看板"])
|
||||
builder(self.content, self.data, PageContext(self.config_vars, self.text_widgets, self._actions(), self.status_var, self.runner))
|
||||
try:
|
||||
self.content_scroll.canvas.yview_moveto(0)
|
||||
@@ -385,11 +802,21 @@ class DashboardApp:
|
||||
|
||||
|
||||
def main() -> None:
|
||||
enforce_dashboard_license_required()
|
||||
local_status = check_license()
|
||||
if local_status.ok:
|
||||
require_online_license_or_exit()
|
||||
try:
|
||||
print_version_banner("gui_dashboard_app")
|
||||
except Exception:
|
||||
pass
|
||||
DashboardApp().run()
|
||||
app = DashboardApp(
|
||||
initial_page="数据看板" if local_status.ok else "授权",
|
||||
license_locked=not local_status.ok,
|
||||
)
|
||||
if local_status.ok:
|
||||
app._start_license_monitor_once()
|
||||
app.run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import tkinter as tk
|
||||
|
||||
from douyin.license.license_manager import get_license_status_payload
|
||||
|
||||
from . import theme
|
||||
from .data import DashboardData, cfg_get
|
||||
from .page_context import PageContext
|
||||
@@ -166,7 +169,32 @@ def build_license(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> Non
|
||||
section(parent, "授权", "输入卡密后自动联网验证")
|
||||
box = card(parent, "卡密验证")
|
||||
box.pack(fill="x")
|
||||
if "license_key_var" not in ctx.vars:
|
||||
ctx.vars["license_key_var"] = tk.StringVar(value="")
|
||||
pack_fields(box, ctx, [("输入卡密", "license_key_var", "")], columns=1)
|
||||
try:
|
||||
os.environ["DOUYIN_LICENSE_REQUIRED"] = "1"
|
||||
payload = get_license_status_payload()
|
||||
except Exception as exc:
|
||||
payload = {"ok": False, "message": f"读取授权状态失败:{exc}", "reason": "status_error"}
|
||||
ok = bool(payload.get("ok"))
|
||||
message = str(payload.get("message") or payload.get("reason") or "未知状态")
|
||||
status = tk.Frame(box, bg=theme.GREEN_SOFT if ok else theme.AMBER_SOFT)
|
||||
status.pack(fill="x", padx=20, pady=(0, 12))
|
||||
tk.Label(
|
||||
status,
|
||||
text=("当前授权有效" if ok else "当前授权未通过"),
|
||||
bg=status["bg"],
|
||||
fg=theme.GREEN if ok else theme.AMBER,
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
).pack(side="left", padx=12, pady=8)
|
||||
tk.Label(
|
||||
status,
|
||||
text=message,
|
||||
bg=status["bg"],
|
||||
fg=theme.TEXT,
|
||||
font=theme.FONT_SMALL,
|
||||
).pack(side="left", padx=(8, 12), pady=8)
|
||||
row = tk.Frame(box, bg=theme.SURFACE)
|
||||
row.pack(fill="x", padx=20, pady=(0, 16))
|
||||
button(row, "验证卡密", None, kind="primary").pack(side="left", padx=(0, 8))
|
||||
button(row, "验证卡密", ctx.action("verify_license"), kind="primary").pack(side="left", padx=(0, 8))
|
||||
@@ -2,8 +2,11 @@ from __future__ import annotations
|
||||
|
||||
import re
|
||||
import tkinter as tk
|
||||
from pathlib import Path
|
||||
from tkinter import ttk
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from . import theme
|
||||
from .data import DashboardData, fmt_ts, load_dashboard_data
|
||||
from .page_context import PageContext
|
||||
@@ -189,7 +192,13 @@ def build_run_log(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> Non
|
||||
def build_preview(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
||||
section(parent, "截图预览", "选择图片 / 打开pic目录 / 刷新预览")
|
||||
toolbar(parent, [("刷新预览", ctx.action("refresh"), "soft"), ("截图+OCR", ctx.action("screenshot_ocr"), "primary"), "打开pic目录"])
|
||||
preview_panel(parent, data.current_screenshot_path, "当前截图").pack(fill="both", expand=True)
|
||||
preview_panel(
|
||||
parent,
|
||||
data.current_screenshot_path,
|
||||
"当前截图",
|
||||
auto_refresh_ms=1000,
|
||||
path_getter=lambda: Path(path_config.get_screenshot_path()),
|
||||
).pack(fill="both", expand=True)
|
||||
|
||||
|
||||
RESERVATION_COLUMNS = (
|
||||
@@ -201,8 +210,8 @@ RESERVATION_COLUMNS = (
|
||||
|
||||
|
||||
HOME_RESERVATION_COLUMNS = (
|
||||
("idx", "#", 32), ("pos", "位置", 54), ("title", "直播间", 120), ("content", "内容", 160),
|
||||
("value", "价值", 58), ("countdown", "倒计时", 76), ("status", "状态", 68), ("target_time", "开奖时间", 132),
|
||||
("idx", "#", 32), ("pos", "位置", 48), ("title", "直播间", 112), ("content", "内容", 214),
|
||||
("value", "价值", 60), ("status", "状态", 72),
|
||||
)
|
||||
|
||||
|
||||
@@ -233,10 +242,15 @@ def _replace_table_rows(tree: ttk.Treeview, columns: tuple[tuple[str, str, int],
|
||||
for item_id in tree.get_children(""):
|
||||
tree.delete(item_id)
|
||||
if rows:
|
||||
for row in rows:
|
||||
tree.insert("", "end", values=[str(row.get(key, "-")) for key, _, _ in columns])
|
||||
for idx, row in enumerate(rows):
|
||||
tree.insert(
|
||||
"",
|
||||
"end",
|
||||
values=[str(row.get(key, "-")) for key, _, _ in columns],
|
||||
tags=("even" if idx % 2 else "odd",),
|
||||
)
|
||||
else:
|
||||
tree.insert("", "end", values=["暂无数据" if idx == 0 else "" for idx, _c in enumerate(columns)])
|
||||
tree.insert("", "end", values=["暂无数据" if idx == 0 else "" for idx, _c in enumerate(columns)], tags=("empty",))
|
||||
try:
|
||||
tree.yview_moveto(top_pos)
|
||||
except Exception:
|
||||
@@ -374,7 +388,13 @@ def build_realtime(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> No
|
||||
body = tk.Frame(parent, bg=theme.BG)
|
||||
body.pack(fill="both", expand=True)
|
||||
text_panel(body, "动作流", data.action_log[-120:], height=16).pack(fill="both", expand=True, pady=(0, 12))
|
||||
preview_panel(body, data.current_screenshot_path, "实时截图").pack(fill="both", expand=True)
|
||||
preview_panel(
|
||||
body,
|
||||
data.current_screenshot_path,
|
||||
"实时截图",
|
||||
auto_refresh_ms=1000,
|
||||
path_getter=lambda: Path(path_config.get_screenshot_path()),
|
||||
).pack(fill="both", expand=True)
|
||||
|
||||
|
||||
def build_ocr(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
||||
|
||||
@@ -4,9 +4,12 @@ import re
|
||||
import tkinter as tk
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from threading import RLock
|
||||
from typing import Any
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
from . import theme
|
||||
from .data import DashboardData, fmt_ts, load_dashboard_data
|
||||
from .page_data import HOME_RESERVATION_COLUMNS, _reservation_rows_for_display, reservation_auto_refresh_control
|
||||
@@ -190,12 +193,13 @@ def build_home(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
||||
]
|
||||
for idx, item in enumerate(values):
|
||||
tile = stat_tile(metrics, *item[:3], color=item[3], soft=item[4], compact=True)
|
||||
tile.grid(row=idx // 3, column=idx % 3, sticky="ew", padx=4, pady=4)
|
||||
tile.grid(row=idx // 3, column=idx % 3, sticky="ew", padx=6, pady=5)
|
||||
|
||||
body = tk.Frame(parent, bg=theme.BG)
|
||||
body.pack(fill="both", expand=True)
|
||||
body.grid_columnconfigure(0, weight=3, minsize=540)
|
||||
body.grid_columnconfigure(1, weight=2, minsize=380)
|
||||
body.pack(fill="both", expand=True, pady=(4, 0))
|
||||
body.grid_columnconfigure(0, weight=4, minsize=620)
|
||||
body.grid_columnconfigure(1, weight=2, minsize=360)
|
||||
body.grid_rowconfigure(0, weight=1)
|
||||
|
||||
left = tk.Frame(body, bg=theme.BG)
|
||||
right = tk.Frame(body, bg=theme.BG)
|
||||
@@ -215,7 +219,14 @@ def build_home(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
|
||||
include_created=False,
|
||||
).pack(side="left")
|
||||
|
||||
preview_panel(right, data.current_screenshot_path, "实时截图").pack(fill="both", expand=True)
|
||||
preview_panel(
|
||||
right,
|
||||
data.current_screenshot_path,
|
||||
"实时截图",
|
||||
max_size=(430, 620),
|
||||
auto_refresh_ms=1000,
|
||||
path_getter=lambda: Path(path_config.get_screenshot_path()),
|
||||
).pack(fill="both", expand=True)
|
||||
|
||||
|
||||
def _statistics_values(data: DashboardData, ctx: PageContext) -> tuple[dict[str, Any], str, str]:
|
||||
|
||||
+16
-194
@@ -47,56 +47,6 @@ def _last_log_time(stats: dict[str, Any]) -> str:
|
||||
return "-"
|
||||
|
||||
|
||||
def _group(parent: tk.Misc, title: str) -> tk.Frame:
|
||||
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
box.pack(fill="both", expand=True)
|
||||
head = tk.Frame(box, bg=theme.SURFACE)
|
||||
head.pack(fill="x", padx=16, pady=(14, 8))
|
||||
tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 10))
|
||||
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_H2).pack(side="left")
|
||||
body = tk.Frame(box, bg=theme.SURFACE)
|
||||
body.pack(fill="both", expand=True, padx=16, pady=(0, 14))
|
||||
return body
|
||||
|
||||
|
||||
def _metric_row(parent: tk.Misc, label: str, value: object, hint: str = "", color: str = theme.TEAL) -> None:
|
||||
row = tk.Frame(parent, bg=theme.SURFACE)
|
||||
row.pack(fill="x", pady=4)
|
||||
tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_UI).pack(side="left")
|
||||
tk.Label(row, text=str(value), bg=theme.SURFACE, fg=color, font=("Microsoft YaHei UI", 15, "bold")).pack(side="right")
|
||||
if hint:
|
||||
tk.Label(parent, text=hint, bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 4))
|
||||
|
||||
|
||||
def _kpi_tile(parent: tk.Misc, title: str, value: object, hint: str, color: str, soft: str) -> tk.Frame:
|
||||
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
box.configure(height=104)
|
||||
box.pack_propagate(False)
|
||||
accent = tk.Frame(box, bg=color, width=4)
|
||||
accent.pack(side="left", fill="y")
|
||||
inner = tk.Frame(box, bg=theme.SURFACE)
|
||||
inner.pack(side="left", fill="both", expand=True, padx=14, pady=10)
|
||||
head = tk.Frame(inner, bg=theme.SURFACE)
|
||||
head.pack(fill="x")
|
||||
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left")
|
||||
tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 9, "bold")).pack(side="right")
|
||||
tk.Label(inner, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 18, "bold")).pack(anchor="w", pady=(4, 0))
|
||||
tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=9, pady=2).pack(anchor="w", pady=(5, 0))
|
||||
return box
|
||||
|
||||
|
||||
def _bar_row(parent: tk.Misc, label: str, value: int, total: int, color: str = theme.TEAL) -> None:
|
||||
row = tk.Frame(parent, bg=theme.SURFACE)
|
||||
row.pack(fill="x", pady=5)
|
||||
tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_UI).pack(side="left")
|
||||
tk.Label(row, text=f"{value} {_fmt_rate(value, total)}", bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="right")
|
||||
track = tk.Frame(parent, bg=theme.BG_ALT, height=8)
|
||||
track.pack(fill="x", pady=(0, 4))
|
||||
pct = 0.0 if total <= 0 else min(1.0, max(0.0, value / total))
|
||||
fill = tk.Frame(track, bg=color, height=8)
|
||||
fill.place(relx=0, rely=0, relwidth=pct, relheight=1)
|
||||
|
||||
|
||||
class StatsDashboardView:
|
||||
def __init__(self, parent: tk.Misc) -> None:
|
||||
self.root = tk.Frame(parent, bg=theme.BG)
|
||||
@@ -112,35 +62,34 @@ class StatsDashboardView:
|
||||
|
||||
def _kpi_tile(self, parent: tk.Misc, key: str, title: str, color: str, soft: str) -> tk.Frame:
|
||||
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
box.configure(height=104)
|
||||
box.configure(height=112)
|
||||
box.pack_propagate(False)
|
||||
tk.Frame(box, bg=color, width=4).pack(side="left", fill="y")
|
||||
inner = tk.Frame(box, bg=theme.SURFACE)
|
||||
inner.pack(side="left", fill="both", expand=True, padx=14, pady=10)
|
||||
inner.pack(fill="both", expand=True, padx=16, pady=12)
|
||||
head = tk.Frame(inner, bg=theme.SURFACE)
|
||||
head.pack(fill="x")
|
||||
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left")
|
||||
tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 9, "bold")).pack(side="right")
|
||||
tk.Label(inner, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 18, "bold")).pack(anchor="w", pady=(4, 0))
|
||||
tk.Label(inner, textvariable=self._var(f"{key}.hint"), bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=9, pady=2).pack(anchor="w", pady=(5, 0))
|
||||
tk.Label(inner, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 22, "bold")).pack(anchor="w", pady=(5, 0))
|
||||
tk.Label(inner, textvariable=self._var(f"{key}.hint"), bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=10, pady=3).pack(anchor="w", pady=(7, 0))
|
||||
return box
|
||||
|
||||
def _metric_row(self, parent: tk.Misc, key: str, label: str, color: str = theme.TEAL) -> None:
|
||||
row = tk.Frame(parent, bg=theme.SURFACE)
|
||||
row.pack(fill="x", pady=4)
|
||||
tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_UI).pack(side="left")
|
||||
tk.Label(row, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE, fg=color, font=("Microsoft YaHei UI", 15, "bold")).pack(side="right")
|
||||
tk.Label(parent, textvariable=self._var(f"{key}.hint"), bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 4))
|
||||
row = tk.Frame(parent, bg=theme.SURFACE_ALT)
|
||||
row.pack(fill="x", pady=5)
|
||||
tk.Label(row, text=label, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=theme.FONT_UI, anchor="w").pack(side="left", fill="x", expand=True, padx=(10, 6), pady=(8, 2))
|
||||
tk.Label(row, textvariable=self._var(f"{key}.value"), bg=theme.SURFACE_ALT, fg=color, font=("Microsoft YaHei UI", 16, "bold")).pack(side="right", padx=10, pady=(8, 2))
|
||||
tk.Label(parent, textvariable=self._var(f"{key}.hint"), bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_SMALL).pack(anchor="w", pady=(0, 5), padx=2)
|
||||
|
||||
def _bar_row(self, parent: tk.Misc, key: str, label: str, color: str = theme.TEAL) -> None:
|
||||
row = tk.Frame(parent, bg=theme.SURFACE)
|
||||
row.pack(fill="x", pady=5)
|
||||
row.pack(fill="x", pady=(7, 3))
|
||||
tk.Label(row, text=label, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_UI).pack(side="left")
|
||||
value_var = self._var(f"{key}.value")
|
||||
tk.Label(row, textvariable=value_var, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="right")
|
||||
track = tk.Frame(parent, bg=theme.BG_ALT, height=8)
|
||||
track = tk.Frame(parent, bg=theme.BG_ALT, height=10)
|
||||
track.pack(fill="x", pady=(0, 4))
|
||||
fill = tk.Frame(track, bg=color, height=8)
|
||||
fill = tk.Frame(track, bg=color, height=10)
|
||||
fill.place(relx=0, rely=0, relwidth=0, relheight=1)
|
||||
self.bars[key] = (value_var, fill)
|
||||
|
||||
@@ -148,11 +97,11 @@ class StatsDashboardView:
|
||||
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
box.pack(fill="both", expand=True)
|
||||
head = tk.Frame(box, bg=theme.SURFACE)
|
||||
head.pack(fill="x", padx=16, pady=(14, 8))
|
||||
head.pack(fill="x", padx=18, pady=(16, 8))
|
||||
tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 10))
|
||||
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.TEXT, font=theme.FONT_H2).pack(side="left")
|
||||
body = tk.Frame(box, bg=theme.SURFACE)
|
||||
body.pack(fill="both", expand=True, padx=16, pady=(0, 14))
|
||||
body.pack(fill="both", expand=True, padx=18, pady=(0, 16))
|
||||
return body
|
||||
|
||||
def _build(self) -> None:
|
||||
@@ -168,7 +117,7 @@ class StatsDashboardView:
|
||||
("total_run", "总运行", theme.BLUE, theme.BLUE_SOFT),
|
||||
]
|
||||
for idx, (key, title, color, soft) in enumerate(kpis):
|
||||
self._kpi_tile(grid, key, title, color, soft).grid(row=idx // 4, column=idx % 4, sticky="ew", padx=4, pady=4)
|
||||
self._kpi_tile(grid, key, title, color, soft).grid(row=idx // 4, column=idx % 4, sticky="ew", padx=6, pady=5)
|
||||
|
||||
panels = tk.Frame(self.root, bg=theme.BG)
|
||||
panels.pack(fill="both", expand=True)
|
||||
@@ -180,7 +129,7 @@ class StatsDashboardView:
|
||||
slots = []
|
||||
for idx in range(6):
|
||||
slot = tk.Frame(panels, bg=theme.BG)
|
||||
slot.grid(row=idx // 2, column=idx % 2, sticky="nsew", padx=(0 if idx % 2 == 0 else 8, 8 if idx % 2 == 0 else 0), pady=6)
|
||||
slot.grid(row=idx // 2, column=idx % 2, sticky="nsew", padx=(0 if idx % 2 == 0 else 10, 10 if idx % 2 == 0 else 0), pady=7)
|
||||
slots.append(slot)
|
||||
|
||||
core = self._group(slots[0], "核心流程")
|
||||
@@ -309,130 +258,3 @@ class StatsDashboardView:
|
||||
self._set("last_countdown", last.get("countdown") or "-", "")
|
||||
self._set("last_value", last.get("prize_value_yuan") or "-", "元")
|
||||
self._set("last_people", f"{last.get('participants') or '-'} / {last.get('copies') or '-'}", "")
|
||||
|
||||
|
||||
def _build_top_cards(parent: tk.Misc, stats: dict[str, Any], current_run: str, total_run: str) -> None:
|
||||
uptime = int(stats.get("uptime_seconds") or 0)
|
||||
if uptime > 0:
|
||||
current_run = _fmt_duration(uptime)
|
||||
grid = flow_grid(parent, 4)
|
||||
values = [
|
||||
("运行状态", "运行中" if stats.get("running") else "未运行", f"日志 {_last_log_time(stats)}", theme.TEAL, theme.TEAL_SOFT),
|
||||
("本次运行", current_run, "当前轮次", theme.BLUE, theme.BLUE_SOFT),
|
||||
("参与成功", _counter(stats, "fudai_attend_ok_unique"), "去重口径", theme.GREEN, theme.GREEN_SOFT),
|
||||
("中奖次数", _counter(stats, "fudai_result_win"), "开奖结果", theme.RED, theme.RED_SOFT),
|
||||
("识别福袋", _counter(stats, "fudai_seen_unique"), "唯一口径", theme.TEAL, theme.TEAL_SOFT),
|
||||
("打开详情", _counter(stats, "fudai_open_detail_unique"), "详情页", theme.BLUE, theme.BLUE_SOFT),
|
||||
("切换直播间", _counter(stats, "switch_room"), "运行动作", theme.AMBER, theme.AMBER_SOFT),
|
||||
("总运行", total_run, "日志累计", theme.BLUE, theme.BLUE_SOFT),
|
||||
]
|
||||
for idx, item in enumerate(values):
|
||||
tile = _kpi_tile(grid, *item[:3], color=item[3], soft=item[4])
|
||||
tile.grid(row=idx // 4, column=idx % 4, sticky="ew", padx=4, pady=4)
|
||||
|
||||
|
||||
def _build_core_flow(parent: tk.Misc, stats: dict[str, Any]) -> None:
|
||||
body = _group(parent, "核心流程")
|
||||
seen = _counter(stats, "fudai_seen_unique")
|
||||
open_detail = _counter(stats, "fudai_open_detail_unique")
|
||||
click = _counter(stats, "fudai_click_attend_unique")
|
||||
attend = _counter(stats, "fudai_attend_ok_unique")
|
||||
win = _counter(stats, "fudai_result_win")
|
||||
no_win = _counter(stats, "fudai_result_no_win")
|
||||
_bar_row(body, "识别福袋", seen, max(seen, 1), theme.TEAL)
|
||||
_bar_row(body, "打开详情", open_detail, max(seen, 1), theme.BLUE)
|
||||
_bar_row(body, "点击参与", click, max(open_detail, 1), theme.AMBER)
|
||||
_bar_row(body, "参与成功", attend, max(click, attend, 1), theme.GREEN)
|
||||
_metric_row(body, "中奖率", _fmt_rate(win, win + no_win), f"中奖 {win} / 未中 {no_win}", theme.RED)
|
||||
|
||||
|
||||
def _build_efficiency(parent: tk.Misc, stats: dict[str, Any]) -> None:
|
||||
body = _group(parent, "效率与动作")
|
||||
uptime = int(stats.get("uptime_seconds") or 0)
|
||||
_metric_row(body, "识别效率", _per_hour(_counter(stats, "fudai_seen_unique"), uptime), "每小时识别福袋", theme.TEAL)
|
||||
_metric_row(body, "参与效率", _per_hour(_counter(stats, "fudai_attend_ok_unique"), uptime), "每小时成功参与", theme.GREEN)
|
||||
_metric_row(body, "切换频率", _per_hour(_counter(stats, "switch_room"), uptime), "每小时切换直播间", theme.AMBER)
|
||||
ocr_attempt = _counter(stats, "ocr_attempt")
|
||||
_metric_row(body, "OCR成功率", _fmt_rate(_counter(stats, "ocr_success"), ocr_attempt), f"尝试 {ocr_attempt}", theme.BLUE)
|
||||
|
||||
|
||||
def _build_skip(parent: tk.Misc, stats: dict[str, Any]) -> None:
|
||||
body = _group(parent, "过滤与跳过")
|
||||
items = [
|
||||
("价值过低", "fudai_skip_value_low", theme.AMBER),
|
||||
("人数过少", "fudai_skip_participants_low", theme.BLUE),
|
||||
("人数过多", "fudai_skip_participants_high", theme.BLUE),
|
||||
("内容过滤", "fudai_skip_content", theme.TEAL),
|
||||
("倒计时太短", "fudai_skip_countdown_short", theme.RED),
|
||||
("倒计时太长", "fudai_skip_countdown_long", theme.AMBER),
|
||||
("需要看播", "fudai_skip_watch_required", theme.RED),
|
||||
]
|
||||
total = sum(_counter(stats, key) for _, key, _ in items)
|
||||
if total <= 0:
|
||||
tk.Label(body, text="暂无跳过记录", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_READ).pack(anchor="w", pady=8)
|
||||
return
|
||||
for label, key, color in items:
|
||||
value = _counter(stats, key)
|
||||
if value > 0:
|
||||
_bar_row(body, label, value, total, color)
|
||||
|
||||
|
||||
def _build_reservation(parent: tk.Misc, stats: dict[str, Any]) -> None:
|
||||
body = _group(parent, "预约与回访")
|
||||
recorded = _counter(stats, "reservation_recorded")
|
||||
back_success = _counter(stats, "reservation_back_success")
|
||||
verify_ok = _counter(stats, "reservation_back_verify_ok")
|
||||
verify_fail = _counter(stats, "reservation_back_verify_fail")
|
||||
_metric_row(body, "记录预约", recorded, "累计写入预约队列", theme.TEAL)
|
||||
_metric_row(body, "回退成功", back_success, f"成功率 {_fmt_rate(back_success, recorded)}", theme.GREEN)
|
||||
_metric_row(body, "回退校验", _fmt_rate(verify_ok, verify_ok + verify_fail), f"成功 {verify_ok} / 失败 {verify_fail}", theme.BLUE)
|
||||
_metric_row(body, "高价值预约", _counter(stats, "fudai_reserved_high_value"), "倒计时长但价值高", theme.AMBER)
|
||||
|
||||
|
||||
def _build_health(parent: tk.Misc, stats: dict[str, Any]) -> None:
|
||||
body = _group(parent, "运行健康")
|
||||
total = _counter(stats, "error_total")
|
||||
detail_errors = _counter(stats, "error_read_detail") + _counter(stats, "fudai_open_error")
|
||||
vision_errors = _counter(stats, "error_ocr") + _counter(stats, "error_screenshot") + _counter(stats, "error_detection")
|
||||
_metric_row(body, "总错误数", total, "运行日志异常计数", theme.RED if total else theme.GREEN)
|
||||
_metric_row(body, "识别/截图异常", vision_errors, "OCR、截图、识别", theme.RED if vision_errors else theme.GREEN)
|
||||
_metric_row(body, "详情异常", detail_errors, "读详情或打开失败", theme.RED if detail_errors else theme.GREEN)
|
||||
_metric_row(body, "慢操作", _counter(stats, "slow_operation"), ">5秒操作", theme.AMBER)
|
||||
|
||||
|
||||
def _build_latest(parent: tk.Misc, stats: dict[str, Any]) -> None:
|
||||
body = _group(parent, "最近福袋")
|
||||
last = stats.get("fudai_last", {}) or {}
|
||||
if not (last.get("content") or last.get("countdown")):
|
||||
tk.Label(body, text="暂无最近福袋信息", bg=theme.SURFACE, fg=theme.SUBTLE, font=theme.FONT_READ).pack(anchor="w", pady=8)
|
||||
return
|
||||
_metric_row(body, "内容", last.get("content") or "-", color=theme.TEXT)
|
||||
_metric_row(body, "倒计时", last.get("countdown") or "-", color=theme.BLUE)
|
||||
_metric_row(body, "价值", f"{last.get('prize_value_yuan') or '-'}", "元", theme.AMBER)
|
||||
participants = last.get("participants")
|
||||
copies = last.get("copies")
|
||||
_metric_row(body, "人数/份数", f"{participants or '-'} / {copies or '-'}", color=theme.TEAL)
|
||||
|
||||
|
||||
def build_stats_dashboard(parent: tk.Misc, stats: dict[str, Any], current_run: str, total_run: str) -> tk.Frame:
|
||||
_build_top_cards(parent, stats, current_run, total_run)
|
||||
grid = tk.Frame(parent, bg=theme.BG)
|
||||
grid.pack(fill="both", expand=True)
|
||||
for col in range(2):
|
||||
grid.grid_columnconfigure(col, weight=1, uniform="stats")
|
||||
for row in range(3):
|
||||
grid.grid_rowconfigure(row, weight=1)
|
||||
|
||||
panels = [
|
||||
_build_core_flow,
|
||||
_build_efficiency,
|
||||
_build_skip,
|
||||
_build_reservation,
|
||||
_build_health,
|
||||
_build_latest,
|
||||
]
|
||||
for idx, builder in enumerate(panels):
|
||||
slot = tk.Frame(grid, bg=theme.BG)
|
||||
slot.grid(row=idx // 2, column=idx % 2, sticky="nsew", padx=(0 if idx % 2 == 0 else 8, 8 if idx % 2 == 0 else 0), pady=6)
|
||||
builder(slot, stats)
|
||||
return grid
|
||||
+64
-40
@@ -3,39 +3,39 @@ from __future__ import annotations
|
||||
from tkinter import ttk
|
||||
|
||||
|
||||
BG = "#f3f6f8"
|
||||
BG_ALT = "#e8eef2"
|
||||
BG = "#f6f8fb"
|
||||
BG_ALT = "#edf2f7"
|
||||
SURFACE = "#ffffff"
|
||||
SURFACE_ALT = "#f7fafc"
|
||||
SURFACE_HOVER = "#edf7f5"
|
||||
BORDER = "#d9e3e8"
|
||||
BORDER_DARK = "#b9c8d0"
|
||||
TEXT = "#10201f"
|
||||
MUTED = "#5d6f78"
|
||||
SUBTLE = "#94a4ad"
|
||||
SURFACE_ALT = "#f8fafc"
|
||||
SURFACE_HOVER = "#eef7f6"
|
||||
BORDER = "#dde7ee"
|
||||
BORDER_DARK = "#b8c7d3"
|
||||
TEXT = "#111827"
|
||||
MUTED = "#5f7285"
|
||||
SUBTLE = "#94a3b8"
|
||||
TEAL = "#0f9488"
|
||||
TEAL_DARK = "#087368"
|
||||
TEAL_SOFT = "#e6f7f3"
|
||||
AMBER = "#a76707"
|
||||
AMBER_SOFT = "#fff4dd"
|
||||
RED = "#c74454"
|
||||
RED_SOFT = "#fff0f2"
|
||||
TEAL_DARK = "#08756e"
|
||||
TEAL_SOFT = "#e5f7f4"
|
||||
AMBER = "#b26a00"
|
||||
AMBER_SOFT = "#fff4dc"
|
||||
RED = "#cf4057"
|
||||
RED_SOFT = "#fff0f3"
|
||||
GREEN = "#15805a"
|
||||
GREEN_SOFT = "#e5f5ee"
|
||||
BLUE = "#2e6fd8"
|
||||
GREEN_SOFT = "#e7f7ef"
|
||||
BLUE = "#2f6fda"
|
||||
BLUE_SOFT = "#eaf2ff"
|
||||
SHADOW = "#e7edf1"
|
||||
SHADOW = "#d9e2ea"
|
||||
|
||||
RADIUS_SM = 8
|
||||
RADIUS_MD = 12
|
||||
RADIUS_LG = 16
|
||||
RADIUS_SM = 12
|
||||
RADIUS_MD = 18
|
||||
RADIUS_LG = 24
|
||||
|
||||
FONT_UI = ("Microsoft YaHei UI", 12)
|
||||
FONT_SMALL = ("Microsoft YaHei UI", 11)
|
||||
FONT_READ = ("Microsoft YaHei UI", 13)
|
||||
FONT_TITLE = ("Microsoft YaHei UI", 18, "bold")
|
||||
FONT_H2 = ("Microsoft YaHei UI", 14, "bold")
|
||||
FONT_MONO = ("Consolas", 13)
|
||||
FONT_UI = ("Microsoft YaHei UI", 14)
|
||||
FONT_SMALL = ("Microsoft YaHei UI", 12)
|
||||
FONT_READ = ("Microsoft YaHei UI", 14)
|
||||
FONT_TITLE = ("Microsoft YaHei UI", 21, "bold")
|
||||
FONT_H2 = ("Microsoft YaHei UI", 16, "bold")
|
||||
FONT_MONO = ("Consolas", 14)
|
||||
|
||||
|
||||
def setup_styles(root) -> None:
|
||||
@@ -51,35 +51,59 @@ def setup_styles(root) -> None:
|
||||
style.configure("Toolbar.TFrame", background=SURFACE)
|
||||
style.configure("Surface.TFrame", background=SURFACE)
|
||||
style.configure("Alt.TFrame", background=SURFACE_ALT)
|
||||
style.configure("Card.TFrame", background=SURFACE, borderwidth=1, relief="solid")
|
||||
style.configure("Card.TFrame", background=SURFACE, borderwidth=0, relief="flat")
|
||||
style.configure("Muted.TLabel", background=SURFACE, foreground=MUTED, font=FONT_SMALL)
|
||||
style.configure("Title.TLabel", background=BG, foreground=TEXT, font=FONT_TITLE)
|
||||
style.configure("H2.TLabel", background=SURFACE, foreground=TEXT, font=FONT_H2)
|
||||
style.configure("Value.TLabel", background=SURFACE, foreground=TEXT, font=("Microsoft YaHei UI", 22, "bold"))
|
||||
style.configure("Value.TLabel", background=SURFACE, foreground=TEXT, font=("Microsoft YaHei UI", 26, "bold"))
|
||||
style.configure("Small.TLabel", background=SURFACE, foreground=MUTED, font=FONT_SMALL)
|
||||
style.configure("Sidebar.TButton", padding=(12, 8), anchor="w")
|
||||
style.configure("Primary.TButton", padding=(14, 8), foreground="#ffffff", background=TEAL, borderwidth=0)
|
||||
style.configure("Sidebar.TButton", padding=(14, 10), anchor="w")
|
||||
style.configure("Primary.TButton", padding=(16, 10), foreground="#ffffff", background=TEAL, borderwidth=0)
|
||||
style.map("Primary.TButton", background=[("active", TEAL_DARK)])
|
||||
style.configure("Danger.TButton", padding=(14, 8), foreground=RED)
|
||||
style.configure("Soft.TButton", padding=(12, 7))
|
||||
style.configure("Danger.TButton", padding=(16, 10), foreground=RED)
|
||||
style.configure("Soft.TButton", padding=(14, 9))
|
||||
style.configure("Dashboard.TNotebook", background=BG, borderwidth=0)
|
||||
style.configure("Dashboard.TNotebook.Tab", padding=(16, 9), font=FONT_SMALL)
|
||||
style.configure(
|
||||
"Treeview",
|
||||
font=("Microsoft YaHei UI", 13),
|
||||
rowheight=38,
|
||||
font=("Microsoft YaHei UI", 14),
|
||||
rowheight=44,
|
||||
background=SURFACE,
|
||||
fieldbackground=SURFACE,
|
||||
borderwidth=0,
|
||||
relief="flat",
|
||||
)
|
||||
style.map("Treeview", background=[("selected", TEAL_SOFT)], foreground=[("selected", TEXT)])
|
||||
style.map("Treeview", background=[("selected", TEAL_DARK)], foreground=[("selected", "#ffffff")])
|
||||
style.configure(
|
||||
"Treeview.Heading",
|
||||
font=("Microsoft YaHei UI", 12, "bold"),
|
||||
background="#edf3f1",
|
||||
font=("Microsoft YaHei UI", 13, "bold"),
|
||||
background="#eaf1f4",
|
||||
foreground=TEXT,
|
||||
relief="flat",
|
||||
padding=(10, 10),
|
||||
)
|
||||
style.configure(
|
||||
"Dashboard.Treeview",
|
||||
font=("Microsoft YaHei UI", 14),
|
||||
rowheight=46,
|
||||
background=SURFACE,
|
||||
fieldbackground=SURFACE,
|
||||
foreground=TEXT,
|
||||
borderwidth=0,
|
||||
relief="flat",
|
||||
)
|
||||
style.map(
|
||||
"Dashboard.Treeview",
|
||||
background=[("selected", TEAL_DARK)],
|
||||
foreground=[("selected", "#ffffff")],
|
||||
)
|
||||
style.configure(
|
||||
"Dashboard.Treeview.Heading",
|
||||
font=("Microsoft YaHei UI", 13, "bold"),
|
||||
background="#eaf1f4",
|
||||
foreground=TEXT,
|
||||
relief="flat",
|
||||
padding=(10, 11),
|
||||
)
|
||||
style.configure(
|
||||
"TCombobox",
|
||||
@@ -88,7 +112,7 @@ def setup_styles(root) -> None:
|
||||
foreground=TEXT,
|
||||
bordercolor=BORDER,
|
||||
arrowcolor=MUTED,
|
||||
padding=(8, 4),
|
||||
padding=(10, 7),
|
||||
)
|
||||
style.map(
|
||||
"TCombobox",
|
||||
@@ -102,6 +126,6 @@ def setup_styles(root) -> None:
|
||||
foreground=TEXT,
|
||||
bordercolor=BORDER,
|
||||
arrowcolor=MUTED,
|
||||
padding=(6, 3),
|
||||
padding=(9, 6),
|
||||
)
|
||||
style.map("TSpinbox", bordercolor=[("focus", TEAL), ("active", TEAL)])
|
||||
+253
-69
@@ -27,6 +27,9 @@ BUTTON_ICONS = {
|
||||
"打开pic目录": "□",
|
||||
"打开目录": "□",
|
||||
"验证卡密": "✓",
|
||||
"上传诊断日志": "⇧",
|
||||
"上传日志": "⇧",
|
||||
"检查更新": "↻",
|
||||
"刷新状态": "⟳",
|
||||
"保存日志配置": "✓",
|
||||
"查看大图": "▢",
|
||||
@@ -126,6 +129,17 @@ class RoundedSurface(tk.Frame):
|
||||
width = max(2, self.winfo_width())
|
||||
height = max(2, self.winfo_height())
|
||||
self._canvas.delete("all")
|
||||
if self._outline != self._fill:
|
||||
rounded_rect(
|
||||
self._canvas,
|
||||
3,
|
||||
4,
|
||||
width - 2,
|
||||
height - 1,
|
||||
self._radius,
|
||||
fill=theme.SHADOW,
|
||||
outline=theme.SHADOW,
|
||||
)
|
||||
rounded_rect(
|
||||
self._canvas,
|
||||
1,
|
||||
@@ -165,15 +179,15 @@ class RoundedButton(tk.Canvas):
|
||||
self.kind = kind
|
||||
self._state = "normal"
|
||||
colors = {
|
||||
"primary": (theme.TEAL, "#ffffff", theme.TEAL_DARK),
|
||||
"danger": (theme.RED_SOFT, theme.RED, "#ffe5e2"),
|
||||
"amber": (theme.AMBER_SOFT, "#8a5a00", "#ffe8b8"),
|
||||
"soft": (theme.SURFACE, theme.TEXT, theme.SURFACE_HOVER),
|
||||
"ghost": (theme.SURFACE, theme.TEXT, theme.TEAL_SOFT),
|
||||
"primary": (theme.TEAL, "#ffffff", theme.TEAL_DARK, theme.TEAL),
|
||||
"danger": (theme.RED_SOFT, theme.RED, "#ffe5e2", "#f2ccd1"),
|
||||
"amber": (theme.AMBER_SOFT, "#8a5a00", "#ffe8b8", "#f0d6a0"),
|
||||
"soft": (theme.SURFACE, theme.TEXT, theme.SURFACE_HOVER, theme.BORDER),
|
||||
"ghost": (theme.SURFACE, theme.TEXT, theme.TEAL_SOFT, theme.SURFACE),
|
||||
}
|
||||
self.bg_color, self.fg_color, self.hover_color = colors.get(kind, colors["soft"])
|
||||
w = width or max(98, len(self.text) * 14 + 34)
|
||||
super().__init__(parent, width=w, height=38, bg=_parent_bg(parent), highlightthickness=0, bd=0, cursor="hand2")
|
||||
self.bg_color, self.fg_color, self.hover_color, self.outline_color = colors.get(kind, colors["soft"])
|
||||
w = width or max(118, len(self.text) * 16 + 42)
|
||||
super().__init__(parent, width=w, height=46, bg=_parent_bg(parent), highlightthickness=0, bd=0, cursor="hand2")
|
||||
self._draw(self.bg_color)
|
||||
self.bind("<Button-1>", self._click)
|
||||
self.bind("<Enter>", lambda _e: self._draw(self.hover_color))
|
||||
@@ -181,10 +195,10 @@ class RoundedButton(tk.Canvas):
|
||||
|
||||
def _draw(self, fill: str) -> None:
|
||||
self.delete("all")
|
||||
outline = theme.TEAL if self.kind == "primary" else theme.BORDER
|
||||
outline = self.outline_color
|
||||
fg = self.fg_color if self._state != "disabled" else theme.SUBTLE
|
||||
rounded_rect(self, 1, 1, int(self["width"]) - 2, int(self["height"]) - 2, theme.RADIUS_SM, fill=fill, outline=outline)
|
||||
self.create_text(int(self["width"]) // 2, int(self["height"]) // 2, text=self.text, fill=fg, font=("Microsoft YaHei UI", 12, "bold") if self.kind == "primary" else theme.FONT_UI)
|
||||
self.create_text(int(self["width"]) // 2, int(self["height"]) // 2, text=self.text, fill=fg, font=("Microsoft YaHei UI", 14, "bold") if self.kind == "primary" else theme.FONT_UI)
|
||||
|
||||
def _click(self, _event) -> None:
|
||||
if self.command and self._state != "disabled":
|
||||
@@ -211,25 +225,126 @@ class RoundedNavButton(tk.Canvas):
|
||||
self.text = _with_icon(text, NAV_ICONS.get(text))
|
||||
self.command = command
|
||||
self.active = active
|
||||
super().__init__(parent, height=34, bg=theme.SURFACE, highlightthickness=0, bd=0, cursor="hand2")
|
||||
self.enabled = True
|
||||
super().__init__(parent, height=46, bg=theme.SURFACE, highlightthickness=0, bd=0, cursor="hand2")
|
||||
self.bind("<Configure>", lambda _e: self._draw())
|
||||
self.bind("<Button-1>", lambda _e: self.command())
|
||||
self.bind("<Button-1>", lambda _e: self._invoke())
|
||||
self.bind("<Enter>", lambda _e: self._draw(hover=True))
|
||||
self.bind("<Leave>", lambda _e: self._draw())
|
||||
|
||||
def _invoke(self) -> None:
|
||||
if self.enabled:
|
||||
self.command()
|
||||
|
||||
def set_active(self, active: bool) -> None:
|
||||
self.active = active
|
||||
self._draw()
|
||||
|
||||
def set_enabled(self, enabled: bool) -> None:
|
||||
self.enabled = bool(enabled)
|
||||
self.configure(cursor="hand2" if self.enabled else "arrow")
|
||||
self._draw()
|
||||
|
||||
def _draw(self, hover: bool = False) -> None:
|
||||
self.delete("all")
|
||||
width = max(1, self.winfo_width())
|
||||
bg = theme.TEAL_SOFT if self.active else (theme.SURFACE_HOVER if hover else theme.SURFACE)
|
||||
fg = theme.TEAL_DARK if self.active else theme.TEXT
|
||||
rounded_rect(self, 1, 2, width - 2, 32, theme.RADIUS_SM, fill=bg, outline=bg)
|
||||
if not self.enabled:
|
||||
bg = theme.SURFACE
|
||||
fg = theme.MUTED
|
||||
else:
|
||||
bg = theme.TEAL_SOFT if self.active else (theme.SURFACE_HOVER if hover else theme.SURFACE)
|
||||
fg = theme.TEAL_DARK if self.active else theme.TEXT
|
||||
rounded_rect(self, 1, 4, width - 2, 42, theme.RADIUS_SM, fill=bg, outline=bg)
|
||||
if self.active:
|
||||
rounded_rect(self, 3, 8, 8, 26, 4, fill=theme.TEAL, outline=theme.TEAL)
|
||||
self.create_text(18 if self.active else 13, 17, text=self.text, anchor="w", fill=fg, font=("Microsoft YaHei UI", 11, "bold") if self.active else theme.FONT_UI)
|
||||
rounded_rect(self, 4, 12, 10, 34, 4, fill=theme.TEAL, outline=theme.TEAL)
|
||||
self.create_text(22 if self.active else 15, 23, text=self.text, anchor="w", fill=fg, font=("Microsoft YaHei UI", 13, "bold") if self.active else theme.FONT_UI)
|
||||
|
||||
|
||||
class SlimScrollbar(tk.Canvas):
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
*,
|
||||
command: Callable[[str, int | float, str | None], None] | None = None,
|
||||
orient: str = "vertical",
|
||||
) -> None:
|
||||
self.orient = "horizontal" if str(orient).startswith("h") else "vertical"
|
||||
super().__init__(
|
||||
parent,
|
||||
width=14 if self.orient == "vertical" else 1,
|
||||
height=14 if self.orient == "horizontal" else 1,
|
||||
bg=theme.SURFACE,
|
||||
highlightthickness=0,
|
||||
bd=0,
|
||||
cursor="hand2",
|
||||
)
|
||||
self.command = command
|
||||
self.first = 0.0
|
||||
self.last = 1.0
|
||||
self._drag_y: int | None = None
|
||||
self.bind("<Configure>", lambda _e: self._draw())
|
||||
self.bind("<Button-1>", self._jump)
|
||||
self.bind("<B1-Motion>", self._drag)
|
||||
self.bind("<ButtonRelease-1>", lambda _e: setattr(self, "_drag_y", None))
|
||||
|
||||
def set(self, first: float | str, last: float | str) -> None:
|
||||
self.first = max(0.0, min(1.0, float(first)))
|
||||
self.last = max(self.first, min(1.0, float(last)))
|
||||
self._draw()
|
||||
|
||||
def _track_length(self) -> int:
|
||||
size = self.winfo_width() if self.orient == "horizontal" else self.winfo_height()
|
||||
return max(1, int(size))
|
||||
|
||||
def _thumb_bounds(self) -> tuple[int, int, int]:
|
||||
length = self._track_length()
|
||||
track_start = 10
|
||||
track_end = max(track_start + 1, length - 10)
|
||||
track_len = track_end - track_start
|
||||
min_thumb = 46 if self.orient == "horizontal" else 42
|
||||
thumb_len = max(min_thumb, int(track_len * max(0.08, self.last - self.first)))
|
||||
travel = max(1, track_len - thumb_len)
|
||||
start = track_start + int(travel * self.first)
|
||||
return start, min(track_end, start + thumb_len), travel
|
||||
|
||||
def _draw(self) -> None:
|
||||
self.delete("all")
|
||||
length = self._track_length()
|
||||
if self.orient == "horizontal":
|
||||
self.create_line(10, 7, length - 10, 7, fill=theme.BG_ALT, width=8, capstyle="round")
|
||||
else:
|
||||
self.create_line(7, 10, 7, length - 10, fill=theme.BG_ALT, width=8, capstyle="round")
|
||||
if self.last - self.first >= 0.995:
|
||||
if self.orient == "horizontal":
|
||||
self.create_line(10, 7, length - 10, 7, fill=theme.TEAL_SOFT, width=8, capstyle="round")
|
||||
self.create_line(10, 7, length - 10, 7, fill=theme.BORDER_DARK, width=3, capstyle="round")
|
||||
else:
|
||||
self.create_line(7, 10, 7, length - 10, fill=theme.TEAL_SOFT, width=8, capstyle="round")
|
||||
self.create_line(7, 10, 7, length - 10, fill=theme.BORDER_DARK, width=3, capstyle="round")
|
||||
return
|
||||
start, end, _travel = self._thumb_bounds()
|
||||
if self.orient == "horizontal":
|
||||
self.create_line(start, 7, end, 7, fill=theme.TEAL, width=8, capstyle="round")
|
||||
self.create_line(start + 5, 7, end - 5, 7, fill=theme.TEAL_DARK, width=3, capstyle="round")
|
||||
else:
|
||||
self.create_line(7, start, 7, end, fill=theme.TEAL, width=8, capstyle="round")
|
||||
self.create_line(7, start + 5, 7, end - 5, fill=theme.TEAL_DARK, width=3, capstyle="round")
|
||||
|
||||
def _moveto_from_position(self, pos: int) -> None:
|
||||
if not self.command:
|
||||
return
|
||||
start, end, travel = self._thumb_bounds()
|
||||
thumb_len = max(1, end - start)
|
||||
target = (pos - 10 - thumb_len / 2) / max(1, travel)
|
||||
self.command("moveto", max(0.0, min(1.0, target)), None)
|
||||
|
||||
def _jump(self, event) -> None:
|
||||
self._drag_y = int(event.x if self.orient == "horizontal" else event.y)
|
||||
self._moveto_from_position(self._drag_y)
|
||||
|
||||
def _drag(self, event) -> None:
|
||||
self._drag_y = int(event.x if self.orient == "horizontal" else event.y)
|
||||
self._moveto_from_position(self._drag_y)
|
||||
|
||||
|
||||
def clear(frame: tk.Misc) -> None:
|
||||
@@ -246,19 +361,19 @@ def nav_button(parent, text: str, command: Callable[[], None], *, active: bool =
|
||||
|
||||
|
||||
def pill(parent, text: str, *, fg: str = theme.TEAL, bg: str = theme.TEAL_SOFT) -> tk.Label:
|
||||
return tk.Label(parent, text=text, bg=bg, fg=fg, font=("Microsoft YaHei UI", 10, "bold"), padx=10, pady=3)
|
||||
return tk.Label(parent, text=text, bg=bg, fg=fg, font=("Microsoft YaHei UI", 10, "bold"), padx=11, pady=4)
|
||||
|
||||
|
||||
def status_pill(parent, text: str, *, color: str = theme.GREEN, bg: str = theme.GREEN_SOFT) -> tk.Label:
|
||||
return tk.Label(parent, text=text, bg=bg, fg=color, font=("Microsoft YaHei UI", 11, "bold"), padx=14, pady=5)
|
||||
return tk.Label(parent, text=text, bg=bg, fg=color, font=("Microsoft YaHei UI", 11, "bold"), padx=15, pady=6)
|
||||
|
||||
|
||||
def card(parent, title: str | None = None, *, padding: int = 14) -> tk.Frame:
|
||||
frame = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
if title:
|
||||
head = tk.Frame(frame, bg=theme.SURFACE)
|
||||
head.pack(fill="x", padx=padding + 2, pady=(padding, 7))
|
||||
tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 10))
|
||||
head.pack(fill="x", padx=padding + 4, pady=(padding + 2, 8))
|
||||
tk.Frame(head, bg=theme.TEAL, width=4, height=18).pack(side="left", padx=(0, 11))
|
||||
ttk.Label(head, text=title, style="H2.TLabel").pack(side="left")
|
||||
return frame
|
||||
|
||||
@@ -277,26 +392,25 @@ def metric(parent, title: str, value: object, hint: str = "", color: str = theme
|
||||
def stat_tile(parent, title: str, value: object, hint: str, *, color: str, soft: str, compact: bool = False) -> tk.Frame:
|
||||
box = rounded_surface(parent, fill=theme.SURFACE, outline=theme.BORDER, radius=theme.RADIUS_MD)
|
||||
if compact:
|
||||
box.configure(height=72)
|
||||
accent = tk.Frame(box, bg=color, width=4)
|
||||
accent.pack(side="left", fill="y")
|
||||
box.configure(height=104)
|
||||
box.pack_propagate(False)
|
||||
inner = tk.Frame(box, bg=theme.SURFACE)
|
||||
inner.pack(side="left", fill="both", expand=True)
|
||||
inner.pack(fill="both", expand=True, padx=18, pady=14)
|
||||
head = tk.Frame(inner, bg=theme.SURFACE)
|
||||
head.pack(fill="x", padx=16, pady=(10, 2))
|
||||
head.pack(fill="x")
|
||||
tk.Label(head, text=title, bg=theme.SURFACE, fg=theme.MUTED, font=theme.FONT_SMALL).pack(side="left")
|
||||
tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 10, "bold")).pack(side="right")
|
||||
tk.Label(inner, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 19, "bold")).pack(anchor="w", padx=16)
|
||||
tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 10, "bold"), padx=11, pady=3).pack(anchor="w", padx=16, pady=(6, 10))
|
||||
tk.Label(head, text="●", bg=theme.SURFACE, fg=color, font=("Segoe UI", 11, "bold")).pack(side="right")
|
||||
tk.Label(inner, text=str(value), bg=theme.SURFACE, fg=theme.TEXT, font=("Microsoft YaHei UI", 24 if compact else 25, "bold")).pack(anchor="w", pady=(5, 0))
|
||||
tk.Label(inner, text=hint, bg=soft, fg=color, font=("Microsoft YaHei UI", 11, "bold"), padx=12, pady=4).pack(anchor="w", pady=(7, 0))
|
||||
return box
|
||||
|
||||
|
||||
def section(parent, title: str, subtitle: str = "") -> tk.Frame:
|
||||
row = tk.Frame(parent, bg=theme.BG)
|
||||
row.pack(fill="x", pady=(2, 10))
|
||||
row.pack(fill="x", pady=(2, 12))
|
||||
ttk.Label(row, text=title, style="Title.TLabel").pack(side="left")
|
||||
if subtitle:
|
||||
tk.Label(row, text=subtitle, bg=theme.TEAL_SOFT, fg=theme.TEAL_DARK, font=theme.FONT_SMALL, padx=12, pady=4).pack(side="left", padx=(12, 0))
|
||||
tk.Label(row, text=subtitle, bg=theme.TEAL_SOFT, fg=theme.TEAL_DARK, font=theme.FONT_SMALL, padx=14, pady=7).pack(side="left", padx=(14, 0))
|
||||
return row
|
||||
|
||||
|
||||
@@ -333,8 +447,8 @@ def text_panel(parent, title: str, lines: Iterable[str], height: int = 10) -> tk
|
||||
|
||||
def log_panel(parent, title: str, lines: Iterable[str], height: int = 24) -> tuple[tk.Frame, tk.Text]:
|
||||
box = card(parent, title)
|
||||
wrap = tk.Frame(box, bg=theme.SURFACE_ALT)
|
||||
wrap.pack(fill="both", expand=True, padx=11, pady=(4, 11))
|
||||
wrap = tk.Frame(box, bg=theme.SURFACE_ALT, highlightbackground=theme.BORDER, highlightthickness=1)
|
||||
wrap.pack(fill="both", expand=True, padx=13, pady=(4, 13))
|
||||
wrap.grid_rowconfigure(0, weight=1)
|
||||
wrap.grid_columnconfigure(0, weight=1)
|
||||
text = tk.Text(
|
||||
@@ -351,12 +465,12 @@ def log_panel(parent, title: str, lines: Iterable[str], height: int = 24) -> tup
|
||||
spacing1=3,
|
||||
spacing3=4,
|
||||
)
|
||||
yscroll = ttk.Scrollbar(wrap, orient="vertical", command=text.yview)
|
||||
xscroll = ttk.Scrollbar(wrap, orient="horizontal", command=text.xview)
|
||||
yscroll = SlimScrollbar(wrap, orient="vertical", command=lambda *args: text.yview(*[a for a in args if a is not None]))
|
||||
xscroll = SlimScrollbar(wrap, orient="horizontal", command=lambda *args: text.xview(*[a for a in args if a is not None]))
|
||||
text.configure(yscrollcommand=yscroll.set, xscrollcommand=xscroll.set)
|
||||
text.grid(row=0, column=0, sticky="nsew")
|
||||
yscroll.grid(row=0, column=1, sticky="ns")
|
||||
xscroll.grid(row=1, column=0, sticky="ew")
|
||||
yscroll.grid(row=0, column=1, sticky="ns", padx=(4, 6), pady=8)
|
||||
xscroll.grid(row=1, column=0, sticky="ew", padx=8, pady=(4, 6))
|
||||
content = "\n".join(list(lines)[-1000:]) or "暂无数据"
|
||||
text.insert("1.0", content)
|
||||
text.configure(state="disabled")
|
||||
@@ -376,24 +490,44 @@ def log_panel(parent, title: str, lines: Iterable[str], height: int = 24) -> tup
|
||||
|
||||
def table_panel(parent, title: str, columns: Sequence[tuple[str, str, int]], rows: Sequence[dict], height: int = 8) -> tk.Frame:
|
||||
box = card(parent, title)
|
||||
table_wrap = tk.Frame(box, bg=theme.SURFACE)
|
||||
table_wrap.pack(fill="both", expand=True, padx=14, pady=(4, 14))
|
||||
table_wrap = tk.Frame(box, bg=theme.SURFACE_ALT, highlightbackground=theme.BORDER, highlightthickness=1, bd=0)
|
||||
table_wrap.pack(fill="both", expand=True, padx=16, pady=(4, 16))
|
||||
table_wrap.grid_rowconfigure(0, weight=1)
|
||||
table_wrap.grid_columnconfigure(0, weight=1)
|
||||
tree = ttk.Treeview(table_wrap, columns=[c[0] for c in columns], show="headings", height=height)
|
||||
ybar = ttk.Scrollbar(table_wrap, orient="vertical", command=tree.yview)
|
||||
xbar = ttk.Scrollbar(table_wrap, orient="horizontal", command=tree.xview)
|
||||
tree = ttk.Treeview(table_wrap, columns=[c[0] for c in columns], show="headings", height=height, style="Dashboard.Treeview")
|
||||
tree.tag_configure("odd", background=theme.SURFACE)
|
||||
tree.tag_configure("even", background="#f7fbfc")
|
||||
tree.tag_configure("empty", background=theme.SURFACE_ALT, foreground=theme.MUTED)
|
||||
ybar = SlimScrollbar(table_wrap, orient="vertical", command=lambda *args: tree.yview(*[a for a in args if a is not None]))
|
||||
xbar = SlimScrollbar(table_wrap, orient="horizontal", command=lambda *args: tree.xview(*[a for a in args if a is not None]))
|
||||
tree.configure(yscrollcommand=ybar.set, xscrollcommand=xbar.set)
|
||||
for key, label, width in columns:
|
||||
total_width = sum(width for _key, _label, width in columns)
|
||||
compact_table = total_width <= 640
|
||||
for idx, (key, label, width) in enumerate(columns):
|
||||
tree.heading(key, text=label)
|
||||
tree.column(key, width=width, minwidth=min(width, 90), anchor="w", stretch=False)
|
||||
for row in rows:
|
||||
tree.insert("", "end", values=[str(row.get(key, "-")) for key, _, _ in columns])
|
||||
anchor = "center" if width <= 90 or key in {"idx", "pos", "value", "status"} else "w"
|
||||
stretch = compact_table or len(columns) <= 5 or idx == len(columns) - 1
|
||||
min_width = min(width, 76) if width <= 90 else min(width, 120)
|
||||
tree.column(key, width=width, minwidth=min_width, anchor=anchor, stretch=stretch)
|
||||
for idx, row in enumerate(rows):
|
||||
tree.insert("", "end", values=[str(row.get(key, "-")) for key, _, _ in columns], tags=("even" if idx % 2 else "odd",))
|
||||
if not rows:
|
||||
tree.insert("", "end", values=["暂无数据" if idx == 0 else "" for idx, _c in enumerate(columns)])
|
||||
tree.insert("", "end", values=["暂无数据" if idx == 0 else "" for idx, _c in enumerate(columns)], tags=("empty",))
|
||||
tree.grid(row=0, column=0, sticky="nsew")
|
||||
ybar.grid(row=0, column=1, sticky="ns")
|
||||
xbar.grid(row=1, column=0, sticky="ew")
|
||||
ybar.grid(row=0, column=1, sticky="ns", padx=(4, 6), pady=8)
|
||||
xbar.grid(row=1, column=0, sticky="ew", padx=10, pady=(4, 7))
|
||||
|
||||
def _wheel(event):
|
||||
tree.yview_scroll(int(-1 * (event.delta / 120)), "units")
|
||||
return "break"
|
||||
|
||||
def _shift_wheel(event):
|
||||
tree.xview_scroll(int(-1 * (event.delta / 120)), "units")
|
||||
return "break"
|
||||
|
||||
tree.bind("<MouseWheel>", _wheel)
|
||||
tree.bind("<Shift-MouseWheel>", _shift_wheel)
|
||||
table_wrap.configure(width=max(1, min(total_width + 36, 980)))
|
||||
box.tree = tree # type: ignore[attr-defined]
|
||||
box.columns_spec = list(columns) # type: ignore[attr-defined]
|
||||
return box
|
||||
@@ -417,7 +551,7 @@ def mini_table(parent, title: str, rows: Sequence[tuple[str, str, str]], *, colo
|
||||
|
||||
def field_shell(parent, label: str) -> tk.Frame:
|
||||
row = rounded_surface(parent, fill=theme.SURFACE_ALT, outline=theme.BORDER, radius=theme.RADIUS_SM)
|
||||
tk.Label(row, text=label, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=theme.FONT_SMALL).pack(anchor="w", padx=9, pady=(7, 1))
|
||||
tk.Label(row, text=label, bg=theme.SURFACE_ALT, fg=theme.MUTED, font=theme.FONT_SMALL).pack(anchor="w", padx=11, pady=(8, 2))
|
||||
return row
|
||||
|
||||
|
||||
@@ -493,8 +627,8 @@ def switch_row(parent, label: str, variable: tk.Variable | None = None, value: b
|
||||
bd=0,
|
||||
anchor="w",
|
||||
justify="left",
|
||||
font=theme.FONT_SMALL,
|
||||
).pack(fill="x", padx=9, pady=6)
|
||||
font=theme.FONT_UI,
|
||||
).pack(fill="x", padx=10, pady=8)
|
||||
return row
|
||||
|
||||
|
||||
@@ -510,25 +644,75 @@ def toolbar(parent, actions: Sequence[tuple[str, Callable[[], None] | None, str]
|
||||
return row
|
||||
|
||||
|
||||
def preview_panel(parent, image_path: Path | None, title: str = "截图预览", max_size: tuple[int, int] = (360, 560)) -> tk.Frame:
|
||||
def _preview_signature(image_path: Path | None) -> tuple[str, int, int] | None:
|
||||
try:
|
||||
if not image_path or not image_path.exists():
|
||||
return None
|
||||
st = image_path.stat()
|
||||
return (str(image_path), int(getattr(st, "st_mtime_ns", int(st.st_mtime * 1_000_000_000))), int(st.st_size))
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def preview_panel(
|
||||
parent,
|
||||
image_path: Path | None,
|
||||
title: str = "截图预览",
|
||||
max_size: tuple[int, int] = (360, 560),
|
||||
*,
|
||||
auto_refresh_ms: int = 0,
|
||||
path_getter: Callable[[], Path | None] | None = None,
|
||||
) -> tk.Frame:
|
||||
box = card(parent, title)
|
||||
body = tk.Frame(box, bg=theme.SURFACE_ALT, highlightbackground=theme.BORDER, highlightthickness=1)
|
||||
body.pack(fill="both", expand=True, padx=14, pady=(4, 14))
|
||||
if image_path and image_path.exists():
|
||||
try:
|
||||
from PIL import Image, ImageTk
|
||||
body.pack(fill="both", expand=True, padx=16, pady=(4, 16))
|
||||
box._preview_signature = object() # type: ignore[attr-defined]
|
||||
|
||||
img = Image.open(image_path).convert("RGB")
|
||||
img.thumbnail(max_size)
|
||||
photo = ImageTk.PhotoImage(img)
|
||||
label = tk.Label(body, image=photo, bg=theme.SURFACE_ALT)
|
||||
label.image = photo
|
||||
label.pack(expand=True, pady=12)
|
||||
ttk.Label(body, text=os.path.basename(str(image_path)), background=theme.SURFACE_ALT, foreground=theme.MUTED).pack(pady=(0, 8))
|
||||
return box
|
||||
def _render(path: Path | None, signature: tuple[str, int, int] | None) -> None:
|
||||
box._preview_signature = signature # type: ignore[attr-defined]
|
||||
for child in body.winfo_children():
|
||||
child.destroy()
|
||||
if path and path.exists():
|
||||
try:
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
img = Image.open(path).convert("RGB")
|
||||
img.thumbnail(max_size)
|
||||
photo = ImageTk.PhotoImage(img)
|
||||
label = tk.Label(body, image=photo, bg=theme.SURFACE_ALT)
|
||||
label.image = photo
|
||||
label.pack(expand=True, pady=12)
|
||||
ttk.Label(body, text=os.path.basename(str(path)), background=theme.SURFACE_ALT, foreground=theme.MUTED).pack(pady=(0, 8))
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
tk.Label(body, text="暂无截图\n点击“截图+OCR”后刷新", bg=theme.SURFACE_ALT, fg=theme.MUTED, font=("Microsoft YaHei UI", 13)).pack(expand=True)
|
||||
|
||||
def _current_path() -> Path | None:
|
||||
if path_getter is not None:
|
||||
try:
|
||||
return path_getter()
|
||||
except Exception:
|
||||
return image_path
|
||||
return image_path
|
||||
|
||||
def _refresh() -> None:
|
||||
try:
|
||||
if not box.winfo_exists():
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
tk.Label(body, text="暂无截图\n点击“截图+OCR”后刷新", bg=theme.SURFACE_ALT, fg=theme.MUTED, font=("Microsoft YaHei UI", 13)).pack(expand=True)
|
||||
return
|
||||
path = _current_path()
|
||||
signature = _preview_signature(path)
|
||||
if signature != getattr(box, "_preview_signature", None):
|
||||
_render(path, signature)
|
||||
if auto_refresh_ms > 0:
|
||||
try:
|
||||
box.after(auto_refresh_ms, _refresh)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_refresh()
|
||||
return box
|
||||
|
||||
|
||||
@@ -536,12 +720,12 @@ class ScrollFrame(ttk.Frame):
|
||||
def __init__(self, parent):
|
||||
super().__init__(parent, style="Dashboard.TFrame")
|
||||
self.canvas = tk.Canvas(self, bg=theme.BG, highlightthickness=0, bd=0)
|
||||
self.scroll = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
|
||||
self.scroll = SlimScrollbar(self, orient="vertical", command=lambda *args: self.canvas.yview(*[a for a in args if a is not None]))
|
||||
self.inner = tk.Frame(self.canvas, bg=theme.BG)
|
||||
self.window_id = self.canvas.create_window((0, 0), window=self.inner, anchor="nw")
|
||||
self.canvas.configure(yscrollcommand=self.scroll.set)
|
||||
self.canvas.pack(side="left", fill="both", expand=True)
|
||||
self.scroll.pack(side="right", fill="y")
|
||||
self.scroll.pack(side="right", fill="y", padx=(6, 0), pady=6)
|
||||
self.inner.bind("<Configure>", lambda _e: self.canvas.configure(scrollregion=self.canvas.bbox("all")))
|
||||
self.canvas.bind("<Configure>", lambda e: self.canvas.itemconfigure(self.window_id, width=e.width))
|
||||
self.canvas.bind_all("<MouseWheel>", self._wheel)
|
||||
|
||||
@@ -8,10 +8,10 @@ _BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
if str(_BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_BASE_DIR))
|
||||
|
||||
from douyin.updater.bootstrap import run_startup_update_check_early
|
||||
from gui.components.update_progress import run_gui_startup_update_check_early
|
||||
|
||||
|
||||
run_startup_update_check_early(app_name="gui_app")
|
||||
run_gui_startup_update_check_early(app_name="gui_app")
|
||||
|
||||
from douyin.core.version import print_version_banner # noqa: E402
|
||||
from gui.gui_app import main # noqa: E402
|
||||
|
||||
+136
-6
@@ -7,18 +7,100 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
from typing import Optional
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
DEFAULT_ADB_SERVER_PORT = "5037"
|
||||
FALLBACK_ADB_SERVER_PORTS = ("5038", "5039", "5040")
|
||||
_ADB_SERVER_PROBED_FOR: set[str] = set()
|
||||
|
||||
|
||||
def _normalize_adb_path(adb: str | None) -> str:
|
||||
value = str(adb or "").strip()
|
||||
if value.startswith('"') and value.endswith('"'):
|
||||
value = value[1:-1]
|
||||
return value
|
||||
|
||||
|
||||
def _adb_env(port: str | None = None) -> dict[str, str]:
|
||||
env = os.environ.copy()
|
||||
if port:
|
||||
env["ANDROID_ADB_SERVER_PORT"] = str(port)
|
||||
# Windows 上 adb 的 Bonjour backend 经常没有 daemon;openscreen 更稳定。
|
||||
env.setdefault("ADB_MDNS_OPENSCREEN", "1")
|
||||
return env
|
||||
|
||||
|
||||
def _adb_server_responds(adb_exe: str, port: str, timeout: float = 4.0) -> bool:
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[adb_exe, "devices"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=timeout,
|
||||
env=_adb_env(port),
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
out = ((proc.stdout or "") + "\n" + (proc.stderr or "")).lower()
|
||||
if proc.returncode != 0:
|
||||
return False
|
||||
return "failed to start daemon" not in out and "cannot connect to daemon" not in out
|
||||
|
||||
|
||||
def ensure_adb_server_port(adb_exe: str) -> None:
|
||||
"""Ensure later adb subprocesses inherit a working server port.
|
||||
|
||||
On some Windows machines the default 5037 daemon fails to start while a
|
||||
fallback port works. The GUI gets the adb path once and every later
|
||||
operation inherits this process environment, so doing the probe here keeps
|
||||
dashboard / legacy GUI / web GUI consistent.
|
||||
"""
|
||||
adb_path = os.path.abspath(str(adb_exe or ""))
|
||||
if not adb_path or adb_path in _ADB_SERVER_PROBED_FOR:
|
||||
return
|
||||
_ADB_SERVER_PROBED_FOR.add(adb_path)
|
||||
|
||||
os.environ.setdefault("ADB_MDNS_OPENSCREEN", "1")
|
||||
if os.environ.get("ANDROID_ADB_SERVER_PORT"):
|
||||
return
|
||||
|
||||
if _adb_server_responds(adb_path, DEFAULT_ADB_SERVER_PORT):
|
||||
return
|
||||
for port in FALLBACK_ADB_SERVER_PORTS:
|
||||
if _adb_server_responds(adb_path, port):
|
||||
os.environ["ANDROID_ADB_SERVER_PORT"] = port
|
||||
return
|
||||
|
||||
|
||||
def _prepare_adb_path(adb: str) -> str:
|
||||
path = os.path.abspath(adb)
|
||||
ensure_adb_server_port(path)
|
||||
return path
|
||||
|
||||
|
||||
def find_adb_executable() -> str:
|
||||
"""返回可用的 adb 可执行文件路径(优先 PATH,其次默认安装目录)。"""
|
||||
"""返回可用的 adb 可执行文件路径。"""
|
||||
env_adb = _normalize_adb_path(os.environ.get("ADB_EXECUTABLE"))
|
||||
if env_adb and os.path.exists(env_adb):
|
||||
return _prepare_adb_path(env_adb)
|
||||
|
||||
bundled_adb = path_config.find_bundled_adb()
|
||||
if bundled_adb:
|
||||
return _prepare_adb_path(bundled_adb)
|
||||
|
||||
adb = shutil.which("adb")
|
||||
if adb:
|
||||
return adb
|
||||
return _prepare_adb_path(adb)
|
||||
|
||||
# 默认安装目录(我们之前下载的 platform-tools)
|
||||
# 默认安装目录(本机开发/打包机常用 platform-tools 位置)
|
||||
localapp = os.environ.get("LOCALAPPDATA") or ""
|
||||
candidates = []
|
||||
if localapp:
|
||||
@@ -33,7 +115,7 @@ def find_adb_executable() -> str:
|
||||
|
||||
for p in candidates:
|
||||
if os.path.exists(p):
|
||||
return p
|
||||
return _prepare_adb_path(p)
|
||||
return ""
|
||||
|
||||
|
||||
@@ -50,15 +132,63 @@ def list_adb_devices(adb_exe: str) -> list[str]:
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
env=_adb_env(),
|
||||
timeout=5,
|
||||
)
|
||||
except FileNotFoundError:
|
||||
except (FileNotFoundError, subprocess.TimeoutExpired):
|
||||
return []
|
||||
devices: list[str] = []
|
||||
for line in (proc.stdout or "").splitlines()[1:]:
|
||||
parts = line.split()
|
||||
if len(parts) >= 2 and parts[1] == "device":
|
||||
devices.append(parts[0])
|
||||
return devices
|
||||
return _normalize_mdns_device_serials(adb_exe, devices)
|
||||
|
||||
|
||||
def _normalize_mdns_device_serials(adb_exe: str, devices: list[str]) -> list[str]:
|
||||
"""Convert Android wireless-debug mDNS serials to stable ip:port targets."""
|
||||
mdns_serials = [d for d in devices if "._adb" in d or d.startswith("adb-")]
|
||||
if not mdns_serials:
|
||||
return devices
|
||||
mdns_targets: list[str] = []
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[adb_exe, "mdns", "services"],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
check=False,
|
||||
env=_adb_env(),
|
||||
timeout=2,
|
||||
)
|
||||
if proc.returncode == 0:
|
||||
for line in (proc.stdout or "").splitlines():
|
||||
if "_adb-tls-pairing" in line or "_adb" not in line:
|
||||
continue
|
||||
m = re.search(r"(\d{1,3}(?:\.\d{1,3}){3}):(\d{1,5})", line)
|
||||
if m:
|
||||
mdns_targets.append(f"{m.group(1)}:{m.group(2)}")
|
||||
except Exception:
|
||||
mdns_targets = []
|
||||
|
||||
out: list[str] = []
|
||||
has_ip_target = any(_is_ip_port_device(d) for d in devices) or bool(mdns_targets)
|
||||
for device in devices:
|
||||
if device in mdns_serials and mdns_targets:
|
||||
for target in mdns_targets:
|
||||
if target not in out:
|
||||
out.append(target)
|
||||
continue
|
||||
if device in mdns_serials and has_ip_target:
|
||||
continue
|
||||
if device not in out:
|
||||
out.append(device)
|
||||
return out
|
||||
|
||||
|
||||
def _is_ip_port_device(device: str) -> bool:
|
||||
return bool(re.fullmatch(r"\d{1,3}(?:\.\d{1,3}){3}:\d{1,5}", str(device or "").strip()))
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ import subprocess
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
from .adb import find_adb_executable, list_adb_devices
|
||||
from .adb import _adb_env, find_adb_executable, list_adb_devices
|
||||
|
||||
|
||||
def _discover_mdns_connect_targets(adb_exe: str) -> list[tuple[str, int]]:
|
||||
@@ -38,6 +38,7 @@ def _connect_wifi_adb_once(adb_exe: str, target: str) -> tuple[bool, str, str]:
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
env=_adb_env(),
|
||||
)
|
||||
|
||||
output = ((proc.stdout or "") + "\n" + (proc.stderr or "")).strip()
|
||||
@@ -142,6 +143,7 @@ def enable_wifi_adb(adb_exe: str, device_id: str) -> tuple[bool, str]:
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
env=_adb_env(),
|
||||
)
|
||||
|
||||
if proc.returncode == 0:
|
||||
@@ -241,6 +243,7 @@ def disconnect_wifi_adb(
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
env=_adb_env(),
|
||||
)
|
||||
|
||||
output = (proc.stdout or "") + "\n" + (proc.stderr or "")
|
||||
@@ -281,6 +284,7 @@ def get_device_ip(adb_exe: str, device_id: str) -> tuple[bool, str]:
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
env=_adb_env(),
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return False, "获取设备IP超时"
|
||||
@@ -315,6 +319,7 @@ def get_device_ip(adb_exe: str, device_id: str) -> tuple[bool, str]:
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
env=_adb_env(),
|
||||
)
|
||||
except Exception:
|
||||
proc2 = None
|
||||
@@ -352,6 +357,7 @@ def get_device_ip(adb_exe: str, device_id: str) -> tuple[bool, str]:
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=10,
|
||||
env=_adb_env(),
|
||||
)
|
||||
if proc3.returncode == 0:
|
||||
m = re.search(r"inet\s+addr:?\s*(\d+\.\d+\.\d+\.\d+)", proc3.stdout or "")
|
||||
|
||||
@@ -17,6 +17,8 @@ from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from dataclasses import dataclass
|
||||
from typing import Callable, Iterable, Optional
|
||||
|
||||
from .adb import _adb_env, list_adb_devices
|
||||
|
||||
|
||||
DEFAULT_ADB_PORT = 5555
|
||||
HI_PORT_MIN = 37000
|
||||
@@ -665,10 +667,6 @@ def scan_open_ports(
|
||||
|
||||
def _run_adb(adb_exe: str, args: list[str], timeout: float = 5.0) -> tuple[int, str]:
|
||||
"""运行 adb 命令,返回 (returncode, stdout+stderr)。"""
|
||||
env = os.environ.copy()
|
||||
# Windows 常见:Bonjour backend 无 daemon,mDNS 发现始终为空。
|
||||
# 默认强制 openscreen,除非用户显式覆盖。
|
||||
env.setdefault("ADB_MDNS_OPENSCREEN", "1")
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
[adb_exe, *args],
|
||||
@@ -678,7 +676,7 @@ def _run_adb(adb_exe: str, args: list[str], timeout: float = 5.0) -> tuple[int,
|
||||
errors="replace",
|
||||
check=False,
|
||||
timeout=timeout,
|
||||
env=env,
|
||||
env=_adb_env(),
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return -1, "timeout"
|
||||
@@ -730,6 +728,21 @@ def discover_mdns_targets(adb_exe: str) -> list[tuple[str, int]]:
|
||||
return targets
|
||||
|
||||
|
||||
def discover_connected_wifi_targets(adb_exe: str) -> list[tuple[str, int]]:
|
||||
"""Return already-connected WiFi ADB targets from adb devices as scan fallback."""
|
||||
targets: list[tuple[str, int]] = []
|
||||
seen: set[tuple[str, int]] = set()
|
||||
for device in list_adb_devices(adb_exe):
|
||||
parsed = _parse_target_ip_port(device)
|
||||
if not parsed:
|
||||
continue
|
||||
if parsed in seen:
|
||||
continue
|
||||
seen.add(parsed)
|
||||
targets.append(parsed)
|
||||
return targets
|
||||
|
||||
|
||||
def verify_adb_target(adb_exe: str, target: str, timeout: float = 5.0) -> tuple[str, str]:
|
||||
"""对一个 ip:port 调 `adb connect <target>`,解析输出。
|
||||
|
||||
@@ -888,11 +901,17 @@ def discover_adb_devices(
|
||||
|
||||
# 2) mDNS 发现(Android 11+ 无线调试常见随机端口)
|
||||
mdns_targets = discover_mdns_targets(adb_exe)
|
||||
connected_wifi_targets = discover_connected_wifi_targets(adb_exe)
|
||||
if on_phase and mdns_targets:
|
||||
try:
|
||||
on_phase(f"mDNS 发现 {len(mdns_targets)} 个 ADB 候选目标")
|
||||
except Exception:
|
||||
pass
|
||||
if on_phase and connected_wifi_targets:
|
||||
try:
|
||||
on_phase(f"已连接设备兜底发现 {len(connected_wifi_targets)} 个 WiFi ADB 目标")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
quick_open_targets: list[tuple[str, int]] = []
|
||||
quick_hosts: list[str] = []
|
||||
@@ -956,7 +975,8 @@ def discover_adb_devices(
|
||||
all_open_targets.extend(open_targets)
|
||||
|
||||
# 合并 mDNS + 网段扫描,并去重
|
||||
all_targets = list(mdns_targets)
|
||||
all_targets = list(connected_wifi_targets)
|
||||
all_targets.extend(mdns_targets)
|
||||
all_targets.extend(quick_open_targets)
|
||||
all_targets.extend(all_open_targets)
|
||||
uniq_open: list[tuple[str, int]] = []
|
||||
|
||||
@@ -8,10 +8,10 @@ _BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
if str(_BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_BASE_DIR))
|
||||
|
||||
from douyin.updater.bootstrap import run_startup_update_check_early
|
||||
from gui.components.update_progress import run_gui_startup_update_check_early
|
||||
|
||||
|
||||
run_startup_update_check_early(app_name="gui_dashboard_app")
|
||||
run_gui_startup_update_check_early(app_name="gui_dashboard_app")
|
||||
|
||||
from gui.dashboard_app.app import main # noqa: E402
|
||||
|
||||
|
||||
+7
-3
@@ -24,7 +24,7 @@ if __name__ == "__main__":
|
||||
run_startup_update_check_early(app_name="web_gui")
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.license.license_manager import require_online_license_or_exit, start_online_license_monitor
|
||||
from douyin.license.license_manager import check_license, require_online_license_or_exit, start_online_license_monitor
|
||||
|
||||
# 从子包 re-export 顶层 helper(保持兼容)
|
||||
from gui.web_gui_pkg import (
|
||||
@@ -910,8 +910,12 @@ class Handler(BaseHTTPRequestHandler):
|
||||
|
||||
|
||||
def main() -> int:
|
||||
require_online_license_or_exit()
|
||||
start_online_license_monitor(on_line=lambda line: print(line, flush=True))
|
||||
local_status = check_license()
|
||||
if local_status.ok:
|
||||
require_online_license_or_exit()
|
||||
start_online_license_monitor(on_line=lambda line: print(line, flush=True))
|
||||
else:
|
||||
print(f"[LICENSE] 等待授权: {local_status.reason} - {local_status.message}", flush=True)
|
||||
host = get_web_gui_host()
|
||||
# 支持 PORT / WEB_GUI_PORT 两种环境变量,默认 8000
|
||||
port = get_web_gui_port()
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def render_license_gate_html(csrf_token: str) -> str:
|
||||
return f"""<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>卡密验证 - 抖音自动化助手</title>
|
||||
<style>
|
||||
:root {{
|
||||
color-scheme: light;
|
||||
--bg: #f5f8fb;
|
||||
--surface: #ffffff;
|
||||
--text: #16202a;
|
||||
--muted: #6f7f8f;
|
||||
--border: #dce7ef;
|
||||
--teal: #13998f;
|
||||
--teal-dark: #08746d;
|
||||
--teal-soft: #e6f7f5;
|
||||
--danger: #c83a4b;
|
||||
}}
|
||||
* {{ box-sizing: border-box; }}
|
||||
body {{
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 28px;
|
||||
font: 16px/1.55 "Microsoft YaHei UI", "Microsoft YaHei", Arial, sans-serif;
|
||||
color: var(--text);
|
||||
background:
|
||||
radial-gradient(circle at 18% 12%, rgba(19, 153, 143, .12), transparent 30%),
|
||||
linear-gradient(135deg, #fbfdff 0%, var(--bg) 100%);
|
||||
}}
|
||||
.gate {{
|
||||
width: min(520px, 100%);
|
||||
padding: 34px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 22px;
|
||||
background: rgba(255, 255, 255, .92);
|
||||
box-shadow: 0 24px 70px rgba(22, 32, 42, .10);
|
||||
}}
|
||||
.brand {{ display: flex; gap: 16px; align-items: center; margin-bottom: 28px; }}
|
||||
.mark {{
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
border-radius: 14px;
|
||||
color: #fff;
|
||||
background: var(--teal);
|
||||
font-size: 23px;
|
||||
font-weight: 800;
|
||||
}}
|
||||
h1 {{ margin: 0; font-size: 26px; line-height: 1.2; }}
|
||||
p {{ margin: 7px 0 0; color: var(--muted); }}
|
||||
label {{ display: block; margin: 0 0 10px; font-weight: 700; }}
|
||||
input {{
|
||||
width: 100%;
|
||||
height: 52px;
|
||||
padding: 0 16px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
outline: none;
|
||||
font: inherit;
|
||||
background: #fbfdff;
|
||||
}}
|
||||
input:focus {{
|
||||
border-color: var(--teal);
|
||||
box-shadow: 0 0 0 4px var(--teal-soft);
|
||||
background: #fff;
|
||||
}}
|
||||
button {{
|
||||
width: 100%;
|
||||
height: 52px;
|
||||
margin-top: 18px;
|
||||
border: 0;
|
||||
border-radius: 14px;
|
||||
color: #fff;
|
||||
background: var(--teal);
|
||||
font: inherit;
|
||||
font-weight: 800;
|
||||
cursor: pointer;
|
||||
}}
|
||||
button:disabled {{ cursor: wait; opacity: .75; }}
|
||||
.msg {{
|
||||
min-height: 24px;
|
||||
margin-top: 14px;
|
||||
color: var(--muted);
|
||||
font-size: 15px;
|
||||
}}
|
||||
.msg.error {{ color: var(--danger); }}
|
||||
.msg.ok {{ color: var(--teal-dark); }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="gate" aria-labelledby="title">
|
||||
<div class="brand">
|
||||
<div class="mark">抖</div>
|
||||
<div>
|
||||
<h1 id="title">卡密验证</h1>
|
||||
<p>首次启动需要先验证卡密,成功后进入控制台。</p>
|
||||
</div>
|
||||
</div>
|
||||
<form id="license-form">
|
||||
<label for="license-input">输入卡密</label>
|
||||
<input id="license-input" name="license_text" autocomplete="off" autofocus>
|
||||
<button id="submit-btn" type="submit">验证并进入</button>
|
||||
<div id="message" class="msg" role="status"></div>
|
||||
</form>
|
||||
</main>
|
||||
<script>
|
||||
const csrfToken = {csrf_token!r};
|
||||
const form = document.getElementById("license-form");
|
||||
const input = document.getElementById("license-input");
|
||||
const button = document.getElementById("submit-btn");
|
||||
const message = document.getElementById("message");
|
||||
form.addEventListener("submit", async (event) => {{
|
||||
event.preventDefault();
|
||||
const licenseText = input.value.trim();
|
||||
message.className = "msg";
|
||||
if (!licenseText) {{
|
||||
message.textContent = "请先输入卡密。";
|
||||
message.classList.add("error");
|
||||
input.focus();
|
||||
return;
|
||||
}}
|
||||
button.disabled = true;
|
||||
message.textContent = "正在验证...";
|
||||
try {{
|
||||
const res = await fetch("/api/license", {{
|
||||
method: "POST",
|
||||
headers: {{
|
||||
"Content-Type": "application/json",
|
||||
"X-CSRF-Token": csrfToken
|
||||
}},
|
||||
body: JSON.stringify({{ license_text: licenseText }})
|
||||
}});
|
||||
const data = await res.json().catch(() => ({{}}));
|
||||
if (!res.ok || !data.ok) {{
|
||||
throw new Error(data.message || data.error || "卡密验证失败");
|
||||
}}
|
||||
message.textContent = "验证成功,正在进入...";
|
||||
message.classList.add("ok");
|
||||
window.location.reload();
|
||||
}} catch (err) {{
|
||||
message.textContent = err && err.message ? err.message : "卡密验证失败";
|
||||
message.classList.add("error");
|
||||
}} finally {{
|
||||
button.disabled = false;
|
||||
}}
|
||||
}});
|
||||
</script>
|
||||
</body>
|
||||
</html>"""
|
||||
@@ -2,12 +2,33 @@ import json
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
|
||||
|
||||
SECURITY_HEADERS = (
|
||||
("X-Content-Type-Options", "nosniff"),
|
||||
("Referrer-Policy", "no-referrer"),
|
||||
("X-Frame-Options", "DENY"),
|
||||
)
|
||||
|
||||
|
||||
def send_security_headers(handler: BaseHTTPRequestHandler) -> None:
|
||||
for key, value in SECURITY_HEADERS:
|
||||
handler.send_header(key, value)
|
||||
|
||||
|
||||
def send_html_security_headers(handler: BaseHTTPRequestHandler) -> None:
|
||||
send_security_headers(handler)
|
||||
handler.send_header(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'",
|
||||
)
|
||||
|
||||
|
||||
def send_json(handler: BaseHTTPRequestHandler, obj, status: int = 200) -> None:
|
||||
data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
||||
handler.send_response(status)
|
||||
handler.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
send_security_headers(handler)
|
||||
handler.end_headers()
|
||||
try:
|
||||
handler.wfile.write(data)
|
||||
|
||||
@@ -7,10 +7,12 @@ from urllib.parse import parse_qs
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.license.license_manager import (
|
||||
check_license,
|
||||
get_default_activation_url,
|
||||
get_license_status_payload,
|
||||
install_license_or_activate,
|
||||
)
|
||||
from gui.web_gui_pkg.license_gate import render_license_gate_html
|
||||
from gui.web_gui_pkg import (
|
||||
_wg_log,
|
||||
find_adb_executable,
|
||||
@@ -19,6 +21,7 @@ from gui.web_gui_pkg import (
|
||||
write_config,
|
||||
proc_runner_ops as _proc_ops,
|
||||
)
|
||||
from gui.web_gui_pkg.request_parsing import send_html_security_headers, send_security_headers
|
||||
|
||||
BASE_DIR = (
|
||||
path_config.PROJECT_ROOT
|
||||
@@ -33,6 +36,23 @@ _EMPTY_PNG_BYTES = bytes.fromhex(
|
||||
"1f15c4890000000a49444154789c636000000200015dc1b2ea00000000"
|
||||
"49454e44ae426082"
|
||||
)
|
||||
_LICENSE_REQUIRED_POST_PATHS = {
|
||||
"/api/start-run",
|
||||
"/api/force-stop",
|
||||
"/api/pause",
|
||||
"/api/resume",
|
||||
"/api/back-key",
|
||||
"/api/wifi/enable",
|
||||
"/api/wifi/connect",
|
||||
"/api/wifi/disconnect",
|
||||
"/api/wifi/scan",
|
||||
"/api/wifi/last/clear",
|
||||
"/api/wifi/auto-reconnect",
|
||||
"/api/test-yanghao",
|
||||
"/api/test-comment",
|
||||
"/api/stop",
|
||||
"/api/screenshot",
|
||||
}
|
||||
|
||||
|
||||
def _is_local_request(handler) -> bool:
|
||||
@@ -72,6 +92,31 @@ def _license_activation_settings() -> tuple[str, int]:
|
||||
return activation_url, max(1, timeout_seconds)
|
||||
|
||||
|
||||
def _license_gate_payload() -> dict:
|
||||
status = check_license()
|
||||
payload = get_license_status_payload()
|
||||
payload.update(
|
||||
{
|
||||
"ok": False,
|
||||
"error": "license_required",
|
||||
"reason": status.reason,
|
||||
"message": status.message,
|
||||
}
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def _send_html(handler, html: str, status: int = 200) -> None:
|
||||
data = html.encode("utf-8")
|
||||
handler.send_response(status)
|
||||
handler.send_header("Content-Type", "text/html; charset=utf-8")
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
send_html_security_headers(handler)
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
|
||||
|
||||
def _is_invalid_ports_spec(spec) -> bool:
|
||||
"""判断端口规格是否为明确非法输入。"""
|
||||
if spec is None:
|
||||
@@ -312,6 +357,7 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
|
||||
handler.send_header("Content-Type", "image/png")
|
||||
handler.send_header("Content-Length", str(len(_EMPTY_PNG_BYTES)))
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
send_security_headers(handler)
|
||||
handler.end_headers()
|
||||
handler.wfile.write(_EMPTY_PNG_BYTES)
|
||||
return
|
||||
@@ -329,6 +375,7 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
|
||||
handler.send_header("Content-Type", ctype)
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
send_security_headers(handler)
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
return
|
||||
@@ -337,6 +384,9 @@ def handle_get(handler, u, runner, csrf_token: str) -> None:
|
||||
handler.send_error(HTTPStatus.FORBIDDEN)
|
||||
return
|
||||
|
||||
if u.path in {"/", "/index.html"} and not check_license().ok:
|
||||
return _send_html(handler, render_license_gate_html(csrf_token))
|
||||
|
||||
handler._serve_static(u.path)
|
||||
|
||||
|
||||
@@ -349,6 +399,8 @@ def handle_post(handler, u, runner, csrf_token: str) -> None:
|
||||
return handler._send_json(
|
||||
{"ok": False, "error": "Invalid CSRF token"}, status=403
|
||||
)
|
||||
if u.path in _LICENSE_REQUIRED_POST_PATHS and not check_license().ok:
|
||||
return handler._send_json(_license_gate_payload(), status=403)
|
||||
|
||||
if u.path == "/api/config":
|
||||
body = handler._read_json()
|
||||
|
||||
@@ -3,6 +3,8 @@ from http import HTTPStatus
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from typing import Callable
|
||||
|
||||
from gui.web_gui_pkg.request_parsing import send_html_security_headers, send_security_headers
|
||||
|
||||
|
||||
def serve_static(
|
||||
handler: BaseHTTPRequestHandler,
|
||||
@@ -60,6 +62,7 @@ def serve_static(
|
||||
handler.send_response(HTTPStatus.NOT_MODIFIED)
|
||||
handler.send_header("ETag", etag)
|
||||
handler.send_header("Cache-Control", cache_control)
|
||||
send_security_headers(handler)
|
||||
handler.end_headers()
|
||||
return
|
||||
except Exception:
|
||||
@@ -68,6 +71,10 @@ def serve_static(
|
||||
handler.send_header("Content-Type", ctype)
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.send_header("Cache-Control", cache_control)
|
||||
if ext == ".html":
|
||||
send_html_security_headers(handler)
|
||||
else:
|
||||
send_security_headers(handler)
|
||||
if etag:
|
||||
handler.send_header("ETag", etag)
|
||||
handler.end_headers()
|
||||
|
||||
@@ -16,6 +16,9 @@ GET /api/v1/health
|
||||
POST /api/v1/activate
|
||||
POST /api/v1/verify
|
||||
POST /api/v1/verify_license
|
||||
POST /api/v1/redeem/external/create
|
||||
POST /api/v1/redeem/claim
|
||||
GET /redeem/{token}
|
||||
GET /api/v1/update/manifest
|
||||
GET /api/v1/update/download/{filename}
|
||||
GET /admin
|
||||
@@ -32,6 +35,47 @@ GET /admin
|
||||
|
||||
成功后返回 `license` 字段,客户端本地验签通过才会写入 `license.dat`。
|
||||
|
||||
## 闲鱼自动发货接入
|
||||
|
||||
自动发货系统不要直接拿真实卡密,只调用服务端生成一次性兑换链接。买家打开兑换链接后,服务端才生成正式 `DG-` 卡密。
|
||||
|
||||
服务端先配置外部接口 token:
|
||||
|
||||
```bash
|
||||
export DYGJ_LICENSE_EXTERNAL_API_TOKEN="一段足够长的随机密钥"
|
||||
```
|
||||
|
||||
外部自动发货系统请求:
|
||||
|
||||
```text
|
||||
POST /api/v1/redeem/external/create
|
||||
Authorization: Bearer 一段足够长的随机密钥
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"platform": "xianyu",
|
||||
"external_order_id": "闲鱼订单号",
|
||||
"customer": "买家备注",
|
||||
"days": 30,
|
||||
"max_devices": 1,
|
||||
"expires_hours": 72
|
||||
}
|
||||
```
|
||||
|
||||
返回只包含 `claim_url`,不返回真实卡密:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"claim_url": "https://dy.absfan.cn/redeem/xxxx",
|
||||
"token_hint": "xxxx...xxxx",
|
||||
"expires_at": "2026-06-24T12:00:00Z"
|
||||
}
|
||||
```
|
||||
|
||||
把 `claim_url` 通过闲鱼聊天自动发给买家即可。这个设计可以避免员工、闲鱼自动发货项目或聊天日志直接接触真实卡密库存。
|
||||
|
||||
## Docker 部署
|
||||
|
||||
```bash
|
||||
@@ -82,7 +126,9 @@ export DYGJ_LICENSE_ADMIN_TOKEN="$(cat secrets/admin_token.txt)"
|
||||
|
||||
不要把管理员 token 放到 URL 里,避免进入浏览器历史、访问日志或截图。
|
||||
生产环境默认关闭 `/docs`、`/redoc` 和 `/openapi.json`;确实需要临时查看时设置 `DYGJ_LICENSE_ENABLE_DOCS=1`。
|
||||
如果服务通过 HTTPS 访问,建议设置 `DYGJ_LICENSE_SECURE_COOKIES=1`。
|
||||
生产环境建议显式设置 `DYGJ_LICENSE_PUBLIC_BASE_URL=https://你的域名`,服务会用它生成兑换链接和更新下载地址。
|
||||
设置 HTTPS 的 `DYGJ_LICENSE_PUBLIC_BASE_URL` 后,后台 Cookie 会默认带 `Secure`;如需手动覆盖,可设置 `DYGJ_LICENSE_SECURE_COOKIES=1`。
|
||||
服务端会校验 Host 头,默认允许 `dy.absfan.cn`、`127.0.0.1`、`localhost` 和测试域名;自定义域名可设置 `DYGJ_LICENSE_ALLOWED_HOSTS=你的域名,备用域名`。
|
||||
只有在前面有可信反向代理时,才设置 `DYGJ_LICENSE_TRUST_FORWARDED_FOR=1`。
|
||||
|
||||
## 自动更新
|
||||
@@ -93,17 +139,37 @@ export DYGJ_LICENSE_ADMIN_TOKEN="$(cat secrets/admin_token.txt)"
|
||||
http://服务器IP:18100/admin
|
||||
```
|
||||
|
||||
登录后在“在线更新”区域上传新版安装包 `.exe`,填写版本号(例如 `3.3.4`)后点击“上传并发布”。服务端会:
|
||||
登录后在“在线更新”区域先上传新版安装包 `.exe`,填写版本号(例如 `3.3.4`)后点击“上传并发布”。服务端会:
|
||||
|
||||
- 保存安装包到 `data/updates/`
|
||||
- 自动计算安装包 SHA256
|
||||
- 生成 `/api/v1/update/manifest`
|
||||
- 使用服务端私钥给 manifest 签名
|
||||
|
||||
默认上传大小限制:完整安装包最大 700 MB,差量包最大 250 MB。需要调整时设置:
|
||||
|
||||
```bash
|
||||
export DYGJ_LICENSE_MAX_INSTALLER_UPLOAD_MB=700
|
||||
export DYGJ_LICENSE_MAX_DELTA_UPLOAD_MB=250
|
||||
```
|
||||
|
||||
如果要发布差量更新,再上传 `DouyinGuaji-旧版本_to_新版本_delta.zip`,并填写来源版本和目标版本。新客户端会优先下载匹配自己当前版本的差量包;没有匹配差量包时,才回退下载完整安装包。
|
||||
|
||||
生成差量包示例:
|
||||
|
||||
```bash
|
||||
python -m tools.update_delta build \
|
||||
--old dist/DouyinGuaji-3.3.5 \
|
||||
--new dist/DouyinGuaji-3.3.6 \
|
||||
--out dist/delta/DouyinGuaji-3.3.5_to_3.3.6_delta.zip \
|
||||
--from-version 3.3.5 \
|
||||
--to-version 3.3.6
|
||||
```
|
||||
|
||||
打包后的客户端默认读取:
|
||||
|
||||
```text
|
||||
https://dy.absfan.cn/api/v1/update/manifest
|
||||
```
|
||||
|
||||
如果后台未发布更新,manifest 返回 `version=0.0.0`,客户端不会下载。发布高于客户端当前版本的安装包后,客户端启动时会下载、校验签名和 SHA256,然后启动安装器并退出旧进程。
|
||||
如果后台未发布更新,manifest 返回 `version=0.0.0`,客户端不会下载。发布高于客户端当前版本的更新后,客户端启动时会校验 manifest 签名、下载并校验 SHA256,然后退出旧进程执行差量更新或完整安装。
|
||||
+476
-10
@@ -3,17 +3,20 @@ from __future__ import annotations
|
||||
import base64
|
||||
import hmac
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import tempfile
|
||||
import time
|
||||
from html import escape
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from urllib.parse import urljoin
|
||||
from urllib.parse import urljoin, urlparse
|
||||
|
||||
from fastapi import FastAPI, File, Form, Request, UploadFile
|
||||
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
|
||||
from pydantic import BaseModel
|
||||
from starlette.middleware.trustedhost import TrustedHostMiddleware
|
||||
|
||||
from license_server.core import LicenseActionResult, LicenseService, UpdateManifest
|
||||
|
||||
@@ -22,9 +25,15 @@ RATE_LIMIT_WINDOW_SECONDS = 60
|
||||
RATE_LIMIT_MAX_REQUESTS = 30
|
||||
ADMIN_LOGIN_RATE_LIMIT_MAX_REQUESTS = 10
|
||||
VERIFY_LICENSE_RATE_LIMIT_MAX_REQUESTS = 600
|
||||
EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS = 10
|
||||
REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS = 60
|
||||
ADMIN_CSRF_COOKIE = "dygj_admin_csrf"
|
||||
ADMIN_SESSION_COOKIE = "dygj_admin_session"
|
||||
ADMIN_SESSION_SECONDS = 12 * 60 * 60
|
||||
DEFAULT_MAX_INSTALLER_UPLOAD_BYTES = 700 * 1024 * 1024
|
||||
DEFAULT_MAX_DELTA_UPLOAD_BYTES = 250 * 1024 * 1024
|
||||
DEFAULT_MAX_DIAGNOSTIC_LOG_UPLOAD_BYTES = 500 * 1024 * 1024
|
||||
UPLOAD_CHUNK_BYTES = 1024 * 1024
|
||||
|
||||
|
||||
class ActivateRequest(BaseModel):
|
||||
@@ -41,6 +50,19 @@ class VerifyLicenseRequest(BaseModel):
|
||||
license: dict[str, Any]
|
||||
|
||||
|
||||
class CreateRedeemRequest(BaseModel):
|
||||
days: int
|
||||
max_devices: int = 1
|
||||
customer: str = ""
|
||||
platform: str = ""
|
||||
external_order_id: str = ""
|
||||
expires_hours: int = 72
|
||||
|
||||
|
||||
class ClaimRedeemRequest(BaseModel):
|
||||
token: str
|
||||
|
||||
|
||||
def result_response(result: LicenseActionResult) -> JSONResponse:
|
||||
body: dict[str, Any] = {
|
||||
"ok": result.ok,
|
||||
@@ -86,6 +108,10 @@ def admin_token_from_env() -> str:
|
||||
return str(os.environ.get("DYGJ_LICENSE_ADMIN_TOKEN") or "").strip()
|
||||
|
||||
|
||||
def external_api_token_from_env() -> str:
|
||||
return str(os.environ.get("DYGJ_LICENSE_EXTERNAL_API_TOKEN") or "").strip()
|
||||
|
||||
|
||||
def _env_bool(name: str, default: bool = False) -> bool:
|
||||
raw = str(os.environ.get(name) or "").strip().lower()
|
||||
if raw in {"1", "true", "yes", "y", "on"}:
|
||||
@@ -95,6 +121,84 @@ def _env_bool(name: str, default: bool = False) -> bool:
|
||||
return default
|
||||
|
||||
|
||||
def _env_int(name: str, default: int) -> int:
|
||||
raw = str(os.environ.get(name) or "").strip()
|
||||
if not raw:
|
||||
return int(default)
|
||||
try:
|
||||
value = int(raw)
|
||||
except ValueError:
|
||||
return int(default)
|
||||
return value if value > 0 else int(default)
|
||||
|
||||
|
||||
def _configured_public_base_url() -> str:
|
||||
return str(os.environ.get("DYGJ_LICENSE_PUBLIC_BASE_URL") or "").strip()
|
||||
|
||||
|
||||
def _default_secure_cookies() -> bool:
|
||||
return _configured_public_base_url().lower().startswith("https://")
|
||||
|
||||
|
||||
def _allowed_hosts_from_env() -> list[str]:
|
||||
raw = str(os.environ.get("DYGJ_LICENSE_ALLOWED_HOSTS") or "").strip()
|
||||
hosts = [h.strip() for h in raw.split(",") if h.strip()]
|
||||
configured = _configured_public_base_url()
|
||||
if configured:
|
||||
parsed = urlparse(configured)
|
||||
if parsed.hostname:
|
||||
hosts.append(parsed.hostname)
|
||||
hosts.extend(["dy.absfan.cn", "127.0.0.1", "localhost", "testserver"])
|
||||
result: list[str] = []
|
||||
for host in hosts:
|
||||
if host and host not in result:
|
||||
result.append(host)
|
||||
return result
|
||||
|
||||
|
||||
async def _save_upload_to_temp(
|
||||
upload: UploadFile,
|
||||
*,
|
||||
upload_dir: Path,
|
||||
max_bytes: int,
|
||||
suffix: str,
|
||||
) -> Path:
|
||||
upload_dir.mkdir(parents=True, exist_ok=True)
|
||||
tmp_name = ""
|
||||
total = 0
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(
|
||||
"wb",
|
||||
delete=False,
|
||||
dir=str(upload_dir),
|
||||
suffix=suffix,
|
||||
) as tmp:
|
||||
tmp_name = tmp.name
|
||||
while True:
|
||||
chunk = await upload.read(UPLOAD_CHUNK_BYTES)
|
||||
if not chunk:
|
||||
break
|
||||
total += len(chunk)
|
||||
if total > max_bytes:
|
||||
raise ValueError(f"上传文件超过大小限制(最大 {max_bytes // (1024 * 1024)} MB)")
|
||||
tmp.write(chunk)
|
||||
if total <= 0:
|
||||
raise ValueError("上传文件为空")
|
||||
return Path(tmp_name)
|
||||
except Exception:
|
||||
if tmp_name:
|
||||
try:
|
||||
Path(tmp_name).unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
finally:
|
||||
try:
|
||||
await upload.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _admin_allowed(request: Request, admin_token: str) -> bool:
|
||||
expected = str(admin_token or "").strip()
|
||||
if not expected:
|
||||
@@ -119,6 +223,17 @@ def _admin_allowed(request: Request, admin_token: str) -> bool:
|
||||
return hmac.compare_digest(supplied, expected)
|
||||
|
||||
|
||||
def _bearer_token_allowed(request: Request, expected_token: str) -> bool:
|
||||
expected = str(expected_token or "").strip()
|
||||
if not expected:
|
||||
return False
|
||||
auth = str(request.headers.get("authorization") or "").strip()
|
||||
if not auth.lower().startswith("bearer "):
|
||||
return False
|
||||
supplied = auth.split(" ", 1)[1].strip()
|
||||
return hmac.compare_digest(supplied, expected)
|
||||
|
||||
|
||||
def _session_hash(raw: str) -> str:
|
||||
return hashlib.sha256(str(raw or "").encode("utf-8")).hexdigest()
|
||||
|
||||
@@ -212,7 +327,7 @@ def _rate_limited(request: Request, scope: str, *, max_requests: int | None = No
|
||||
|
||||
|
||||
def _public_base_url(request: Request) -> str:
|
||||
configured = str(os.environ.get("DYGJ_LICENSE_PUBLIC_BASE_URL") or "").strip()
|
||||
configured = _configured_public_base_url()
|
||||
if configured:
|
||||
return configured.rstrip("/")
|
||||
return str(request.base_url).rstrip("/")
|
||||
@@ -241,6 +356,19 @@ def _signed_update_manifest(service: LicenseService, request: Request) -> dict[s
|
||||
"notes": manifest.notes,
|
||||
"published_at": manifest.published_at,
|
||||
}
|
||||
if manifest.delta:
|
||||
raw_deltas = manifest.delta if isinstance(manifest.delta, list) else [manifest.delta]
|
||||
deltas: list[dict[str, Any]] = []
|
||||
for raw_delta in raw_deltas:
|
||||
if not isinstance(raw_delta, dict):
|
||||
continue
|
||||
delta = dict(raw_delta)
|
||||
delta_filename = str(delta.get("filename") or "")
|
||||
if delta_filename:
|
||||
delta_path = f"/api/v1/update/download/{delta_filename}"
|
||||
delta["url"] = urljoin(_public_base_url(request) + "/", delta_path.lstrip("/"))
|
||||
deltas.append(delta)
|
||||
payload["delta"] = deltas[0] if len(deltas) == 1 else deltas
|
||||
payload["signature"] = service.sign_payload(payload)
|
||||
return payload
|
||||
|
||||
@@ -250,17 +378,38 @@ def _update_summary_html(manifest: UpdateManifest) -> str:
|
||||
sha = manifest.sha256[:12] + "..." if manifest.sha256 else "-"
|
||||
file_name = manifest.filename or "-"
|
||||
published = manifest.published_at or "-"
|
||||
raw_delta = manifest.delta or {}
|
||||
delta_text = "-"
|
||||
if raw_delta:
|
||||
deltas = raw_delta if isinstance(raw_delta, list) else [raw_delta]
|
||||
delta_text = "<br>".join(
|
||||
f"{escape(str(delta.get('from_version') or ''))}"
|
||||
f" -> {escape(str(delta.get('to_version') or ''))} / "
|
||||
f"<code>{escape(str(delta.get('filename') or '-'))}</code>"
|
||||
for delta in deltas
|
||||
if isinstance(delta, dict)
|
||||
)
|
||||
return (
|
||||
"<div class='update-state'>"
|
||||
f"<b>{escape(status)}</b>"
|
||||
f"<span>版本:<code>{escape(manifest.version or '0.0.0')}</code></span>"
|
||||
f"<span>文件:<code>{escape(file_name)}</code></span>"
|
||||
f"<span>SHA256:<code>{escape(sha)}</code></span>"
|
||||
f"<span>差量包:{delta_text}</span>"
|
||||
f"<span>发布时间:{escape(published)}</span>"
|
||||
"</div>"
|
||||
)
|
||||
|
||||
|
||||
def _format_bytes(size: int) -> str:
|
||||
value = float(size or 0)
|
||||
for unit in ("B", "KB", "MB", "GB"):
|
||||
if value < 1024 or unit == "GB":
|
||||
return f"{value:.1f} {unit}" if unit != "B" else f"{int(value)} B"
|
||||
value /= 1024
|
||||
return f"{int(size)} B"
|
||||
|
||||
|
||||
def _admin_page(
|
||||
service: LicenseService,
|
||||
csrf_token: str,
|
||||
@@ -271,6 +420,7 @@ def _admin_page(
|
||||
stats = service.stats()
|
||||
card_rows = service.list_cards(limit=50)
|
||||
audit_rows = service.audit_logs(limit=30)
|
||||
diagnostic_rows = service.list_diagnostic_logs(limit=30)
|
||||
update_manifest = service.load_update_manifest()
|
||||
update_html = _update_summary_html(update_manifest)
|
||||
created_rows = "".join(
|
||||
@@ -299,6 +449,18 @@ def _admin_page(
|
||||
"</tr>"
|
||||
for row in audit_rows
|
||||
)
|
||||
diagnostic_html = "".join(
|
||||
"<tr>"
|
||||
f"<td>{escape(row.uploaded_at)}</td>"
|
||||
f"<td><code>{escape(row.code_hint)}</code></td>"
|
||||
f"<td><code>{escape(row.machine_fingerprint[:16])}</code></td>"
|
||||
f"<td>{escape(row.filename)}</td>"
|
||||
f"<td>{escape(_format_bytes(row.size))}</td>"
|
||||
f"<td><code>{escape(row.sha256[:12])}...</code></td>"
|
||||
f"<td><a href='/admin/logs/download/{escape(row.key)}'>下载</a></td>"
|
||||
"</tr>"
|
||||
for row in diagnostic_rows
|
||||
)
|
||||
message_html = f"<p class='msg'>{escape(message)}</p>" if message else ""
|
||||
html = f"""<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
@@ -394,11 +556,18 @@ def _admin_page(
|
||||
<label>强制更新 <input name="force" value="1" /></label>
|
||||
<button type="submit">上传并发布</button>
|
||||
</form>
|
||||
<form class="update" method="post" action="/admin/update/publish-delta" enctype="multipart/form-data" style="margin-top:10px">
|
||||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||||
<label>来源版本 <input name="from_version" placeholder="例如 3.3.5" /></label>
|
||||
<label>目标版本 <input name="to_version" placeholder="例如 3.3.6" /></label>
|
||||
<label>差量 zip <input name="delta_file" type="file" accept=".zip" /></label>
|
||||
<button class="secondary" type="submit">上传差量包</button>
|
||||
</form>
|
||||
<form method="post" action="/admin/update/disable" style="margin-top:10px">
|
||||
<input type="hidden" name="csrf_token" value="{csrf_attr}" />
|
||||
<button class="secondary" type="submit">关闭更新</button>
|
||||
</form>
|
||||
<div class="help">客户端读取 <code>/api/v1/update/manifest</code>,manifest 会用服务端私钥签名,安装包下载后再做 SHA256 校验。</div>
|
||||
<div class="help">新客户端优先读取差量包,版本不匹配时自动回退完整安装包;manifest、安装包和差量包都会校验签名与 SHA256。</div>
|
||||
</section>
|
||||
<section>
|
||||
<h2>最近卡密</h2>
|
||||
@@ -407,6 +576,14 @@ def _admin_page(
|
||||
<tbody>{table_rows}</tbody>
|
||||
</table>
|
||||
</section>
|
||||
<section>
|
||||
<h2>客户端诊断日志</h2>
|
||||
<div class="help">同一卡密只保留最新一份日志包,新上传会覆盖旧包。</div>
|
||||
<table>
|
||||
<thead><tr><th>上传时间</th><th>卡密</th><th>机器</th><th>文件名</th><th>大小</th><th>SHA256</th><th>操作</th></tr></thead>
|
||||
<tbody>{diagnostic_html}</tbody>
|
||||
</table>
|
||||
</section>
|
||||
<section>
|
||||
<h2>最近审计日志</h2>
|
||||
<table>
|
||||
@@ -424,6 +601,7 @@ def create_app(
|
||||
*,
|
||||
service: LicenseService | None = None,
|
||||
admin_token: str | None = None,
|
||||
external_api_token: str | None = None,
|
||||
) -> FastAPI:
|
||||
docs_enabled = _env_bool("DYGJ_LICENSE_ENABLE_DOCS", default=False)
|
||||
app = FastAPI(
|
||||
@@ -432,10 +610,26 @@ def create_app(
|
||||
redoc_url="/redoc" if docs_enabled else None,
|
||||
openapi_url="/openapi.json" if docs_enabled else None,
|
||||
)
|
||||
app.add_middleware(TrustedHostMiddleware, allowed_hosts=_allowed_hosts_from_env())
|
||||
app.state.license_service = service
|
||||
app.state.admin_token = admin_token if admin_token is not None else admin_token_from_env()
|
||||
app.state.secure_cookies = _env_bool("DYGJ_LICENSE_SECURE_COOKIES", default=False)
|
||||
app.state.external_api_token = (
|
||||
external_api_token if external_api_token is not None else external_api_token_from_env()
|
||||
)
|
||||
app.state.secure_cookies = _env_bool("DYGJ_LICENSE_SECURE_COOKIES", default=_default_secure_cookies())
|
||||
app.state.trust_forwarded_for = _env_bool("DYGJ_LICENSE_TRUST_FORWARDED_FOR", default=False)
|
||||
app.state.max_installer_upload_bytes = _env_int(
|
||||
"DYGJ_LICENSE_MAX_INSTALLER_UPLOAD_MB",
|
||||
DEFAULT_MAX_INSTALLER_UPLOAD_BYTES // (1024 * 1024),
|
||||
) * 1024 * 1024
|
||||
app.state.max_delta_upload_bytes = _env_int(
|
||||
"DYGJ_LICENSE_MAX_DELTA_UPLOAD_MB",
|
||||
DEFAULT_MAX_DELTA_UPLOAD_BYTES // (1024 * 1024),
|
||||
) * 1024 * 1024
|
||||
app.state.max_diagnostic_log_upload_bytes = _env_int(
|
||||
"DYGJ_LICENSE_MAX_DIAGNOSTIC_LOG_UPLOAD_MB",
|
||||
DEFAULT_MAX_DIAGNOSTIC_LOG_UPLOAD_BYTES // (1024 * 1024),
|
||||
) * 1024 * 1024
|
||||
app.state.rate_limit_buckets = {}
|
||||
app.state.admin_sessions = {}
|
||||
|
||||
@@ -476,6 +670,198 @@ def create_app(
|
||||
return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试"))
|
||||
return result_response(get_service().verify_license_doc(req.license))
|
||||
|
||||
@app.post("/api/v1/logs/upload")
|
||||
async def upload_logs(
|
||||
request: Request,
|
||||
license: str = Form(""),
|
||||
log_file: UploadFile = File(...),
|
||||
) -> JSONResponse:
|
||||
if _rate_limited(request, "logs_upload", max_requests=10):
|
||||
return result_response(LicenseActionResult(False, "rate_limited", "请求过于频繁,请稍后再试"))
|
||||
try:
|
||||
license_doc = json.loads(str(license or ""))
|
||||
if not isinstance(license_doc, dict):
|
||||
raise ValueError("license must be object")
|
||||
except Exception:
|
||||
return JSONResponse({"ok": False, "reason": "invalid_license", "message": "授权数据格式无效"}, status_code=400)
|
||||
tmp_path: Path | None = None
|
||||
try:
|
||||
tmp_path = await _save_upload_to_temp(
|
||||
log_file,
|
||||
upload_dir=get_service().diagnostic_log_dir / ".uploads",
|
||||
max_bytes=app.state.max_diagnostic_log_upload_bytes,
|
||||
suffix=".zip.upload",
|
||||
)
|
||||
entry = get_service().save_diagnostic_log_file(
|
||||
license_doc=license_doc,
|
||||
filename=str(log_file.filename or "diagnostic-logs.zip"),
|
||||
file_path=tmp_path,
|
||||
)
|
||||
return JSONResponse(
|
||||
{
|
||||
"ok": True,
|
||||
"message": "日志上传成功",
|
||||
"filename": entry.filename,
|
||||
"size": entry.size,
|
||||
"uploaded_at": entry.uploaded_at,
|
||||
}
|
||||
)
|
||||
except ValueError as exc:
|
||||
reason = str(exc) or "upload_failed"
|
||||
status_code = 413 if "超过大小限制" in reason else 403
|
||||
return JSONResponse({"ok": False, "reason": reason, "message": reason}, status_code=status_code)
|
||||
except Exception as exc:
|
||||
return JSONResponse({"ok": False, "reason": "upload_failed", "message": str(exc)}, status_code=500)
|
||||
finally:
|
||||
if tmp_path is not None:
|
||||
try:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@app.post("/api/v1/redeem/external/create")
|
||||
def redeem_external_create(request: Request, req: CreateRedeemRequest) -> JSONResponse:
|
||||
if not _bearer_token_allowed(request, app.state.external_api_token):
|
||||
if _rate_limited(
|
||||
request,
|
||||
"redeem_create_auth",
|
||||
max_requests=EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS,
|
||||
):
|
||||
return JSONResponse(
|
||||
{"ok": False, "reason": "rate_limited", "message": "请求过于频繁,请稍后再试"},
|
||||
status_code=429,
|
||||
)
|
||||
return JSONResponse(
|
||||
{"ok": False, "reason": "forbidden", "message": "外部接口 token 无效"},
|
||||
status_code=403,
|
||||
)
|
||||
if _rate_limited(request, "redeem_create"):
|
||||
return JSONResponse(
|
||||
{"ok": False, "reason": "rate_limited", "message": "请求过于频繁,请稍后再试"},
|
||||
status_code=429,
|
||||
)
|
||||
try:
|
||||
token = get_service().create_redeem_token(
|
||||
days=req.days,
|
||||
max_devices=req.max_devices,
|
||||
customer=req.customer,
|
||||
platform=req.platform,
|
||||
external_order_id=req.external_order_id,
|
||||
expires_hours=req.expires_hours,
|
||||
)
|
||||
except ValueError as exc:
|
||||
return JSONResponse(
|
||||
{"ok": False, "reason": "invalid_params", "message": str(exc)},
|
||||
status_code=400,
|
||||
)
|
||||
claim_path = f"/redeem#{token.token}"
|
||||
claim_url = urljoin(_public_base_url(request) + "/", claim_path.lstrip("/"))
|
||||
return JSONResponse(
|
||||
{
|
||||
"ok": True,
|
||||
"reason": "ok",
|
||||
"claim_url": claim_url,
|
||||
"token_hint": token.token_hint,
|
||||
"expires_at": token.expires_at.isoformat().replace("+00:00", "Z"),
|
||||
}
|
||||
)
|
||||
|
||||
@app.post("/api/v1/redeem/claim")
|
||||
def redeem_claim(request: Request, req: ClaimRedeemRequest) -> JSONResponse:
|
||||
if _rate_limited(
|
||||
request,
|
||||
"redeem_claim",
|
||||
max_requests=REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS,
|
||||
):
|
||||
return JSONResponse(
|
||||
{"ok": False, "reason": "rate_limited", "message": "请求过于频繁,请稍后再试"},
|
||||
status_code=429,
|
||||
)
|
||||
result = get_service().claim_redeem_token(req.token)
|
||||
if result.ok and result.card is not None:
|
||||
return JSONResponse(
|
||||
{
|
||||
"ok": True,
|
||||
"reason": "ok",
|
||||
"message": result.message,
|
||||
"card_key": result.card.code,
|
||||
"days": result.card.days,
|
||||
"max_devices": result.card.max_devices,
|
||||
}
|
||||
)
|
||||
status = 409 if result.reason == "already_redeemed" else _status_for_reason(result.reason)
|
||||
return JSONResponse(
|
||||
{"ok": False, "reason": result.reason, "message": result.message},
|
||||
status_code=status,
|
||||
)
|
||||
|
||||
@app.get("/redeem")
|
||||
def redeem_page() -> HTMLResponse:
|
||||
return _redeem_page_html()
|
||||
|
||||
@app.get("/redeem/{token}")
|
||||
def redeem_legacy_page(token: str) -> HTMLResponse:
|
||||
script_token = json.dumps(str(token or ""))
|
||||
return HTMLResponse(
|
||||
f"""<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8" /><title>兑换授权</title></head>
|
||||
<body><script>location.replace("/redeem#" + encodeURIComponent({script_token}));</script></body></html>"""
|
||||
)
|
||||
|
||||
def _redeem_page_html() -> HTMLResponse:
|
||||
html = f"""<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<title>兑换授权</title>
|
||||
<style>
|
||||
body {{ margin: 0; min-height: 100vh; display: grid; place-items: center; font-family: "Microsoft YaHei", sans-serif; background: linear-gradient(135deg, #0f172a, #1e293b); color: #0f172a; }}
|
||||
main {{ width: min(520px, calc(100vw - 32px)); background: #fff; border-radius: 24px; padding: 28px; box-shadow: 0 28px 80px rgba(0, 0, 0, .35); }}
|
||||
h1 {{ margin: 0 0 8px; font-size: 28px; }}
|
||||
p {{ color: #64748b; line-height: 1.7; }}
|
||||
code {{ display: block; word-break: break-all; background: #f1f5f9; padding: 12px; border-radius: 12px; }}
|
||||
button {{ width: 100%; margin-top: 16px; padding: 12px 16px; cursor: pointer; border: 0; border-radius: 12px; background: #2563eb; color: white; font-weight: 800; font-size: 15px; }}
|
||||
#result {{ margin-top: 14px; padding: 12px; border-radius: 12px; background: #f8fafc; min-height: 24px; }}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>兑换软件授权</h1>
|
||||
<p>点击兑换后会生成正式卡密。卡密只显示一次,请妥善保存。</p>
|
||||
<code id="tokenPreview">正在读取兑换链接...</code>
|
||||
<button id="claim">立即兑换</button>
|
||||
<div id="result"></div>
|
||||
</main>
|
||||
<script>
|
||||
const token = decodeURIComponent((location.hash || "").replace(/^#/, ""));
|
||||
document.getElementById("tokenPreview").textContent = token ? token : "兑换链接缺少 token";
|
||||
document.getElementById("claim").addEventListener("click", async () => {{
|
||||
const result = document.getElementById("result");
|
||||
if (!token) {{
|
||||
result.textContent = "兑换链接缺少 token";
|
||||
return;
|
||||
}}
|
||||
result.textContent = "正在兑换...";
|
||||
const resp = await fetch("/api/v1/redeem/claim", {{
|
||||
method: "POST",
|
||||
headers: {{ "content-type": "application/json" }},
|
||||
body: JSON.stringify({{ token }})
|
||||
}});
|
||||
const data = await resp.json();
|
||||
if (data.ok) {{
|
||||
result.textContent = "兑换成功,卡密:";
|
||||
const code = document.createElement("code");
|
||||
code.textContent = data.card_key || "";
|
||||
result.appendChild(code);
|
||||
}} else {{
|
||||
result.textContent = data.message || data.reason || "兑换失败";
|
||||
}}
|
||||
}});
|
||||
</script>
|
||||
</body>
|
||||
</html>"""
|
||||
return HTMLResponse(html)
|
||||
|
||||
@app.get("/api/v1/update/manifest")
|
||||
def update_manifest(request: Request) -> JSONResponse:
|
||||
return JSONResponse(_signed_update_manifest(get_service(), request))
|
||||
@@ -485,15 +871,20 @@ def create_app(
|
||||
service = get_service()
|
||||
manifest = service.load_update_manifest()
|
||||
safe_name = Path(str(filename or "")).name
|
||||
if not manifest.enabled or safe_name != manifest.filename:
|
||||
allowed_names = {manifest.filename}
|
||||
if manifest.delta:
|
||||
for delta in manifest.delta if isinstance(manifest.delta, list) else [manifest.delta]:
|
||||
if isinstance(delta, dict) and delta.get("filename"):
|
||||
allowed_names.add(str(delta.get("filename")))
|
||||
if not manifest.enabled or safe_name not in allowed_names:
|
||||
return JSONResponse({"ok": False, "reason": "not_found"}, status_code=404)
|
||||
target = service.update_dir / manifest.filename
|
||||
target = service.update_dir / safe_name
|
||||
if not target.exists():
|
||||
return JSONResponse({"ok": False, "reason": "file_missing"}, status_code=404)
|
||||
return FileResponse(
|
||||
target,
|
||||
media_type="application/octet-stream",
|
||||
filename=manifest.filename,
|
||||
filename=safe_name,
|
||||
)
|
||||
|
||||
@app.get("/admin")
|
||||
@@ -511,6 +902,19 @@ def create_app(
|
||||
)
|
||||
return response
|
||||
|
||||
@app.get("/admin/logs/download/{key}")
|
||||
def admin_log_download(request: Request, key: str) -> Response:
|
||||
if not _admin_allowed(request, app.state.admin_token):
|
||||
return RedirectResponse("/admin/login", status_code=303)
|
||||
target = get_service().diagnostic_log_path(key)
|
||||
if target is None:
|
||||
return JSONResponse({"ok": False, "reason": "not_found"}, status_code=404)
|
||||
return FileResponse(
|
||||
target,
|
||||
media_type="application/zip",
|
||||
filename=f"diagnostic-{key[:12]}.zip",
|
||||
)
|
||||
|
||||
@app.get("/admin/login")
|
||||
def admin_login_page() -> HTMLResponse:
|
||||
return _login_page()
|
||||
@@ -630,18 +1034,80 @@ def create_app(
|
||||
csrf = _csrf_token(request)
|
||||
if not _csrf_allowed(request, csrf_token):
|
||||
return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试")
|
||||
tmp_path: Path | None = None
|
||||
try:
|
||||
content = await installer.read()
|
||||
manifest = get_service().publish_update(
|
||||
service = get_service()
|
||||
tmp_path = await _save_upload_to_temp(
|
||||
installer,
|
||||
upload_dir=service.update_dir / ".uploads",
|
||||
max_bytes=app.state.max_installer_upload_bytes,
|
||||
suffix=".exe.upload",
|
||||
)
|
||||
manifest = service.publish_update_file(
|
||||
version=version,
|
||||
filename=installer.filename or "",
|
||||
content=content,
|
||||
file_path=tmp_path,
|
||||
force=str(force).strip() not in {"0", "false", "False", "否"},
|
||||
notes=notes,
|
||||
)
|
||||
msg = f"已发布更新 V{manifest.version},文件={manifest.filename}"
|
||||
except Exception as exc:
|
||||
msg = f"发布更新失败:{exc}"
|
||||
finally:
|
||||
if tmp_path is not None:
|
||||
try:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
return _admin_page(get_service(), csrf, message=msg)
|
||||
|
||||
@app.post("/admin/update/publish-delta")
|
||||
async def admin_update_publish_delta(
|
||||
request: Request,
|
||||
csrf_token: str = Form(""),
|
||||
from_version: str = Form(""),
|
||||
to_version: str = Form(""),
|
||||
delta_file: UploadFile = File(...),
|
||||
) -> HTMLResponse:
|
||||
if not _admin_allowed(request, app.state.admin_token):
|
||||
return _admin_forbidden()
|
||||
csrf = _csrf_token(request)
|
||||
if not _csrf_allowed(request, csrf_token):
|
||||
return _admin_page(get_service(), csrf, message="CSRF 校验失败,请刷新后台页面后重试")
|
||||
tmp_path: Path | None = None
|
||||
try:
|
||||
service = get_service()
|
||||
tmp_path = await _save_upload_to_temp(
|
||||
delta_file,
|
||||
upload_dir=service.update_dir / ".uploads",
|
||||
max_bytes=app.state.max_delta_upload_bytes,
|
||||
suffix=".zip.upload",
|
||||
)
|
||||
manifest = service.publish_delta_update_file(
|
||||
from_version=from_version,
|
||||
to_version=to_version,
|
||||
filename=delta_file.filename or "",
|
||||
file_path=tmp_path,
|
||||
)
|
||||
raw_delta = manifest.delta or {}
|
||||
deltas = raw_delta if isinstance(raw_delta, list) else [raw_delta]
|
||||
delta = next(
|
||||
(
|
||||
item for item in deltas
|
||||
if isinstance(item, dict)
|
||||
and str(item.get("from_version") or "") == str(from_version).strip().lstrip("Vv")
|
||||
),
|
||||
deltas[-1] if deltas else {},
|
||||
)
|
||||
msg = f"已发布差量更新 {delta.get('from_version')} -> {delta.get('to_version')},文件={delta.get('filename')}"
|
||||
except Exception as exc:
|
||||
msg = f"发布差量更新失败:{exc}"
|
||||
finally:
|
||||
if tmp_path is not None:
|
||||
try:
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
return _admin_page(get_service(), csrf, message=msg)
|
||||
|
||||
@app.post("/admin/update/disable")
|
||||
|
||||
+484
-18
@@ -5,6 +5,7 @@ import hashlib
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import shutil
|
||||
import sqlite3
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta, timezone
|
||||
@@ -19,6 +20,9 @@ MAX_CARD_DAYS = 3660
|
||||
MAX_CREATE_COUNT = 100
|
||||
MAX_CARD_DEVICES = 20
|
||||
MAX_CUSTOMER_LENGTH = 120
|
||||
MAX_REDEEM_EXPIRES_HOURS = 24 * 30
|
||||
MAX_PLATFORM_LENGTH = 40
|
||||
MAX_EXTERNAL_ORDER_LENGTH = 120
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -29,6 +33,27 @@ class CreatedCard:
|
||||
customer: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CreatedRedeemToken:
|
||||
token: str
|
||||
token_hint: str
|
||||
days: int
|
||||
max_devices: int
|
||||
customer: str
|
||||
platform: str
|
||||
external_order_id: str
|
||||
expires_at: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RedeemClaimResult:
|
||||
ok: bool
|
||||
reason: str
|
||||
message: str
|
||||
card: CreatedCard | None = None
|
||||
expires_at: datetime | None = None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LicenseActionResult:
|
||||
ok: bool
|
||||
@@ -72,6 +97,17 @@ class AuditLogEntry:
|
||||
created_at: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DiagnosticLogEntry:
|
||||
key: str
|
||||
code_hint: str
|
||||
machine_fingerprint: str
|
||||
filename: str
|
||||
size: int
|
||||
sha256: str
|
||||
uploaded_at: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UpdateManifest:
|
||||
enabled: bool
|
||||
@@ -81,6 +117,7 @@ class UpdateManifest:
|
||||
force: bool
|
||||
notes: str
|
||||
published_at: str
|
||||
delta: dict[str, Any] | list[dict[str, Any]] | None = None
|
||||
|
||||
|
||||
def utcnow() -> datetime:
|
||||
@@ -130,6 +167,14 @@ def generate_card_code() -> str:
|
||||
return f"DG-{groups}"
|
||||
|
||||
|
||||
def generate_redeem_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def hash_redeem_token(token: str) -> str:
|
||||
return hashlib.sha256(str(token or "").strip().encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def sanitize_update_filename(filename: str, *, version: str = "") -> str:
|
||||
raw = Path(str(filename or "")).name.strip()
|
||||
if not raw.lower().endswith(".exe"):
|
||||
@@ -139,10 +184,36 @@ def sanitize_update_filename(filename: str, *, version: str = "") -> str:
|
||||
return cleaned or "DouyinGuaji-Setup.exe"
|
||||
|
||||
|
||||
def sanitize_delta_filename(filename: str, *, from_version: str = "", to_version: str = "") -> str:
|
||||
raw = Path(str(filename or "")).name.strip()
|
||||
if not raw.lower().endswith(".zip"):
|
||||
safe_from = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(from_version or "old"))
|
||||
safe_to = re.sub(r"[^0-9A-Za-z_.-]+", "_", str(to_version or "latest"))
|
||||
raw = f"DouyinGuaji-{safe_from}_to_{safe_to}_delta.zip"
|
||||
cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", raw).strip(" .")
|
||||
return cleaned or "DouyinGuaji-delta.zip"
|
||||
|
||||
|
||||
def sanitize_diagnostic_log_filename(filename: str) -> str:
|
||||
raw = Path(str(filename or "")).name.strip()
|
||||
if not raw.lower().endswith(".zip"):
|
||||
raw = "diagnostic-logs.zip"
|
||||
cleaned = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', "_", raw).strip(" .")
|
||||
return cleaned or "diagnostic-logs.zip"
|
||||
|
||||
|
||||
def sha256_bytes(data: bytes) -> str:
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def sha256_file(path: str | Path) -> str:
|
||||
digest = hashlib.sha256()
|
||||
with Path(path).open("rb") as f:
|
||||
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
||||
digest.update(chunk)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def _bounded_int(value: int, *, name: str, minimum: int, maximum: int) -> int:
|
||||
parsed = int(value)
|
||||
if parsed < minimum or parsed > maximum:
|
||||
@@ -174,6 +245,12 @@ class LicenseService:
|
||||
def update_manifest_path(self) -> Path:
|
||||
return self.db_path.parent / "update_manifest.json"
|
||||
|
||||
@property
|
||||
def diagnostic_log_dir(self) -> Path:
|
||||
path = self.db_path.parent / "diagnostic_logs"
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
conn = sqlite3.connect(self.db_path, timeout=10)
|
||||
conn.row_factory = sqlite3.Row
|
||||
@@ -181,6 +258,12 @@ class LicenseService:
|
||||
conn.execute("PRAGMA busy_timeout = 10000")
|
||||
return conn
|
||||
|
||||
def _connect_immediate(self) -> sqlite3.Connection:
|
||||
conn = self._connect()
|
||||
conn.isolation_level = None
|
||||
conn.execute("BEGIN IMMEDIATE")
|
||||
return conn
|
||||
|
||||
def _init_db(self) -> None:
|
||||
with self._connect() as conn:
|
||||
conn.execute("PRAGMA journal_mode = WAL")
|
||||
@@ -217,6 +300,23 @@ class LicenseService:
|
||||
reason TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS redeem_tokens (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
token_hash TEXT NOT NULL UNIQUE,
|
||||
token_hint TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'pending',
|
||||
days INTEGER NOT NULL,
|
||||
max_devices INTEGER NOT NULL DEFAULT 1,
|
||||
customer TEXT NOT NULL DEFAULT '',
|
||||
platform TEXT NOT NULL DEFAULT '',
|
||||
external_order_id TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
redeemed_at TEXT,
|
||||
license_id INTEGER,
|
||||
FOREIGN KEY(license_id) REFERENCES license_keys(id)
|
||||
);
|
||||
"""
|
||||
)
|
||||
|
||||
@@ -235,31 +335,115 @@ class LicenseService:
|
||||
cards: list[CreatedCard] = []
|
||||
with self._connect() as conn:
|
||||
for _ in range(count):
|
||||
code = generate_card_code()
|
||||
card = CreatedCard(
|
||||
code=code,
|
||||
card, _license_id = self._insert_card(
|
||||
conn,
|
||||
days=days,
|
||||
max_devices=max_devices,
|
||||
customer=customer,
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO license_keys
|
||||
(code_hash, code_hint, status, days, max_devices, customer, created_at)
|
||||
VALUES (?, ?, 'active', ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
hash_card_code(code),
|
||||
mask_card_code(code),
|
||||
days,
|
||||
max_devices,
|
||||
card.customer,
|
||||
iso_utc(utcnow()),
|
||||
),
|
||||
)
|
||||
cards.append(card)
|
||||
return cards
|
||||
|
||||
def create_redeem_token(
|
||||
self,
|
||||
*,
|
||||
days: int,
|
||||
max_devices: int = 1,
|
||||
customer: str = "",
|
||||
platform: str = "",
|
||||
external_order_id: str = "",
|
||||
expires_hours: int = 72,
|
||||
) -> CreatedRedeemToken:
|
||||
days = _bounded_int(days, name="days", minimum=1, maximum=MAX_CARD_DAYS)
|
||||
max_devices = _bounded_int(max_devices, name="max_devices", minimum=1, maximum=MAX_CARD_DEVICES)
|
||||
expires_hours = _bounded_int(
|
||||
expires_hours,
|
||||
name="expires_hours",
|
||||
minimum=1,
|
||||
maximum=MAX_REDEEM_EXPIRES_HOURS,
|
||||
)
|
||||
customer = str(customer or "").strip()[:MAX_CUSTOMER_LENGTH]
|
||||
platform = str(platform or "").strip()[:MAX_PLATFORM_LENGTH]
|
||||
external_order_id = str(external_order_id or "").strip()[:MAX_EXTERNAL_ORDER_LENGTH]
|
||||
token = generate_redeem_token()
|
||||
token_hint = mask_card_code(token)
|
||||
expires_at = utcnow() + timedelta(hours=expires_hours)
|
||||
with self._connect() as conn:
|
||||
conn.execute(
|
||||
"""
|
||||
INSERT INTO redeem_tokens
|
||||
(token_hash, token_hint, status, days, max_devices, customer, platform,
|
||||
external_order_id, created_at, expires_at)
|
||||
VALUES (?, ?, 'pending', ?, ?, ?, ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
hash_redeem_token(token),
|
||||
token_hint,
|
||||
days,
|
||||
max_devices,
|
||||
customer,
|
||||
platform,
|
||||
external_order_id,
|
||||
iso_utc(utcnow()),
|
||||
iso_utc(expires_at),
|
||||
),
|
||||
)
|
||||
self._audit(conn, "redeem_create", token, "", "ok")
|
||||
return CreatedRedeemToken(
|
||||
token=token,
|
||||
token_hint=token_hint,
|
||||
days=days,
|
||||
max_devices=max_devices,
|
||||
customer=customer,
|
||||
platform=platform,
|
||||
external_order_id=external_order_id,
|
||||
expires_at=expires_at,
|
||||
)
|
||||
|
||||
def claim_redeem_token(self, token: str) -> RedeemClaimResult:
|
||||
raw_token = str(token or "").strip()
|
||||
if not raw_token:
|
||||
return RedeemClaimResult(False, "missing_token", "缺少兑换码")
|
||||
with self._connect_immediate() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM redeem_tokens WHERE token_hash = ?",
|
||||
(hash_redeem_token(raw_token),),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
self._audit(conn, "redeem_claim", raw_token, "", "not_found")
|
||||
return RedeemClaimResult(False, "not_found", "兑换链接不存在")
|
||||
status = str(row["status"] or "").strip().lower()
|
||||
if status == "redeemed":
|
||||
self._audit(conn, "redeem_claim", raw_token, "", "already_redeemed")
|
||||
return RedeemClaimResult(False, "already_redeemed", "兑换链接已使用")
|
||||
if status != "pending":
|
||||
self._audit(conn, "redeem_claim", raw_token, "", status or "inactive")
|
||||
return RedeemClaimResult(False, status or "inactive", "兑换链接不可用")
|
||||
expires_at = parse_utc(row["expires_at"])
|
||||
if utcnow() > expires_at:
|
||||
conn.execute(
|
||||
"UPDATE redeem_tokens SET status = 'expired' WHERE id = ?",
|
||||
(row["id"],),
|
||||
)
|
||||
self._audit(conn, "redeem_claim", raw_token, "", "expired")
|
||||
return RedeemClaimResult(False, "expired", "兑换链接已过期", expires_at=expires_at)
|
||||
card, license_id = self._insert_card(
|
||||
conn,
|
||||
days=int(row["days"]),
|
||||
max_devices=int(row["max_devices"]),
|
||||
customer=str(row["customer"] or ""),
|
||||
)
|
||||
conn.execute(
|
||||
"""
|
||||
UPDATE redeem_tokens
|
||||
SET status = 'redeemed', redeemed_at = ?, license_id = ?
|
||||
WHERE id = ?
|
||||
""",
|
||||
(iso_utc(utcnow()), license_id, row["id"]),
|
||||
)
|
||||
self._audit(conn, "redeem_claim", raw_token, "", "ok")
|
||||
return RedeemClaimResult(True, "ok", "兑换成功", card=card, expires_at=expires_at)
|
||||
|
||||
def revoke(self, code: str) -> bool:
|
||||
with self._connect() as conn:
|
||||
cur = conn.execute(
|
||||
@@ -380,6 +564,7 @@ class LicenseService:
|
||||
if not isinstance(raw, dict):
|
||||
return UpdateManifest(False, "0.0.0", "", "", False, "manifest 格式错误", "")
|
||||
raw_filename = str(raw.get("filename") or "").strip()
|
||||
delta = self._normalize_manifest_delta(raw.get("delta"), to_version=str(raw.get("version") or ""))
|
||||
return UpdateManifest(
|
||||
enabled=bool(raw.get("enabled")),
|
||||
version=str(raw.get("version") or "0.0.0").strip() or "0.0.0",
|
||||
@@ -388,8 +573,62 @@ class LicenseService:
|
||||
force=bool(raw.get("force")),
|
||||
notes=str(raw.get("notes") or ""),
|
||||
published_at=str(raw.get("published_at") or ""),
|
||||
delta=delta,
|
||||
)
|
||||
|
||||
def _normalize_manifest_delta(
|
||||
self,
|
||||
raw_delta: Any,
|
||||
*,
|
||||
to_version: str,
|
||||
) -> dict[str, Any] | list[dict[str, Any]] | None:
|
||||
candidates = raw_delta if isinstance(raw_delta, list) else [raw_delta] if isinstance(raw_delta, dict) else []
|
||||
out: list[dict[str, Any]] = []
|
||||
for item in candidates:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
delta = dict(item)
|
||||
delta_filename = str(delta.get("filename") or "").strip()
|
||||
if delta_filename:
|
||||
delta["filename"] = sanitize_delta_filename(
|
||||
delta_filename,
|
||||
from_version=str(delta.get("from_version") or ""),
|
||||
to_version=str(delta.get("to_version") or to_version),
|
||||
)
|
||||
out.append(delta)
|
||||
if not out:
|
||||
return None
|
||||
return out[0] if len(out) == 1 else out
|
||||
|
||||
def _append_delta_to_manifest(
|
||||
self,
|
||||
existing: UpdateManifest,
|
||||
delta: dict[str, Any],
|
||||
) -> UpdateManifest:
|
||||
raw_existing = existing.delta
|
||||
deltas = list(raw_existing) if isinstance(raw_existing, list) else [raw_existing] if isinstance(raw_existing, dict) else []
|
||||
next_deltas = [
|
||||
item for item in deltas
|
||||
if str(item.get("from_version") or "") != str(delta.get("from_version") or "")
|
||||
]
|
||||
next_deltas.append(delta)
|
||||
next_deltas.sort(key=lambda item: str(item.get("from_version") or ""))
|
||||
manifest = UpdateManifest(
|
||||
enabled=existing.enabled,
|
||||
version=existing.version,
|
||||
filename=existing.filename,
|
||||
sha256=existing.sha256,
|
||||
force=existing.force,
|
||||
notes=existing.notes,
|
||||
published_at=existing.published_at,
|
||||
delta=next_deltas[0] if len(next_deltas) == 1 else next_deltas,
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return manifest
|
||||
|
||||
def publish_update(
|
||||
self,
|
||||
*,
|
||||
@@ -417,6 +656,7 @@ class LicenseService:
|
||||
force=bool(force),
|
||||
notes=str(notes or "").strip()[:500],
|
||||
published_at=iso_utc(utcnow()),
|
||||
delta=None,
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
@@ -424,6 +664,184 @@ class LicenseService:
|
||||
)
|
||||
return manifest
|
||||
|
||||
def publish_update_file(
|
||||
self,
|
||||
*,
|
||||
version: str,
|
||||
filename: str,
|
||||
file_path: str | Path,
|
||||
force: bool = True,
|
||||
notes: str = "",
|
||||
) -> UpdateManifest:
|
||||
version = str(version or "").strip().lstrip("Vv")
|
||||
if not re.fullmatch(r"\d+(?:\.\d+){0,3}", version):
|
||||
raise ValueError("version must look like 3.3.4")
|
||||
source = Path(file_path)
|
||||
if not source.is_file() or source.stat().st_size <= 0:
|
||||
raise ValueError("installer file is empty")
|
||||
safe_filename = sanitize_update_filename(filename, version=version)
|
||||
if not safe_filename.lower().endswith(".exe"):
|
||||
raise ValueError("installer must be an .exe file")
|
||||
target = self.update_dir / safe_filename
|
||||
shutil.copyfile(source, target)
|
||||
manifest = UpdateManifest(
|
||||
enabled=True,
|
||||
version=version,
|
||||
filename=safe_filename,
|
||||
sha256=sha256_file(target),
|
||||
force=bool(force),
|
||||
notes=str(notes or "").strip()[:500],
|
||||
published_at=iso_utc(utcnow()),
|
||||
delta=None,
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return manifest
|
||||
|
||||
def publish_delta_update(
|
||||
self,
|
||||
*,
|
||||
from_version: str,
|
||||
to_version: str,
|
||||
filename: str,
|
||||
content: bytes,
|
||||
) -> UpdateManifest:
|
||||
existing = self.load_update_manifest()
|
||||
if not existing.enabled:
|
||||
raise ValueError("publish full installer before delta")
|
||||
to_version = str(to_version or "").strip().lstrip("Vv")
|
||||
from_version = str(from_version or "").strip().lstrip("Vv")
|
||||
if existing.version != to_version:
|
||||
raise ValueError("delta target version must match current manifest version")
|
||||
if not re.fullmatch(r"\d+(?:\.\d+){0,3}", from_version):
|
||||
raise ValueError("from_version must look like 3.3.4")
|
||||
if not content:
|
||||
raise ValueError("delta file is empty")
|
||||
safe_filename = sanitize_delta_filename(filename, from_version=from_version, to_version=to_version)
|
||||
if not safe_filename.lower().endswith(".zip"):
|
||||
raise ValueError("delta must be a .zip file")
|
||||
target = self.update_dir / safe_filename
|
||||
target.write_bytes(content)
|
||||
delta = {
|
||||
"schema": 1,
|
||||
"from_version": from_version,
|
||||
"to_version": to_version,
|
||||
"filename": safe_filename,
|
||||
"sha256": sha256_bytes(content),
|
||||
"size": len(content),
|
||||
}
|
||||
return self._append_delta_to_manifest(existing, delta)
|
||||
|
||||
def publish_delta_update_file(
|
||||
self,
|
||||
*,
|
||||
from_version: str,
|
||||
to_version: str,
|
||||
filename: str,
|
||||
file_path: str | Path,
|
||||
) -> UpdateManifest:
|
||||
existing = self.load_update_manifest()
|
||||
if not existing.enabled:
|
||||
raise ValueError("publish full installer before delta")
|
||||
to_version = str(to_version or "").strip().lstrip("Vv")
|
||||
from_version = str(from_version or "").strip().lstrip("Vv")
|
||||
if existing.version != to_version:
|
||||
raise ValueError("delta target version must match current manifest version")
|
||||
if not re.fullmatch(r"\d+(?:\.\d+){0,3}", from_version):
|
||||
raise ValueError("from_version must look like 3.3.4")
|
||||
source = Path(file_path)
|
||||
if not source.is_file() or source.stat().st_size <= 0:
|
||||
raise ValueError("delta file is empty")
|
||||
safe_filename = sanitize_delta_filename(filename, from_version=from_version, to_version=to_version)
|
||||
if not safe_filename.lower().endswith(".zip"):
|
||||
raise ValueError("delta must be a .zip file")
|
||||
target = self.update_dir / safe_filename
|
||||
shutil.copyfile(source, target)
|
||||
delta = {
|
||||
"schema": 1,
|
||||
"from_version": from_version,
|
||||
"to_version": to_version,
|
||||
"filename": safe_filename,
|
||||
"sha256": sha256_file(target),
|
||||
"size": target.stat().st_size,
|
||||
}
|
||||
return self._append_delta_to_manifest(existing, delta)
|
||||
|
||||
def save_diagnostic_log_file(
|
||||
self,
|
||||
*,
|
||||
license_doc: dict[str, Any],
|
||||
filename: str,
|
||||
file_path: str | Path,
|
||||
) -> DiagnosticLogEntry:
|
||||
source = Path(file_path)
|
||||
if not source.is_file() or source.stat().st_size <= 0:
|
||||
raise ValueError("diagnostic log file is empty")
|
||||
payload = self._validated_license_payload_for_upload(license_doc)
|
||||
card_hash = str(payload.get("card_hash") or "").strip().lower()
|
||||
raw_machine = str(payload.get("machine_fingerprint") or "").strip()
|
||||
safe_original = sanitize_diagnostic_log_filename(filename)
|
||||
key = hashlib.sha256(card_hash.encode("ascii")).hexdigest()
|
||||
target = self.diagnostic_log_dir / f"{key}.zip"
|
||||
shutil.copyfile(source, target)
|
||||
uploaded_at = iso_utc(utcnow())
|
||||
meta = {
|
||||
"key": key,
|
||||
"code_hint": f"{card_hash[:8]}...{card_hash[-4:]}",
|
||||
"machine_fingerprint": raw_machine,
|
||||
"filename": safe_original,
|
||||
"stored_filename": target.name,
|
||||
"size": target.stat().st_size,
|
||||
"sha256": sha256_file(target),
|
||||
"uploaded_at": uploaded_at,
|
||||
}
|
||||
target.with_suffix(".json").write_text(
|
||||
json.dumps(meta, ensure_ascii=False, indent=2),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return DiagnosticLogEntry(
|
||||
key=key,
|
||||
code_hint=str(meta["code_hint"]),
|
||||
machine_fingerprint=raw_machine,
|
||||
filename=safe_original,
|
||||
size=int(meta["size"]),
|
||||
sha256=str(meta["sha256"]),
|
||||
uploaded_at=uploaded_at,
|
||||
)
|
||||
|
||||
def list_diagnostic_logs(self, *, limit: int = 30) -> list[DiagnosticLogEntry]:
|
||||
rows: list[DiagnosticLogEntry] = []
|
||||
for meta_path in sorted(
|
||||
self.diagnostic_log_dir.glob("*.json"),
|
||||
key=lambda p: p.stat().st_mtime,
|
||||
reverse=True,
|
||||
)[: max(1, int(limit))]:
|
||||
try:
|
||||
meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
||||
rows.append(
|
||||
DiagnosticLogEntry(
|
||||
key=str(meta.get("key") or meta_path.stem),
|
||||
code_hint=str(meta.get("code_hint") or ""),
|
||||
machine_fingerprint=str(meta.get("machine_fingerprint") or ""),
|
||||
filename=str(meta.get("filename") or ""),
|
||||
size=int(meta.get("size") or 0),
|
||||
sha256=str(meta.get("sha256") or ""),
|
||||
uploaded_at=str(meta.get("uploaded_at") or ""),
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
continue
|
||||
return rows
|
||||
|
||||
def diagnostic_log_path(self, key: str) -> Path | None:
|
||||
raw = str(key or "").strip()
|
||||
if not re.fullmatch(r"[0-9a-f]{64}", raw):
|
||||
return None
|
||||
target = self.diagnostic_log_dir / f"{raw}.zip"
|
||||
return target if target.is_file() else None
|
||||
|
||||
def disable_update(self) -> UpdateManifest:
|
||||
existing = self.load_update_manifest()
|
||||
manifest = UpdateManifest(
|
||||
@@ -434,6 +852,7 @@ class LicenseService:
|
||||
force=False,
|
||||
notes=existing.notes,
|
||||
published_at=existing.published_at,
|
||||
delta=existing.delta,
|
||||
)
|
||||
self.update_manifest_path.write_text(
|
||||
json.dumps(manifest.__dict__, ensure_ascii=False, indent=2),
|
||||
@@ -553,6 +972,21 @@ class LicenseService:
|
||||
touch_last_seen=False,
|
||||
)
|
||||
|
||||
def _validated_license_payload_for_upload(self, license_doc: dict[str, Any]) -> dict[str, Any]:
|
||||
result = self.verify_license_doc(license_doc)
|
||||
if not result.ok:
|
||||
raise ValueError(result.reason)
|
||||
payload = license_doc.get("payload") if isinstance(license_doc, dict) else None
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("invalid_format")
|
||||
card_hash = str(payload.get("card_hash") or "").strip().lower()
|
||||
raw_machine = str(payload.get("machine_fingerprint") or "").strip()
|
||||
if len(card_hash) != 64 or any(ch not in "0123456789abcdef" for ch in card_hash):
|
||||
raise ValueError("invalid_card_hash")
|
||||
if not raw_machine:
|
||||
raise ValueError("missing_machine")
|
||||
return payload
|
||||
|
||||
def _verify_card_row(
|
||||
self,
|
||||
conn: sqlite3.Connection,
|
||||
@@ -605,6 +1039,38 @@ class LicenseService:
|
||||
(str(code_hash or "").strip().lower(),),
|
||||
).fetchone()
|
||||
|
||||
def _insert_card(
|
||||
self,
|
||||
conn: sqlite3.Connection,
|
||||
*,
|
||||
days: int,
|
||||
max_devices: int,
|
||||
customer: str,
|
||||
) -> tuple[CreatedCard, int]:
|
||||
code = generate_card_code()
|
||||
card = CreatedCard(
|
||||
code=code,
|
||||
days=int(days),
|
||||
max_devices=int(max_devices),
|
||||
customer=str(customer or "").strip()[:MAX_CUSTOMER_LENGTH],
|
||||
)
|
||||
cur = conn.execute(
|
||||
"""
|
||||
INSERT INTO license_keys
|
||||
(code_hash, code_hint, status, days, max_devices, customer, created_at)
|
||||
VALUES (?, ?, 'active', ?, ?, ?, ?)
|
||||
""",
|
||||
(
|
||||
hash_card_code(code),
|
||||
mask_card_code(code),
|
||||
card.days,
|
||||
card.max_devices,
|
||||
card.customer,
|
||||
iso_utc(utcnow()),
|
||||
),
|
||||
)
|
||||
return card, int(cur.lastrowid)
|
||||
|
||||
def _invalid_card_reason(self, card: sqlite3.Row) -> str:
|
||||
status = str(card["status"] or "").strip().lower()
|
||||
if status == "revoked":
|
||||
|
||||
@@ -45,6 +45,26 @@ def _ops_log(msg: str, level: str = "INFO") -> None:
|
||||
pass
|
||||
|
||||
|
||||
def _adb_shell_png_variants(data: bytes) -> list[bytes]:
|
||||
if not data:
|
||||
return []
|
||||
variants: list[bytes] = []
|
||||
|
||||
def _add(candidate: bytes) -> None:
|
||||
if candidate and candidate not in variants:
|
||||
variants.append(candidate)
|
||||
|
||||
marker = b"\x89PNG"
|
||||
idx = data.find(marker)
|
||||
if idx > 0:
|
||||
data = data[idx:]
|
||||
|
||||
_add(data)
|
||||
_add(data.replace(b"\r\r\n", b"\r\n"))
|
||||
_add(data.replace(b"\r\n", b"\n"))
|
||||
return variants
|
||||
|
||||
|
||||
|
||||
|
||||
class ScreenshotOperations:
|
||||
@@ -169,60 +189,119 @@ class ScreenshotOperations:
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _write_valid_png_bytes(data: bytes) -> bool:
|
||||
for candidate in _adb_shell_png_variants(data):
|
||||
try:
|
||||
with open(tmp_file, "wb") as f:
|
||||
f.write(candidate)
|
||||
if _valid_png(tmp_file):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
def _try_shell_stdout_fallback() -> bool:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[adb, "-s", device_id, "shell", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=True,
|
||||
timeout=8,
|
||||
)
|
||||
if _write_valid_png_bytes(result.stdout or b"") and _safe_replace_file(tmp_file, out_file):
|
||||
if _valid_png(out_file):
|
||||
_mirror_screenshot_to_external(out_file)
|
||||
elapsed = (time.time() - direct_start) * 1000
|
||||
_ops_log(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (shell stdout回退,耗时: {elapsed:.0f}ms)")
|
||||
return True
|
||||
_ops_log(f"[截图] shell stdout回退输出无效: bytes={len(result.stdout or b'')}")
|
||||
except subprocess.CalledProcessError as e:
|
||||
_ops_log(f"[截图] shell stdout回退失败:ADB命令错误 (返回码: {e.returncode})")
|
||||
except subprocess.TimeoutExpired:
|
||||
_ops_log(f"[截图] shell stdout回退失败:操作超时 (设备ID: {device_id})")
|
||||
except Exception as e:
|
||||
_ops_log(f"[截图] shell stdout回退失败:{e}")
|
||||
return False
|
||||
|
||||
def _format_adb_stderr(value: bytes | str | None) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, bytes):
|
||||
text = value.decode("utf-8", errors="replace")
|
||||
else:
|
||||
text = str(value)
|
||||
text = " ".join(text.strip().split())
|
||||
return text[-500:]
|
||||
|
||||
adb_recovered = False
|
||||
|
||||
def _recover_adb_once(reason: str) -> None:
|
||||
nonlocal adb_recovered
|
||||
if adb_recovered:
|
||||
return
|
||||
adb_recovered = True
|
||||
_ops_log(f"[截图] ADB截图输出异常,尝试重启ADB服务后重试: {reason}", "WARNING")
|
||||
for args, timeout in (
|
||||
([adb, "kill-server"], 5),
|
||||
([adb, "start-server"], 8),
|
||||
):
|
||||
try:
|
||||
proc = subprocess.run(
|
||||
args,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
timeout=timeout,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
err = _format_adb_stderr(proc.stderr or proc.stdout)
|
||||
_ops_log(f"[截图] ADB恢复命令返回异常 rc={proc.returncode} err={err}", "WARNING")
|
||||
except Exception as exc:
|
||||
_ops_log(f"[截图] ADB恢复命令执行失败: {exc}", "WARNING")
|
||||
time.sleep(0.5)
|
||||
|
||||
# 优先走 exec-out:只需 1 次 adb 调用;不在手机端落盘,减少 I/O 与卡顿
|
||||
# 为避免被并发读取到"半写入文件",写入 tmp 后再原子替换。
|
||||
for _ in range(2):
|
||||
for attempt in range(2):
|
||||
try:
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
except Exception:
|
||||
pass
|
||||
# 使用 Popen 流式读取,边接收数据边写入文件,提高性能
|
||||
t_exec_start = time.time()
|
||||
try:
|
||||
process = subprocess.Popen(
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.DEVNULL,
|
||||
result = subprocess.run(
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
check=False,
|
||||
timeout=10,
|
||||
)
|
||||
exec_ms = (time.time() - t_exec_start) * 1000
|
||||
timetag2 = datetime.now().strftime("%H:%M:%S")
|
||||
out = result.stdout or b""
|
||||
err = _format_adb_stderr(result.stderr)
|
||||
if result.returncode != 0:
|
||||
reason = f"rc={result.returncode} bytes={len(out)} err={err or '<empty>'}"
|
||||
_ops_log(f"[截图] exec-out 返回异常: {reason}", "WARNING")
|
||||
if result.returncode == 4294967295:
|
||||
_ops_log(f"[截图] exec-out 异常:设备连接失败或ADB服务异常 (设备ID: {device_id})")
|
||||
if attempt == 0:
|
||||
_recover_adb_once(reason)
|
||||
continue
|
||||
if not _write_valid_png_bytes(out):
|
||||
reason = f"rc=0 bytes={len(out)} err={err or '<empty>'}"
|
||||
_ops_log(
|
||||
f"[截图] exec-out 输出无效: {reason} attempt={attempt + 1}/2",
|
||||
"WARNING",
|
||||
)
|
||||
|
||||
# 流式写入文件,避免等待整个命令完成
|
||||
with open(tmp_file, "wb") as f:
|
||||
while True:
|
||||
chunk = process.stdout.read(65536) # 64KB 缓冲
|
||||
if not chunk:
|
||||
break
|
||||
f.write(chunk)
|
||||
# 确保数据落盘,避免后续读取到半写文件
|
||||
try:
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 等待进程完成并检查返回码
|
||||
return_code = process.wait(timeout=10)
|
||||
if return_code != 0:
|
||||
# 特殊处理常见的adb错误码
|
||||
if return_code == 4294967295: # 0xFFFFFFFF
|
||||
raise subprocess.CalledProcessError(
|
||||
return_code,
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
f"设备连接失败或ADB服务异常 (错误码: {return_code})"
|
||||
)
|
||||
else:
|
||||
raise subprocess.CalledProcessError(return_code, [adb, "-s", device_id, "exec-out", "screencap", "-p"])
|
||||
|
||||
t_exec_end = time.time()
|
||||
exec_ms = (t_exec_end - t_exec_start) * 1000
|
||||
timetag2 = datetime.now().strftime("%H:%M:%S")
|
||||
_ops_log(f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms (device_id={device_id})")
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
# Popen 超时,记录并重新抛出异常
|
||||
_ops_log(f"[截图] exec-out 流式读取超时")
|
||||
raise
|
||||
if attempt == 0:
|
||||
_recover_adb_once(reason)
|
||||
continue
|
||||
_ops_log(
|
||||
f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms bytes={len(out)} (device_id={device_id})"
|
||||
)
|
||||
if _valid_png(tmp_file):
|
||||
# 使用安全的文件替换函数并二次验证目标文件,避免写入截断导致后续读取失败
|
||||
if _safe_replace_file(tmp_file, out_file):
|
||||
@@ -246,7 +325,10 @@ class ScreenshotOperations:
|
||||
_ops_log(f"[{timetag}] [截图] 文件替换失败,但截图已保存到临时文件,将尝试回退方案")
|
||||
except subprocess.TimeoutExpired:
|
||||
# 超时异常,记录并继续重试
|
||||
_ops_log(f"[截图] exec-out 超时,尝试重试或回退方案")
|
||||
reason = f"timeout device_id={device_id}"
|
||||
_ops_log(f"[截图] exec-out 超时,尝试重试或回退方案", "WARNING")
|
||||
if attempt == 0:
|
||||
_recover_adb_once(reason)
|
||||
try:
|
||||
if os.path.exists(tmp_file):
|
||||
os.remove(tmp_file)
|
||||
@@ -314,7 +396,7 @@ class ScreenshotOperations:
|
||||
return False
|
||||
else:
|
||||
_ops_log("[截图] 回退方案截图无效")
|
||||
return False
|
||||
return _try_shell_stdout_fallback()
|
||||
except subprocess.CalledProcessError as e:
|
||||
# 特殊处理adb错误
|
||||
if e.returncode == 4294967295:
|
||||
@@ -325,6 +407,8 @@ class ScreenshotOperations:
|
||||
_ops_log(f"[截图] 回退方案失败:操作超时 (设备ID: {device_id})")
|
||||
except Exception as e:
|
||||
_ops_log(f"[截图] 回退方案失败:{e}")
|
||||
if _try_shell_stdout_fallback():
|
||||
return True
|
||||
return False
|
||||
|
||||
def _find_pic_path(self, picname: str, for_reading: bool = True) -> Optional[str]:
|
||||
|
||||
+36
-3
@@ -27,6 +27,12 @@ powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_
|
||||
|
||||
该流程会生成 `build\cythonized-src\`,其中核心模块以 `.pyd` 形式存在。该目录是中间产物,不要直接分发;最终仍然只分发 `dist\DouyinGuaji-<version>\` 或 Inno 生成的安装包。
|
||||
|
||||
如果只是小更新、想复用 PyInstaller 缓存来加快打包,可以额外加 `-ReuseCache`。注意:改到 `douyin/fudai`、`douyin/reservation`、`douyin/detection` 或 `douyin/stage` 时,Cython 核心仍会重新编译;`-ReuseCache` 主要复用 PyInstaller 的分析/收集缓存。
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -ReuseCache
|
||||
```
|
||||
|
||||
如果需要继续使用旧的 PyArmor 路线,可额外加 `-UsePyArmor`。注意:PyArmor 试用版会在混淆文件头部留下 trial 标记,正式分发前建议购买/配置正式授权后重新打包。若 PyArmor 授权不可用,旧路线会失败并停止。
|
||||
|
||||
仅本机开发调试需要生成明文包时,才显式加 `-NoCythonForDevOnly`:
|
||||
@@ -63,9 +69,20 @@ dist\DouyinGuaji-<version>\
|
||||
- `web_gui.exe`:Web GUI 服务入口
|
||||
- `run_cli.exe`:后台运行入口,桌面 GUI / Web GUI 会调用它
|
||||
- `assets/`、`webui/`、`config/`:运行所需资源
|
||||
- `platform-tools/`:随包 ADB 运行组件,至少包含 `adb.exe`、`AdbWinApi.dll`、`AdbWinUsbApi.dll`
|
||||
- `android-tools/`:随包手机侧辅助组件,当前包含 `ADBKeyboard.apk`
|
||||
- `drivers/HiSuite/`:默认不随包;仅在显式传入华为/荣耀 HiSuite 官方安装器时复制
|
||||
- `logs/`、`pic/`、`state/`:运行时输出目录
|
||||
- `license.dat`:默认不随包分发;仅本地测试包需要时才使用 `-IncludeLicense` 显式复制
|
||||
|
||||
华为/荣耀手机如果在新电脑上 MTP 或 ADB 识别异常,可先从华为官方页面下载 HiSuite 安装器,再在打包时显式带入:
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -HiSuiteInstallerPath "C:\path\to\HiSuite.exe"
|
||||
```
|
||||
|
||||
该参数只把安装器放入 `drivers\HiSuite\` 方便目标电脑手动安装,不会静默安装第三方驱动。
|
||||
|
||||
测试包如需临时带入本地 `license.dat`:
|
||||
|
||||
```powershell
|
||||
@@ -86,11 +103,27 @@ iscc packaging\inno\douyin_guaji.iss /DMyAppVersion=3.3.3
|
||||
dist\installer\DouyinGuaji-3.3.3-Setup.exe
|
||||
```
|
||||
|
||||
## 从零安装验收
|
||||
|
||||
打完便携包和安装包后,运行:
|
||||
|
||||
```powershell
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File tools\ci\fresh_install_smoke.ps1
|
||||
```
|
||||
|
||||
脚本会静默安装到 `artifacts\fresh_install_ci\DouyinGuajiApp`,并检查默认配置、随包 ADB、ADBKeyboard、WebGUI 首次卡密门禁、未授权运行接口拦截、Dashboard 首次启动不闪退。
|
||||
|
||||
验收报告:
|
||||
|
||||
```text
|
||||
artifacts\fresh_install_ci\fresh_install_report.json
|
||||
```
|
||||
|
||||
## 发给别人前检查
|
||||
|
||||
- 打包脚本会自动运行 `python -m tools.distribution_manifest dist\DouyinGuaji-<version>`,防止源码、调试产物、个人配置和旧日志混入分发目录。
|
||||
- 最终分发目录只应保留根目录三个 exe、一个 `_internal/`、运行时白名单 `assets/`、运行时白名单 `webui/`、`config/README.md`、`logs/.keep`、`pic/.keep`、`state/.keep`。正式分发不要包含 `license.dat`、`README.md`、`artifacts/`、`tests/`、源码目录、调试截图、临时模板或 debug/README 页面。
|
||||
- 目标电脑需要能使用 ADB,或者把 Android platform-tools 加入 PATH。
|
||||
- 最终分发目录只应保留根目录三个 exe、一个 `_internal/`、运行时白名单 `assets/`、运行时白名单 `webui/`、`platform-tools/` 中的 ADB 白名单文件、`android-tools/ADBKeyboard.apk`、`config/README.md`、`logs/.keep`、`pic/.keep`、`state/.keep`。正式分发不要包含 `license.dat`、`README.md`、`artifacts/`、`tests/`、源码目录、调试截图、临时模板或 debug/README 页面。
|
||||
- 正式包会自带 ADB,不要求目标电脑额外安装 Android platform-tools 或配置 PATH。程序在需要中文输入且设备未安装 ADBKeyboard 时,会尝试从随包 `android-tools/ADBKeyboard.apk` 自动安装到手机。新电脑仍需要在手机上开启开发者选项/USB 调试并允许本机 RSA 授权;部分品牌手机首次 USB 识别还需要 Windows 能正确安装对应 USB 驱动。
|
||||
- 首次启动 PaddleOCR 相关组件可能较慢,杀毒软件也可能扫描 exe。
|
||||
- `config/config.json` 是本地运行配置,默认不随安装包带个人配置;让使用者首次打开后在 GUI 中保存配置。
|
||||
- `config/default_config.json` 会随安装包复制为 `config/config.json`,只放正式默认值,不放个人设备、卡密或运行状态。
|
||||
- 默认 Cython 编译后仍要以 `python -m tools.distribution_manifest dist\DouyinGuaji-<version>` 的结果为准;PASS 才能发给别人。使用 `-NoCythonForDevOnly` 生成的明文包禁止分发。
|
||||
@@ -7,6 +7,9 @@ param(
|
||||
[switch]$PackExe,
|
||||
[switch]$PackExeForce,
|
||||
[switch]$IncludeLicense,
|
||||
[switch]$ReuseCache,
|
||||
[string]$PlatformToolsDir = "",
|
||||
[string]$HiSuiteInstallerPath = "",
|
||||
[string]$UpxDir = ""
|
||||
)
|
||||
|
||||
@@ -61,7 +64,6 @@ if ($UsePyArmor -and -not $NoObfuscateForDevOnly) {
|
||||
}
|
||||
|
||||
$CommonArgs = @(
|
||||
"--clean",
|
||||
"--noconfirm",
|
||||
"--distpath", $DistRoot,
|
||||
"--workpath", (Join-Path $Root "build\pyinstaller"),
|
||||
@@ -70,8 +72,27 @@ $CommonArgs = @(
|
||||
"--hidden-import", "PIL._tkinter_finder",
|
||||
"--hidden-import", "ttkbootstrap",
|
||||
"--hidden-import", "logging.handlers",
|
||||
"--hidden-import", "cryptography.hazmat.primitives.serialization"
|
||||
"--hidden-import", "cryptography.hazmat.primitives.serialization",
|
||||
"--collect-submodules", "cv2",
|
||||
"--collect-submodules", "numpy",
|
||||
"--collect-submodules", "PIL",
|
||||
"--collect-submodules", "paddle",
|
||||
"--collect-submodules", "paddleocr",
|
||||
"--collect-submodules", "paddlex",
|
||||
"--collect-submodules", "pyclipper",
|
||||
"--collect-submodules", "shapely",
|
||||
"--collect-binaries", "cv2",
|
||||
"--collect-binaries", "numpy",
|
||||
"--collect-binaries", "paddle",
|
||||
"--collect-binaries", "pyclipper",
|
||||
"--collect-binaries", "shapely",
|
||||
"--collect-data", "PIL",
|
||||
"--collect-data", "paddlex",
|
||||
"--collect-data", "paddleocr"
|
||||
)
|
||||
if (-not $ReuseCache) {
|
||||
$CommonArgs = @("--clean") + $CommonArgs
|
||||
}
|
||||
|
||||
$GuiArgs = @(
|
||||
"--collect-submodules", "gui"
|
||||
@@ -128,30 +149,19 @@ foreach ($name in @("DouyinGuajiGUI", "web_gui", "run_cli")) {
|
||||
Remove-Item -LiteralPath $srcDir -Recurse -Force
|
||||
}
|
||||
|
||||
$RuntimeAssets = @(
|
||||
"coupon.png",
|
||||
"fav.png",
|
||||
"fudai.png",
|
||||
"fudai_icon_countdown_v20260618.png",
|
||||
"fudai_icon_pending_v20260618.png",
|
||||
"fudai_icon_purple_left_v20260618.png",
|
||||
"fudai_icon_red_left_v20260618.png",
|
||||
"fudai_task_status_dacheng_shape.png",
|
||||
"like.png",
|
||||
"x.png",
|
||||
"xin.png"
|
||||
)
|
||||
$AssetsTarget = Join-Path $DistRoot "assets"
|
||||
if (Test-Path $AssetsTarget) {
|
||||
Remove-Item -LiteralPath $AssetsTarget -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Force $AssetsTarget | Out-Null
|
||||
foreach ($name in $RuntimeAssets) {
|
||||
$src = Join-Path $Root "assets\$name"
|
||||
if (-not (Test-Path $src)) {
|
||||
throw "Missing runtime asset: assets\$name"
|
||||
}
|
||||
Copy-Item -LiteralPath $src -Destination (Join-Path $AssetsTarget $name) -Force
|
||||
$RuntimeAssetFiles = Get-ChildItem -LiteralPath (Join-Path $Root "assets") -File | Where-Object {
|
||||
$_.Extension -ieq ".png"
|
||||
}
|
||||
if (-not $RuntimeAssetFiles) {
|
||||
throw "Missing runtime assets: assets\*.png"
|
||||
}
|
||||
foreach ($asset in $RuntimeAssetFiles) {
|
||||
Copy-Item -LiteralPath $asset.FullName -Destination (Join-Path $AssetsTarget $asset.Name) -Force
|
||||
}
|
||||
|
||||
$WebuiTarget = Join-Path $DistRoot "webui"
|
||||
@@ -174,14 +184,107 @@ foreach ($dir in @("css", "js", "partials")) {
|
||||
} | Copy-Item -Destination $dstDir -Force
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force (Join-Path $DistRoot "config") | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $Root "config\README.md") -Destination (Join-Path $DistRoot "config\README.md") -Force
|
||||
$ConfigTarget = Join-Path $DistRoot "config"
|
||||
New-Item -ItemType Directory -Force $ConfigTarget | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $Root "config\README.md") -Destination (Join-Path $ConfigTarget "README.md") -Force
|
||||
$DefaultConfig = Join-Path $Root "config\default_config.json"
|
||||
if (-not (Test-Path $DefaultConfig)) {
|
||||
throw "Missing default runtime config: config\default_config.json"
|
||||
}
|
||||
Copy-Item -LiteralPath $DefaultConfig -Destination (Join-Path $ConfigTarget "config.json") -Force
|
||||
foreach ($dir in @("logs", "pic", "state")) {
|
||||
$runtimeDir = Join-Path $DistRoot $dir
|
||||
New-Item -ItemType Directory -Force $runtimeDir | Out-Null
|
||||
New-Item -ItemType File -Force (Join-Path $runtimeDir ".keep") | Out-Null
|
||||
}
|
||||
|
||||
$PlatformToolCandidates = @()
|
||||
if ($PlatformToolsDir) {
|
||||
$PlatformToolCandidates += $PlatformToolsDir
|
||||
}
|
||||
foreach ($envName in @("ANDROID_PLATFORM_TOOLS", "ANDROID_HOME", "ANDROID_SDK_ROOT")) {
|
||||
$envValue = [Environment]::GetEnvironmentVariable($envName)
|
||||
if (-not $envValue) {
|
||||
continue
|
||||
}
|
||||
if ($envName -eq "ANDROID_PLATFORM_TOOLS") {
|
||||
$PlatformToolCandidates += $envValue
|
||||
} else {
|
||||
$PlatformToolCandidates += (Join-Path $envValue "platform-tools")
|
||||
}
|
||||
}
|
||||
if ($env:LOCALAPPDATA) {
|
||||
$PlatformToolCandidates += (Join-Path $env:LOCALAPPDATA "platform-tools")
|
||||
}
|
||||
$PlatformToolCandidates += (Join-Path $Root "platform-tools")
|
||||
|
||||
$ResolvedPlatformTools = ""
|
||||
foreach ($candidate in $PlatformToolCandidates) {
|
||||
if (-not $candidate) {
|
||||
continue
|
||||
}
|
||||
$adbCandidate = Join-Path $candidate "adb.exe"
|
||||
if (Test-Path $adbCandidate) {
|
||||
$ResolvedPlatformTools = (Resolve-Path $candidate).Path
|
||||
break
|
||||
}
|
||||
}
|
||||
if (-not $ResolvedPlatformTools) {
|
||||
throw "Missing Android platform-tools. Provide -PlatformToolsDir or install it under LOCALAPPDATA\platform-tools."
|
||||
}
|
||||
$PlatformToolsTarget = Join-Path $DistRoot "platform-tools"
|
||||
if (Test-Path $PlatformToolsTarget) {
|
||||
Remove-Item -LiteralPath $PlatformToolsTarget -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Force $PlatformToolsTarget | Out-Null
|
||||
$PlatformToolFiles = @(
|
||||
"adb.exe",
|
||||
"AdbWinApi.dll",
|
||||
"AdbWinUsbApi.dll",
|
||||
"NOTICE.txt",
|
||||
"source.properties"
|
||||
)
|
||||
foreach ($name in $PlatformToolFiles) {
|
||||
$src = Join-Path $ResolvedPlatformTools $name
|
||||
if ($name -in @("adb.exe", "AdbWinApi.dll", "AdbWinUsbApi.dll") -and -not (Test-Path $src)) {
|
||||
throw "Missing required platform-tools file: $name"
|
||||
}
|
||||
if (Test-Path $src) {
|
||||
Copy-Item -LiteralPath $src -Destination (Join-Path $PlatformToolsTarget $name) -Force
|
||||
}
|
||||
}
|
||||
|
||||
$AndroidToolsTarget = Join-Path $DistRoot "android-tools"
|
||||
if (Test-Path $AndroidToolsTarget) {
|
||||
Remove-Item -LiteralPath $AndroidToolsTarget -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Force $AndroidToolsTarget | Out-Null
|
||||
$AdbKeyboardApk = Join-Path $Root "tools\adb\ADBKeyboard.apk"
|
||||
if (-not (Test-Path $AdbKeyboardApk)) {
|
||||
throw "Missing Android helper: tools\adb\ADBKeyboard.apk"
|
||||
}
|
||||
Copy-Item -LiteralPath $AdbKeyboardApk -Destination (Join-Path $AndroidToolsTarget "ADBKeyboard.apk") -Force
|
||||
|
||||
if ($HiSuiteInstallerPath) {
|
||||
if (-not (Test-Path -LiteralPath $HiSuiteInstallerPath)) {
|
||||
throw "HiSuite installer not found: $HiSuiteInstallerPath"
|
||||
}
|
||||
$DriverTarget = Join-Path $DistRoot "drivers\HiSuite"
|
||||
if (Test-Path $DriverTarget) {
|
||||
Remove-Item -LiteralPath $DriverTarget -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Force $DriverTarget | Out-Null
|
||||
$installerItem = Get-Item -LiteralPath $HiSuiteInstallerPath
|
||||
Copy-Item -LiteralPath $installerItem.FullName -Destination (Join-Path $DriverTarget $installerItem.Name) -Force
|
||||
@"
|
||||
Huawei / Honor USB driver helper
|
||||
|
||||
If Windows cannot show the phone as MTP or ADB is unstable, install HiSuite on the computer, reconnect the phone, choose File Transfer / MTP on the phone, and allow USB debugging authorization.
|
||||
|
||||
This third-party installer is provided only when explicitly passed to the build script.
|
||||
"@ | Set-Content -LiteralPath (Join-Path $DriverTarget "README.txt") -Encoding UTF8
|
||||
}
|
||||
|
||||
$licensePath = Join-Path $Root "license.dat"
|
||||
if ($IncludeLicense -and (Test-Path $licensePath)) {
|
||||
Copy-Item -LiteralPath $licensePath -Destination (Join-Path $DistRoot "license.dat") -Force
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
# 这里的 version 由 tools/dev/bump_version.py 与 version.py 同步维护。
|
||||
# 注意:为兼容 PEP 440,这里去掉 "V" 前缀,仅保留数字部分(如 V3.3.3 → 3.3.3)。
|
||||
name = "douyin_guaji"
|
||||
version = "3.3.3"
|
||||
version = "3.3.11"
|
||||
description = "基于 ADB + OCR + 像素检测 + 模板匹配的抖音直播间福袋自动挂机工具"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -13,6 +13,7 @@ opencv-python>=4.5.0
|
||||
|
||||
# OCR识别 - PaddleOCR(主要OCR引擎)
|
||||
paddleocr>=3.0.0
|
||||
paddlex>=3.0.0
|
||||
|
||||
# 深度学习框架(PaddleOCR的依赖)
|
||||
# 注意:PaddleOCR 3.0 需要 PaddlePaddle 3.0+
|
||||
|
||||
+377
-3
@@ -18,19 +18,57 @@ def test_compare_versions_handles_v_prefix_and_patch_order():
|
||||
assert compare_versions("3.3.2", "3.3.3") < 0
|
||||
|
||||
|
||||
def test_load_settings_is_disabled_without_manifest_url(tmp_path, monkeypatch):
|
||||
def test_load_settings_uses_default_server_without_manifest_url(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.updater import force_update
|
||||
from douyin.updater.force_update import load_update_settings
|
||||
|
||||
cfg = tmp_path / "config.json"
|
||||
cfg.write_text(json.dumps({}), encoding="utf-8")
|
||||
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg))
|
||||
monkeypatch.delenv("DOUYIN_UPDATE_MANIFEST_URL", raising=False)
|
||||
monkeypatch.delenv("DOUYIN_AUTO_UPDATE_ENABLED", raising=False)
|
||||
monkeypatch.delenv("DOUYIN_DISABLE_AUTO_UPDATE", raising=False)
|
||||
|
||||
settings = load_update_settings()
|
||||
|
||||
assert settings.enabled is True
|
||||
assert settings.manifest_url == force_update.DEFAULT_UPDATE_MANIFEST_URL
|
||||
assert settings.require_signed_manifest is True
|
||||
|
||||
|
||||
def test_load_settings_can_disable_default_auto_update(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.updater.force_update import load_update_settings
|
||||
|
||||
cfg = tmp_path / "config.json"
|
||||
cfg.write_text(json.dumps({"auto_update": {"enabled": True}}), encoding="utf-8")
|
||||
cfg.write_text(json.dumps({"auto_update": {"enabled": False}}), encoding="utf-8")
|
||||
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg))
|
||||
monkeypatch.delenv("DOUYIN_UPDATE_MANIFEST_URL", raising=False)
|
||||
monkeypatch.delenv("DOUYIN_AUTO_UPDATE_ENABLED", raising=False)
|
||||
monkeypatch.delenv("DOUYIN_DISABLE_AUTO_UPDATE", raising=False)
|
||||
|
||||
settings = load_update_settings()
|
||||
|
||||
assert settings.enabled is False
|
||||
assert settings.manifest_url == ""
|
||||
assert settings.manifest_url
|
||||
|
||||
|
||||
def test_manual_update_settings_enable_check_without_fail_closed(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.updater.force_update import load_manual_update_settings
|
||||
|
||||
cfg = tmp_path / "config.json"
|
||||
cfg.write_text(json.dumps({"auto_update": {"enabled": False}}), encoding="utf-8")
|
||||
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg))
|
||||
monkeypatch.delenv("DOUYIN_UPDATE_MANIFEST_URL", raising=False)
|
||||
monkeypatch.delenv("DOUYIN_DISABLE_AUTO_UPDATE", raising=False)
|
||||
|
||||
settings = load_manual_update_settings()
|
||||
|
||||
assert settings.enabled is True
|
||||
assert settings.fail_closed is False
|
||||
assert settings.manifest_url
|
||||
|
||||
|
||||
def test_load_settings_uses_default_server_for_frozen_exe(tmp_path, monkeypatch):
|
||||
@@ -104,6 +142,342 @@ def test_forced_update_downloads_verifies_and_launches_installer(tmp_path):
|
||||
assert any(arg.startswith("/LOG=") for arg in launched[0])
|
||||
|
||||
|
||||
def test_default_update_settings_launch_visible_installer_and_disable_delta(tmp_path):
|
||||
from douyin.updater.force_update import DEFAULT_INSTALLER_ARGS, UpdateSettings
|
||||
|
||||
settings = UpdateSettings(enabled=True, manifest_url="https://example.test/update.json", download_dir=tmp_path)
|
||||
|
||||
assert "/VERYSILENT" not in DEFAULT_INSTALLER_ARGS
|
||||
assert "/SILENT" not in DEFAULT_INSTALLER_ARGS
|
||||
assert "/SUPPRESSMSGBOXES" not in DEFAULT_INSTALLER_ARGS
|
||||
assert settings.allow_delta is False
|
||||
|
||||
|
||||
def test_forced_update_prefers_matching_delta_package(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
import zipfile
|
||||
|
||||
file_payload = b"new exe bytes"
|
||||
file_sha = hashlib.sha256(file_payload).hexdigest()
|
||||
delta_zip = tmp_path / "delta-source.zip"
|
||||
with zipfile.ZipFile(delta_zip, "w") as zf:
|
||||
zf.writestr(
|
||||
"manifest.json",
|
||||
json.dumps(
|
||||
{
|
||||
"schema": 1,
|
||||
"from_version": "3.3.3",
|
||||
"to_version": "3.3.4",
|
||||
"files": [{"path": "DouyinGuajiGUI.exe", "sha256": file_sha, "size": len(file_payload)}],
|
||||
"delete": [],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
)
|
||||
zf.writestr("files/DouyinGuajiGUI.exe", file_payload)
|
||||
delta_payload = delta_zip.read_bytes()
|
||||
delta_sha = hashlib.sha256(delta_payload).hexdigest()
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
allow_delta=True,
|
||||
)
|
||||
downloaded: list[str] = []
|
||||
launched: list[Path] = []
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict:
|
||||
return {
|
||||
"version": "3.3.4",
|
||||
"url": "https://example.test/full.exe",
|
||||
"sha256": "0" * 64,
|
||||
"delta": {
|
||||
"from_version": "3.3.3",
|
||||
"to_version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"sha256": delta_sha,
|
||||
},
|
||||
}
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
downloaded.append(url)
|
||||
dest.write_bytes(delta_payload)
|
||||
|
||||
result = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=fetch_manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: pytest.fail("should not launch full installer"),
|
||||
launch_delta_update=lambda path, version: launched.append(path),
|
||||
)
|
||||
|
||||
assert result.status == "delta_update_started"
|
||||
assert result.exit_required is True
|
||||
assert downloaded == ["https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip"]
|
||||
assert launched == [tmp_path / "DouyinGuaji-3.3.3_to_3.3.4_delta.zip"]
|
||||
assert result.delta_path == launched[0]
|
||||
|
||||
|
||||
def test_forced_update_picks_matching_delta_from_list(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
import zipfile
|
||||
|
||||
file_payload = b"latest bytes"
|
||||
file_sha = hashlib.sha256(file_payload).hexdigest()
|
||||
delta_zip = tmp_path / "delta-source.zip"
|
||||
with zipfile.ZipFile(delta_zip, "w") as zf:
|
||||
zf.writestr(
|
||||
"manifest.json",
|
||||
json.dumps(
|
||||
{
|
||||
"schema": 1,
|
||||
"from_version": "3.3.7",
|
||||
"to_version": "3.3.9",
|
||||
"files": [{"path": "DouyinGuajiGUI.exe", "sha256": file_sha, "size": len(file_payload)}],
|
||||
"delete": [],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
)
|
||||
zf.writestr("files/DouyinGuajiGUI.exe", file_payload)
|
||||
delta_payload = delta_zip.read_bytes()
|
||||
delta_sha = hashlib.sha256(delta_payload).hexdigest()
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
allow_delta=True,
|
||||
)
|
||||
downloaded: list[str] = []
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
downloaded.append(url)
|
||||
dest.write_bytes(delta_payload)
|
||||
|
||||
result = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.7",
|
||||
fetch_manifest=lambda url, timeout: {
|
||||
"version": "3.3.9",
|
||||
"url": "https://example.test/full.exe",
|
||||
"sha256": "0" * 64,
|
||||
"delta": [
|
||||
{
|
||||
"from_version": "3.3.8",
|
||||
"to_version": "3.3.9",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.8_to_3.3.9_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.8_to_3.3.9_delta.zip",
|
||||
"sha256": "1" * 64,
|
||||
},
|
||||
{
|
||||
"from_version": "3.3.7",
|
||||
"to_version": "3.3.9",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.7_to_3.3.9_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.7_to_3.3.9_delta.zip",
|
||||
"sha256": delta_sha,
|
||||
},
|
||||
],
|
||||
},
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: pytest.fail("should not launch full installer"),
|
||||
launch_delta_update=lambda path, version: None,
|
||||
)
|
||||
|
||||
assert result.status == "delta_update_started"
|
||||
assert downloaded == ["https://example.test/DouyinGuaji-3.3.7_to_3.3.9_delta.zip"]
|
||||
|
||||
|
||||
def test_forced_update_falls_back_to_full_installer_when_delta_download_fails(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
full_payload = b"full installer"
|
||||
full_sha = hashlib.sha256(full_payload).hexdigest()
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
allow_delta=True,
|
||||
)
|
||||
downloaded: list[str] = []
|
||||
launched: list[list[str]] = []
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict:
|
||||
return {
|
||||
"version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"filename": "DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": full_sha,
|
||||
"delta": {
|
||||
"from_version": "3.3.3",
|
||||
"to_version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"sha256": "1" * 64,
|
||||
},
|
||||
}
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
downloaded.append(url)
|
||||
if url.endswith("_delta.zip"):
|
||||
raise OSError("network interrupted")
|
||||
dest.write_bytes(full_payload)
|
||||
|
||||
result = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=fetch_manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: launched.append(cmd),
|
||||
launch_delta_update=lambda path, version: pytest.fail("should not launch broken delta"),
|
||||
)
|
||||
|
||||
assert result.status == "update_started"
|
||||
assert downloaded == [
|
||||
"https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"https://example.test/DouyinGuaji-3.3.4-Setup.exe",
|
||||
]
|
||||
assert launched
|
||||
assert launched[0][0] == str(tmp_path / "DouyinGuaji-3.3.4-Setup.exe")
|
||||
|
||||
|
||||
def test_forced_update_logs_delta_failure_before_full_fallback(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
full_payload = b"full installer"
|
||||
full_sha = hashlib.sha256(full_payload).hexdigest()
|
||||
logs_dir = tmp_path / "logs"
|
||||
monkeypatch.setattr(path_config, "get_logs_dir", lambda: str(logs_dir))
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
allow_delta=True,
|
||||
)
|
||||
|
||||
def fetch_manifest(url: str, timeout: float) -> dict:
|
||||
return {
|
||||
"version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"filename": "DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": full_sha,
|
||||
"delta": {
|
||||
"from_version": "3.3.3",
|
||||
"to_version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"sha256": "1" * 64,
|
||||
},
|
||||
}
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
if url.endswith("_delta.zip"):
|
||||
raise OSError("network interrupted")
|
||||
dest.write_bytes(full_payload)
|
||||
|
||||
result = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=fetch_manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: None,
|
||||
launch_delta_update=lambda path, version: pytest.fail("should not launch broken delta"),
|
||||
)
|
||||
|
||||
log_path = logs_dir / "updates" / "update-client.log"
|
||||
lines = [json.loads(line) for line in log_path.read_text(encoding="utf-8").splitlines()]
|
||||
|
||||
assert result.status == "update_started"
|
||||
assert any(item["event"] == "delta_download_start" for item in lines)
|
||||
failed = [item for item in lines if item["event"] == "delta_failed_fallback_full"]
|
||||
assert failed
|
||||
assert "network interrupted" in failed[0]["error"]
|
||||
|
||||
|
||||
def test_forced_update_skips_delta_after_previous_started_attempt_still_old_version(tmp_path):
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
import zipfile
|
||||
|
||||
full_payload = b"full installer"
|
||||
full_sha = hashlib.sha256(full_payload).hexdigest()
|
||||
file_payload = b"new exe"
|
||||
file_sha = hashlib.sha256(file_payload).hexdigest()
|
||||
delta_zip = tmp_path / "delta-source.zip"
|
||||
with zipfile.ZipFile(delta_zip, "w") as zf:
|
||||
zf.writestr(
|
||||
"manifest.json",
|
||||
json.dumps(
|
||||
{
|
||||
"schema": 1,
|
||||
"from_version": "3.3.3",
|
||||
"to_version": "3.3.4",
|
||||
"files": [{"path": "DouyinGuajiGUI.exe", "sha256": file_sha, "size": len(file_payload)}],
|
||||
"delete": [],
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
)
|
||||
zf.writestr("files/DouyinGuajiGUI.exe", file_payload)
|
||||
delta_payload = delta_zip.read_bytes()
|
||||
delta_sha = hashlib.sha256(delta_payload).hexdigest()
|
||||
settings = UpdateSettings(
|
||||
enabled=True,
|
||||
manifest_url="https://example.test/update.json",
|
||||
download_dir=tmp_path,
|
||||
allow_delta=True,
|
||||
)
|
||||
launched_installers: list[list[str]] = []
|
||||
launched_deltas: list[Path] = []
|
||||
|
||||
manifest = {
|
||||
"version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.4-Setup.exe",
|
||||
"filename": "DouyinGuaji-3.3.4-Setup.exe",
|
||||
"sha256": full_sha,
|
||||
"delta": {
|
||||
"from_version": "3.3.3",
|
||||
"to_version": "3.3.4",
|
||||
"url": "https://example.test/DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"filename": "DouyinGuaji-3.3.3_to_3.3.4_delta.zip",
|
||||
"sha256": delta_sha,
|
||||
},
|
||||
}
|
||||
|
||||
def download(url: str, dest: Path, timeout: float) -> None:
|
||||
if url.endswith("_delta.zip"):
|
||||
dest.write_bytes(delta_payload)
|
||||
else:
|
||||
dest.write_bytes(full_payload)
|
||||
|
||||
first = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=lambda url, timeout: manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: pytest.fail("first attempt should prefer delta"),
|
||||
launch_delta_update=lambda path, version: launched_deltas.append(path),
|
||||
)
|
||||
|
||||
second = perform_forced_update(
|
||||
settings,
|
||||
current_version="3.3.3",
|
||||
fetch_manifest=lambda url, timeout: manifest,
|
||||
download_file=download,
|
||||
launch_installer=lambda cmd: launched_installers.append(cmd),
|
||||
launch_delta_update=lambda path, version: pytest.fail("second attempt should skip failed delta"),
|
||||
)
|
||||
|
||||
assert first.status == "delta_update_started"
|
||||
assert launched_deltas == [tmp_path / "DouyinGuaji-3.3.3_to_3.3.4_delta.zip"]
|
||||
assert second.status == "update_started"
|
||||
assert launched_installers
|
||||
|
||||
|
||||
def test_forced_update_accepts_signed_manifest(tmp_path, monkeypatch):
|
||||
from douyin.updater import force_update
|
||||
from douyin.updater.force_update import UpdateSettings, perform_forced_update
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def test_fresh_install_smoke_script_covers_new_machine_contract():
|
||||
script = Path("tools/ci/fresh_install_smoke.ps1").read_text(encoding="utf-8")
|
||||
|
||||
assert "tools.distribution_manifest" in script
|
||||
assert "tools.exe_packing" in script
|
||||
assert "Start-Process -FilePath $Installer" in script
|
||||
assert "config\\config.json" in script
|
||||
assert "platform-tools\\adb.exe" in script
|
||||
assert "android-tools\\ADBKeyboard.apk" in script
|
||||
assert "adb.exe\") `\n -Arguments @(\"version\")" in script
|
||||
assert "run_cli.exe\") `\n -Arguments @(\"--help\")" in script
|
||||
assert "cli_fails_closed_without_license" in script
|
||||
assert "web_gui.exe" in script
|
||||
assert "license-form" in script
|
||||
assert "license-input" in script
|
||||
assert "/api/license" in script
|
||||
assert "/api/start-run" in script
|
||||
assert "license_required" in script
|
||||
assert "DouyinGuajiGUI.exe" in script
|
||||
assert "fresh_install_report.json" in script
|
||||
assert "DOUYIN_DISABLE_AUTO_UPDATE" in script
|
||||
assert "Assert-UnderDirectory $WorkRoot $ArtifactsRoot" in script
|
||||
|
||||
|
||||
def test_windows_package_ci_builds_installer_then_runs_fresh_install_smoke():
|
||||
workflow = Path(".github/workflows/windows-package-ci.yml").read_text(encoding="utf-8")
|
||||
|
||||
assert "runs-on: windows-latest" in workflow
|
||||
assert "choco install innosetup" in workflow
|
||||
assert "packaging\\pyinstaller\\build_windows.ps1 -SkipInstall -ReuseCache" in workflow
|
||||
assert "packaging\\inno\\douyin_guaji.iss" in workflow
|
||||
assert "tools\\ci\\fresh_install_smoke.ps1" in workflow
|
||||
assert "actions/upload-artifact@v4" in workflow
|
||||
@@ -11,14 +11,14 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts():
|
||||
"DouyinGuajiGUI.exe",
|
||||
"_internal/python310.dll",
|
||||
"assets/fudai_task_count_v2_one_task.png",
|
||||
"assets/README.txt",
|
||||
"README.md",
|
||||
"douyin/core/douyin_fudai.py",
|
||||
"artifacts/debug.png",
|
||||
"config/config.json",
|
||||
"config/private.tmp",
|
||||
"logs/unified.log",
|
||||
"pic/debug_captures/a.png",
|
||||
"license.dat",
|
||||
"assets/README.txt",
|
||||
"webui/debug.html",
|
||||
"webui/js/README.md",
|
||||
"DouyinGuajiGUI/_internal/base_library.zip",
|
||||
@@ -31,13 +31,14 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts():
|
||||
|
||||
assert "douyin/core/douyin_fudai.py" in blocked
|
||||
assert "artifacts/debug.png" in blocked
|
||||
assert "config/config.json" in blocked
|
||||
assert "config/config.json" not in blocked
|
||||
assert "config/private.tmp" in blocked
|
||||
assert "logs/unified.log" in blocked
|
||||
assert "pic/debug_captures/a.png" in blocked
|
||||
assert "license.dat" in blocked
|
||||
assert "README.md" in blocked
|
||||
assert "assets/README.txt" in blocked
|
||||
assert "assets/fudai_task_count_v2_one_task.png" in blocked
|
||||
assert "assets/fudai_task_count_v2_one_task.png" not in blocked
|
||||
assert "webui/debug.html" in blocked
|
||||
assert "webui/js/README.md" in blocked
|
||||
assert "DouyinGuajiGUI/_internal/base_library.zip" in blocked
|
||||
@@ -55,12 +56,19 @@ def test_distribution_manifest_blocks_project_native_binaries_outside_core_allow
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"_internal/paddle/libs/paddle.dll",
|
||||
"_internal/paddlex/.version",
|
||||
"_internal/tests/evil.pyd",
|
||||
"_internal/tools/helper.dll",
|
||||
"_internal/douyin/fudai/core/compiled.cp312-win_amd64.pyd",
|
||||
"_internal/numpy/core/runtime.pyd",
|
||||
"webui/index.html",
|
||||
"platform-tools/adb.exe",
|
||||
"platform-tools/AdbWinApi.dll",
|
||||
"platform-tools/AdbWinUsbApi.dll",
|
||||
"android-tools/ADBKeyboard.apk",
|
||||
"config/README.md",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
@@ -83,13 +91,24 @@ def test_distribution_manifest_allows_expected_runtime_shape():
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"_internal/paddle/libs/paddle.dll",
|
||||
"_internal/paddlex/.version",
|
||||
"assets/fudai.png",
|
||||
"assets/desktop.png",
|
||||
"assets/fudai_task_count_v2_one_task.png",
|
||||
"assets/fudai_task_status_dacheng_shape.png",
|
||||
"assets/fudai_icon_red_left_v20260618.png",
|
||||
"webui/index.html",
|
||||
"webui/css/base.css",
|
||||
"webui/js/api_client.js",
|
||||
"platform-tools/adb.exe",
|
||||
"platform-tools/AdbWinApi.dll",
|
||||
"platform-tools/AdbWinUsbApi.dll",
|
||||
"platform-tools/NOTICE.txt",
|
||||
"platform-tools/source.properties",
|
||||
"android-tools/ADBKeyboard.apk",
|
||||
"config/README.md",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
@@ -98,6 +117,40 @@ def test_distribution_manifest_allows_expected_runtime_shape():
|
||||
assert find_distribution_issues(entries) == []
|
||||
|
||||
|
||||
def test_distribution_manifest_blocks_unexpected_platform_tools_files():
|
||||
from tools.distribution_manifest import find_forbidden_distribution_entries
|
||||
|
||||
entries = [
|
||||
"platform-tools/adb.exe",
|
||||
"platform-tools/fastboot.exe",
|
||||
"platform-tools/mke2fs.conf",
|
||||
]
|
||||
|
||||
blocked = find_forbidden_distribution_entries(entries)
|
||||
|
||||
assert "platform-tools/adb.exe" not in blocked
|
||||
assert "platform-tools/fastboot.exe" in blocked
|
||||
assert "platform-tools/mke2fs.conf" in blocked
|
||||
|
||||
|
||||
def test_distribution_manifest_allows_explicit_hisuite_driver_bundle_only():
|
||||
from tools.distribution_manifest import find_forbidden_distribution_entries
|
||||
|
||||
entries = [
|
||||
"drivers/HiSuite/HiSuite_Installer.exe",
|
||||
"drivers/HiSuite/README.txt",
|
||||
"drivers/HiSuite/debug.log",
|
||||
"drivers/OtherDriver/setup.exe",
|
||||
]
|
||||
|
||||
blocked = find_forbidden_distribution_entries(entries)
|
||||
|
||||
assert "drivers/HiSuite/HiSuite_Installer.exe" not in blocked
|
||||
assert "drivers/HiSuite/README.txt" not in blocked
|
||||
assert "drivers/HiSuite/debug.log" in blocked
|
||||
assert "drivers/OtherDriver/setup.exe" in blocked
|
||||
|
||||
|
||||
def test_distribution_manifest_can_allow_license_for_local_test_package():
|
||||
from tools.distribution_manifest import find_distribution_issues
|
||||
|
||||
@@ -107,9 +160,16 @@ def test_distribution_manifest_can_allow_license_for_local_test_package():
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"_internal/paddle/libs/paddle.dll",
|
||||
"_internal/paddlex/.version",
|
||||
"assets/fudai.png",
|
||||
"webui/index.html",
|
||||
"platform-tools/adb.exe",
|
||||
"platform-tools/AdbWinApi.dll",
|
||||
"platform-tools/AdbWinUsbApi.dll",
|
||||
"android-tools/ADBKeyboard.apk",
|
||||
"config/README.md",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
@@ -130,7 +190,12 @@ def test_distribution_manifest_requires_python_runtime_dll():
|
||||
"_internal/base_library.zip",
|
||||
"assets/fudai.png",
|
||||
"webui/index.html",
|
||||
"platform-tools/adb.exe",
|
||||
"platform-tools/AdbWinApi.dll",
|
||||
"platform-tools/AdbWinUsbApi.dll",
|
||||
"android-tools/ADBKeyboard.apk",
|
||||
"config/README.md",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
@@ -141,6 +206,60 @@ def test_distribution_manifest_requires_python_runtime_dll():
|
||||
assert "_internal/python*.dll" in issues
|
||||
|
||||
|
||||
def test_distribution_manifest_requires_bundled_android_runtime():
|
||||
from tools.distribution_manifest import find_distribution_issues
|
||||
|
||||
entries = [
|
||||
"DouyinGuajiGUI.exe",
|
||||
"web_gui.exe",
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"_internal/paddle/libs/paddle.dll",
|
||||
"_internal/paddlex/.version",
|
||||
"assets/fudai.png",
|
||||
"webui/index.html",
|
||||
"config/README.md",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
]
|
||||
|
||||
issues = find_distribution_issues(entries)
|
||||
|
||||
assert "platform-tools/adb.exe" in issues
|
||||
assert "platform-tools/AdbWinApi.dll" in issues
|
||||
assert "platform-tools/AdbWinUsbApi.dll" in issues
|
||||
assert "android-tools/ADBKeyboard.apk" in issues
|
||||
|
||||
|
||||
def test_distribution_manifest_requires_bundled_ocr_runtime_data():
|
||||
from tools.distribution_manifest import find_distribution_issues
|
||||
|
||||
entries = [
|
||||
"DouyinGuajiGUI.exe",
|
||||
"web_gui.exe",
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"platform-tools/adb.exe",
|
||||
"platform-tools/AdbWinApi.dll",
|
||||
"platform-tools/AdbWinUsbApi.dll",
|
||||
"android-tools/ADBKeyboard.apk",
|
||||
"config/README.md",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
]
|
||||
|
||||
issues = find_distribution_issues(entries)
|
||||
|
||||
assert "_internal/paddlex/.version" in issues
|
||||
assert "_internal/paddle/*" in issues
|
||||
|
||||
|
||||
def test_distribution_manifest_cli_passes_clean_tree(tmp_path):
|
||||
dist = tmp_path / "dist"
|
||||
for rel in [
|
||||
@@ -149,12 +268,19 @@ def test_distribution_manifest_cli_passes_clean_tree(tmp_path):
|
||||
"run_cli.exe",
|
||||
"_internal/base_library.zip",
|
||||
"_internal/python312.dll",
|
||||
"_internal/paddle/libs/paddle.dll",
|
||||
"_internal/paddlex/.version",
|
||||
"assets/fudai.png",
|
||||
"assets/fudai_task_status_dacheng_shape.png",
|
||||
"webui/css/base.css",
|
||||
"webui/js/api_client.js",
|
||||
"webui/index.html",
|
||||
"platform-tools/adb.exe",
|
||||
"platform-tools/AdbWinApi.dll",
|
||||
"platform-tools/AdbWinUsbApi.dll",
|
||||
"android-tools/ADBKeyboard.apk",
|
||||
"config/README.md",
|
||||
"config/config.json",
|
||||
"logs/.keep",
|
||||
"pic/.keep",
|
||||
"state/.keep",
|
||||
|
||||
@@ -151,14 +151,14 @@ class TestReservationPrejoinFansclub:
|
||||
assert a.last_attend_fail_reason == "fansclub_required"
|
||||
assert any(c.args == (543, 2070) for c in a.click.call_args_list)
|
||||
assert any(c.args == (500, 470) for c in a.click.call_args_list)
|
||||
assert any(c.args == ("MOCK", 540, 2006) for c in a.operation.click.call_args_list)
|
||||
assert any(c.args == ("MOCK", 550, 2050) for c in a.operation.click.call_args_list)
|
||||
a.cut_pic.assert_not_called()
|
||||
a.operation.analyse_pic_word.assert_not_called()
|
||||
a._shot_and_diagnose.assert_not_called()
|
||||
log_msgs = [str(c) for c in a._log_kv.call_args_list]
|
||||
assert any("快速预处理" in m for m in log_msgs)
|
||||
|
||||
def test_fast_prejoin_uses_short_configured_delays(self):
|
||||
def test_fast_prejoin_clamps_too_short_configured_delays(self):
|
||||
a = _mk_analyser(auto_join_fansclub=True)
|
||||
a.reservation_prejoin_fansclub_participate_wait_seconds = 0.2
|
||||
a.reservation_prejoin_fansclub_confirm_wait_seconds = 0.3
|
||||
@@ -166,4 +166,22 @@ class TestReservationPrejoinFansclub:
|
||||
handle_reservation_prejoin_fansclub(a, "加入购物粉丝团并关注主播")
|
||||
|
||||
delay_args = [c.args[0] for c in a.operation.delay.call_args_list]
|
||||
assert delay_args == [0.2, 0.3]
|
||||
assert delay_args == [0.8, 1.2]
|
||||
|
||||
def test_fast_prejoin_keeps_safe_configured_delays(self):
|
||||
a = _mk_analyser(auto_join_fansclub=True)
|
||||
a.reservation_prejoin_fansclub_participate_wait_seconds = 0.9
|
||||
a.reservation_prejoin_fansclub_confirm_wait_seconds = 1.3
|
||||
|
||||
handle_reservation_prejoin_fansclub(a, "加入购物粉丝团并关注主播")
|
||||
|
||||
delay_args = [c.args[0] for c in a.operation.delay.call_args_list]
|
||||
assert delay_args == [0.9, 1.3]
|
||||
|
||||
def test_fast_prejoin_default_delays_wait_for_join_page_and_result(self):
|
||||
a = _mk_analyser(auto_join_fansclub=True)
|
||||
|
||||
handle_reservation_prejoin_fansclub(a, "加入直播粉丝团并关注主播")
|
||||
|
||||
delay_args = [c.args[0] for c in a.operation.delay.call_args_list]
|
||||
assert delay_args == [1.2, 1.6]
|
||||
@@ -176,7 +176,7 @@ class TestFudaiDetailOcrGuiConfig:
|
||||
vars_ = build_config_vars({})
|
||||
|
||||
assert vars_["fudai_detail_regions_legacy_content_x1_var"].get() == 389
|
||||
assert vars_["fudai_detail_regions_v2_0_two_task_content_y1_var"].get() == 1410
|
||||
assert vars_["fudai_detail_regions_v2_0_two_task_content_y1_var"].get() == 1368
|
||||
assert vars_["fudai_detail_regions_v2_0_one_task_info_line_x1_var"].get() == 430
|
||||
assert vars_["pixel_regions_fudai_task_status_x1_var"].get() == 820
|
||||
assert vars_["pixel_regions_live_room_icon_bbox_x1_var"].get() == 999
|
||||
@@ -276,11 +276,83 @@ class TestAdbFunctions:
|
||||
result = list_adb_devices("/nonexistent/path/to/adb")
|
||||
assert isinstance(result, list)
|
||||
|
||||
def test_list_adb_devices_normalizes_mdns_serial_to_ip_port(self, monkeypatch):
|
||||
from gui.gui_core_pkg import adb as adb_mod
|
||||
|
||||
calls = []
|
||||
|
||||
class _Proc:
|
||||
returncode = 0
|
||||
|
||||
def __init__(self, stdout: str):
|
||||
self.stdout = stdout
|
||||
self.stderr = ""
|
||||
|
||||
def fake_run(cmd, **kwargs):
|
||||
calls.append(cmd)
|
||||
if cmd[1:3] == ["devices", "-l"]:
|
||||
return _Proc(
|
||||
"List of devices attached\n"
|
||||
"adb-ABC._adb-tls-connect._tcp device product:x model:x\n"
|
||||
)
|
||||
if cmd[1:3] == ["mdns", "services"]:
|
||||
return _Proc(
|
||||
"List of discovered mdns services\n"
|
||||
"adb-ABC _adb-tls-connect._tcp 192.168.10.105:46107\n"
|
||||
)
|
||||
return _Proc("")
|
||||
|
||||
monkeypatch.setattr(adb_mod.subprocess, "run", fake_run)
|
||||
|
||||
assert adb_mod.list_adb_devices("/adb") == ["192.168.10.105:46107"]
|
||||
assert calls[0][1:3] == ["devices", "-l"]
|
||||
assert calls[1][1:3] == ["mdns", "services"]
|
||||
|
||||
def test_resolve_adb_device_with_invalid_id_raises(self):
|
||||
# 指定了不存在的 device_id 应抛 RuntimeError
|
||||
with pytest.raises(RuntimeError):
|
||||
resolve_adb_device("", "nonexistent_device_xyz")
|
||||
|
||||
def test_find_adb_executable_falls_back_when_default_server_port_fails(
|
||||
self, monkeypatch
|
||||
):
|
||||
from gui.gui_core_pkg import adb as adb_mod
|
||||
|
||||
calls: list[str] = []
|
||||
|
||||
class _Proc:
|
||||
def __init__(self, returncode: int, stdout: str = "", stderr: str = ""):
|
||||
self.returncode = returncode
|
||||
self.stdout = stdout
|
||||
self.stderr = stderr
|
||||
|
||||
def fake_run(_cmd, **kwargs):
|
||||
port = kwargs["env"].get("ANDROID_ADB_SERVER_PORT")
|
||||
calls.append(port)
|
||||
if port == "5037":
|
||||
return _Proc(
|
||||
1,
|
||||
"",
|
||||
"failed to start daemon\ncannot connect to daemon",
|
||||
)
|
||||
if port == "5038":
|
||||
return _Proc(0, "List of devices attached\n", "")
|
||||
return _Proc(1, "", "failed")
|
||||
|
||||
monkeypatch.delenv("ANDROID_ADB_SERVER_PORT", raising=False)
|
||||
monkeypatch.setattr(adb_mod, "_ADB_SERVER_PROBED_FOR", set())
|
||||
monkeypatch.setattr(adb_mod.os.path, "exists", lambda p: p == "C:/adb.exe")
|
||||
monkeypatch.setattr(adb_mod.path_config, "find_bundled_adb", lambda: "")
|
||||
monkeypatch.setattr(adb_mod.shutil, "which", lambda _name: "")
|
||||
monkeypatch.setattr(adb_mod.subprocess, "run", fake_run)
|
||||
monkeypatch.setenv("ADB_EXECUTABLE", "C:/adb.exe")
|
||||
|
||||
result = adb_mod.find_adb_executable()
|
||||
|
||||
assert result.endswith("adb.exe")
|
||||
assert os.environ["ANDROID_ADB_SERVER_PORT"] == "5038"
|
||||
assert calls[:2] == ["5037", "5038"]
|
||||
|
||||
|
||||
class TestWifiAdbDialog:
|
||||
def test_open_wifi_adb_dialog_binds_toggle_button_without_nameerror(self, monkeypatch):
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
|
||||
def test_license_server_api_activates_card(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
@@ -179,6 +181,157 @@ def test_admin_can_publish_update_and_download_installer(tmp_path):
|
||||
assert download.content == payload
|
||||
|
||||
|
||||
def test_admin_publish_update_rejects_oversized_upload(tmp_path, monkeypatch):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
monkeypatch.setenv("DYGJ_LICENSE_MAX_INSTALLER_UPLOAD_MB", "1")
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
client = TestClient(api.create_app(service=service, admin_token="secret"))
|
||||
client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
|
||||
payload = b"x" * (1024 * 1024 + 1)
|
||||
|
||||
published = client.post(
|
||||
"/admin/update/publish",
|
||||
cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"},
|
||||
data={
|
||||
"csrf_token": "csrf-token",
|
||||
"version": "3.3.4",
|
||||
"notes": "oversized",
|
||||
"force": "1",
|
||||
},
|
||||
files={"installer": ("DouyinGuaji-3.3.4-Setup.exe", payload, "application/octet-stream")},
|
||||
)
|
||||
manifest = client.get("/api/v1/update/manifest").json()
|
||||
|
||||
assert published.status_code == 200
|
||||
assert "超过大小限制" in published.text
|
||||
assert manifest["enabled"] is False
|
||||
|
||||
|
||||
def test_admin_can_publish_delta_update_and_download_zip(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
client = TestClient(api.create_app(service=service, admin_token="secret"))
|
||||
client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
|
||||
installer_payload = b"installer bytes"
|
||||
delta_payload = b"zip bytes"
|
||||
|
||||
client.post(
|
||||
"/admin/update/publish",
|
||||
cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"},
|
||||
data={
|
||||
"csrf_token": "csrf-token",
|
||||
"version": "3.3.6",
|
||||
"notes": "smoke",
|
||||
"force": "1",
|
||||
},
|
||||
files={"installer": ("DouyinGuaji-3.3.6-Setup.exe", installer_payload, "application/octet-stream")},
|
||||
)
|
||||
published_delta = client.post(
|
||||
"/admin/update/publish-delta",
|
||||
cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"},
|
||||
data={
|
||||
"csrf_token": "csrf-token",
|
||||
"from_version": "3.3.5",
|
||||
"to_version": "3.3.6",
|
||||
},
|
||||
files={"delta_file": ("DouyinGuaji-3.3.5_to_3.3.6_delta.zip", delta_payload, "application/zip")},
|
||||
)
|
||||
manifest = client.get("/api/v1/update/manifest").json()
|
||||
download = client.get("/api/v1/update/download/DouyinGuaji-3.3.5_to_3.3.6_delta.zip")
|
||||
|
||||
assert published_delta.status_code == 200
|
||||
assert "已发布差量更新 3.3.5 -> 3.3.6" in published_delta.text
|
||||
assert manifest["delta"]["from_version"] == "3.3.5"
|
||||
assert manifest["delta"]["to_version"] == "3.3.6"
|
||||
assert manifest["delta"]["url"].endswith("/api/v1/update/download/DouyinGuaji-3.3.5_to_3.3.6_delta.zip")
|
||||
assert manifest["delta"]["sha256"] == hashlib.sha256(delta_payload).hexdigest()
|
||||
assert isinstance(manifest["signature"], str)
|
||||
assert download.status_code == 200
|
||||
assert download.content == delta_payload
|
||||
|
||||
|
||||
def test_admin_can_publish_multiple_cumulative_delta_updates(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
client = TestClient(api.create_app(service=service, admin_token="secret"))
|
||||
client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
|
||||
|
||||
client.post(
|
||||
"/admin/update/publish",
|
||||
cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"},
|
||||
data={"csrf_token": "csrf-token", "version": "3.3.9", "notes": "", "force": "1"},
|
||||
files={"installer": ("DouyinGuaji-3.3.9-Setup.exe", b"installer", "application/octet-stream")},
|
||||
)
|
||||
for from_version, payload in [("3.3.7", b"delta37"), ("3.3.8", b"delta38")]:
|
||||
resp = client.post(
|
||||
"/admin/update/publish-delta",
|
||||
cookies={api.ADMIN_CSRF_COOKIE: "csrf-token"},
|
||||
data={"csrf_token": "csrf-token", "from_version": from_version, "to_version": "3.3.9"},
|
||||
files={"delta_file": (f"DouyinGuaji-{from_version}_to_3.3.9_delta.zip", payload, "application/zip")},
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
|
||||
manifest = client.get("/api/v1/update/manifest").json()
|
||||
deltas = manifest["delta"]
|
||||
|
||||
assert isinstance(deltas, list)
|
||||
assert [item["from_version"] for item in deltas] == ["3.3.7", "3.3.8"]
|
||||
assert deltas[0]["url"].endswith("/api/v1/update/download/DouyinGuaji-3.3.7_to_3.3.9_delta.zip")
|
||||
download = client.get("/api/v1/update/download/DouyinGuaji-3.3.7_to_3.3.9_delta.zip")
|
||||
assert download.status_code == 200
|
||||
assert download.content == b"delta37"
|
||||
|
||||
|
||||
def test_license_server_rejects_untrusted_host(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
client = TestClient(api.create_app(service=service), base_url="https://evil.example")
|
||||
|
||||
resp = client.get("/api/v1/health")
|
||||
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
def test_public_https_base_url_enables_secure_admin_cookies(tmp_path, monkeypatch):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
monkeypatch.setenv("DYGJ_LICENSE_PUBLIC_BASE_URL", "https://dy.absfan.cn")
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
client = TestClient(
|
||||
api.create_app(service=service, admin_token="secret"),
|
||||
base_url="https://dy.absfan.cn",
|
||||
)
|
||||
|
||||
login = client.post("/admin/login", data={"admin_token": "secret"}, follow_redirects=False)
|
||||
|
||||
assert login.status_code == 303
|
||||
assert "secure" in login.headers["set-cookie"].lower()
|
||||
|
||||
|
||||
def test_admin_page_shows_stats_cards_and_audit_logs(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
@@ -373,3 +526,140 @@ def test_api_rate_limits_repeated_failed_activation(tmp_path, monkeypatch):
|
||||
|
||||
assert limited.status_code == 429
|
||||
assert limited.json()["reason"] == "rate_limited"
|
||||
|
||||
|
||||
def test_external_redeem_create_requires_bearer_token(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
client = TestClient(
|
||||
api.create_app(service=service, external_api_token="external-secret"),
|
||||
base_url="https://dy.absfan.cn",
|
||||
)
|
||||
|
||||
resp = client.post(
|
||||
"/api/v1/redeem/external/create",
|
||||
json={
|
||||
"platform": "xianyu",
|
||||
"external_order_id": "ORDER-1",
|
||||
"customer": "buyer-a",
|
||||
"days": 30,
|
||||
"max_devices": 1,
|
||||
},
|
||||
)
|
||||
|
||||
assert resp.status_code == 403
|
||||
assert resp.json()["reason"] == "forbidden"
|
||||
|
||||
|
||||
def test_external_redeem_create_returns_claim_url_without_card_key(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
client = TestClient(
|
||||
api.create_app(service=service, external_api_token="external-secret"),
|
||||
base_url="https://dy.absfan.cn",
|
||||
)
|
||||
|
||||
resp = client.post(
|
||||
"/api/v1/redeem/external/create",
|
||||
headers={"authorization": "Bearer external-secret"},
|
||||
json={
|
||||
"platform": "xianyu",
|
||||
"external_order_id": "ORDER-1",
|
||||
"customer": "buyer-a",
|
||||
"days": 30,
|
||||
"max_devices": 1,
|
||||
},
|
||||
)
|
||||
body = resp.json()
|
||||
|
||||
assert resp.status_code == 200
|
||||
assert body["ok"] is True
|
||||
assert body["claim_url"].startswith("https://dy.absfan.cn/redeem#")
|
||||
assert "card_key" not in body
|
||||
assert service.stats()["total"] == 0
|
||||
|
||||
|
||||
def test_redeem_claim_exchanges_token_for_card_once(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
token = service.create_redeem_token(
|
||||
days=30,
|
||||
max_devices=1,
|
||||
customer="buyer-a",
|
||||
platform="xianyu",
|
||||
external_order_id="ORDER-1",
|
||||
)
|
||||
client = TestClient(api.create_app(service=service), base_url="https://dy.absfan.cn")
|
||||
|
||||
first = client.post("/api/v1/redeem/claim", json={"token": token.token})
|
||||
second = client.post("/api/v1/redeem/claim", json={"token": token.token})
|
||||
|
||||
assert first.status_code == 200
|
||||
assert first.json()["ok"] is True
|
||||
assert first.json()["card_key"].startswith("DG-")
|
||||
assert second.status_code == 409
|
||||
assert second.json()["reason"] == "already_redeemed"
|
||||
|
||||
|
||||
def test_redeem_claim_is_rate_limited(tmp_path, monkeypatch):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
monkeypatch.setattr(api, "REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS", 2)
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
client = TestClient(api.create_app(service=service), base_url="https://dy.absfan.cn")
|
||||
|
||||
for _ in range(2):
|
||||
assert client.post("/api/v1/redeem/claim", json={"token": "missing"}).status_code == 404
|
||||
|
||||
limited = client.post("/api/v1/redeem/claim", json={"token": "missing"})
|
||||
|
||||
assert limited.status_code == 429
|
||||
assert limited.json()["reason"] == "rate_limited"
|
||||
|
||||
|
||||
def test_external_redeem_auth_failures_are_rate_limited(tmp_path, monkeypatch):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
monkeypatch.setattr(api, "EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS", 2)
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
client = TestClient(
|
||||
api.create_app(service=service, external_api_token="external-secret"),
|
||||
base_url="https://dy.absfan.cn",
|
||||
)
|
||||
|
||||
for _ in range(2):
|
||||
assert client.post(
|
||||
"/api/v1/redeem/external/create",
|
||||
json={"days": 1},
|
||||
).status_code == 403
|
||||
|
||||
limited = client.post(
|
||||
"/api/v1/redeem/external/create",
|
||||
json={"days": 1},
|
||||
)
|
||||
|
||||
assert limited.status_code == 429
|
||||
assert limited.json()["reason"] == "rate_limited"
|
||||
@@ -100,3 +100,89 @@ def test_license_server_verify_license_doc_requires_card_hash(tmp_path):
|
||||
|
||||
assert result.ok is False
|
||||
assert result.reason == "invalid_signature"
|
||||
|
||||
|
||||
def test_license_server_redeem_token_creates_card_only_when_claimed(tmp_path):
|
||||
from license_server import core
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
|
||||
token = service.create_redeem_token(
|
||||
days=14,
|
||||
max_devices=2,
|
||||
customer="xianyu-order-1",
|
||||
platform="xianyu",
|
||||
external_order_id="ORDER-1",
|
||||
)
|
||||
before = service.stats()
|
||||
claimed = service.claim_redeem_token(token.token)
|
||||
second = service.claim_redeem_token(token.token)
|
||||
|
||||
assert before["total"] == 0
|
||||
assert claimed.ok is True
|
||||
assert claimed.card is not None
|
||||
assert claimed.card.code.startswith("DG-")
|
||||
assert claimed.card.days == 14
|
||||
assert claimed.card.max_devices == 2
|
||||
assert claimed.card.customer == "xianyu-order-1"
|
||||
assert second.ok is False
|
||||
assert second.reason == "already_redeemed"
|
||||
assert service.stats()["total"] == 1
|
||||
|
||||
|
||||
def test_license_server_redeem_token_rejects_expired_token(tmp_path, monkeypatch):
|
||||
from datetime import timedelta
|
||||
|
||||
from license_server import core
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
start = core.utcnow()
|
||||
monkeypatch.setattr(core, "utcnow", lambda: start)
|
||||
token = service.create_redeem_token(
|
||||
days=7,
|
||||
max_devices=1,
|
||||
customer="expired-order",
|
||||
platform="xianyu",
|
||||
external_order_id="ORDER-EXPIRED",
|
||||
expires_hours=1,
|
||||
)
|
||||
monkeypatch.setattr(core, "utcnow", lambda: start + timedelta(hours=2))
|
||||
|
||||
result = service.claim_redeem_token(token.token)
|
||||
|
||||
assert result.ok is False
|
||||
assert result.reason == "expired"
|
||||
assert service.stats()["total"] == 0
|
||||
|
||||
|
||||
def test_license_server_redeem_token_is_single_use_under_concurrency(tmp_path, monkeypatch):
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import time
|
||||
|
||||
from license_server import core
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM
|
||||
|
||||
service = core.LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
token = service.create_redeem_token(
|
||||
days=7,
|
||||
max_devices=1,
|
||||
customer="race-order",
|
||||
platform="xianyu",
|
||||
external_order_id="ORDER-RACE",
|
||||
)
|
||||
original_insert_card = service._insert_card
|
||||
|
||||
def slow_insert(*args, **kwargs):
|
||||
time.sleep(0.2)
|
||||
return original_insert_card(*args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(service, "_insert_card", slow_insert)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||
results = list(pool.map(lambda _idx: service.claim_redeem_token(token.token), range(2)))
|
||||
|
||||
assert sorted(result.reason for result in results) == ["already_redeemed", "ok"]
|
||||
assert sum(1 for result in results if result.ok) == 1
|
||||
assert service.stats()["total"] == 1
|
||||
@@ -0,0 +1,170 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import zipfile
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from tests.license_test_keys import TEST_PRIVATE_KEY_PEM, TEST_PUBLIC_KEY_PEM
|
||||
|
||||
|
||||
def test_build_diagnostic_log_archive_tails_logs_only(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.diagnostics import log_upload
|
||||
|
||||
logs_dir = tmp_path / "logs"
|
||||
logs_dir.mkdir()
|
||||
(logs_dir / "unified.log").write_text("a" * 40, encoding="utf-8")
|
||||
(logs_dir / "actions.log").write_text("action\n", encoding="utf-8")
|
||||
(tmp_path / "license.dat").write_text("secret", encoding="utf-8")
|
||||
pic_dir = tmp_path / "pic"
|
||||
state_dir = tmp_path / "state"
|
||||
pic_dir.mkdir()
|
||||
state_dir.mkdir()
|
||||
monkeypatch.setattr(path_config, "get_logs_dir", lambda: str(logs_dir))
|
||||
monkeypatch.setattr(path_config, "get_pic_dir", lambda: str(pic_dir))
|
||||
monkeypatch.setattr(path_config, "get_state_dir", lambda: str(state_dir))
|
||||
monkeypatch.setattr(path_config, "get_config_path", lambda: str(tmp_path / "missing-config.json"))
|
||||
|
||||
archive = log_upload.build_diagnostic_log_archive(
|
||||
output_dir=tmp_path,
|
||||
max_source_bytes=10,
|
||||
max_archive_bytes=1024 * 1024,
|
||||
)
|
||||
|
||||
with zipfile.ZipFile(archive) as zf:
|
||||
names = set(zf.namelist())
|
||||
assert "logs/unified.log" in names
|
||||
assert "logs/actions.log" in names
|
||||
assert "license.dat" not in names
|
||||
assert zf.read("logs/unified.log") == b"a" * 10
|
||||
|
||||
|
||||
def test_build_diagnostic_log_archive_includes_runtime_context_and_recent_images(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from douyin.diagnostics import log_upload
|
||||
|
||||
logs_dir = tmp_path / "logs"
|
||||
logs_dir.mkdir()
|
||||
pic_dir = tmp_path / "pic"
|
||||
pic_dir.mkdir()
|
||||
state_dir = tmp_path / "state"
|
||||
state_dir.mkdir()
|
||||
cfg_path = tmp_path / "config.json"
|
||||
(logs_dir / "screenshot_calls.jsonl").write_text("call\n", encoding="utf-8")
|
||||
(pic_dir / "screenshot.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"x" * 2048)
|
||||
(pic_dir / "screenshot.png.tmp").write_bytes(b"broken screenshot output")
|
||||
(pic_dir / "latest.png").write_bytes(b"\x89PNG\r\n\x1a\n" + b"y" * 2048)
|
||||
(state_dir / "room_pos_map.json").write_text('{"1": "room"}', encoding="utf-8")
|
||||
cfg_path.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"device_id": "dev-1",
|
||||
"license": {"card_key": "DG-SHOULD-NOT-LEAK"},
|
||||
"api_token": "secret",
|
||||
},
|
||||
ensure_ascii=False,
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setattr(path_config, "get_logs_dir", lambda: str(logs_dir))
|
||||
monkeypatch.setattr(path_config, "get_pic_dir", lambda: str(pic_dir))
|
||||
monkeypatch.setattr(path_config, "get_state_dir", lambda: str(state_dir))
|
||||
monkeypatch.setattr(path_config, "get_config_path", lambda: str(cfg_path))
|
||||
|
||||
archive = log_upload.build_diagnostic_log_archive(output_dir=tmp_path, max_archive_bytes=1024 * 1024)
|
||||
|
||||
with zipfile.ZipFile(archive) as zf:
|
||||
names = set(zf.namelist())
|
||||
assert "logs/screenshot_calls.jsonl" in names
|
||||
assert "pic/screenshot.png" in names
|
||||
assert "pic/screenshot.png.tmp" in names
|
||||
assert "pic/latest.png" in names
|
||||
assert "state/room_pos_map.json" in names
|
||||
assert "config/config.redacted.json" in names
|
||||
assert "diagnostics/environment.json" in names
|
||||
redacted = json.loads(zf.read("config/config.redacted.json").decode("utf-8"))
|
||||
assert redacted["license"]["card_key"] == "<redacted>"
|
||||
assert redacted["api_token"] == "<redacted>"
|
||||
|
||||
|
||||
def test_license_server_log_upload_overwrites_same_card(tmp_path):
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from license_server import api
|
||||
from license_server.core import LicenseService
|
||||
|
||||
service = LicenseService(db_path=tmp_path / "license.db", private_key_pem=TEST_PRIVATE_KEY_PEM)
|
||||
card = service.create_cards(days=5, count=1, customer="log-user")[0]
|
||||
activated = service.activate(card.code, machine_fingerprint="machine-api")
|
||||
assert activated.license_doc is not None
|
||||
client = TestClient(api.create_app(service=service))
|
||||
|
||||
first = client.post(
|
||||
"/api/v1/logs/upload",
|
||||
data={"license": json.dumps(activated.license_doc, ensure_ascii=False)},
|
||||
files={"log_file": ("one.zip", b"first", "application/zip")},
|
||||
)
|
||||
second = client.post(
|
||||
"/api/v1/logs/upload",
|
||||
data={"license": json.dumps(activated.license_doc, ensure_ascii=False)},
|
||||
files={"log_file": ("two.zip", b"second", "application/zip")},
|
||||
)
|
||||
entries = service.list_diagnostic_logs()
|
||||
stored = service.diagnostic_log_path(entries[0].key)
|
||||
|
||||
assert first.status_code == 200
|
||||
assert second.status_code == 200
|
||||
assert len(entries) == 1
|
||||
assert entries[0].filename == "two.zip"
|
||||
assert stored is not None
|
||||
assert stored.read_bytes() == b"second"
|
||||
|
||||
|
||||
def test_upload_diagnostic_logs_posts_signed_license_and_file(tmp_path, monkeypatch):
|
||||
from tools.license_dev import create_dev_license
|
||||
from douyin.core import path_config
|
||||
from douyin.license import license_manager
|
||||
from douyin.diagnostics import log_upload
|
||||
|
||||
logs_dir = tmp_path / "logs"
|
||||
logs_dir.mkdir()
|
||||
(logs_dir / "unified.log").write_text("hello\n", encoding="utf-8")
|
||||
license_path = tmp_path / "license.dat"
|
||||
monkeypatch.setattr(license_manager, "PUBLIC_KEY_PEM", TEST_PUBLIC_KEY_PEM)
|
||||
monkeypatch.setattr(license_manager, "get_machine_fingerprint", lambda: "machine-a")
|
||||
monkeypatch.setattr(log_upload, "get_default_license_path", lambda: license_path)
|
||||
monkeypatch.setattr(path_config, "get_logs_dir", lambda: str(logs_dir))
|
||||
create_dev_license(
|
||||
output_path=license_path,
|
||||
machine_fingerprint="machine-a",
|
||||
expires_at=datetime.now(timezone.utc) + timedelta(days=3),
|
||||
private_key_pem=TEST_PRIVATE_KEY_PEM,
|
||||
)
|
||||
calls = {}
|
||||
|
||||
def fake_post(url, *, license_doc, file_path, timeout_seconds=20):
|
||||
calls["url"] = url
|
||||
calls["license_doc"] = license_doc
|
||||
calls["file_path"] = file_path
|
||||
calls["timeout_seconds"] = timeout_seconds
|
||||
return {"ok": True, "message": "ok"}
|
||||
|
||||
result = log_upload.upload_diagnostic_logs(
|
||||
upload_url="https://license.example.test/api/v1/logs/upload",
|
||||
http_post_file=fake_post,
|
||||
)
|
||||
|
||||
assert result.ok is True
|
||||
assert calls["license_doc"]["payload"]["machine_fingerprint"] == "machine-a"
|
||||
assert calls["file_path"].exists()
|
||||
assert calls["file_path"].stat().st_size <= log_upload.DEFAULT_MAX_ARCHIVE_BYTES
|
||||
assert calls["file_path"].stat().st_size <= 500 * 1024 * 1024
|
||||
assert calls.get("timeout_seconds") == 120
|
||||
|
||||
|
||||
def test_log_upload_defaults_allow_500mb_archives():
|
||||
from douyin.diagnostics import log_upload
|
||||
from license_server import api
|
||||
|
||||
assert log_upload.DEFAULT_MAX_ARCHIVE_BYTES == 500 * 1024 * 1024
|
||||
assert api.DEFAULT_MAX_DIAGNOSTIC_LOG_UPLOAD_BYTES == 500 * 1024 * 1024
|
||||
@@ -253,17 +253,40 @@ def test_windows_packaging_script_protects_core_modules_by_default():
|
||||
assert '"--collect-submodules", "operations"' in cli_block
|
||||
assert '"--hidden-import", "logging.handlers"' in script
|
||||
assert '"--hidden-import", "cryptography.hazmat.primitives.serialization"' in script
|
||||
assert '"--collect-submodules", "cv2"' in script
|
||||
assert '"--collect-submodules", "numpy"' in script
|
||||
assert '"--collect-submodules", "PIL"' in script
|
||||
assert '"--collect-submodules", "paddle"' in script
|
||||
assert '"--collect-submodules", "paddleocr"' in script
|
||||
assert '"--collect-submodules", "paddlex"' in script
|
||||
assert '"--collect-submodules", "pyclipper"' in script
|
||||
assert '"--collect-submodules", "shapely"' in script
|
||||
assert '"--collect-binaries", "cv2"' in script
|
||||
assert '"--collect-binaries", "numpy"' in script
|
||||
assert '"--collect-binaries", "paddle"' in script
|
||||
assert '"--collect-binaries", "pyclipper"' in script
|
||||
assert '"--collect-binaries", "shapely"' in script
|
||||
assert '"--collect-data", "PIL"' in script
|
||||
assert '"--collect-data", "paddlex"' in script
|
||||
assert '"--collect-data", "paddleocr"' in script
|
||||
assert "tools.exe_packing $DistRoot --smoke-only" in script
|
||||
assert "Executable smoke check failed" in script
|
||||
assert "Post-smoke distribution manifest check failed" in script
|
||||
assert "[switch]$IncludeLicense" in script
|
||||
assert '"--add-data", "assets;assets"' not in script
|
||||
assert '"--add-data", "webui;webui"' not in script
|
||||
assert "$RuntimeAssets = @(" in script
|
||||
assert 'assets\$name' in script
|
||||
assert "$RuntimeAssetFiles = Get-ChildItem" in script
|
||||
assert 'assets\*.png' in script
|
||||
assert "tools\\adb\\ADBKeyboard.apk" in script
|
||||
assert "$IncludeLicense -and" in script
|
||||
assert '$ManifestArgs += "--allow-license"' in script
|
||||
assert "Get-ChildItem -LiteralPath $srcInternal -Force | Copy-Item" in script
|
||||
assert "Join-Path $BuildSourceRoot \"gui\\gui_dashboard_app_entry.py\"" in script
|
||||
assert "Join-Path $BuildSourceRoot \"gui\\web_gui_entry.py\"" in script
|
||||
assert "Join-Path $BuildSourceRoot \"bin\\run_cli_entry.py\"" in script
|
||||
assert '[string]$PlatformToolsDir = ""' in script
|
||||
assert '"ANDROID_PLATFORM_TOOLS", "ANDROID_HOME", "ANDROID_SDK_ROOT"' in script
|
||||
assert '$PlatformToolFiles = @(' in script
|
||||
assert '"adb.exe"' in script
|
||||
assert '"AdbWinApi.dll"' in script
|
||||
assert '"AdbWinUsbApi.dll"' in script
|
||||
@@ -119,6 +119,11 @@ class TestSpecificPaths:
|
||||
os.path.join(PROJECT_ROOT, "run_cli.exe")
|
||||
]
|
||||
|
||||
def test_bundled_adb_path_uses_project_root(self):
|
||||
assert path_config.get_bundled_adb_path() == os.path.join(
|
||||
PROJECT_ROOT, "platform-tools", "adb.exe"
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 路径间不应互相重复
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
PNG_BYTES = b"\x89PNG\r\n\x1a\n" + (b"x" * 2048) + b"IEND"
|
||||
|
||||
|
||||
def test_capture_screenshot_direct_invalid_fallback_png_returns_false(tmp_path):
|
||||
from douyin.core.underlying_operations_pkg.screenshot_direct import (
|
||||
capture_screenshot_direct,
|
||||
@@ -44,7 +48,7 @@ def test_capture_screenshot_direct_uses_shell_stdout_fallback_when_execout_and_p
|
||||
|
||||
pic_dir = tmp_path / "pic"
|
||||
pic_dir.mkdir()
|
||||
png_bytes = b"\x89PNG\r\n\x1a\n" + (b"x" * 2048) + b"IEND"
|
||||
png_bytes = PNG_BYTES
|
||||
calls: list[list[str]] = []
|
||||
|
||||
class FakePopen:
|
||||
@@ -77,3 +81,107 @@ def test_capture_screenshot_direct_uses_shell_stdout_fallback_when_execout_and_p
|
||||
assert result is True
|
||||
assert (pic_dir / "screenshot.png").exists()
|
||||
assert any(cmd[:5] == ["adb", "-s", "MOCK", "shell", "screencap"] and len(cmd) == 6 for cmd in calls)
|
||||
|
||||
|
||||
def test_capture_screenshot_direct_tries_stdout_after_invalid_pull_file(tmp_path):
|
||||
from douyin.core.underlying_operations_pkg.screenshot_direct import (
|
||||
capture_screenshot_direct,
|
||||
)
|
||||
|
||||
fake_self = SimpleNamespace(
|
||||
_adb_path=lambda: "adb",
|
||||
get_screenshot=lambda *_a, **_k: False,
|
||||
)
|
||||
|
||||
pic_dir = tmp_path / "pic"
|
||||
pic_dir.mkdir()
|
||||
calls: list[list[str]] = []
|
||||
|
||||
class FakePopen:
|
||||
returncode = 4294967295
|
||||
|
||||
def __init__(self, cmd, **_kwargs):
|
||||
calls.append(list(cmd))
|
||||
|
||||
def communicate(self, timeout=None): # noqa: ARG002
|
||||
return b"broken", None
|
||||
|
||||
def fake_run(cmd, **kwargs):
|
||||
calls.append(list(cmd))
|
||||
if cmd[:5] == ["adb", "-s", "MOCK", "shell", "screencap"] and len(cmd) == 7:
|
||||
return SimpleNamespace(returncode=0, stdout=b"", stderr=b"")
|
||||
if cmd[:4] == ["adb", "-s", "MOCK", "pull"]:
|
||||
with open(cmd[4], "wb") as f:
|
||||
f.write(b"not a png")
|
||||
return SimpleNamespace(returncode=0, stdout=b"", stderr=b"")
|
||||
if cmd[:5] == ["adb", "-s", "MOCK", "shell", "screencap"] and len(cmd) == 6:
|
||||
return SimpleNamespace(returncode=0, stdout=PNG_BYTES.replace(b"\r\n", b"\r\r\n"), stderr=b"")
|
||||
raise RuntimeError(f"unexpected command: {cmd}")
|
||||
|
||||
with patch(
|
||||
"douyin.core.underlying_operations_pkg.screenshot_direct.path_config.get_pic_dir",
|
||||
return_value=str(pic_dir),
|
||||
), patch(
|
||||
"douyin.core.underlying_operations_pkg.screenshot_direct.subprocess.Popen",
|
||||
FakePopen,
|
||||
), patch(
|
||||
"douyin.core.underlying_operations_pkg.screenshot_direct.subprocess.run",
|
||||
side_effect=fake_run,
|
||||
):
|
||||
result = capture_screenshot_direct(fake_self, "MOCK", "pic")
|
||||
|
||||
assert result is True
|
||||
assert (pic_dir / "screenshot.png").read_bytes().startswith(b"\x89PNG")
|
||||
assert any(cmd[:5] == ["adb", "-s", "MOCK", "shell", "screencap"] and len(cmd) == 6 for cmd in calls)
|
||||
|
||||
|
||||
def test_screenshot_operations_recovers_after_zero_byte_execout(tmp_path, monkeypatch):
|
||||
from douyin.core import path_config
|
||||
from PIL import Image
|
||||
|
||||
from operations import screenshot_operations
|
||||
|
||||
pic_dir = tmp_path / "pic"
|
||||
pic_dir.mkdir()
|
||||
buf = BytesIO()
|
||||
image = Image.new("RGB", (256, 256))
|
||||
image.putdata(
|
||||
[
|
||||
((x * 17 + y * 3) % 255, (y * 19 + x * 5) % 255, (x * y) % 255)
|
||||
for y in range(256)
|
||||
for x in range(256)
|
||||
]
|
||||
)
|
||||
image.save(buf, format="PNG")
|
||||
png_bytes = buf.getvalue()
|
||||
calls: list[list[str]] = []
|
||||
execout_count = 0
|
||||
|
||||
def fake_run(cmd, **_kwargs):
|
||||
nonlocal execout_count
|
||||
calls.append(list(cmd))
|
||||
if cmd[:4] == ["adb", "-s", "MOCK", "exec-out"]:
|
||||
execout_count += 1
|
||||
if execout_count == 1:
|
||||
return SimpleNamespace(returncode=0, stdout=b"", stderr=b"")
|
||||
return SimpleNamespace(returncode=0, stdout=png_bytes, stderr=b"")
|
||||
if cmd == ["adb", "kill-server"] or cmd == ["adb", "start-server"]:
|
||||
return SimpleNamespace(returncode=0, stdout=b"", stderr=b"")
|
||||
raise AssertionError(f"unexpected command: {cmd}")
|
||||
|
||||
monkeypatch.setenv("ADB_EXECUTABLE", "adb")
|
||||
monkeypatch.setattr(
|
||||
path_config,
|
||||
"get_pic_dir",
|
||||
lambda: str(pic_dir),
|
||||
raising=False,
|
||||
)
|
||||
monkeypatch.setattr(screenshot_operations.subprocess, "run", fake_run)
|
||||
monkeypatch.setattr(screenshot_operations, "_mirror_screenshot_to_external", lambda *_: None)
|
||||
|
||||
result = screenshot_operations.ScreenshotOperations().get_screenshot("MOCK", use_service=False)
|
||||
|
||||
assert result is True
|
||||
assert (pic_dir / "screenshot.png").read_bytes().startswith(b"\x89PNG")
|
||||
assert ["adb", "kill-server"] in calls
|
||||
assert ["adb", "start-server"] in calls
|
||||
@@ -1,5 +1,6 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
@@ -7,8 +8,12 @@ from pathlib import Path
|
||||
|
||||
def _assert_bootstrap_before(path: str, *late_markers: str) -> None:
|
||||
text = Path(path).read_text(encoding="utf-8")
|
||||
import_marker = "from douyin.updater.bootstrap import run_startup_update_check_early"
|
||||
call_marker = "run_startup_update_check_early("
|
||||
import_marker = (
|
||||
"from douyin.updater.bootstrap import run_startup_update_check_early"
|
||||
if "run_startup_update_check_early(" in text
|
||||
else "from gui.components.update_progress import run_gui_startup_update_check_early"
|
||||
)
|
||||
call_marker = "run_startup_update_check_early(" if "run_startup_update_check_early(" in text else "run_gui_startup_update_check_early("
|
||||
assert import_marker in text
|
||||
assert call_marker in text
|
||||
call_index = text.index(call_marker)
|
||||
@@ -25,9 +30,10 @@ def _assert_packaging_uses_wrapper(wrapper_path: str, target_script: str) -> Non
|
||||
|
||||
def _assert_wrapper_imports_target_after_bootstrap(path: str, target_import: str) -> None:
|
||||
text = Path(path).read_text(encoding="utf-8")
|
||||
assert "run_startup_update_check_early(" in text
|
||||
call_marker = "run_startup_update_check_early(" if "run_startup_update_check_early(" in text else "run_gui_startup_update_check_early("
|
||||
assert call_marker in text
|
||||
assert target_import in text
|
||||
assert text.index("run_startup_update_check_early(") < text.index(target_import)
|
||||
assert text.index(call_marker) < text.index(target_import)
|
||||
|
||||
|
||||
def _assert_source_entry_bootstraps_under_main_guard(path: str, late_marker: str) -> None:
|
||||
@@ -74,6 +80,90 @@ def test_dashboard_gui_runs_update_bootstrap_before_gui_imports():
|
||||
_assert_packaging_uses_wrapper("gui\\gui_dashboard_app_entry.py", "gui\\dashboard_app\\app.py")
|
||||
|
||||
|
||||
def test_dashboard_gui_main_forces_license_required(monkeypatch):
|
||||
from gui.dashboard_app import app as dashboard_app
|
||||
|
||||
calls = {
|
||||
"app_started": False,
|
||||
"monitor_started": False,
|
||||
"required_at_check": "",
|
||||
"initial_page": "",
|
||||
"license_locked": None,
|
||||
}
|
||||
|
||||
class FakeDashboardApp:
|
||||
def __init__(self, *, initial_page="数据看板", license_locked=False) -> None:
|
||||
calls["app_started"] = True
|
||||
calls["initial_page"] = initial_page
|
||||
calls["license_locked"] = license_locked
|
||||
|
||||
def _on_runner_line(self, line: str) -> None:
|
||||
pass
|
||||
|
||||
def _start_license_monitor_once(self) -> None:
|
||||
calls["monitor_started"] = True
|
||||
|
||||
def run(self) -> None:
|
||||
calls["run_called"] = True
|
||||
|
||||
class MissingStatus:
|
||||
ok = False
|
||||
|
||||
def fake_require_online_license_or_exit() -> None:
|
||||
calls["required_at_check"] = os.environ.get("DOUYIN_LICENSE_REQUIRED", "")
|
||||
|
||||
monkeypatch.delenv("DOUYIN_LICENSE_REQUIRED", raising=False)
|
||||
monkeypatch.setattr(dashboard_app, "check_license", lambda: MissingStatus())
|
||||
monkeypatch.setattr(dashboard_app, "DashboardApp", FakeDashboardApp)
|
||||
monkeypatch.setattr(dashboard_app, "require_online_license_or_exit", fake_require_online_license_or_exit)
|
||||
|
||||
dashboard_app.main()
|
||||
|
||||
assert os.environ.get("DOUYIN_LICENSE_REQUIRED") == "1"
|
||||
assert calls["required_at_check"] == ""
|
||||
assert calls["app_started"] is True
|
||||
assert calls["initial_page"] == "授权"
|
||||
assert calls["license_locked"] is True
|
||||
assert calls["monitor_started"] is False
|
||||
assert calls["run_called"] is True
|
||||
|
||||
|
||||
def test_dashboard_gui_main_checks_online_license_when_local_license_exists(monkeypatch):
|
||||
from gui.dashboard_app import app as dashboard_app
|
||||
|
||||
calls = {"required_at_check": "", "monitor_started": False, "initial_page": ""}
|
||||
|
||||
class FakeDashboardApp:
|
||||
def __init__(self, *, initial_page="数据看板", license_locked=False) -> None:
|
||||
calls["initial_page"] = initial_page
|
||||
calls["license_locked"] = license_locked
|
||||
|
||||
def _start_license_monitor_once(self) -> None:
|
||||
calls["monitor_started"] = True
|
||||
|
||||
def run(self) -> None:
|
||||
calls["run_called"] = True
|
||||
|
||||
class OkStatus:
|
||||
ok = True
|
||||
|
||||
def fake_require_online_license_or_exit() -> None:
|
||||
calls["required_at_check"] = os.environ.get("DOUYIN_LICENSE_REQUIRED", "")
|
||||
|
||||
monkeypatch.delenv("DOUYIN_LICENSE_REQUIRED", raising=False)
|
||||
monkeypatch.setattr(dashboard_app, "check_license", lambda: OkStatus())
|
||||
monkeypatch.setattr(dashboard_app, "DashboardApp", FakeDashboardApp)
|
||||
monkeypatch.setattr(dashboard_app, "require_online_license_or_exit", fake_require_online_license_or_exit)
|
||||
|
||||
dashboard_app.main()
|
||||
|
||||
assert calls["required_at_check"] == "1"
|
||||
assert calls["initial_page"] == "数据看板"
|
||||
assert calls["license_locked"] is False
|
||||
assert calls["monitor_started"] is True
|
||||
assert calls["run_called"] is True
|
||||
|
||||
|
||||
def test_web_gui_runs_update_bootstrap_before_gui_imports():
|
||||
_assert_bootstrap_before(
|
||||
"gui/web_gui_entry.py",
|
||||
|
||||
@@ -27,6 +27,10 @@ class TestAdbPath:
|
||||
def test_default_returns_adb(self, monkeypatch):
|
||||
# 默认走 ADB_EXECUTABLE 环境变量;如果未设,应返回 'adb'
|
||||
monkeypatch.delenv("ADB_EXECUTABLE", raising=False)
|
||||
monkeypatch.setattr(
|
||||
"douyin.core.underlying_operations_pkg.adb_helpers.path_config.find_bundled_adb",
|
||||
lambda: None,
|
||||
)
|
||||
assert _adb_path() == "adb"
|
||||
|
||||
def test_env_override(self, monkeypatch):
|
||||
@@ -38,6 +42,14 @@ class TestAdbPath:
|
||||
# 包了引号的应当去引号返回 raw 路径
|
||||
assert _adb_path() == "C:\\Program Files\\adb.exe"
|
||||
|
||||
def test_uses_bundled_adb_when_env_missing(self, monkeypatch):
|
||||
monkeypatch.delenv("ADB_EXECUTABLE", raising=False)
|
||||
monkeypatch.setattr(
|
||||
"douyin.core.underlying_operations_pkg.adb_helpers.path_config.find_bundled_adb",
|
||||
lambda: r"C:\App\platform-tools\adb.exe",
|
||||
)
|
||||
assert _adb_path() == r"C:\App\platform-tools\adb.exe"
|
||||
|
||||
|
||||
class TestAdbArgs:
|
||||
def test_basic(self):
|
||||
@@ -74,6 +86,50 @@ class TestPickAdbKeyboardIme:
|
||||
assert result in ("", None)
|
||||
|
||||
|
||||
def test_ensure_adbkeyboard_installs_bundled_apk_when_missing(monkeypatch, tmp_path):
|
||||
from douyin.core.underlying_operations_pkg import text_input
|
||||
|
||||
apk = tmp_path / "ADBKeyboard.apk"
|
||||
apk.write_bytes(b"apk")
|
||||
calls = []
|
||||
|
||||
class Ops:
|
||||
def __init__(self):
|
||||
self.list_count = 0
|
||||
|
||||
def get_current_ime(self, _device_id):
|
||||
return "com.example/.Ime"
|
||||
|
||||
def list_imes(self, _device_id):
|
||||
self.list_count += 1
|
||||
if self.list_count == 1:
|
||||
return ["com.example/.Ime"]
|
||||
return ["com.android.adbkeyboard/.AdbIME"]
|
||||
|
||||
def _pick_adbkeyboard_ime(self, imes):
|
||||
return _pick_adbkeyboard_ime(imes)
|
||||
|
||||
def _adb_path(self):
|
||||
return "adb"
|
||||
|
||||
def try_set_ime(self, _device_id, ime_id):
|
||||
return ime_id == "com.android.adbkeyboard/.AdbIME"
|
||||
|
||||
def fake_run(cmd, **_kwargs):
|
||||
calls.append(cmd)
|
||||
return type("Proc", (), {"returncode": 0})()
|
||||
|
||||
monkeypatch.setattr(text_input.path_config, "get_bundled_adbkeyboard_apk_path", lambda: str(apk))
|
||||
monkeypatch.setattr(text_input.subprocess, "run", fake_run)
|
||||
|
||||
ok, prev, ime = text_input.ensure_adbkeyboard_ime(Ops(), "device1")
|
||||
|
||||
assert ok is True
|
||||
assert prev == "com.example/.Ime"
|
||||
assert ime == "com.android.adbkeyboard/.AdbIME"
|
||||
assert calls and calls[0][-2:] == ["-r", str(apk)]
|
||||
|
||||
|
||||
# ============================================================
|
||||
# bounds.py — _parse_bounds
|
||||
# ============================================================
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import zipfile
|
||||
|
||||
|
||||
def test_update_delta_build_and_apply_round_trip(tmp_path):
|
||||
from tools.update_delta import apply_delta_zip, create_delta_zip
|
||||
|
||||
old_root = tmp_path / "old"
|
||||
new_root = tmp_path / "new"
|
||||
target = tmp_path / "target"
|
||||
old_root.mkdir()
|
||||
new_root.mkdir()
|
||||
(old_root / "same.txt").write_text("same", encoding="utf-8")
|
||||
(old_root / "changed.txt").write_text("old", encoding="utf-8")
|
||||
(old_root / "removed.txt").write_text("remove me", encoding="utf-8")
|
||||
(old_root / "nested").mkdir()
|
||||
(old_root / "nested" / "old.txt").write_text("old nested", encoding="utf-8")
|
||||
(new_root / "same.txt").write_text("same", encoding="utf-8")
|
||||
(new_root / "changed.txt").write_text("new", encoding="utf-8")
|
||||
(new_root / "added.txt").write_text("added", encoding="utf-8")
|
||||
(new_root / "nested").mkdir()
|
||||
(new_root / "nested" / "new.txt").write_text("new nested", encoding="utf-8")
|
||||
shutil.copytree(old_root, target)
|
||||
delta = tmp_path / "delta.zip"
|
||||
|
||||
manifest = create_delta_zip(old_root, new_root, delta, "3.3.5", "3.3.6")
|
||||
applied = apply_delta_zip(delta, target)
|
||||
|
||||
assert manifest["from_version"] == "3.3.5"
|
||||
assert manifest["to_version"] == "3.3.6"
|
||||
assert sorted(item["path"] for item in manifest["files"]) == [
|
||||
"added.txt",
|
||||
"changed.txt",
|
||||
"nested/new.txt",
|
||||
]
|
||||
assert manifest["delete"] == ["nested/old.txt", "removed.txt"]
|
||||
assert applied["to_version"] == "3.3.6"
|
||||
assert (target / "same.txt").read_text(encoding="utf-8") == "same"
|
||||
assert (target / "changed.txt").read_text(encoding="utf-8") == "new"
|
||||
assert (target / "added.txt").read_text(encoding="utf-8") == "added"
|
||||
assert (target / "nested" / "new.txt").read_text(encoding="utf-8") == "new nested"
|
||||
assert not (target / "removed.txt").exists()
|
||||
|
||||
with zipfile.ZipFile(delta) as zf:
|
||||
package_manifest = json.loads(zf.read("manifest.json").decode("utf-8"))
|
||||
assert package_manifest["files"] == manifest["files"]
|
||||
|
||||
|
||||
def test_update_delta_build_many_creates_cumulative_delta_packages(tmp_path):
|
||||
from tools.update_delta import create_delta_zips
|
||||
|
||||
old37 = tmp_path / "DouyinGuaji-3.3.7"
|
||||
old38 = tmp_path / "DouyinGuaji-3.3.8"
|
||||
new = tmp_path / "DouyinGuaji-3.3.9"
|
||||
out = tmp_path / "delta"
|
||||
for root, text in [(old37, "37"), (old38, "38"), (new, "39")]:
|
||||
root.mkdir()
|
||||
(root / "app.txt").write_text(text, encoding="utf-8")
|
||||
|
||||
manifests = create_delta_zips([old37, old38], new, out, to_version="3.3.9")
|
||||
|
||||
assert [item["from_version"] for item in manifests] == ["3.3.7", "3.3.8"]
|
||||
assert (out / "DouyinGuaji-3.3.7_to_3.3.9_delta.zip").exists()
|
||||
assert (out / "DouyinGuaji-3.3.8_to_3.3.9_delta.zip").exists()
|
||||
@@ -280,3 +280,6 @@ class TestRequestParsing:
|
||||
|
||||
assert dummy.status == 200
|
||||
assert dummy.header_finished is True
|
||||
assert ("X-Content-Type-Options", "nosniff") in dummy.headers
|
||||
assert ("Referrer-Policy", "no-referrer") in dummy.headers
|
||||
assert ("X-Frame-Options", "DENY") in dummy.headers
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
@@ -16,6 +17,9 @@ class _DummyHandler:
|
||||
self.calls = []
|
||||
self.client_address = ("127.0.0.1", 12345)
|
||||
self.static_calls = []
|
||||
self.response_status = None
|
||||
self.response_headers = []
|
||||
self.wfile = io.BytesIO()
|
||||
|
||||
def _read_json(self):
|
||||
return self._body
|
||||
@@ -28,6 +32,15 @@ class _DummyHandler:
|
||||
self.calls.append((status, {"error": "send_error"}))
|
||||
return None
|
||||
|
||||
def send_response(self, status):
|
||||
self.response_status = status
|
||||
|
||||
def send_header(self, name, value):
|
||||
self.response_headers.append((name, value))
|
||||
|
||||
def end_headers(self):
|
||||
return None
|
||||
|
||||
def _serve_static(self, rel_path):
|
||||
self.static_calls.append(rel_path)
|
||||
return None
|
||||
@@ -60,6 +73,30 @@ class _DummyRunner:
|
||||
|
||||
|
||||
def _post(path: str, body: dict, monkeypatch, csrf: str = "token"):
|
||||
class OkStatus:
|
||||
ok = True
|
||||
|
||||
monkeypatch.setattr(routes, "check_license", lambda: OkStatus())
|
||||
handler = _DummyHandler(body=body, csrf_token=csrf)
|
||||
runner = _DummyRunner()
|
||||
u = SimpleNamespace(path=path, query="")
|
||||
routes.handle_post(handler, u, runner, "token")
|
||||
assert handler.calls, f"{path} should produce a response"
|
||||
return handler.calls[-1]
|
||||
|
||||
|
||||
def _post_without_license(path: str, body: dict, monkeypatch, csrf: str = "token"):
|
||||
class MissingStatus:
|
||||
ok = False
|
||||
reason = "missing"
|
||||
message = "缺少授权文件"
|
||||
|
||||
monkeypatch.setattr(routes, "check_license", lambda: MissingStatus())
|
||||
monkeypatch.setattr(
|
||||
routes,
|
||||
"get_license_status_payload",
|
||||
lambda: {"ok": False, "required": True, "reason": "missing", "message": "缺少授权文件"},
|
||||
)
|
||||
handler = _DummyHandler(body=body, csrf_token=csrf)
|
||||
runner = _DummyRunner()
|
||||
u = SimpleNamespace(path=path, query="")
|
||||
@@ -77,6 +114,22 @@ def _get(path: str, monkeypatch, query: str = ""):
|
||||
return handler.calls[-1]
|
||||
|
||||
|
||||
def _license_ok(monkeypatch):
|
||||
class OkStatus:
|
||||
ok = True
|
||||
|
||||
monkeypatch.setattr(routes, "check_license", lambda: OkStatus())
|
||||
|
||||
|
||||
def _license_missing(monkeypatch):
|
||||
class MissingStatus:
|
||||
ok = False
|
||||
reason = "missing"
|
||||
message = "缺少授权文件"
|
||||
|
||||
monkeypatch.setattr(routes, "check_license", lambda: MissingStatus())
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw,expected",
|
||||
[
|
||||
@@ -130,6 +183,34 @@ def test_license_status_route_returns_public_payload(monkeypatch):
|
||||
assert obj == {"ok": True, "reason": "ok", "customer": "demo"}
|
||||
|
||||
|
||||
def test_web_root_requires_license_gate_before_static_app(monkeypatch):
|
||||
_license_missing(monkeypatch)
|
||||
handler = _DummyHandler()
|
||||
runner = _DummyRunner()
|
||||
u = SimpleNamespace(path="/", query="")
|
||||
|
||||
routes.handle_get(handler, u, runner, "token")
|
||||
|
||||
html = handler.wfile.getvalue().decode("utf-8")
|
||||
assert handler.response_status == 200
|
||||
assert "卡密验证" in html
|
||||
assert "输入卡密" in html
|
||||
assert "window.location.reload" in html
|
||||
assert handler.static_calls == []
|
||||
|
||||
|
||||
def test_web_root_enters_static_app_when_license_exists(monkeypatch):
|
||||
_license_ok(monkeypatch)
|
||||
handler = _DummyHandler()
|
||||
runner = _DummyRunner()
|
||||
u = SimpleNamespace(path="/", query="")
|
||||
|
||||
routes.handle_get(handler, u, runner, "token")
|
||||
|
||||
assert handler.static_calls == ["/"]
|
||||
assert handler.wfile.getvalue() == b""
|
||||
|
||||
|
||||
def test_license_install_route_accepts_code(monkeypatch):
|
||||
calls = {}
|
||||
|
||||
@@ -224,6 +305,26 @@ def test_license_install_route_rejects_empty_code(monkeypatch):
|
||||
assert obj["error"] == "missing license_text"
|
||||
|
||||
|
||||
def test_runtime_actions_require_license_but_license_route_stays_available(monkeypatch):
|
||||
calls = []
|
||||
|
||||
def fake_install(*_args, **_kwargs):
|
||||
calls.append("install")
|
||||
return SimpleNamespace(ok=False, reason="bad", message="bad license")
|
||||
|
||||
monkeypatch.setattr(routes, "install_license_or_activate", fake_install)
|
||||
|
||||
status, obj = _post_without_license("/api/start-run", {}, monkeypatch)
|
||||
assert status == 403
|
||||
assert obj["error"] == "license_required"
|
||||
assert obj["reason"] == "missing"
|
||||
|
||||
status, obj = _post_without_license("/api/license", {"license_text": "DG-DEMO"}, monkeypatch)
|
||||
assert status == 400
|
||||
assert obj["reason"] == "bad"
|
||||
assert calls == ["install"]
|
||||
|
||||
|
||||
def test_config_accepts_fudai_detail_v2_ocr_switches_and_ui_mode(monkeypatch):
|
||||
written = {}
|
||||
|
||||
@@ -518,6 +619,27 @@ def test_rejects_non_local_get_api_requests(monkeypatch):
|
||||
assert obj.get("error") == "Local access only"
|
||||
|
||||
|
||||
def test_license_gate_html_has_security_headers(monkeypatch):
|
||||
monkeypatch.setattr(routes, "check_license", lambda: SimpleNamespace(ok=False))
|
||||
monkeypatch.setattr(
|
||||
routes,
|
||||
"render_license_gate_html",
|
||||
lambda token: "<!doctype html><html><body>gate</body></html>", # noqa: ARG005
|
||||
)
|
||||
handler = _DummyHandler()
|
||||
runner = _DummyRunner()
|
||||
u = SimpleNamespace(path="/", query="")
|
||||
|
||||
routes.handle_get(handler, u, runner, "token")
|
||||
|
||||
headers = dict(handler.response_headers)
|
||||
assert handler.response_status == 200
|
||||
assert headers["X-Content-Type-Options"] == "nosniff"
|
||||
assert headers["Referrer-Policy"] == "no-referrer"
|
||||
assert headers["X-Frame-Options"] == "DENY"
|
||||
assert "Content-Security-Policy" in headers
|
||||
|
||||
|
||||
def test_rejects_non_local_pic_requests(monkeypatch):
|
||||
handler = _DummyHandler()
|
||||
handler.client_address = ("192.168.1.50", 55555)
|
||||
|
||||
@@ -441,6 +441,18 @@ class TestDiscoverAdbDevices:
|
||||
assert len(devs) == 1
|
||||
assert devs[0].target == "192.168.10.66:40075"
|
||||
|
||||
def test_connected_wifi_devices_are_scan_fallback(self):
|
||||
with patch.object(scan, "discover_mdns_targets", return_value=[]), \
|
||||
patch.object(scan, "discover_connected_wifi_targets", return_value=[("192.168.10.105", 46107)]), \
|
||||
patch.object(scan, "get_local_subnets", return_value=["192.168.10.0/30"]), \
|
||||
patch.object(scan, "scan_open_ports", return_value=[]), \
|
||||
patch.object(scan, "verify_adb_target", return_value=("connected", "already connected")), \
|
||||
patch.object(scan, "query_device_model", return_value="PEPM00"):
|
||||
devs = scan.discover_adb_devices("/adb")
|
||||
|
||||
assert len(devs) == 1
|
||||
assert devs[0].target == "192.168.10.105:46107"
|
||||
|
||||
def test_returns_devs_with_correct_ports(self):
|
||||
"""两个 (ip, port) 分别返回各自端口的 DiscoveredDevice。"""
|
||||
with patch.object(
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from gui.components.wifi_adb_scan_dialog import split_target_for_fields
|
||||
|
||||
|
||||
def test_split_target_for_fields_preserves_random_wireless_port():
|
||||
assert split_target_for_fields("192.168.10.105:36493") == (
|
||||
"192.168.10.105",
|
||||
"36493",
|
||||
)
|
||||
|
||||
|
||||
def test_split_target_for_fields_keeps_plain_ip_unchanged():
|
||||
assert split_target_for_fields("192.168.10.105") == ("192.168.10.105", "")
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
param(
|
||||
[string]$Version = "",
|
||||
[string]$DistDir = "",
|
||||
[string]$Installer = "",
|
||||
[string]$WorkRoot = "",
|
||||
[int]$WebPort = 18080,
|
||||
[int]$WebStartupTimeoutSeconds = 45,
|
||||
[int]$DashboardStartupSeconds = 8
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Resolve-FullPath([string]$PathText) {
|
||||
if ([System.IO.Path]::IsPathRooted($PathText)) {
|
||||
return [System.IO.Path]::GetFullPath($PathText)
|
||||
}
|
||||
return [System.IO.Path]::GetFullPath((Join-Path $Root $PathText))
|
||||
}
|
||||
|
||||
function Assert-UnderDirectory([string]$Child, [string]$Parent, [string]$Label) {
|
||||
$childFull = [System.IO.Path]::GetFullPath($Child).TrimEnd('\', '/')
|
||||
$parentFull = [System.IO.Path]::GetFullPath($Parent).TrimEnd('\', '/')
|
||||
if (-not $childFull.StartsWith($parentFull, [System.StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw "$Label must be under $parentFull, got $childFull"
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-FileExists([string]$PathText, [string]$Label) {
|
||||
if (-not (Test-Path -LiteralPath $PathText -PathType Leaf)) {
|
||||
throw "Missing $Label`: $PathText"
|
||||
}
|
||||
}
|
||||
|
||||
function Assert-DirExists([string]$PathText, [string]$Label) {
|
||||
if (-not (Test-Path -LiteralPath $PathText -PathType Container)) {
|
||||
throw "Missing $Label`: $PathText"
|
||||
}
|
||||
}
|
||||
|
||||
function ConvertTo-ProcessArgument([string]$Arg) {
|
||||
if ($Arg -notmatch '[\s"]') {
|
||||
return $Arg
|
||||
}
|
||||
return '"' + ($Arg -replace '\\(?=\\*")', '$0$0' -replace '"', '\"') + '"'
|
||||
}
|
||||
|
||||
function Invoke-CheckedProcess([string]$FilePath, [string[]]$Arguments, [string]$Label, [string]$WorkingDirectory = "") {
|
||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
||||
$psi.FileName = $FilePath
|
||||
$psi.Arguments = (($Arguments | ForEach-Object { ConvertTo-ProcessArgument $_ }) -join " ")
|
||||
if ($WorkingDirectory) {
|
||||
$psi.WorkingDirectory = $WorkingDirectory
|
||||
}
|
||||
$psi.UseShellExecute = $false
|
||||
$psi.RedirectStandardOutput = $true
|
||||
$psi.RedirectStandardError = $true
|
||||
$proc = [System.Diagnostics.Process]::Start($psi)
|
||||
$stdout = $proc.StandardOutput.ReadToEnd()
|
||||
$stderr = $proc.StandardError.ReadToEnd()
|
||||
$proc.WaitForExit()
|
||||
if ($proc.ExitCode -ne 0) {
|
||||
$detail = (($stderr + " " + $stdout) -replace "\s+", " ").Trim()
|
||||
throw "$Label failed with exit code $($proc.ExitCode): $detail"
|
||||
}
|
||||
return $stdout
|
||||
}
|
||||
|
||||
function Invoke-ProcessCapture([string]$FilePath, [string[]]$Arguments, [string]$WorkingDirectory = "") {
|
||||
$psi = New-Object System.Diagnostics.ProcessStartInfo
|
||||
$psi.FileName = $FilePath
|
||||
$psi.Arguments = (($Arguments | ForEach-Object { ConvertTo-ProcessArgument $_ }) -join " ")
|
||||
if ($WorkingDirectory) {
|
||||
$psi.WorkingDirectory = $WorkingDirectory
|
||||
}
|
||||
$psi.UseShellExecute = $false
|
||||
$psi.RedirectStandardOutput = $true
|
||||
$psi.RedirectStandardError = $true
|
||||
$proc = [System.Diagnostics.Process]::Start($psi)
|
||||
$stdout = $proc.StandardOutput.ReadToEnd()
|
||||
$stderr = $proc.StandardError.ReadToEnd()
|
||||
$proc.WaitForExit()
|
||||
return [pscustomobject]@{
|
||||
ExitCode = $proc.ExitCode
|
||||
Stdout = $stdout
|
||||
Stderr = $stderr
|
||||
}
|
||||
}
|
||||
|
||||
$Root = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\.."))
|
||||
Set-Location $Root
|
||||
|
||||
if (-not $Version) {
|
||||
$Version = (python -c "from douyin.core.version import APP_VERSION; print(str(APP_VERSION).lstrip('Vv'))").Trim()
|
||||
}
|
||||
if (-not $DistDir) {
|
||||
$DistDir = Join-Path $Root "dist\DouyinGuaji-$Version"
|
||||
}
|
||||
if (-not $Installer) {
|
||||
$Installer = Join-Path $Root "dist\installer\DouyinGuaji-$Version-Setup.exe"
|
||||
}
|
||||
if (-not $WorkRoot) {
|
||||
$WorkRoot = Join-Path $Root "artifacts\fresh_install_ci"
|
||||
}
|
||||
|
||||
$DistDir = Resolve-FullPath $DistDir
|
||||
$Installer = Resolve-FullPath $Installer
|
||||
$WorkRoot = Resolve-FullPath $WorkRoot
|
||||
$ArtifactsRoot = Resolve-FullPath "artifacts"
|
||||
Assert-UnderDirectory $WorkRoot $ArtifactsRoot "WorkRoot"
|
||||
|
||||
Assert-DirExists $DistDir "portable dist"
|
||||
Assert-FileExists $Installer "installer"
|
||||
|
||||
python -m tools.distribution_manifest $DistDir
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "distribution manifest check failed"
|
||||
}
|
||||
|
||||
python -m tools.exe_packing $DistDir --smoke-only
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "exe smoke check failed"
|
||||
}
|
||||
|
||||
if (Test-Path -LiteralPath $WorkRoot) {
|
||||
Remove-Item -LiteralPath $WorkRoot -Recurse -Force
|
||||
}
|
||||
New-Item -ItemType Directory -Force $WorkRoot | Out-Null
|
||||
|
||||
$InstallDir = Join-Path $WorkRoot "DouyinGuajiApp"
|
||||
$InstallLog = Join-Path $WorkRoot "install.log"
|
||||
$InstallerHash = (Get-FileHash -LiteralPath $Installer -Algorithm SHA256).Hash
|
||||
$InstallArgs = @(
|
||||
"/VERYSILENT",
|
||||
"/SUPPRESSMSGBOXES",
|
||||
"/NORESTART",
|
||||
"/DIR=$InstallDir",
|
||||
"/LOG=$InstallLog"
|
||||
)
|
||||
$installProc = Start-Process -FilePath $Installer -ArgumentList $InstallArgs -Wait -PassThru
|
||||
if ($installProc.ExitCode -ne 0) {
|
||||
throw "installer exited with code $($installProc.ExitCode); log=$InstallLog"
|
||||
}
|
||||
|
||||
Assert-DirExists $InstallDir "installed app"
|
||||
Assert-FileExists (Join-Path $InstallDir "DouyinGuajiGUI.exe") "dashboard exe"
|
||||
Assert-FileExists (Join-Path $InstallDir "web_gui.exe") "web gui exe"
|
||||
Assert-FileExists (Join-Path $InstallDir "run_cli.exe") "cli exe"
|
||||
Assert-FileExists (Join-Path $InstallDir "config\config.json") "default runtime config"
|
||||
Assert-FileExists (Join-Path $InstallDir "platform-tools\adb.exe") "bundled adb"
|
||||
Assert-FileExists (Join-Path $InstallDir "platform-tools\AdbWinApi.dll") "ADB Win API"
|
||||
Assert-FileExists (Join-Path $InstallDir "platform-tools\AdbWinUsbApi.dll") "ADB USB API"
|
||||
Assert-FileExists (Join-Path $InstallDir "android-tools\ADBKeyboard.apk") "ADBKeyboard helper"
|
||||
|
||||
$adbVersion = Invoke-CheckedProcess `
|
||||
-FilePath (Join-Path $InstallDir "platform-tools\adb.exe") `
|
||||
-Arguments @("version") `
|
||||
-Label "bundled adb version" `
|
||||
-WorkingDirectory $InstallDir
|
||||
|
||||
$cliProbe = Invoke-ProcessCapture `
|
||||
-FilePath (Join-Path $InstallDir "run_cli.exe") `
|
||||
-Arguments @("--help") `
|
||||
-WorkingDirectory $InstallDir
|
||||
if ($cliProbe.ExitCode -ne 86 -or (($cliProbe.Stdout + $cliProbe.Stderr) -notmatch "missing|缺少")) {
|
||||
throw "run_cli --help should fail closed without license, got exit=$($cliProbe.ExitCode)"
|
||||
}
|
||||
|
||||
$licensePath = Join-Path $InstallDir "license.dat"
|
||||
if (Test-Path -LiteralPath $licensePath) {
|
||||
throw "fresh install unexpectedly contains license.dat"
|
||||
}
|
||||
|
||||
$webLog = Join-Path $WorkRoot "web_gui.stdout.log"
|
||||
$webErr = Join-Path $WorkRoot "web_gui.stderr.log"
|
||||
$oldPort = $env:PORT
|
||||
$oldDisableUpdate = $env:DOUYIN_DISABLE_AUTO_UPDATE
|
||||
$oldLicenseRequired = $env:DOUYIN_LICENSE_REQUIRED
|
||||
$oldSkipOcr = $env:SKIP_OCR_INIT
|
||||
$webProc = $null
|
||||
try {
|
||||
$env:PORT = [string]$WebPort
|
||||
$env:DOUYIN_DISABLE_AUTO_UPDATE = "1"
|
||||
$env:DOUYIN_LICENSE_REQUIRED = "1"
|
||||
$env:SKIP_OCR_INIT = "1"
|
||||
$webProc = Start-Process `
|
||||
-FilePath (Join-Path $InstallDir "web_gui.exe") `
|
||||
-WorkingDirectory $InstallDir `
|
||||
-RedirectStandardOutput $webLog `
|
||||
-RedirectStandardError $webErr `
|
||||
-WindowStyle Hidden `
|
||||
-PassThru
|
||||
|
||||
$rootResponse = $null
|
||||
$deadline = (Get-Date).AddSeconds($WebStartupTimeoutSeconds)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
if ($webProc.HasExited) {
|
||||
throw "web_gui exited early with code $($webProc.ExitCode); stdout=$webLog stderr=$webErr"
|
||||
}
|
||||
try {
|
||||
$rootResponse = Invoke-WebRequest -Uri "http://127.0.0.1:$WebPort/" -UseBasicParsing -TimeoutSec 2
|
||||
break
|
||||
} catch {
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
}
|
||||
if ($null -eq $rootResponse) {
|
||||
throw "web_gui did not become ready on port $WebPort"
|
||||
}
|
||||
if ([int]$rootResponse.StatusCode -ne 200) {
|
||||
throw "web root returned status $($rootResponse.StatusCode)"
|
||||
}
|
||||
if (-not ($rootResponse.Content.Contains("license-form") -and $rootResponse.Content.Contains("license-input"))) {
|
||||
throw "web root did not render the first-run license gate"
|
||||
}
|
||||
|
||||
$licenseStatus = Invoke-RestMethod -Uri "http://127.0.0.1:$WebPort/api/license" -TimeoutSec 10
|
||||
if ($licenseStatus.ok -ne $false -or "$($licenseStatus.reason)" -ne "missing") {
|
||||
throw "expected missing license status, got ok=$($licenseStatus.ok) reason=$($licenseStatus.reason)"
|
||||
}
|
||||
|
||||
$csrf = Invoke-RestMethod -Uri "http://127.0.0.1:$WebPort/api/csrf-token" -TimeoutSec 10
|
||||
$startRunStatus = $null
|
||||
$startRunBody = ""
|
||||
try {
|
||||
Invoke-RestMethod `
|
||||
-Uri "http://127.0.0.1:$WebPort/api/start-run" `
|
||||
-Method Post `
|
||||
-ContentType "application/json" `
|
||||
-Headers @{"X-CSRF-Token" = $csrf.token} `
|
||||
-Body "{}" `
|
||||
-TimeoutSec 10 | Out-Null
|
||||
throw "start-run unexpectedly succeeded without license"
|
||||
} catch {
|
||||
$startRunStatus = [int]$_.Exception.Response.StatusCode
|
||||
$startRunBody = $_.ErrorDetails.Message
|
||||
}
|
||||
if ($startRunStatus -ne 403 -or $startRunBody -notlike "*license_required*") {
|
||||
throw "expected /api/start-run 403 license_required, got status=$startRunStatus body=$startRunBody"
|
||||
}
|
||||
} finally {
|
||||
if ($webProc -and -not $webProc.HasExited) {
|
||||
Stop-Process -Id $webProc.Id -Force
|
||||
}
|
||||
$env:PORT = $oldPort
|
||||
$env:DOUYIN_DISABLE_AUTO_UPDATE = $oldDisableUpdate
|
||||
$env:DOUYIN_LICENSE_REQUIRED = $oldLicenseRequired
|
||||
$env:SKIP_OCR_INIT = $oldSkipOcr
|
||||
}
|
||||
|
||||
$dashProc = $null
|
||||
try {
|
||||
$env:DOUYIN_DISABLE_AUTO_UPDATE = "1"
|
||||
$env:DOUYIN_LICENSE_REQUIRED = "1"
|
||||
$env:SKIP_OCR_INIT = "1"
|
||||
$dashProc = Start-Process `
|
||||
-FilePath (Join-Path $InstallDir "DouyinGuajiGUI.exe") `
|
||||
-WorkingDirectory $InstallDir `
|
||||
-WindowStyle Hidden `
|
||||
-PassThru
|
||||
Start-Sleep -Seconds $DashboardStartupSeconds
|
||||
if ($dashProc.HasExited) {
|
||||
throw "dashboard exited early with code $($dashProc.ExitCode)"
|
||||
}
|
||||
} finally {
|
||||
if ($dashProc -and -not $dashProc.HasExited) {
|
||||
Stop-Process -Id $dashProc.Id -Force
|
||||
}
|
||||
$env:DOUYIN_DISABLE_AUTO_UPDATE = $oldDisableUpdate
|
||||
$env:DOUYIN_LICENSE_REQUIRED = $oldLicenseRequired
|
||||
$env:SKIP_OCR_INIT = $oldSkipOcr
|
||||
}
|
||||
|
||||
$report = [ordered]@{
|
||||
ok = $true
|
||||
version = $Version
|
||||
installer = $Installer
|
||||
installer_sha256 = $InstallerHash
|
||||
install_dir = $InstallDir
|
||||
web_port = $WebPort
|
||||
checks = [ordered]@{
|
||||
distribution_manifest = "pass"
|
||||
exe_smoke = "pass"
|
||||
silent_install = "pass"
|
||||
bundled_config = "pass"
|
||||
bundled_adb = "pass"
|
||||
adb_version = ($adbVersion -split "`r?`n" | Select-Object -First 1)
|
||||
cli_fails_closed_without_license = "pass"
|
||||
web_license_gate = "pass"
|
||||
web_runtime_requires_license = "pass"
|
||||
dashboard_waits_for_license = "pass"
|
||||
}
|
||||
}
|
||||
$reportPath = Join-Path $WorkRoot "fresh_install_report.json"
|
||||
$report | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath $reportPath -Encoding UTF8
|
||||
Write-Host "[FRESH-INSTALL] PASS version=$Version report=$reportPath"
|
||||
@@ -33,7 +33,6 @@ FORBIDDEN_PREFIXES = (
|
||||
)
|
||||
|
||||
FORBIDDEN_EXACT = {
|
||||
"config/config.json",
|
||||
"douyin_guaji.code-workspace",
|
||||
"license.dat",
|
||||
"pyproject.toml",
|
||||
@@ -46,15 +45,22 @@ FORBIDDEN_EXACT = {
|
||||
|
||||
ALLOWED_ASSET_FILES = {
|
||||
"assets/coupon.png",
|
||||
"assets/desktop.png",
|
||||
"assets/fav.png",
|
||||
"assets/fudai.png",
|
||||
"assets/fudai_icon_countdown_v20260618.png",
|
||||
"assets/fudai_icon_pending_v20260618.png",
|
||||
"assets/fudai_icon_purple_left_v20260618.png",
|
||||
"assets/fudai_icon_red_left_v20260618.png",
|
||||
"assets/fudai_task_count_digit_1.png",
|
||||
"assets/fudai_task_count_digit_2.png",
|
||||
"assets/fudai_task_count_v2_one_task.png",
|
||||
"assets/fudai_task_count_v2_two_task.png",
|
||||
"assets/fudai_task_status_dacheng_shape.png",
|
||||
"assets/like.png",
|
||||
"assets/quan.png",
|
||||
"assets/x.png",
|
||||
"assets/xiangqing.png",
|
||||
"assets/xin.png",
|
||||
}
|
||||
|
||||
@@ -76,6 +82,33 @@ ALLOWED_WEBUI_SUFFIXES = {
|
||||
".js",
|
||||
}
|
||||
|
||||
ALLOWED_PLATFORM_TOOLS_FILES = {
|
||||
"platform-tools/adb.exe",
|
||||
"platform-tools/adbwinapi.dll",
|
||||
"platform-tools/adbwinusbapi.dll",
|
||||
"platform-tools/notice.txt",
|
||||
"platform-tools/source.properties",
|
||||
}
|
||||
|
||||
ALLOWED_ANDROID_TOOLS_FILES = {
|
||||
"android-tools/adbkeyboard.apk",
|
||||
}
|
||||
|
||||
ALLOWED_DRIVER_PREFIXES = (
|
||||
"drivers/hisuite/",
|
||||
)
|
||||
|
||||
ALLOWED_DRIVER_SUFFIXES = {
|
||||
".exe",
|
||||
".msi",
|
||||
".txt",
|
||||
}
|
||||
|
||||
ALLOWED_CONFIG_FILES = {
|
||||
"config/readme.md",
|
||||
"config/config.json",
|
||||
}
|
||||
|
||||
FORBIDDEN_SUFFIXES = (
|
||||
".py",
|
||||
".pyc",
|
||||
@@ -150,6 +183,16 @@ def is_forbidden_distribution_entry(entry: str, *, allow_license: bool = False)
|
||||
if not any(lower.startswith(prefix) for prefix in ALLOWED_WEBUI_DIRS):
|
||||
return True
|
||||
return Path(lower).suffix not in ALLOWED_WEBUI_SUFFIXES
|
||||
if lower.startswith("platform-tools/"):
|
||||
return lower not in ALLOWED_PLATFORM_TOOLS_FILES
|
||||
if lower.startswith("android-tools/"):
|
||||
return lower not in ALLOWED_ANDROID_TOOLS_FILES
|
||||
if any(lower.startswith(prefix) for prefix in ALLOWED_DRIVER_PREFIXES):
|
||||
return Path(lower).suffix not in ALLOWED_DRIVER_SUFFIXES
|
||||
if lower.startswith("drivers/"):
|
||||
return True
|
||||
if lower.startswith("config/"):
|
||||
return lower not in ALLOWED_CONFIG_FILES
|
||||
if any(lower.startswith(prefix.lower()) for prefix in FORBIDDEN_PREFIXES):
|
||||
return True
|
||||
return any(lower.endswith(suffix) for suffix in FORBIDDEN_SUFFIXES)
|
||||
@@ -173,10 +216,24 @@ def find_missing_required_runtime_entries(entries: list[str]) -> list[str]:
|
||||
for required in ("DouyinGuajiGUI.exe", "web_gui.exe", "run_cli.exe"):
|
||||
if required.lower() not in normalized:
|
||||
missing.append(required)
|
||||
for required in (
|
||||
"platform-tools/adb.exe",
|
||||
"platform-tools/AdbWinApi.dll",
|
||||
"platform-tools/AdbWinUsbApi.dll",
|
||||
"android-tools/ADBKeyboard.apk",
|
||||
):
|
||||
if required.lower() not in normalized:
|
||||
missing.append(required)
|
||||
if not any(entry.startswith("_internal/") and entry.startswith("_internal/python") and entry.endswith(".dll") for entry in normalized):
|
||||
missing.append("_internal/python*.dll")
|
||||
if "_internal/base_library.zip" not in normalized:
|
||||
missing.append("_internal/base_library.zip")
|
||||
for required in ("_internal/paddlex/.version",):
|
||||
if required.lower() not in normalized:
|
||||
missing.append(required)
|
||||
for prefix in ("_internal/paddle/",):
|
||||
if not any(entry.startswith(prefix) for entry in normalized):
|
||||
missing.append(prefix + "*")
|
||||
return missing
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import shutil
|
||||
import sys
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def sha256_file(path: Path) -> str:
|
||||
h = hashlib.sha256()
|
||||
with path.open("rb") as f:
|
||||
for chunk in iter(lambda: f.read(1024 * 1024), b""):
|
||||
h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def iter_files(root: Path) -> dict[str, Path]:
|
||||
result: dict[str, Path] = {}
|
||||
for path in root.rglob("*"):
|
||||
if path.is_file():
|
||||
result[path.relative_to(root).as_posix()] = path
|
||||
return result
|
||||
|
||||
|
||||
def build_delta_manifest(old_root: Path, new_root: Path, from_version: str, to_version: str) -> dict[str, Any]:
|
||||
old_files = iter_files(old_root)
|
||||
new_files = iter_files(new_root)
|
||||
changed: list[dict[str, Any]] = []
|
||||
for rel, new_path in sorted(new_files.items()):
|
||||
new_hash = sha256_file(new_path)
|
||||
old_path = old_files.get(rel)
|
||||
if old_path is not None and sha256_file(old_path) == new_hash:
|
||||
continue
|
||||
changed.append(
|
||||
{
|
||||
"path": rel,
|
||||
"sha256": new_hash,
|
||||
"size": new_path.stat().st_size,
|
||||
}
|
||||
)
|
||||
deleted = sorted(set(old_files) - set(new_files))
|
||||
return {
|
||||
"schema": 1,
|
||||
"from_version": from_version.strip().lstrip("Vv"),
|
||||
"to_version": to_version.strip().lstrip("Vv"),
|
||||
"files": changed,
|
||||
"delete": deleted,
|
||||
}
|
||||
|
||||
|
||||
def create_delta_zip(old_root: Path, new_root: Path, out_path: Path, from_version: str, to_version: str) -> dict[str, Any]:
|
||||
old_root = old_root.resolve()
|
||||
new_root = new_root.resolve()
|
||||
if not old_root.is_dir():
|
||||
raise FileNotFoundError(f"old root not found: {old_root}")
|
||||
if not new_root.is_dir():
|
||||
raise FileNotFoundError(f"new root not found: {new_root}")
|
||||
manifest = build_delta_manifest(old_root, new_root, from_version, to_version)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = out_path.with_suffix(out_path.suffix + ".tmp")
|
||||
if tmp.exists():
|
||||
tmp.unlink()
|
||||
with zipfile.ZipFile(tmp, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
|
||||
zf.writestr(
|
||||
"manifest.json",
|
||||
json.dumps(manifest, ensure_ascii=False, indent=2).encode("utf-8"),
|
||||
)
|
||||
for item in manifest["files"]:
|
||||
rel = item["path"]
|
||||
zf.write(new_root / rel, f"files/{rel}")
|
||||
if out_path.exists():
|
||||
out_path.unlink()
|
||||
tmp.replace(out_path)
|
||||
manifest["delta_sha256"] = sha256_file(out_path)
|
||||
manifest["delta_size"] = out_path.stat().st_size
|
||||
return manifest
|
||||
|
||||
|
||||
def create_delta_zips(
|
||||
old_roots: list[Path],
|
||||
new_root: Path,
|
||||
out_dir: Path,
|
||||
*,
|
||||
to_version: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
manifests: list[dict[str, Any]] = []
|
||||
for old_root in old_roots:
|
||||
from_version = infer_dist_version(old_root)
|
||||
out_path = out_dir / f"DouyinGuaji-{from_version}_to_{to_version.strip().lstrip('Vv')}_delta.zip"
|
||||
manifests.append(
|
||||
create_delta_zip(
|
||||
old_root,
|
||||
new_root,
|
||||
out_path,
|
||||
from_version,
|
||||
to_version,
|
||||
)
|
||||
)
|
||||
return manifests
|
||||
|
||||
|
||||
def infer_dist_version(path: Path) -> str:
|
||||
name = path.name
|
||||
for prefix in ("DouyinGuaji-", "douyin-guaji-", "douyin_guaji-"):
|
||||
if name.startswith(prefix):
|
||||
candidate = name[len(prefix):].strip().lstrip("Vv")
|
||||
if candidate:
|
||||
return candidate
|
||||
raise ValueError(f"cannot infer version from directory name: {path}")
|
||||
|
||||
|
||||
def apply_delta_zip(delta_path: Path, target_root: Path) -> dict[str, Any]:
|
||||
target_root = target_root.resolve()
|
||||
with zipfile.ZipFile(delta_path) as zf:
|
||||
manifest = json.loads(zf.read("manifest.json").decode("utf-8-sig"))
|
||||
for rel in manifest.get("delete") or []:
|
||||
target = (target_root / str(rel)).resolve()
|
||||
if target == target_root or target_root not in target.parents:
|
||||
raise ValueError(f"unsafe delete path: {rel}")
|
||||
if target.is_dir():
|
||||
shutil.rmtree(target)
|
||||
elif target.exists():
|
||||
target.unlink()
|
||||
for item in manifest.get("files") or []:
|
||||
rel = str(item["path"])
|
||||
target = (target_root / rel).resolve()
|
||||
if target_root not in target.parents:
|
||||
raise ValueError(f"unsafe write path: {rel}")
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
data = zf.read(f"files/{rel}")
|
||||
expected = str(item["sha256"]).lower()
|
||||
actual = hashlib.sha256(data).hexdigest()
|
||||
if actual != expected:
|
||||
raise ValueError(f"hash mismatch in delta file: {rel}")
|
||||
target.write_bytes(data)
|
||||
return manifest
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Build or apply DouyinGuaji delta update packages.")
|
||||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||||
build = sub.add_parser("build", help="Create a delta zip from two portable distributions.")
|
||||
build.add_argument("--old", required=True, type=Path)
|
||||
build.add_argument("--new", required=True, type=Path)
|
||||
build.add_argument("--out", required=True, type=Path)
|
||||
build.add_argument("--from-version", required=True)
|
||||
build.add_argument("--to-version", required=True)
|
||||
build_many = sub.add_parser("build-many", help="Create cumulative delta zips from multiple old distributions to one new distribution.")
|
||||
build_many.add_argument("--old", required=True, type=Path, nargs="+")
|
||||
build_many.add_argument("--new", required=True, type=Path)
|
||||
build_many.add_argument("--out-dir", required=True, type=Path)
|
||||
build_many.add_argument("--to-version", required=True)
|
||||
apply = sub.add_parser("apply", help="Apply a delta zip to a target directory for local verification.")
|
||||
apply.add_argument("--delta", required=True, type=Path)
|
||||
apply.add_argument("--target", required=True, type=Path)
|
||||
args = parser.parse_args(argv)
|
||||
if args.cmd == "build":
|
||||
manifest = create_delta_zip(args.old, args.new, args.out, args.from_version, args.to_version)
|
||||
print(json.dumps(manifest, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
if args.cmd == "build-many":
|
||||
manifests = create_delta_zips(args.old, args.new, args.out_dir, to_version=args.to_version)
|
||||
print(json.dumps({"deltas": manifests}, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
manifest = apply_delta_zip(args.delta, args.target)
|
||||
print(json.dumps({"ok": True, "from_version": manifest.get("from_version"), "to_version": manifest.get("to_version")}, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
Reference in new issue
Block a user