25 Commits
Author SHA1 Message Date
Your Name 1202dffa32 chore(release): bump version to V3.3.11
Windows Package CI / package-fresh-install (push) Has been cancelled
2026-06-29 02:19:44 +08:00
Your Name e24b0bdd1e fix(updater): use visible full installer by default 2026-06-29 02:19:14 +08:00
Your Name 1c686a6595 chore(release): bump version to V3.3.10 2026-06-29 01:31:57 +08:00
Your Name 9c8a037c4e fix(logs): allow larger diagnostic uploads 2026-06-29 01:07:50 +08:00
Your Name 94e0c6432f fix(fudai): stabilize reservation fansclub prejoin 2026-06-29 01:01:48 +08:00
Your Name 51c1c2da39 fix(dashboard): refresh live screenshot and package driver helper 2026-06-29 00:53:50 +08:00
Your Name 60306dd4e0 fix(screenshot): recover adb after empty screencap output
Windows Package CI / package-fresh-install (push) Waiting to run
2026-06-29 00:35:07 +08:00
Your Name 329b7756f4 fix(gui): 增强 WiFi ADB 发现和更新进度
Windows Package CI / package-fresh-install (push) Waiting to run
2026-06-29 00:15:13 +08:00
Your Name 16019ee649 fix(gui): 自动恢复 ADB server 端口
Windows Package CI / package-fresh-install (push) Waiting to run
2026-06-28 23:57:10 +08:00
Your Name 60332db82b fix(gui): 保留 WiFi ADB 随机端口
Windows Package CI / package-fresh-install (push) Waiting to run
2026-06-28 23:44:14 +08:00
Your Name c2cbee9592 Polish dashboard table styling 2026-06-28 23:30:09 +08:00
Your Name ab37165baf Improve delta update failure logging
Windows Package CI / package-fresh-install (push) Waiting to run
2026-06-28 22:16:12 +08:00
Your Name c0cb274728 Improve dashboard diagnostics and update UI 2026-06-28 21:26:48 +08:00
Your Name a870e0cbf9 fix: fall back to full installer after delta update failure
Windows Package CI / package-fresh-install (push) Waiting to run
2026-06-28 18:41:40 +08:00
Your Name 13aa60c06a feat: add manual update check button 2026-06-28 14:22:35 +08:00
Your Name f010853b97 fix: harden screenshot capture and diagnostics 2026-06-28 13:44:40 +08:00
Your Name ee3424cd9e fix: harden license server and web gui security 2026-06-28 09:24:22 +08:00
Your Name 7c6189fd5e docs: add full security audit 2026-06-28 09:12:31 +08:00
Your Name 7745f9a57f ci: add fresh install package smoke test
Windows Package CI / package-fresh-install (push) Waiting to run
2026-06-28 09:03:13 +08:00
Your Name f5a77867ee fix: require license gate before gui entry 2026-06-28 08:50:05 +08:00
Your Name 407c3b37c2 fix: allow first-run license activation 2026-06-28 07:55:02 +08:00
Your Name e315aaf80b feat: support delta update packages 2026-06-28 00:32:01 +08:00
Your Name 7234bf0cac style: unify dashboard scrollbars 2026-06-27 23:40:25 +08:00
Your Name 39996405d5 fix: require license for dashboard gui 2026-06-27 23:35:24 +08:00
Your Name 383c947a03 style: refine dashboard toolbar and license feedback 2026-06-27 23:25:47 +08:00
57 changed files with 5939 additions and 315 deletions

No files matched your search

+87
View File
@@ -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
+39
View File
@@ -15,6 +15,45 @@
## [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
+501
View File
@@ -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/
@@ -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
+2 -2
View File
@@ -10,8 +10,8 @@
from typing import Optional
APP_NAME = "douyin_guaji"
APP_VERSION = "V3.3.5"
APP_BUILD_DATE = "2026-06-27"
APP_VERSION = "V3.3.11"
APP_BUILD_DATE = "2026-06-29"
# 兼容旧代码与测试:提供 VERSION / RELEASE_DATE 别名
# tests 期望: from version import VERSION, RELEASE_DATE, print_version_banner
+1
View File
@@ -0,0 +1 @@
"""Diagnostic helpers for packaged clients."""
+346
View File
@@ -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
+2 -2
View File
@@ -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,7 +30,13 @@ 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:
raw = getattr(analyser, attr_name, default_seconds)
if not isinstance(raw, (int, float, str)):
@@ -38,7 +44,7 @@ def _fast_delay(analyser: Any, attr_name: str, default_seconds: float) -> None:
seconds = float(raw or default_seconds)
except Exception:
seconds = default_seconds
seconds = max(0.0, min(seconds, 3.0))
seconds = max(float(min_seconds or 0.0), min(seconds, 3.0))
try:
analyser.operation.delay(seconds)
except Exception:
@@ -77,7 +83,12 @@ def handle_reservation_prejoin_fansclub(
pass
return False
_fast_delay(analyser, "reservation_prejoin_fansclub_participate_wait_seconds", 1.2)
_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)
@@ -121,7 +132,12 @@ def handle_reservation_prejoin_fansclub(
pass
return False
_fast_delay(analyser, "reservation_prejoin_fansclub_confirm_wait_seconds", 1.6)
_fast_delay(
analyser,
"reservation_prejoin_fansclub_confirm_wait_seconds",
1.6,
min_seconds=1.2,
)
try:
analyser.click(*DETAIL_OUTSIDE_CLICK)
+5 -1
View File
@@ -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
View File
@@ -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)
+201
View File
@@ -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 ""))
+7 -6
View File
@@ -298,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:
# 如果断开的就是上次记住的设备,清掉记录避免下次启动徒劳重试
@@ -466,7 +467,7 @@ def open_wifi_adb_dialog(
(
("连接", connect_wifi, "primary", 124),
("断开连接", disconnect_wifi, "soft", 132),
("扫描局域网", lambda: open_scan_dialog(dialog, adb_exe, ip_var, on_line, refresh_device_lists), "soft", 142),
("扫描局域网", lambda: open_scan_dialog(dialog, adb_exe, ip_var, on_line, refresh_device_lists, port_var), "soft", 142),
),
columns=1,
)
+19 -2
View File
@@ -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, ""
+432 -41
View File
@@ -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,11 +35,15 @@ 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, field_shell, 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)
@@ -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,6 +85,23 @@ 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)
@@ -81,6 +121,12 @@ class DashboardApp:
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,
@@ -98,35 +144,53 @@ class DashboardApp:
font=theme.FONT_SMALL,
).pack(side="right", padx=(0, 8))
tool_row = tk.Frame(top, bg=theme.SURFACE)
tool_row.pack(fill="x", padx=20, pady=(0, 10))
for col in (1, 6):
tool_row.grid_columnconfigure(col, weight=1)
ttk.Label(tool_row, text="设备:", background=theme.SURFACE, foreground=theme.MUTED, font=("Microsoft YaHei UI", 13, "bold")).grid(row=0, column=0, sticky="w")
self.device_combo = ttk.Combobox(tool_row, textvariable=self.device_var, values=[], width=44, state="readonly")
self.device_combo.grid(row=0, column=1, sticky="ew", padx=(8, 18), pady=(0, 10))
button(tool_row, "刷新设备", self.refresh_devices, width=150).grid(row=0, column=2, sticky="e", padx=5, pady=(0, 10))
self.scan_button = button(tool_row, "扫描 WiFi", self.scan_wifi, width=136)
self.scan_button.grid(row=0, column=3, sticky="e", padx=5, pady=(0, 10))
button(tool_row, "WiFi ADB", self.open_wifi_adb, width=132).grid(row=0, column=4, sticky="e", padx=5, pady=(0, 10))
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)
y_shell = field_shell(tool_row, "Y偏移")
y_shell.grid(row=1, column=0, columnspan=2, sticky="ew", pady=(0, 2), padx=(0, 18))
y_entry = tk.Entry(
y_shell,
textvariable=self.y_var,
width=12,
bg=theme.SURFACE_ALT,
fg=theme.TEXT,
insertbackground=theme.TEAL,
relief="flat",
bd=0,
font=theme.FONT_UI,
)
y_entry.pack(fill="x", padx=11, pady=(0, 9))
actions = tk.Frame(tool_row, bg=theme.SURFACE)
actions.grid(row=1, column=2, columnspan=4, sticky="w")
button(actions, "保存配置", self.save_config, width=150).pack(side="left", padx=(0, 10))
button(actions, "截图+OCR", self.screenshot_ocr, kind="primary", width=164).pack(side="left", padx=(0, 10))
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=20, pady=(6, 6))
@@ -139,12 +203,12 @@ class DashboardApp:
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))
@@ -196,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)
@@ -223,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("行为日志"),
}
@@ -309,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,
@@ -327,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,
@@ -339,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,
@@ -348,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),
@@ -363,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()
@@ -394,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)
@@ -421,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__":
+29 -1
View File
@@ -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))
+27 -7
View File
@@ -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:
+13 -3
View File
@@ -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
@@ -194,8 +197,8 @@ def build_home(parent: tk.Misc, data: DashboardData, ctx: PageContext) -> None:
body = tk.Frame(parent, bg=theme.BG)
body.pack(fill="both", expand=True, pady=(4, 0))
body.grid_columnconfigure(0, weight=3, minsize=540)
body.grid_columnconfigure(1, weight=2, minsize=380)
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)
@@ -216,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, "实时截图", max_size=(430, 620)).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]:
+29 -5
View File
@@ -66,20 +66,44 @@ def setup_styles(root) -> None:
style.configure("Dashboard.TNotebook.Tab", padding=(16, 9), font=FONT_SMALL)
style.configure(
"Treeview",
font=("Microsoft YaHei UI", 15),
rowheight=48,
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", 14, "bold"),
background="#eef4f7",
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",
+205 -33
View File
@@ -27,6 +27,9 @@ BUTTON_ICONS = {
"打开pic目录": "□",
"打开目录": "□",
"验证卡密": "✓",
"上传诊断日志": "⇧",
"上传日志": "⇧",
"检查更新": "↻",
"刷新状态": "⟳",
"保存日志配置": "✓",
"查看大图": "▢",
@@ -222,27 +225,128 @@ class RoundedNavButton(tk.Canvas):
self.text = _with_icon(text, NAV_ICONS.get(text))
self.command = command
self.active = active
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
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, 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:
for child in frame.winfo_children():
child.destroy()
@@ -361,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")
@@ -386,26 +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 = 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)
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=theme.SURFACE_ALT)
ybar = ttk.Scrollbar(table_wrap, orient="vertical", command=tree.yview)
xbar = ttk.Scrollbar(table_wrap, orient="horizontal", command=tree.xview)
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)
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
@@ -522,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=16, pady=(4, 16))
if image_path and image_path.exists():
try:
from PIL import Image, ImageTk
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
@@ -548,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)
+2 -2
View File
@@ -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
+120 -6
View File
@@ -7,12 +7,17 @@
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()
@@ -20,19 +25,80 @@ def _normalize_adb_path(adb: str | None) -> str:
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 可执行文件路径。"""
env_adb = _normalize_adb_path(os.environ.get("ADB_EXECUTABLE"))
if env_adb and os.path.exists(env_adb):
return os.path.abspath(env_adb)
return _prepare_adb_path(env_adb)
bundled_adb = path_config.find_bundled_adb()
if bundled_adb:
return bundled_adb
return _prepare_adb_path(bundled_adb)
adb = shutil.which("adb")
if adb:
return adb
return _prepare_adb_path(adb)
# 默认安装目录(本机开发/打包机常用 platform-tools 位置)
localapp = os.environ.get("LOCALAPPDATA") or ""
@@ -49,7 +115,7 @@ def find_adb_executable() -> str:
for p in candidates:
if os.path.exists(p):
return os.path.abspath(p)
return _prepare_adb_path(p)
return ""
@@ -66,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()))
+7 -1
View File
@@ -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 "")
+26 -6
View File
@@ -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]] = []
+2 -2
View File
@@ -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
View File
@@ -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()
+157
View File
@@ -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>"""
+21
View File
@@ -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)
+52
View File
@@ -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()
+7
View File
@@ -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()
+25 -3
View File
@@ -126,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`。
## 自动更新
@@ -137,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,然后退出旧进程执行差量更新或完整安装。
+302 -11
View File
@@ -6,15 +6,17 @@ 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
@@ -28,6 +30,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):
@@ -115,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:
@@ -243,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("/")
@@ -272,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
@@ -281,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,
@@ -302,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(
@@ -330,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">
@@ -425,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>
@@ -438,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>
@@ -464,13 +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.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=False)
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 = {}
@@ -511,6 +670,55 @@ 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):
@@ -641,7 +849,10 @@ document.getElementById("claim").addEventListener("click", async () => {{
}});
const data = await resp.json();
if (data.ok) {{
result.innerHTML = "兑换成功,卡密:<code>" + data.card_key + "</code>";
result.textContent = "兑换成功,卡密:";
const code = document.createElement("code");
code.textContent = data.card_key || "";
result.appendChild(code);
}} else {{
result.textContent = data.message || data.reason || "兑换失败";
}}
@@ -660,15 +871,20 @@ document.getElementById("claim").addEventListener("click", async () => {{
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")
@@ -686,6 +902,19 @@ document.getElementById("claim").addEventListener("click", async () => {{
)
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()
@@ -805,18 +1034,80 @@ document.getElementById("claim").addEventListener("click", async () => {{
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")
+295
View File
@@ -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
@@ -96,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
@@ -105,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:
@@ -171,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:
@@ -206,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
@@ -519,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",
@@ -527,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,
*,
@@ -556,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),
@@ -563,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(
@@ -573,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),
@@ -692,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,
+130 -46
View File
@@ -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]:
+26 -1
View File
@@ -71,9 +71,18 @@ dist\DouyinGuaji-<version>\
- `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
@@ -94,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/`、`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` 生成的明文包禁止分发。
+46 -3
View File
@@ -9,6 +9,7 @@ param(
[switch]$IncludeLicense,
[switch]$ReuseCache,
[string]$PlatformToolsDir = "",
[string]$HiSuiteInstallerPath = "",
[string]$UpxDir = ""
)
@@ -71,7 +72,23 @@ $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
@@ -167,8 +184,14 @@ 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
@@ -242,6 +265,26 @@ if (-not (Test-Path $AdbKeyboardApk)) {
}
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
View File
@@ -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.5"
version = "3.3.11"
description = "基于 ADB + OCR + 像素检测 + 模板匹配的抖音直播间福袋自动挂机工具"
readme = "README.md"
requires-python = ">=3.10"
+1
View File
@@ -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
View File
@@ -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
+38
View File
@@ -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
+63 -2
View File
@@ -15,7 +15,7 @@ def test_distribution_manifest_blocks_source_and_debug_artifacts():
"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",
@@ -31,7 +31,8 @@ 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
@@ -55,6 +56,8 @@ 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",
@@ -65,6 +68,7 @@ def test_distribution_manifest_blocks_project_native_binaries_outside_core_allow
"platform-tools/AdbWinUsbApi.dll",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"config/config.json",
"logs/.keep",
"pic/.keep",
"state/.keep",
@@ -87,6 +91,8 @@ 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",
@@ -102,6 +108,7 @@ def test_distribution_manifest_allows_expected_runtime_shape():
"platform-tools/source.properties",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"config/config.json",
"logs/.keep",
"pic/.keep",
"state/.keep",
@@ -126,6 +133,24 @@ def test_distribution_manifest_blocks_unexpected_platform_tools_files():
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
@@ -135,6 +160,8 @@ 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",
@@ -142,6 +169,7 @@ def test_distribution_manifest_can_allow_license_for_local_test_package():
"platform-tools/AdbWinUsbApi.dll",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"config/config.json",
"logs/.keep",
"pic/.keep",
"state/.keep",
@@ -167,6 +195,7 @@ def test_distribution_manifest_requires_python_runtime_dll():
"platform-tools/AdbWinUsbApi.dll",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"config/config.json",
"logs/.keep",
"pic/.keep",
"state/.keep",
@@ -186,9 +215,12 @@ def test_distribution_manifest_requires_bundled_android_runtime():
"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",
@@ -202,6 +234,32 @@ def test_distribution_manifest_requires_bundled_android_runtime():
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 [
@@ -210,6 +268,8 @@ 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",
@@ -220,6 +280,7 @@ def test_distribution_manifest_cli_passes_clean_tree(tmp_path):
"platform-tools/AdbWinUsbApi.dll",
"android-tools/ADBKeyboard.apk",
"config/README.md",
"config/config.json",
"logs/.keep",
"pic/.keep",
"state/.keep",
+13 -3
View File
@@ -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,7 +166,17 @@ 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)
+72
View File
@@ -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):
+153
View File
@@ -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 -&gt; 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
+170
View File
@@ -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
+16
View File
@@ -253,6 +253,22 @@ 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
+109 -1
View File
@@ -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
+94 -4
View File
@@ -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",
+67
View File
@@ -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()
+3
View File
@@ -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
+122
View File
@@ -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)
+12
View File
@@ -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(
+15
View File
@@ -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", "")
+295
View File
@@ -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"
+27 -1
View File
@@ -33,7 +33,6 @@ FORBIDDEN_PREFIXES = (
)
FORBIDDEN_EXACT = {
"config/config.json",
"douyin_guaji.code-workspace",
"license.dat",
"pyproject.toml",
@@ -95,6 +94,21 @@ 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",
@@ -173,6 +187,12 @@ def is_forbidden_distribution_entry(entry: str, *, allow_license: bool = False)
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)
@@ -208,6 +228,12 @@ def find_missing_required_runtime_entries(entries: list[str]) -> list[str]:
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
+175
View File
@@ -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:]))