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
Your Name 63c726ddea build: include android runtime helpers 2026-06-27 19:33:27 +08:00
Your Name f257c4e3fc build: bundle adb platform tools 2026-06-27 17:59:36 +08:00
Your Name ecbd07cea0 style: tune dashboard typography 2026-06-27 17:59:19 +08:00
Your Name 5aeeef4aee style: polish dashboard wifi adb ui 2026-06-27 13:00:03 +08:00
Your Name 9a75b9b481 docs: audit server and anti-reverse security 2026-06-26 21:50:34 +08:00
Your Name 872d114a0f chore(release): bump version to V3.3.4 2026-06-26 21:11:36 +08:00
Your Name a7d6bc87b6 style: polish dashboard app UI 2026-06-25 08:49:52 +08:00
Your Name cf2b71f831 fix: harden redeem link flow 2026-06-24 22:03:04 +08:00
Your Name 3ab15e69f9 feat: add redeem links for external sales 2026-06-24 18:49:21 +08:00
Your Name 8e8a14cf69 build: allow reusing pyinstaller cache 2026-06-24 03:47:38 +08:00
Your Name 164f76658c fix reservation fansclub prejoin timing 2026-06-24 02:20:20 +08:00
Your Name ffebc8d0dc add direct attend button ocr fallback 2026-06-24 00:56:36 +08:00
Your Name 61d3ad5d83 fix pixel button detection for rgba screenshots 2026-06-24 00:47:55 +08:00
Your Name df46d723c3 avoid back exit during reservation direct attend 2026-06-24 00:17:45 +08:00
Your Name e41796d43a keep reservation after coupon popup during direct attend 2026-06-24 00:10:20 +08:00
Your Name 2b12ddbec3 fix reservation action log tag 2026-06-23 23:54:03 +08:00
Your Name d0166d27d3 security: harden license server and packaging checks 2026-06-23 23:47:19 +08:00
Your Name 9062ee7204 fix fudai countdown full-line ocr 2026-06-23 23:32:20 +08:00
Your Name 008d7f82b3 build: package dashboard with cythonized core 2026-06-23 23:30:29 +08:00
Your Name 4dea1328ec fix one-task countdown config crop 2026-06-23 22:49:30 +08:00
Your Name dc34b7484b fix one-task countdown box root cause 2026-06-23 22:18:54 +08:00
Your Name ed0aca5f28 fix fansclub recheck and countdown fallback 2026-06-23 22:00:31 +08:00
Your Name 33c6f7a54f fix normal fansclub recovery flow 2026-06-23 20:28:41 +08:00
Your Name 91a3aa5abf fix fansclub join wait protection 2026-06-23 20:10:13 +08:00
Your Name a2a899bb9f fix countdown frame fallback 2026-06-23 19:54:40 +08:00
Your Name 3ace80dcca add countdown OCR voting fallback 2026-06-23 19:18:12 +08:00
Your Name ab664e4da8 fix countdown digit extraction regression 2026-06-23 19:05:07 +08:00
Your Name 7086ab1d6e fix: stabilize fudai countdown OCR crops 2026-06-23 15:11:29 +08:00
Your Name 5ebca337eb fix: require obfuscation for release packaging 2026-06-23 15:11:29 +08:00
Your Name 7890320ff7 docs: explain adb and navigation setup 2026-06-23 14:34:37 +08:00
Your Name 18908aeff7 docs: require mobile navigation bar in exe guide 2026-06-23 14:14:50 +08:00
Your Name bd762f6be6 docs: write dashboard exe readme 2026-06-23 13:52:51 +08:00
Your Name 1bef130e51 docs: simplify readme usage guide 2026-06-23 13:47:53 +08:00
Your Name 5d3d58a2f9 fix: retry reservation direct attend icon scan 2026-06-23 12:07:36 +08:00
Your Name 25df550304 fix: prioritize reservation conflicts by value 2026-06-23 11:46:02 +08:00
Your Name 4af2adc4d6 fix: preserve fudai detail countdown detection 2026-06-23 11:22:23 +08:00
Your Name 77413fa7d1 docs: add full security review 2026-06-23 11:15:57 +08:00
Your Name aeeabd8ba2 security: use domain for license endpoints 2026-06-23 10:57:35 +08:00
Your Name 25876bd25a update server defaults and package assets 2026-06-23 10:48:02 +08:00
Your Name a449b7634c fix: speed up fansclub reservation prejoin 2026-06-23 10:43:17 +08:00
Your Name 0efdc83d0b chore: migrate license server defaults 2026-06-23 10:11:45 +08:00
Your Name 920c51d460 fix: broaden fansclub reservation prejoin match 2026-06-23 10:00:56 +08:00
Your Name ba9ac4cb0e fix: prejoin fansclub before reservation 2026-06-23 09:57:06 +08:00
Your Name f95832579a fix: avoid live-room back on fudai retry 2026-06-23 03:09:14 +08:00
Your Name 5c7d341d9b feat: add server managed auto updates 2026-06-23 03:06:55 +08:00
Your Name ba2e159cad use text inputs for dashboard numeric fields 2026-06-23 03:00:06 +08:00
Your Name fe53debeb1 auto refresh dashboard reservations 2026-06-23 02:45:54 +08:00
Your Name d81e00ddbc add pause resume controls to ui 2026-06-23 02:38:08 +08:00
Your Name 3c7cb45bec fix: parse paddle live tab ocr boxes 2026-06-23 02:30:10 +08:00
Your Name 86bf5cefb1 fix: recognize joined recommendation live tab ocr 2026-06-23 02:17:05 +08:00
Your Name debf016d23 update dashboard stats without rebuilding 2026-06-23 02:15:03 +08:00
Your Name 0c91367c07 improve dashboard live stats and controls 2026-06-23 02:08:38 +08:00
Your Name 25f7f9af9e fix: use ocr live tab and merge stuck room titles 2026-06-23 02:06:53 +08:00
Your Name e286cd46c8 fix dashboard mapping auto refresh 2026-06-23 01:47:39 +08:00
Your Name 8389f85124 fix: speed up reservation direct attend 2026-06-23 01:43:17 +08:00
Your Name 84b9143fa6 Fallback WiFi ADB connect to mdns port 2026-06-23 01:08:03 +08:00
Your Name 20e438ee13 Clarify WiFi ADB scan failure hint 2026-06-23 00:29:34 +08:00
Your Name 5c98bb8353 Support reconnecting multiple WiFi ADB devices 2026-06-23 00:25:56 +08:00
Your Name b533c4e96e Fix reservation direct attend timing guard 2026-06-19 21:52:32 +08:00
Your Name 8fac904ba9 use runtime counters for dashboard statistics 2026-06-19 20:49:01 +08:00
Your Name 680c02d362 expand dashboard statistics page 2026-06-19 20:38:28 +08:00
Your Name 4891f3b019 improve dashboard nav scroll and reservation details 2026-06-19 20:24:59 +08:00
Your Name 0f1baac92f Prevent stale run from restoring room map 2026-06-19 20:24:11 +08:00
Your Name f129206df7 Clear runtime state at fudai startup 2026-06-19 20:18:15 +08:00
Your Name d4931b6820 simplify dashboard license input 2026-06-19 20:14:01 +08:00
Your Name 48b0a32e24 Guard fudai retry and reservation seek verification 2026-06-19 20:01:46 +08:00
Your Name a06218dd16 Clear stale reservation direct attend state 2026-06-19 19:37:24 +08:00
Your Name 23abd486af fix dashboard mapping table coverage 2026-06-19 19:32:55 +08:00
Your Name 17068c7928 Use runtime screenshot in dashboard preview 2026-06-19 19:28:21 +08:00
Your Name b3d3f28ff3 Reduce fudai detection overhead 2026-06-19 19:16:25 +08:00
Your Name 58c1856fad Keep live title OCR in fudai detail path 2026-06-19 18:12:28 +08:00
Your Name 78a75d4843 Tune fudai detail OCR strategy 2026-06-19 14:44:17 +08:00
Your Name 32fcbc4c24 Skip full countdown OCR in fudai critical path 2026-06-19 14:30:47 +08:00
Your Name 6b987fd04f Keep task OCR out of fudai detail critical path 2026-06-19 14:12:23 +08:00
Your Name aa3690fecf Fix fudai wrong-target retry and detail OCR delay 2026-06-19 13:54:18 +08:00
Your Name 207748a901 Improve screenshot fallback and miss samples 2026-06-19 12:54:57 +08:00
Your Name 040ccd8161 feat: enforce online license verification 2026-06-19 11:49:57 +08:00
Your Name c5b7198145 Fix fudai return guards and sample selection 2026-06-19 11:42:34 +08:00
Your Name 0c8166d616 Cold start Douyin before CLI fudai runs 2026-06-19 02:27:47 +08:00
Your Name 2042c56257 Add run log scroll mode control 2026-06-19 02:24:40 +08:00
Your Name 2a7f4f38ab Improve dashboard action log display 2026-06-19 02:17:10 +08:00
Your Name 9ed73bf64b Default fudai regression collection to samples 2026-06-19 02:13:42 +08:00
Your Name ce0e9a3585 Fix dashboard controls and log pages 2026-06-19 02:08:05 +08:00
Your Name 9c329caf72 Add fudai regression artifact collector 2026-06-19 02:03:29 +08:00
Your Name b850afae2c Polish dashboard app visual style 2026-06-19 01:38:15 +08:00
Your Name 240f49825f feat: add license admin web login 2026-06-19 01:29:41 +08:00
Your Name a39545ed5d fix: harden license server security 2026-06-19 01:11:10 +08:00
Your Name ec51772cf0 Fix fudai countdown and room mapping guards 2026-06-18 19:25:46 +08:00
Your Name d6312d8813 feat: expand license admin dashboard 2026-06-18 19:04:07 +08:00
Your Name 28709d2d97 Fix fudai diagnostics and redpacket guard 2026-06-18 18:41:27 +08:00
Your Name cb74a23e81 feat: simplify license activation flow 2026-06-18 18:38:51 +08:00
Your Name 05be83d289 feat: add simple license activation server 2026-06-18 17:39:56 +08:00
Your Name b2db5ed499 Show runtime metrics and screenshot on dashboard 2026-06-18 17:26:00 +08:00
Your Name a25336770f Show live action status on dashboard 2026-06-18 17:15:57 +08:00
Your Name 00821d0926 Refine dashboard overview readability 2026-06-18 17:12:47 +08:00
Your Name c557ce0dfb Fix GUI launch entries 2026-06-18 16:49:38 +08:00
Your Name 8dbaab9d27 Fix v2 fudai detail recognition 2026-06-18 13:27:27 +08:00
Your Name fc96549bd2 fix(packaging): disable paddlex model source checks 2026-06-18 13:24:55 +08:00
Your Name b9b580f521 Refine dashboard app UI 2026-06-18 12:51:03 +08:00
Your Name 22e2ed1508 Clear stale fudai cache when leaving room 2026-06-18 12:44:19 +08:00
Your Name 160b4f1a2d Fix pixel stage finalize details propagation 2026-06-18 12:27:04 +08:00
Your Name 8e7be541d3 fix(packaging): split gui and cli collection 2026-06-18 12:21:24 +08:00
Your Name 89fb278988 Generalize coupon overlay rejection for fudai detection 2026-06-18 12:18:25 +08:00
Your Name b9c5106f62 Harden fudai icon detection against coupon taps 2026-06-18 11:50:50 +08:00
Your Name b74baef555 fix(packaging): keep distribution minimal 2026-06-18 11:14:04 +08:00
Your Name c97e4edc74 Fix reservation backtracking after failed title verify 2026-06-18 11:06:21 +08:00
Your Name fe1a62e92d Fix fudai live flow state and icon fallback 2026-06-18 10:40:47 +08:00
Your Name e977f6054d Add dashboard desktop UI entry 2026-06-18 10:22:12 +08:00
Your Name b61f766ea6 fix(updater): harden forced startup updates 2026-06-18 08:38:21 +08:00
Your Name 55d38c46ec Fix fudai coupon misclick detection 2026-06-18 08:35:04 +08:00
Your Name d48fa4eec3 Add forced startup updater 2026-06-18 07:57:38 +08:00
Your Name 9ffbe47bdb Improve fudai live flow diagnostics 2026-06-18 04:48:16 +08:00
Your Name daa4d1709d Fix installer smoke runtime packaging 2026-06-18 04:43:36 +08:00
Your Name 079bf8537a style(webui): refine typography and spacing 2026-06-18 04:35:19 +08:00
Your Name 1adaefdce6 Add lightweight fudai flow diagnostics 2026-06-18 03:52:18 +08:00
Your Name dbf9b14fac style(webui): apply strict modular ui redesign 2026-06-18 03:29:34 +08:00
Your Name cc4caef6e1 Fix encrypted package runtime validation 2026-06-18 02:59:00 +08:00
Your Name abcee63776 Add guarded UPX exe packing flow 2026-06-18 00:25:21 +08:00
Your Name 11de0f75c7 Add PyArmor obfuscation packaging flow 2026-06-17 23:42:15 +08:00
Your Name 5166678590 Add license key entry to UI 2026-06-17 23:01:21 +08:00
Your Name b1c2128d72 Add local license verification and distribution checks 2026-06-17 22:22:04 +08:00
Your Name 8d1bb28531 make inno installer independent of language pack 2026-06-10 01:33:14 +08:00
Your Name 87838daad4 add windows installer packaging workflow 2026-06-09 21:58:35 +08:00
Your Name 6279b129cb scan wifi adb random port across subnets 2026-06-08 18:17:29 +08:00
Your Name 207cf0eadb improve fudai ocr debug captures 2026-06-05 15:50:00 +08:00
Your Name 62c84939ee add fudai detail and reservation verdict markers 2026-06-05 15:46:43 +08:00
Your Name cd7615db3c limit wifi adb reconnect to lightweight ports 2026-06-05 15:45:37 +08:00
Your Name e3bf99149d wire webui region coordinate edit toggle 2026-06-05 15:45:20 +08:00
Your Name 9b03556b7d expose fudai detail thresholds and regions 2026-06-05 15:36:10 +08:00
Your Name 37a2f94486 detect fudai detail body and dacheng task count 2026-06-04 12:27:14 +08:00
Your Name 5e2ca0587b preserve simple and detail logs 2026-06-04 12:05:38 +08:00
Your Name f07fbb305b fix false fudai detail pixel detection 2026-06-04 11:51:12 +08:00
Your Name 1d564000ca add detail OCR performance diagnostics 2026-06-04 11:39:29 +08:00
Your Name dc6ae7d1e4 fix task count digit detection 2026-06-04 11:15:45 +08:00
Your Name 0c77bf9e0e Keep debug capture history for px and overview 2026-06-03 22:46:53 +08:00
Your Name ca7d64d54b test: isolate region overrides in ui checks 2026-06-03 20:39:47 +08:00
Your Name 4797fa046e feat: expose fudai region coordinates in gui 2026-06-03 20:29:10 +08:00
Your Name bcc4d1151f 修复WiFi ADB随机端口扫描 2026-06-03 17:52:02 +08:00
Your Name daf0c49288 统一日志详细度入口 2026-06-03 17:39:53 +08:00
Your Name 198a30dce1 完善新UI适配与日志简化 2026-06-03 12:40:06 +08:00
Your Name 71a9f4a25f 精简简单模式日志输出 2026-06-03 12:15:47 +08:00
Your Name 40f9812ab1 收口像素检测调试图输出 2026-06-03 12:05:27 +08:00
Your Name 3bcb5cb259 优化详情调试标注与截图复用 2026-06-03 11:36:47 +08:00
Your Name 42aa0f214d 修正调试图标注对齐 2026-06-03 10:47:39 +08:00
Your Name 24b58a8c6d 优化WiFi ADB快速扫描 2026-06-03 08:50:43 +08:00
Your Name e51d37890a 精简像素调试图与日志 2026-06-03 02:11:45 +08:00
Your Name 168ab4e1f8 调整调试图像开关语义 2026-06-03 01:48:02 +08:00
Your Name 098083a354 修正福袋详情调试图与图标检测 2026-06-03 01:34:30 +08:00
Your Name 1d37d57c90 修复福袋详情OCR v2与调试日志 2026-06-03 01:22:13 +08:00
Your Name 2c6f024a24 test: 增补回顶保留映射与同房三连映射回归 2026-06-01 21:18:28 +08:00
Your Name 02a4dc625a test: 增加映射合并与同房三连回顶回归用例 2026-06-01 21:16:42 +08:00
Your Name 147892a144 fix: 根因修复同房三连与映射合并,避免双切房 2026-06-01 21:13:58 +08:00
Your Name 05b9d17951 fix: remove recursive run_once reentry after desktop recovery 2026-06-01 20:58:24 +08:00
Your Name 879bb70075 docs: add chinese txt migration guide 2026-06-01 18:41:27 +08:00
Your Name 36e374ef67 refactor: split large modules and harden live-room fudai flow 2026-06-01 18:39:44 +08:00
Your Name 1845561405 docs: add quick deploy txt and one-click dependency bootstrap 2026-06-01 18:20:10 +08:00
Your Name 5d2d39b3e6 docs: 新增迁移部署指南并补充文档入口 2026-06-01 18:08:10 +08:00
Your Name eaa14ce52f Align web UI with gui_app features and normalize fonts 2026-06-01 17:03:35 +08:00
Your Name 7ebbdd6c1e polish premium monitor reservations logs 2026-06-01 16:42:02 +08:00
Your Name c2010084cf fix(fudai): root-fix countdown minute misread with full-line mm:ss priority 2026-06-01 16:37:11 +08:00
Your Name 33d05fac54 polish premium keywords and debug layouts 2026-06-01 16:28:12 +08:00
Your Name 5ae113cc18 polish premium yanghao settings layout 2026-06-01 16:19:51 +08:00
Your Name c7d6829219 polish premium filter settings layout 2026-06-01 16:09:43 +08:00
Your Name fa7e5070b3 polish premium run settings layout 2026-06-01 16:03:11 +08:00
Your Name 439aa944c7 polish premium stats dashboard 2026-06-01 15:51:10 +08:00
Your Name 6df926eabd refine premium webui command bar 2026-06-01 15:39:10 +08:00
Your Name a0bfb70b34 polish premium webui typography and logs 2026-06-01 15:25:52 +08:00
Your Name d696f2c974 fix(countdown): harden minute OCR selection and normalization 2026-06-01 15:15:01 +08:00
Your Name 3ce3a03f62 clean mobile premium webui backdrop 2026-06-01 14:59:29 +08:00
Your Name 93d950e78f fix: 根治倒计时分钟误识别并统一候选解析策略 2026-06-01 14:48:36 +08:00
Your Name a35b0371ae quiet premium webui chrome 2026-06-01 14:48:03 +08:00
Your Name a6563c11f4 refine premium webui details 2026-06-01 14:32:31 +08:00
Your Name 204ed24c67 polish premium webui layout 2026-06-01 14:10:32 +08:00
Your Name 60741369f2 polish premium webui visuals 2026-06-01 13:45:07 +08:00
Your Name eea0c48a44 refactor webui dashboard layout 2026-06-01 13:35:50 +08:00
Your Name 5a51c951a2 fix(fudai): treat notice text as attended and harden attend/log parsing 2026-06-01 12:33:33 +08:00
Your Name 61dfc1c15c fix: keep parallel OCR stable and add unknown-button fallback 2026-06-01 12:18:21 +08:00
Your Name a68307d7fd fix(wifi-adb): restore hi-port fallback path and harden reconnect/import edge cases 2026-06-01 11:05:47 +08:00
Your Name e33b42597c fix(wifi-adb): force openscreen mdns backend for scan discovery 2026-06-01 09:49:32 +08:00
Your Name f76232f2fc fix(wifi-adb): improve scan with multi-subnet fallback and mdns discovery 2026-06-01 09:40:44 +08:00
Your Name de21921d03 refactor(paths): remove cwd-based mapping path fallbacks 2026-06-01 09:15:41 +08:00
Your Name 37f736c158 fix(webgui): harden config bool parsing and action error handling 2026-06-01 09:07:03 +08:00
Your Name 3659d5b7da refactor: centralize web gui host/port config in path_config 2026-06-01 07:08:47 +08:00
Your Name 1ef7325ead refactor(webgui): extract request and static helpers 2026-06-01 01:05:45 +08:00
Your Name e03dcaa183 docs(webui): record HTML partial split decision 2026-06-01 01:02:54 +08:00
Your Name 458779e809 refactor(webui): extract CSS feature panels 2026-06-01 00:59:47 +08:00
Your Name c361eb4db6 refactor(webui): extract CSS layout and shared components 2026-06-01 00:56:00 +08:00
Your Name 4db6431757 refactor(webui): extract CSS tokens and base rules 2026-06-01 00:46:06 +08:00
Your Name 8351908232 refactor(webui): reduce app script to initialization glue 2026-06-01 00:41:16 +08:00
Your Name 3bc997a4d7 refactor(webui): extract runtime actions and polling 2026-06-01 00:35:49 +08:00
Your Name 48d18daef8 refactor(webui): extract config form bindings 2026-06-01 00:26:39 +08:00
Your Name c6a4410180 refactor(webui): extract dashboard renderers 2026-06-01 00:19:29 +08:00
Your Name a8d1b24dc9 refactor(webui): extract log view behavior 2026-06-01 00:14:49 +08:00
Your Name a94a6d2a71 refactor(webui): extract API client helpers 2026-05-31 11:13:28 +08:00
Your Name 3491970090 refactor(webui): extract DOM and format helpers 2026-05-31 11:07:39 +08:00
Your Name 01ce77eaa6 refactor(webui): extract frontend constants 2026-05-31 10:47:49 +08:00
Your Name 034e55072a refactor(webui): add static module split structure 2026-05-31 10:40:06 +08:00
Your Name ec2f044d8c docs(webui): 制定大文件拆分计划 2026-05-31 10:32:56 +08:00
Your Name 18b75ceda4 refactor(gui): 合并顶部 Y 偏移到设备栏组件 2026-05-31 10:08:02 +08:00
Your Name e9b003f906 refactor(gui): save_logging_config 内置到 left_config_area (169 → 159) 2026-05-30 20:13:22 +08:00
Your Name 95459607dc refactor(gui): format_gui_log_line 内置到 log_pipeline,主文件保留兼容 re-export (178 → 169) 2026-05-30 20:08:35 +08:00
Your Name 0d4796744d docs(specs): gui_app 拆分最终成果(5476 → 178, -96.7%) 2026-05-30 20:04:15 +08:00
Your Name 1cd94e9705 refactor(gui): 删除已不用的 logging/re/_LOGGER + RIGHT/Y 常量 (183 → 178) 2026-05-30 20:01:36 +08:00
Your Name 8c2d93a79f refactor(gui): 删除已不再被 main 使用的 log_color_config fallback 段 (201 → 183) 2026-05-30 19:49:37 +08:00
Your Name 92d60f9931 refactor(gui): 清理 16 个未使用的 _impl 别名 import (223 → 201) 2026-05-30 19:45:27 +08:00
Your Name 29b9788371 refactor(gui): 清理 12 个未使用的 import (239 → 223) 2026-05-30 19:41:14 +08:00
Your Name 7eeaab9a6e refactor(gui): 抽右侧主区域(notebook + 9 tabs + actions + pump_logs)到 components/right_main_area (348 → 239) 2026-05-30 19:30:11 +08:00
Your Name 089cb32e1c refactor(gui): 抽左侧配置区(PanedWindow + 7 Tabs + load/save IO)到 components/left_config_area (389 → 348) 2026-05-30 19:18:43 +08:00
Your Name a06ece4e15 refactor(gui): _open_realtime_viewer 直接定义,删除 forward-declare 模式 (396 → 389) 2026-05-30 19:13:52 +08:00
Your Name 6cebed599d refactor(gui): _async_refresh_preview 闭包内联到 periodic_refreshers (398 → 396) 2026-05-30 19:09:37 +08:00
Your Name da5e000006 refactor(gui): 抽 root window + ttkbootstrap fallback 到 components/root_window (415 → 398) 2026-05-30 19:04:50 +08:00
Your Name 065d73ff9a refactor(gui): _open_realtime_viewer lambda 去重(2 处 → 1 个本地变量) (419 → 415) 2026-05-30 19:00:35 +08:00
Your Name adbd8a2d6e refactor(gui): theme_getter lambda 去重(3 处 → 1 个本地变量) (418 → 419) 2026-05-30 18:54:20 +08:00
Your Name 1235c5910f docs(specs): gui_app 拆分最终成果(5476 → 418, -92%) 2026-05-30 18:49:55 +08:00
Your Name 84c5731cc3 refactor(gui): 抽 on_line + Runner + log_writer 到 components/log_pipeline (440 → 418) 2026-05-30 18:47:36 +08:00
Your Name 8e0ae9396d refactor(gui): actions_log + ocr_results 内置到 simple_tabs (450 → 440) 2026-05-30 18:42:26 +08:00
Your Name a6648c5ce8 refactor(gui): reservation/high_value 用 setup_text_tab_with_refresh 复用 (452 → 450) 2026-05-30 18:37:12 +08:00
Your Name f75d3ae368 refactor(gui): refresh_stats 内置到 setup_stats_tab (470 → 452) 2026-05-30 18:33:21 +08:00
Your Name d9920f1cee refactor(gui): 抽运行日志 Tab UI 到 components/log_tab (487 → 470) 2026-05-30 18:29:00 +08:00
Your Name e763cdc302 refactor(gui): 删除已不用的 BOTTOM/W 兜底常量 (492 → 487) 2026-05-30 18:24:34 +08:00
Your Name fd694f8ce5 refactor(gui): 清理 6 个未使用的 _impl 别名 import (498 → 492) 2026-05-30 18:17:58 +08:00
Your Name 547228fa2d refactor(gui): 清理未使用的 gui_core_pkg + wifi_adb_scan import (508 → 498) 2026-05-30 18:03:30 +08:00
Your Name e7d848023c refactor(gui): 清理 gui_core 中已不再直接用的 8 个 import (518 → 508) 2026-05-30 17:59:46 +08:00
Your Name a1562a513d refactor(gui): 抽顶部常驻按钮区到 components/top_buttons (527 → 518) 2026-05-30 17:55:20 +08:00
Your Name b8f2806ffc refactor(gui): _main_nb 直接引用 show_actions_var 等,删除 3 行 unpack (530 → 527) 2026-05-30 17:48:34 +08:00
Your Name 9642b7b0f8 refactor(gui): 抽顶部设备栏到 components/top_device_bar (607 → 530) 2026-05-30 17:45:01 +08:00
Your Name 9896eb676a refactor(gui): 抽周期性刷新+关闭处理到 components/periodic_refreshers (630 → 607) 2026-05-30 17:40:58 +08:00
Your Name e0c68883dd refactor(gui): 清理 4 个未使用的 stdlib import (634 → 630) 2026-05-30 17:37:12 +08:00
Your Name e0cad29daf refactor(gui): 清理已抽走 var 后的死注释段 (677 → 634) 2026-05-30 17:33:14 +08:00
Your Name 6a8296cab1 refactor(gui): 删除 125 个无用的 _vars_ unpack(只保留 y_var/gui_theme_var) (802 → 677) 2026-05-30 17:30:05 +08:00
Your Name 3626e9cf6f refactor(gui): save_logging_config 复用 _vars_,删除子集 dict (825 → 802) 2026-05-30 17:26:31 +08:00
Your Name 29d930b1de refactor(gui): get_params 复用 _vars_ + device_var,删除子集 dict (855 → 825) 2026-05-30 17:23:43 +08:00
Your Name df758cf224 refactor(gui): config_io 复用 _vars_ 全集,删除 _config_io_vars 子集字典 (982 → 855) 2026-05-30 17:20:52 +08:00
Your Name 47865f5dfa refactor(gui): setup_*_tab 调用直接传 _vars_ 全集 (1110 → 982) 2026-05-30 17:17:55 +08:00
Your Name 9744b75878 refactor(gui): 抽 127 个 Var 声明到 components/config_vars 工厂 (1373 → 1110) 2026-05-30 17:14:39 +08:00
Your Name 200f3a53fc docs(specs): 更新 gui_app 拆分最终成果(5476 → 1373, -75%) 2026-05-30 17:09:08 +08:00
Your Name 7a840120b3 refactor(gui): 抽底部操作按钮区到 components/action_buttons (1417 → 1373) 2026-05-30 17:06:36 +08:00
Your Name e314161b6c refactor(gui): 抽右侧主 Notebook + 实时工具栏到 components/main_notebook (1444 → 1417) 2026-05-30 17:02:35 +08:00
Your Name 3a7a7a3b75 refactor(gui): 抽 keywords_tab UI 到 components/keywords_tab (1461 → 1444) 2026-05-30 16:58:53 +08:00
Your Name 8575f04ab9 refactor(gui): 抽截图预览 Tab 整段 UI 到 components/preview_tab (1537 → 1461) 2026-05-30 16:54:53 +08:00
Your Name 728ef3cd79 refactor(gui): 5 个简单文本 Tab 用 simple_tabs 模板复用 (1571 → 1537) 2026-05-30 16:49:01 +08:00
Your Name 32e374e2c2 refactor(gui): 抽行为日志工具栏到 components/actions_log_toolbar (1649 → 1571) 2026-05-30 16:45:02 +08:00
Your Name aa0f4e05f2 refactor(gui): 抽中奖记录 Tab 整段 UI 到 components/win_record_tab (1739 → 1649) 2026-05-30 16:40:49 +08:00
Your Name 5e3015f59b refactor(gui): 抽日志搜索工具栏到 components/log_search_toolbar (1813 → 1739) 2026-05-30 16:36:43 +08:00
Your Name dc1744a93f refactor(gui): 重排 log_text 创建到搜索栏之前(为下一步抽搜索栏铺路) 2026-05-30 16:33:00 +08:00
Your Name b686a4e3d5 refactor(gui): 抽 log_text 颜色配置到 components/log_text_colors (1878 → 1813) 2026-05-30 16:29:27 +08:00
Your Name 29cef2c578 refactor(gui): 抽 realtime_tab UI 创建到 components/realtime_tab (2037 → 1878) 2026-05-30 16:25:51 +08:00
Your Name e784efd5f8 refactor(gui): 抽 filter_tab UI 创建到 components/filter_tab (2122 → 2037) 2026-05-30 16:18:29 +08:00
Your Name 6c7bbf0945 refactor(gui): 抽 run_tab UI 创建到 components/run_tab (2192 → 2122) 2026-05-30 16:15:24 +08:00
Your Name fe27063913 refactor(gui): 抽 reservation_tab UI 创建到 components/reservation_tab (2334 → 2192) 2026-05-30 16:11:47 +08:00
Your Name 3f04bb23c2 refactor(gui): 抽 yanghao_tab UI 创建到 components/yanghao_tab (2456 → 2334) 2026-05-30 16:06:40 +08:00
Your Name bcb0e363d1 refactor(gui): 抽 logging_tab UI 创建到 components/logging_tab (2656 → 2456) 2026-05-30 15:54:46 +08:00
Your Name b447b6a6a4 refactor(gui): 抽 debug_tab UI 创建到 components/debug_tab (3052 → 2656) 2026-05-30 15:50:58 +08:00
Your Name 3ac8664817 docs(specs): 更新 gui_app 拆分最终成果(5476 → 3052, -44.3%) 2026-05-30 15:42:56 +08:00
Your Name 6bac014c3d refactor(gui): 抽 load_config_to_ui + save_ui_to_config 到 components/config_io (3538 → 3052) 2026-05-30 15:41:27 +08:00
Your Name 3d433080c2 docs(specs): 更新 gui_app 拆分最终成果(5476 → 3538, -35.4%) 2026-05-30 15:27:44 +08:00
Your Name f6d382b0e7 refactor(gui): 抽 get_params 到 components/run_params_builder (3563 → 3538) 2026-05-30 15:26:17 +08:00
Your Name 2a05be2319 refactor(gui): 抽 save_logging_config 到 components/logging_config_io (3590 → 3563) 2026-05-30 15:22:29 +08:00
Your Name f9839f3dee docs(specs): 补充 gui_app 拆分实际成果(5476 → 3590, -34%) 2026-05-30 15:18:13 +08:00
Your Name 97935d9c48 refactor(gui): 抽 _generic_search_widget 到 components/text_search (3669 → 3590) 2026-05-30 15:16:42 +08:00
Your Name 64c210dd5a refactor(gui): 抽 refresh_run_log 到 components/run_log_view (3715 → 3669) 2026-05-30 15:12:38 +08:00
Your Name 68d1224b53 refactor(gui): 抽 _on_scan_one_click + _handle_scan_result 到 components/wifi_adb_one_click_scan (3775 → 3715) 2026-05-30 15:08:35 +08:00
Your Name 92d524297b refactor(gui): 抽预览 Tab 全部 8 个动作到 components/preview_view (3891 → 3775) 2026-05-30 15:03:45 +08:00
Your Name 59ebe8c1e7 refactor(gui): 抽 win_record Tab 全部 7 个动作到 components/win_record_view (4044 → 3891) 2026-05-30 14:53:11 +08:00
Your Name a7ef92fc7c refactor(gui): 抽 pump_logs 到 components/log_pump (4117 → 4044) 2026-05-30 14:37:03 +08:00
Your Name c5df7a05d2 refactor(gui): 抽 update_ocr_results 到 components/ocr_results_view (4148 → 4117) 2026-05-30 14:30:42 +08:00
Your Name b3380042b8 refactor(gui): 抽 _try_reconnect_last_wifi 到 components/wifi_adb_reconnect (4268 → 4148) 2026-05-30 14:24:19 +08:00
Your Name 4993fad004 refactor(gui): 抽 _open_scan_pick_dialog 到 components/wifi_adb_pick_dialog (4337 → 4268) 2026-05-30 14:18:19 +08:00
Your Name 44b091466d refactor(gui): 抽 actions_log 视图相关到 components/actions_log_view (4463 → 4337) 2026-05-30 14:10:30 +08:00
Your Name 8ea676562c refactor(gui): 抽 do_screenshot + OCR_REGIONS 到 components/screenshot_action (4635 → 4463) 2026-05-30 14:03:31 +08:00
Your Name a07ef00b5e refactor(gui): 抽 refresh_high_value_rooms 到 components/high_value_view (4656 → 4635) 2026-05-30 13:56:36 +08:00
Your Name 5329561b3a refactor(gui): 抽 refresh_reservations 到 components/reservations_view (4913 → 4656) 2026-05-30 13:52:39 +08:00
Your Name 6bffcae2de refactor(gui): 抽 open_wifi_adb_dialog 到 components/wifi_adb_dialog (5274 → 4913) 2026-05-30 13:48:22 +08:00
Your Name ac464788e1 refactor(gui): 抽 open_scan_dialog 到 components/wifi_adb_scan_dialog (5476 → 5274) 2026-05-30 13:43:17 +08:00
Your Name 8dace383ec docs(plans): 添加 gui/gui_app.py 拆分实施计划 2026-05-30 13:26:42 +08:00
Your Name 26f9e5a553 docs(specs): 添加 gui/gui_app.py 拆分设计文档 2026-05-30 13:24:07 +08:00
CodexandClaude Sonnet 4.5 bb90e2983f fix(pil): 补充修复剩余 PIL Image 资源泄漏
覆盖 14 个文件中的 Image.open() 未正确关闭问题:
- fansclub_handler: 5 处(pic/pic_rgb/img 未 close)
- image_ops: 2 处(crop 后 pic 未 close)
- douyin_popups: 2 处(pic.convert 重赋值泄漏原始句柄)
- douyin_fudai: 1 处(open().convert() 链式调用泄漏)
- douyin_robot: 2 处(同上)
- save_files/direct_attend/finder/stage/find_open/detail/_common/ocr_preprocess: 各 1-2 处

统一修复模式:分离 open 与 convert,try/finally 确保原始句柄关闭。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 22:49:50 +08:00
CodexandClaude Sonnet 4.5 c3746b0207 fix(pil): 修复 PIL Image 资源泄漏
Image.open() 后未 close() 导致文件句柄泄漏,用 _raw + try/finally 模式修复。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 22:42:22 +08:00
CodexandClaude Sonnet 4.5 b1fa6af9ce fix(gui): 修复启动后 GUI 卡死约 1.2 秒
delayed_refresh_preview 在 mainloop 启动 300ms 后同步加载大图(PIL
Image.open + load + convert),阻塞主线程。改为:
1. 延迟到 3 秒后再触发预览(GUI 已完全初始化)
2. 图片加载放到后台线程,完成后通过 root.after 回主线程更新

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 21:58:50 +08:00
CodexandClaude Sonnet 4.5 96fdc96f24 refactor(cleanup): 移除剩余死代码模块
- 删除 douyin/utils/douyin_text_utils.py 及其测试
- 移除 performance_tracker.py 中未使用的 track_function 方法
- 移除 param_usage_tracer.py 中未使用的 stop_tracing / is_enabled
- 清理 bin/run_cli.py 和 tests/test_imports.py 中的残留引用

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 21:58:41 +08:00
CodexandClaude Sonnet 4.5 c4544489ac refactor(coords): 提取点击坐标常量,消除硬编码
在 coords.py 添加 DETAIL_OUTSIDE_CLICK、PARTICIPATE_BTN_CLICK、
FANSCLUB_JOIN_CLICK、FANSCLUB_JOIN_FALLBACK_CLICK 常量,
替换 fudai_attend/fansclub_handler/join_decision 中的硬编码坐标。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 21:20:17 +08:00
CodexandClaude Sonnet 4.5 d19d5bfc56 refactor(cleanup): 移除 logging 模块死代码
- unified_logger.py: 删除 5 个从未使用的装饰器/函数
- internal_loggers.py: 删除 3 个未使用方法和工厂函数
- action_logger.py: 删除 3 个未使用方法
- log_formatter.py: 删除 6 个未使用格式化函数(保留 GUI 依赖的 4 个)
- 同步更新 __init__.py 和测试文件

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 21:04:35 +08:00
CodexandClaude Sonnet 4.5 703da834fb fix(security): 修复 shell 注入风险和类型转换未捕获问题
- path_config.py: find_executable Unix 回退路径使用 shlex.quote 防注入
- underlying_operations.py: try_set_ime IME ID 使用 shlex.quote 防注入
- screenshot_direct.py: 环境变量 float/int 转换添加 try/except 容错
- device_select.py: 用户输入 int() 转换添加 try/except 容错
- read_once.py / image_acquirer.py / detail_verifier.py: PIL Image 添加 close()
- detector.py: 移除 return 后不可达死代码
- optimized_entry.py: 统一返回值类型 int,失败时返回 0
- read_once.py: 移除 try/except 中重复的相同代码

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 20:50:26 +08:00
CodexandClaude Sonnet 4.5 4908df19d4 refactor(cleanup): 移除死代码和冗余导入
- douyin_fudai_core.py: 移除未使用的 ThreadPoolExecutor/check_contain 导入
  和被覆盖的 fudai_result_checker 导入
- ocr_executor.py: 移除重复的 _fudai_ocr_executor_state 初始化
- flow_control_pkg: 移除 stage_handler/no_fudai/find_open 中未使用的导入

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 20:27:41 +08:00
CodexandClaude Sonnet 4.5 ca00258bf3 fix(code-quality): 修复 NameError 风险和死代码清理
- detect_by_template.py: 添加缺失的 os 和 path_config 导入
- join_decision.py: 添加缺失的 is_watch_task_fudai 导入
- read_once.py: 添加缺失的 Optional 类型导入
- fudai_detail_validator.py: 使用 extract_2digits 做更健壮的数字解析
- screenshot_manager: 移除未使用的导入和死代码

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 20:22:52 +08:00
CodexandClaude Sonnet 4.5 e62314fa25 fix(import): 修复 fudai_attend 相对导入路径错误
join_decision.py 在 fudai_filter_pkg 子包内,用 .fudai_attend 会查找
fudai_filter_pkg.fudai_attend(不存在),实际模块在上层 core 包。
改为 ..fudai_attend。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 19:26:58 +08:00
CodexandClaude Sonnet 4.5 df69c6ab67 fix(countdown): 修复长倒计时被截断到15分钟的bug
check_countdown 中 >900s 的上限过于激进,将实际的58分钟福袋截断到14:50。
改为 >3600s(1小时)上限,兼容抖音的60分钟福袋。

同时修复 _extract_digits 取后N位的问题,改为取前N位,
避免当子图意外捕获额外数字时(如 "1458")被误提取为 "58"。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 19:22:20 +08:00
CodexandClaude Sonnet 4.5 a50f08de5a fix(fudai): 验证失败时按钮可操作则继续参与
验证失败(如内容识别被禁用导致内容为空)时,若按钮状态为
"可以参与"/"需要加入粉丝团"等可操作状态,继续走参与流程而非
直接返回,避免漏参与有效福袋。同时修正 basic_join_decision 调用签名。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 19:03:51 +08:00
CodexandClaude Sonnet 4.5 8fd38dd30b fix(fudai): validator 内容检查正确尊重 disable 配置
当 config.json 中 fudai_disable_content_recognition=true 时,
跳过内容为空的检查。原实现在 except 块中丢失 disable_content
状态,导致配置生效时仍误判内容为空为验证失败。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 19:00:32 +08:00
CodexandClaude Sonnet 4.5 d850af2c44 fix(fudai): 验证器不再因内容为空而拒绝有效福袋
当奖品价值>0且倒计时合理时,内容为空是正常的(部分福袋无文字
内容),不应判定验证失败导致跳过参与。

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 18:39:13 +08:00
Codex 2fab3f238e fix: entry-point scripts douyin.* import 失败 — sys.path 在 import 之后才设置
bin/run_cli.py 的 _BASE_DIR+sys.path.insert 原在 logging import 之后,
导致 No module named 'douyin' 警告。tools/ 下 5 个脚本完全缺失 sys.path
设置,auto_connect_wifi_adb.py 层级算错只跳到 tools/ 而非项目根。
2026-05-23 18:11:18 +08:00
Codex f750969df3 fix(deps): pin protobuf==3.20.3 修复 PaddleOCR 初始化失败回退到慢速 EasyOCR 2026-05-23 17:43:01 +08:00
Codex 842dd254e3 fix: correct import path for check_detail_height in detect_fudai_detail_page
The relative import from .douyin_detection was looking in the
douyin/detection/pixel/ package, but douyin_detection.py lives
at douyin/detection/douyin_detection.py. This caused every fudai
detail page detection to fail with detection_exception, making the
system always treat successful detail page opens as misclicks.
2026-05-23 17:05:43 +08:00
CodexandClaude Sonnet 4.5 6f38907119 fix(fudai/reservation): 修 3 处拆模块遗留 NameError
- douyin_fudai_core.py: get_fudai_contain 引用 TASK_LIST / PARTICIPATE_BUTTON
  但只导入了 LIVE_ROOM_TITLE,运行时必触发 NameError
- douyin_reservation_verify.py: match_reservation 末尾日志引用
  current_title,但该变量仅在 if expected_title 块内赋值,
  expected_title 为空时 NameError(被 try/except 吞掉但丢失日志)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 13:28:54 +08:00
CodexandClaude Sonnet 4.5 470c68a252 fix(fudai/stage): 修 reservation_check_start NameError + ocr_detection 缩进 + stage 默认值
- douyin_fudai.py: 补回 reservation_check_start 初始化(ffd048f 拆 helper 时丢失)
- ocr_detection.py: 修 _confirm_live_list 中 OCR 变量在 if 块外赋值的缩进 bug
- ocr_detection.py: shopping_redpacket_ocr_confidence_threshold 改 getattr 兜底 0.35
- douyin_stage.py: enable_ocr_mode1 默认值 False→True;像素检测未命中补 return
- config.json: 同步 enable_ocr_mode1 默认值

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-23 11:22:03 +08:00
CodexandClaude Opus 4.7 fe97e82104 fix(gui): 实时查看器/状态 Tab 的耗时解析支持 ms 单位
问题:实际 actions.log 写的是 `耗时=10.00ms`(毫秒),但 _parse_minimal
和 parse_action_duration 的正则只匹配 `s`,导致:
- 实时查看弹窗永远显示"暂无动作"
- 实时状态 Tab 同样空白

同时存在的副 bug:兜底正则在整行匹配,前缀里的 `192.168.5.2:5555` /
日志时间戳 `2026-05-21` 都可能被误识别成耗时。

修复:
- 解析窗口限定到 line.find("耗时") 之后的子串 (tail)
- 优先匹配 ms(顺序很重要:\s*s 会先吃掉 "10ms" 的 m)
- s 单位加 (?![a-zA-Z]) 负向后顾,避免匹配 "ms" / "second" 之类
- 同步修复 gui_app.py:3685 的 parse_action_duration(实时状态 Tab)

测试:
- _parse_minimal 加 4 个新测试覆盖 ms / 整数 ms / 优先级 / 前缀干扰
- 全量 1426 passed (+5)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 09:08:58 +08:00
CodexandClaude Opus 4.7 9f330572cc test(gui): 加 gui_app.main() 启动冒烟测试
背景:d759921 抽 _open_realtime_viewer_impl 时误删 16 行搜索工具栏定义,
gui_app 启动时报 NameError,但 pytest 1421 passed 没抓住——def main()
里的 NameError 只有真正调用 main() 才触发,单纯 import 不会执行函数体。

新测试通过 patch tk.Misc.mainloop 让 GUI 创建完所有控件后立刻 quit,
覆盖 def main() 内部所有顶层语句,能抓住 NameError / AttributeError /
ImportError 这类启动期失败。

已验证:临时 revert ca6c2e4 后该测试 FAIL(精确指向 L3994 NameError),
恢复 ca6c2e4 后 PASS。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 08:59:30 +08:00
CodexandClaude Opus 4.7 4277bf7fa4 fix(gui): WiFi 扫描显示 adb 真实返回,state=failed 不再误导为"请授权"
问题:扫描提示 "192.168.5.2:5555 当前状态=failed,请先在手机上授权后重试",
但 failed 表示 adb connect 既不成功也不是 unauthorized(通常是 adb 服务异常 /
设备短暂不可达),不是授权问题。手机不会弹窗,用户照提示去手机上找授权窗
口,永远不会成功。

修复:
- _handle_scan_result: 区分 failed 分支,逐项打印 adb 真实返回(去掉换行
  方便单行显示),并提示用户排查 adb 服务而非"请授权"。
- _open_scan_pick_dialog: 表格新增 "adb 返回" 列(截断 200 字符);
  Toplevel 拓宽到 680x320 容纳新列。
- use_selected: 根据 state 给出针对性提示——unauthorized 让用户授权,
  failed 显示对应 message,其他状态保持通用提示。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 08:55:15 +08:00
CodexandClaude Opus 4.7 ca6c2e4d20 fix(gui): 恢复运行日志 Tab 搜索工具栏定义
d759921 抽 _open_realtime_viewer_impl 时误删了紧随其后的 16 行
"搜索工具栏"块(log_search_frame / log_filter_var / log_search_var /
log_search_entry),导致 gui_app 启动时在 L3964 报
NameError: name 'log_search_entry' is not defined。

恢复这 16 行到原位置,gui_app 可正常启动。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 08:37:30 +08:00
CodexandClaude Opus 4.7 7884132743 test(pkg): 补充 _pkg 子模块单元测试
覆盖 screenshot_manager.save_files / reservation_logic._common /
logging_wrapper_pkg._common 共 14 个测试。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 07:05:23 +08:00
CodexandClaude Opus 4.7 9fbfcb5ed2 chore(gitignore): 忽略 output/ 测试与诊断产物
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 07:05:11 +08:00
CodexandClaude Opus 4.7 87bac9e548 chore(config): 补充新增功能默认配置
新增 GUI realtime_status / swipe_down_back / log_unified 默认值,
与代码中 cfg.get(..., default) 兜底保持一致。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 07:04:59 +08:00
CodexandClaude Opus 4.7 d759921442 refactor(gui): 抽 _open_realtime_viewer_impl 到 components/realtime_viewer (5539 → 5370)
gui_app.py 嵌套函数 _open_realtime_viewer_impl 是 170 行的"实时查看"对话框:
弹 Toplevel 显示当前 pic/screenshot.png + 列表展示 actions.log 中含"耗时"的
最近 80 行,每秒刷新。

抽到 gui/components/realtime_viewer.py:
- open_realtime_viewer(root) 主入口
- _tail_read(path, max_bytes) 末尾字节读取
- _parse_minimal(line) 提取 (动作名, 耗时) 二元组
- 全局单例 _active_win 替代原嵌套 def 的属性式 _win

gui_app.py 中嵌套 def 缩成 4 行委托。

新增 13 个单元测试覆盖 _tail_read 4 种情况 + _parse_minimal 8 种格式。

1421 passed (+13)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:47:58 +08:00
CodexandClaude Opus 4.7 be1eb6eda7 refactor(web_gui): 抽 ProcRunner._update_stats_from_line 解析逻辑到 stats_log_parser (2429 → 1806)
ProcRunner._update_stats_from_line 是 624 行的"日志行 → 计数器更新"方法,与
gui_core.Runner 同名方法行为接近但有差异:
- web_gui 解析 traceId / MDC 信息(gui_core 没有)
- web_gui 没有 _lock / _last_log_ts 字段(不需要锁保护)
- web_gui 没有 unique_keys_* / *_room_pos 这些去重数据结构
- web_gui 有"进入直播间到识别福袋耗时"事件解析

抽到独立的 gui/web_gui_pkg/stats_log_parser.py(不与 gui_core_pkg 版本共享,
避免在两边各加缺失字段,行为差异显式保留在两个文件中):
- update_stats_from_line(runner, line) 主入口
- 16 个 _parse_* 子函数(含 traceId/MDC、enter_to_fudai_seen 等 web_gui 专属段)

ProcRunner._update_stats_from_line 从 624 行变成 4 行委托。

1408 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:41:52 +08:00
CodexandClaude Opus 4.7 3b8f85b9cb refactor(gui_core): 抽 _update_stats_from_line 解析逻辑到 stats_log_parser (1207 → 541)
Runner._update_stats_from_line 是 666 行的"日志行 → 计数器更新"巨型方法。
按业务事件分类 14 个独立段(福袋字段 / 打开-参与计数器 / 跳过原因 /
错误统计 / 粉丝团 / 预约 / 开奖结果 / 直播间切换 / 阶段诊断 / OCR / 性能 /
详情识别 / 福袋查找 / 回退操作)。

抽到 gui/gui_core_pkg/stats_log_parser.py:
- update_stats_from_line(runner, line) 主入口
- 14 个 _parse_* 子函数按事件分组
- 通过 runner.* 调用保持与原 Runner 方法/状态一致

Runner._update_stats_from_line 从 666 行变成 4 行委托。模块级测试更易于
单独覆盖各分类的解析逻辑。

1408 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:35:04 +08:00
CodexandClaude Opus 4.7 fb35670032 refactor(gui): 抽 ThreadSafeLogWriter 到 components/log_writer (5649 → 5537)
gui_app.py 的 ThreadSafeLogWriter 类(109 行)是自包含的日志文件写入器:
threading.Lock 保护、按日期分割、配置开关、PermissionError/Exception 兜底。

抽到 gui/components/log_writer.py,原 gui_app 中的 109 行类定义 + 1 行实例化
替换为 3 行导入 + 实例化。read_config 通过 staticmethod _read_config 延迟导入,
避免循环依赖。

新增 15 个单元测试覆盖:
- __init__:默认 log_dir / 配置开关 / dated_logs / 相对路径解析 / 配置异常兜底
- write:正常写 / 禁用跳过 / 空行跳过 / 时间戳前缀 / 已格式化行原样写
- 100 线程 × 10 行的并发安全测试(确认 1000 行无丢失)
- PermissionError / 通用异常下不抛 + warn 一次

1408 passed (+15)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:29:25 +08:00
CodexandClaude Opus 4.7 230c0d4049 refactor(gui): 抽 refresh_stats 字符串格式化到 stats_formatter (6339 → 5634)
gui_app.py 的 refresh_stats 闭包是 705 行纯字符串构建:把 runner.get_stats()
的字典格式化成多个分段(基本信息/快速汇总/核心统计/跳过/OCR/详情/福袋查找/
性能/粉丝团/切换/预约/错误/价值/最近福袋/中奖记录)。

抽到 gui/components/stats_formatter.py:
- format_stats(stats: Dict) -> List[str] 主入口
- 14 个 _append_* 子段构建器(每段一个,按需追加)
- _section_lines(title, body) 标题包装

闭包改为 16 行委托:调 format_stats + 写入 ScrolledText。

新增 32 个单元测试覆盖:
- 空 dict / 缺字段时的兜底
- 基本运行状态(uptime / pid / exit_code 各种格式)
- 各分段的"有数据 / 无数据"条件
- 关键率计算(打开成功率/点击率/参与成功率/中奖率/跳过率/错误频率)
- 边界情况(attend_ok > clicks 检测到已参与,结果未开奖警告,wins 截断到 10 条)

1393 passed (+32)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:23:53 +08:00
CodexandClaude Opus 4.7 a864f6e23a refactor(fudai): 抽 __init__ 配置默认值到 init_helpers (1559 → 1323)
fudai_analyse.__init__ L119-354 是 236 行配置字段默认值 + 运行时状态初始化:
- ~80 个 self.X = <default_value> 配置字段
- 30+ 个运行时状态字段
- _reservations_state_path 解析 + room_pos_map 旧文件清理

抽到 douyin/core/fudai_modules/init_helpers.py:
- apply_fudai_defaults(self): 主入口
- _apply_yanghao_defaults(self): 推荐页养号子段
- _resolve_reservations_state_path(self): 解析路径,path_config 失败时
  兜底用 ".." 回退(不再用 dirname(__file__) + "state")
- _cleanup_old_room_pos_map_files(self): 清理上次运行的 JSON/CSV/MD 导出

__init__ 中保留:
- L57-117 设备/分辨率/operation/日志系统初始化(依赖较深,难抽)
- L356-357 self.load_config()

行为完全保留:所有字段值、解析顺序、异常兜底全部不变。
test_runtime_path_anchors.test_reservations_state_path_uses_path_config 已更新
为同时检查 douyin_fudai.py 和 init_helpers.py。

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:13:46 +08:00
CodexandClaude Opus 4.7 3a9f01ad74 refactor(fudai_modules): 抽 swipe 兜底重复逻辑到 fudai_device_control (1238 → 1147)
handle_detail_helpers.py 中 _handle_error_status 内联段(L266-318,53 行)
和 _fallback_swipe_up 顶层函数(L1187-1239,53 行)做的是完全一样的事:
没有 swipe_up_to_next_live 时直接 ADB shell input swipe,失败再回退到
operation.swipe。重复 1:1。

新增 douyin/core/fudai_modules/fudai_device_control.py:
- fallback_swipe_up_via_adb(self): 纯 ADB 兜底 swipe
- swipe_up_or_fallback(self): 优先 swipe_up_to_next_live,否则 fallback

handle_detail_helpers 两处都改成 4 行委托。原文件去掉 os/subprocess
import,仅保留 time。

行为完全保留:分辨率换算公式、ADB 路径解析、subprocess 超时 5s、operation.swipe
最终兜底全部不变。

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:07:41 +08:00
CodexandClaude Opus 4.7 8ecd2783db refactor(reservation): 抽 _write_state 闭包到顶层 _write_reservations_state
_run_reservation_attend_window 内嵌的 _write_state 闭包是 75 行 JSON 状态文件
写盘逻辑(含 1s 节流),独立性强,纯写文件无副作用。

抽到顶层 _write_reservations_state(self) helper,原闭包改为单行委托。
内部用到的 import json/os/datetime 移到 helper 内部,主函数顶部去掉。

行为完全保留:
- 1s 节流(避免高频写盘)
- 缺路径时 makedirs
- 异常时通过 self._log_kv 记录 + 不抛

文件总行数 1492 → 1495(+3):闭包变成委托后总行数略增 3,但消除了
1 层嵌套,给后续测试 _write_reservations_state 留出空间(可独立测试)。

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 03:03:19 +08:00
CodexandClaude Opus 4.7 e737002b1e refactor(stage): 抽 "不在直播间" OCR 检测分支到 ocr_detection (1245 → 807)
diagnose_stage_from_current_screen L336-774 是 438 行 "if not in_live_room:"
分支:
- 步骤 2.5:购物红包 OCR 复查(像素命中红包背景时再用 OCR 二次确认)
- 步骤 3:OCR 推荐页/关注列表/直播列表标签栏(含两次精确确认子流程)

抽到 douyin_stage_handler_pkg/ocr_detection.py:
- detect_pages_via_ocr(...) 入口,内部化 in_live_room 检查
- _check_redpacket_ocr_when_not_in_live_room 步骤 2.5
- _confirm_follow_list 关注列表精确截图 + OCR 模式 0/1
- _confirm_live_list 直播列表精确截图 + OCR 模式 0/1

返回 Optional[Tuple[str, str]]:
- ("RECOMMEND_PAGE"/"FOLLOW_LIST"/"LIVE_LIST"/"SHOPPING_REDPACKET_POPUP"
   /"IN_LIVE_ROOM", reason) → caller 立即 return
- None → in_live_room=True,caller 继续后续逻辑

主函数对应位置替换为 17 行委托,_log/_log_summary/_log_separator 通过
参数传入,保持日志格式完全一致。

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:59:02 +08:00
CodexandClaude Opus 4.7 df273ab231 refactor(stage): 抽 OCR 弹窗确认段到 popup_verification (1385 → 1230)
diagnose_stage_from_current_screen L1203-1358 是 156 行"未命中任何阶段
但像素检测到弹窗背景"段,用 OCR 二次确认避免直播间背景色误判:
- 优惠券弹窗:OCR "参与按钮" 区域找"开心收下"(支持模式 0+1 并行)
- 购物红包弹窗:OCR "診斷購物紅包" 区域找"购物红包/邀你抢/抢红包"

抽到 douyin_stage_handler_pkg/popup_verification.py:
- verify_popup_via_ocr(...) 入口,返回 Optional[Tuple[str, str]]
  - ("COUPON_POPUP", reason) / ("SHOPPING_REDPACKET_POPUP", reason)
    → caller 立即 return 该元组
  - None → 没有可疑弹窗或 OCR 确认失败,caller 继续后续逻辑

主函数对应位置替换为 17 行委托,保留原 _log / _log_summary 嵌套闭包通过参数传入,
保持日志格式完全一致。

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:54:00 +08:00
CodexandClaude Opus 4.7 d60b83af68 refactor(reservation): 抽回退校验+二次回退到 attend_window_verify (1437 → 898)
attend_window.process_reservation_attend_window 中 L754-1293 是 540 行
"if ok:"分支:回退操作成功后等待直播间加载 → 调
douyin_reservation_verify.validate_back_to_reservation 校验 → 校验失败时
通过映射表重定位 + 二次回退。

抽到 reservation_logic/attend_window_verify.py:
- handle_back_verify(...) 入口,返回 Optional[bool]
  - True/False  → 主函数应立即返回该值
  - None        → 校验通过/禁用/异常,主函数继续设置锁定期
- _handle_verify_failure: 校验失败的处理流程
- _remap_target_via_room_titles: 映射表重定位(target + 当前直播间位置)
- _retry_seek_with_mapped_diff: 根据 mapped_pos_diff 决定是否二次回退
  - diff=0 + room_pos_before_map 不一致 → 设置 _seek_direction_hint 重试
  - diff=0 + 一致 → 跳过二次回退

主函数对应位置替换为 14 行委托。

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:49:37 +08:00
CodexandClaude Opus 4.7 e46497ea80 refactor(underlying): 抽 cut_pic 图片裁剪到 image_ops (1574 → 1327)
underlying_operations.cut_pic L474-721 是 248 行图片裁剪管道:
- 默认/命名两个分支共享重试 3 次的截图加载验证
- 默认分支裁出 cut.png 或 ocr/<name>.png;命名分支裁出 pic/<target>/<name>.png
- 写入 _ocr_coords_cache 供 analyse_pic_word 调试图像引用
- SAVE_CUT_PIC_DEBUG_IMAGES=1 时保存 cut_pic 调试图

抽到 underlying_operations_pkg/image_ops.py:
- cut_pic(self, left_up, right_down, target, name) -> bool
- _ensure_parent_dir / _validate_coords / _save_cut_debug_images 内部 helper

主类方法替换为 4 行委托。

更新两个旧的源码断言测试以适配抽离:
- test_cut_pic_path:从 inspect.getsource(op.cut_pic) 改为读 image_ops.py 文件源码
- test_runtime_path_anchors:把 path_config.get_pic_dir() 检查范围从单一文件
  扩展到 underlying_operations.py + image_ops.py + ocr_pipeline.py 三处

1361 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:43:36 +08:00
CodexandClaude Opus 4.7 8457219241 refactor(underlying): 抽 analyse_pic_word OCR 管道到 ocr_pipeline (1939 → 1560)
underlying_operations.analyse_pic_word L723-1102 是 380 行 OCR 主管道:
路径解析 + 字节缓存 + PIL 加载 + change_color 预处理 + 调试图像保存
+ EasyOCR/PaddleOCR 调用 + 置信度提取 + 缓存写回 + 成功识别落盘。

抽到 underlying_operations_pkg/ocr_pipeline.py:
- analyse_pic_word(self, picname, change_color, pic_path, return_confidence)
- _save_debug_preprocessed: 预处理后的调试图保存(仅 SAVE_OCR_DEBUG_IMAGES=1)
- _save_debug_after_ocr: 含 OCR 文本预览 + 置信度的 after_ocr 调试图
- _save_success_pic: 成功识别落盘到 ocr/<category>/<picname>_success.png

主类方法替换为 4 行委托。原行为完全保留:缓存 / 二值化 / EasyOCR vs Paddle
predict/ocr 兜底 / [None] 短路 / 异常返回空 / picname 失败诊断日志。

新增 16 个单元测试覆盖:
- 早出 4 种(pic_path 空/不存在/带 confidence/OCR 未初始化)
- OCR 调用路径(EasyOCR / Paddle predict / Paddle ocr 兜底 / [None] 短路 / 异常)
- 缓存命中跳过 OCR / 缓存未命中写回
- change_color 0/1/2 三种模式
- return_confidence True/False 返回类型
- autouse fixture 清 OCR 模块级缓存防止测试污染

1361 passed (+16)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:36:47 +08:00
CodexandClaude Opus 4.7 b200002a00 refactor(finder): 抽 OpenCV 模板匹配兜底到 finder_template_match (635 → 417)
check_have_fudai_with_ready_screenshot L288-513 是像素检测都失败时的最后
兜底(226 行):cv2.matchTemplate(TM_CCOEFF_NORMED) + minMaxLoc 在
156..269 × 351..451 搜索区域里找 fudai.png 模板。

抽到 douyin/detection/detection_pkg/finder_template_match.py:
- match_template(analyser, pic_new, rx, ry, y_pianyi_val, loop) → (det, x)
- _resolve_template_path 从 path_config / 项目根 assets 解析模板路径
  (兜底走 .. 回退,避免推到 detection_pkg/assets)
- _save_search_roi 提取 last_match.png 的保存逻辑

主 finder.py 替换为 7 行委托,从 635 → 417 行。

新增 9 个单元测试覆盖:
- _resolve_template_path:用 path_config / 兜底
- 早出条件:模板路径不存在 / cv2.imread 返回 None / 搜索区域无效
- 命中:max_val>=threshold 时 detected_x 是 1080 基准
- 不命中:max_val<threshold 时返回 False
- 模板太大:cv2.resize 被调用
- cv2 不可用时安全返回 False

1345 passed (+9)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:26:49 +08:00
CodexandClaude Opus 4.7 ab846dae0f refactor(finder): 抽逐像素兜底扫描到 finder_pixel_scan (817 → 635)
check_have_fudai_with_ready_screenshot L279-461 是 numpy 失败时的逐像素
兜底(183 行):optimal_x 从历史 / 默认热区中心选起 → 检查 5 个 y 偏移
(0/±1/±2)→ 每行从 optimal 向两侧交替搜索 → 最后从左到右兜底。

抽到 douyin/detection/detection_pkg/finder_pixel_scan.py:
- scan_pixel_by_pixel(analyser, pic_new, rx, ry, y_pianyi_val) → (detected, x)
- _is_target_pixel / _safe_check_pixel / _pick_optimal_x / _search_along_y
  4 个独立纯函数,每个职责单一

颜色范围常量与 finder_numpy_scan 对齐(_R_MIN/_MAX 等)。

主 finder.py 替换为 8 行委托。

新增 15 个单元测试覆盖:
- _is_target_pixel 边界 / _safe_check_pixel 异常兜底
- _pick_optimal_x 历史命中/越界/无历史 3 种路径
- scan_pixel_by_pixel 主路径成功 / y 偏移 / 越界失败 / pic 异常兜底

1336 passed (+15)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:20:25 +08:00
CodexandClaude Opus 4.7 07cdd662c2 refactor(finder): 抽 numpy 加速扫描段到 finder_numpy_scan (937 → 811)
check_have_fudai_with_ready_screenshot L271-397 是"numpy 加速水平带扫描"
逻辑(126 行):ROI 裁剪 → RGB 颜色掩码 → 列聚合 → 从最优起始列向两侧
交替搜索第一个匹配列 → 写回 last_fudai_x。

抽到 douyin/detection/detection_pkg/finder_numpy_scan.py:
- scan_with_numpy(analyser, pic_new, rx, ry, y_pianyi_val, optimal_x_scaled)
  → (detected, detected_x)
- numpy ImportError / 异常时返回 (False, None),让 caller 走逐像素兜底

主 finder.py 替换为 7 行委托。

新增 8 个单元测试(用真实 PIL.Image + numpy 构造小图):
- 空图返回 False
- 整图目标色命中 + last_fudai_x 写回
- 仅在某段列有目标色,命中位置在该段
- y_pianyi_val 偏移正确传递到扫描带
- ROI 越界返回 False
- optimal_x_scaled 在命中区时优先返回该位置

1321 passed (+8)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:15:43 +08:00
CodexandClaude Opus 4.7 1514122981 chore(finder): 删 check_have_fudai_with_ready_screenshot 末尾 501 行死代码 (1438 → 937)
L938-1438 全部位于 L936 `return False` 之后,永远不会执行:
- 旧版重复参数初始化(retry_delay_s / max_wait_s 等)
- 已被弃用的模板匹配兜底代码块
- 末尾的"以下为旧的像素检测代码"注释块

文件大小直接砍 35%,无任何行为变化。

1313 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:09:36 +08:00
CodexandClaude Opus 4.7 f718dfe2e4 refactor(fudai_attend): 抽 1057 行粉丝团门槛分支到 fansclub_handler (1629 → 573)
attend_choujiang 中"加入粉丝团/粉丝团"按钮分支占 1057 行,含一个 751 行的
内嵌闭包 _recover_to_fudai_detail_after_fansclub 处理"加入页"恢复。该分支
是文件中最大的单一逻辑块,独立性高(没有共享主流程的局部变量,全靠 analyser
属性传递状态)。

新建 fudai_attend_pkg/fansclub_handler.py(1070 行)作为整段抽出后的目的地。
导出顶层函数 handle_fansclub_branch(analyser, attend_button_text) -> bool。

attend_choujiang 中原 elif 块替换为 4 行委托:
    elif attend_button_text and (
        "加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text
    ):
        return handle_fansclub_branch(analyser, attend_button_text)

行为完全保留:
- 设置 analyser.last_attend_fail_reason = "fansclub_required"
- 第一步点参与按钮 (543, 2070)
- 第二步 OCR 找加入粉丝团按钮 + bbox 中心点击(fallback 区域中心)
- 第三步关闭详情页 (500, 470)
- 第四步根据 auto_join_fansclub 等待
- 第五步 _recover_to_fudai_detail_after_fansclub 在加入页再点击 + 返回直播间

新增 9 个单元测试覆盖:
- 总返回 True
- 设置 fail_reason = "fansclub_required"
- 必经的两次坐标点击 (543,2070) / (500,470)
- 截图缺失/OCR 抛异常时的兜底
- auto_join 启用/禁用分支

1313 passed (+9)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 02:05:38 +08:00
CodexandClaude Opus 4.7 2f0eb90d98 refactor(fudai_core): 抽 6 个 fallback OCR 闭包到 OcrTaskRunnerFallback (1350 → 1194)
主并行 OCR 失败时走的备用路径里有 6 个 ocr_*_fallback 闭包,结构与
OcrTaskRunner 类似但更简单(不计耗时、countdown 不做数字提取、日志
tag 改为"备用OCR..."),共 156 行。

复用 ocr_tasks.py 模块新增 OcrTaskRunnerFallback 类,与 OcrTaskRunner
共享 _safe_preprocess / _BUTTON_KEYWORDS / _read_disable_flag。

主流程 6 个闭包定义换成 14 行 runner 实例化 + 方法绑定。

新增 10 个单元测试覆盖 Fallback 的所有方法(disable 跳过 / 异常 /
countdown 不提取数字 / button 关键词短路 + retry)。

1304 passed (+10)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:58:13 +08:00
CodexandClaude Opus 4.7 f38b373636 refactor(fudai_core): 抽 7 个并行 OCR 闭包到 ocr_tasks 模块 (1659 → 1328)
get_fudai_contain L222-553 有 7 个 ocr_* 闭包:task_list / content /
countdown_mm / countdown_ss / value / button / live_room_title。每个都遵循
同样的模板(计时 + analyse_pic_word/digits + perf 字典 + 异常日志),共 330 行。

抽到 douyin_fudai_core_pkg/ocr_tasks.py 的 OcrTaskRunner 类:
- 7 个方法对应 7 个并行任务
- 共享耗时 dict + lock 在构造器传入
- _record_duration / _log_warn 提取出共有的 finally + except 模板
- _BUTTON_KEYWORDS 关键词常量化(原本是闭包里硬编码 tuple)
- _safe_preprocess 顶层 helper

主流程从 7 个闭包定义 + 配置开关重复读取(330 行)变成 22 行 runner 实例化 +
方法绑定,并保留 ocr_task_list / ocr_content / ... 名字给后续 executor.submit
当作 Callable 传入,行为完全不变。

新增 22 个单元测试覆盖:
- _safe_preprocess 兜底
- 7 个方法的成功 / disable 跳过 / 异常 / 边界
- ocr_button 关键词短路 + 重试逻辑
- 所有方法都正确记录耗时到 perf_durations

1294 passed (+22)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:52:22 +08:00
CodexandClaude Opus 4.7 457edcfdc8 refactor(fudai_core): 合并 4 个 renwu 分支截图准备到 cut_regions (1825 → 1651)
get_fudai_contain L160-334 按 renwu (1/2/3/其他) 重复 4 次相似的 175 行
分支,每个分支都做"内容/倒计时(切两段)/价值"4 次 cut_pic + 可选调试截图,
唯一差异只是 countdown_box 常量。

抽到 douyin_fudai_core_pkg/cut_regions.py:
- _select_countdown_box(renwu) 选坐标
- cut_detail_regions(analyser, renwu, save_debug_images) 统一切割

原 175 行 4 个重复分支替换为 8 行调用,净减 167 行。

新增 12 个单元测试覆盖:
- _select_countdown_box 4 种 renwu
- cut_detail_regions 调 cut_pic 4 次 / 名称顺序 / 30%-30% 分割比例
- save_debug_images 开关效果

1272 passed (+12)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:47:36 +08:00
CodexandClaude Opus 4.7 03b471513d refactor(fudai_core): 抽 _run_heavy_ocr 闭包到 heavy_ocr 模块 (1953 → 1822)
_run_heavy_ocr 是 get_fudai_contain 中的 142 行闭包,按需对 6 个字段
(task_list / content / countdown_mm / countdown_ss / value / button)
跑较重的 OCR 模型补齐轻量 OCR 漏掉的字段。

抽到 douyin_fudai_core_pkg/heavy_ocr.py:
- run_heavy_ocr(analyser, fields) 顶层主函数
- _read_disable_flag(analyser, attr, cfg_key) 提取重复的 attr→config.json
  fallback 配置开关读取(原闭包里 task_list 和 content 各重复一次)
- _ocr_digits_with_fallback(analyser, picname) 提取 mm/ss 分支共有的
  digits→word 兜底数字提取逻辑

原闭包改为 4 行委托。配置开关、日志和异常兜底行为完全一致。

新增 18 个单元测试覆盖:
- _read_disable_flag 4 种状态(attr 优先 / config 兜底 / 都缺 / 文件不存在)
- _ocr_digits_with_fallback 5 个分支
- run_heavy_ocr 9 个字段组合 + disable 跳过路径

1260 passed (+18)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:39:24 +08:00
CodexandClaude Opus 4.7 2707773b15 refactor(fudai_core): 抽 _read_countdown_split 闭包到 countdown_split 模块 (2124 → 1953)
douyin_fudai_core.py 的 get_fudai_contain 函数体只有 1 个,但里面嵌了
多个闭包做 OCR 子任务。最大的 _read_countdown_split (172 行) 把倒计时
区域分割成"分钟"+"秒"两段分别识别再组合 mm:ss。

抽到 douyin_fudai_core_pkg/countdown_split.py 的 read_countdown_split
顶层函数(203 行,含独立的 _extract_digits 纯函数)。原闭包改为薄壳委托,
保留 box 默认绑定 analyser/save_debug_images 闭包变量的语义。

新增 16 个单元测试覆盖:
- _extract_digits 纯函数(前导零 / 非数字 / 边界)
- read_countdown_split 主路径 + OCR 失败 + 秒>=60 警告 + 切图失败
- 切割比例(30% / 30%)正确性
- save_debug_images 开关效果

1242 passed (+16)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:30:35 +08:00
CodexandClaude Opus 4.7 07eee6da52 fix(paths): 修同类型 5 处路径推导 bug + 加回归测试
cut_pic 路径 bug 之后再做地毯式排查,发现 5 处类似潜在 bug:
fallback 分支用 dirname(__file__) 推根级目录,path_config 不可用时
会指向错误位置(推到 douyin/core/pic 等子目录而非项目根 pic/)。

修复:
- underlying_operations.py: screenshot_calls.jsonl 路径 + OCR category 目录
  改用 path_config.get_logs_dir() / get_pic_dir()
- douyin_fudai.py: 2 处 actions.log 兜底路径
  优先 path_config.get_actions_log_path(),兜底加 ".." 回到项目根
- fudai_detail_room_title.py: 截图复用 fallback 路径加 ".." 回退
- fudai_detail_orchestrator_pkg/read_once.py: 同上 2 处 fallback

新增 11 个回归测试覆盖:
- 关键文件不再用单步 dirname/__file__/pic 写法
- path_config 仍把所有路径锚到 PROJECT_ROOT
- 兜底分支必须含 ".." 表示回退

注:douyin_fudai.py:299 的 reservations.json 因 dirname 恰好等于
PROJECT_ROOT/douyin/core,跟 path_config.get_reservations_path() 一致,
不是 bug,未改动。

1226 passed (+11 新增)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:21:27 +08:00
CodexandClaude Opus 4.7 52b811d0cb feat(scan): WiFi-ADB 扫描支持自定义/多端口(覆盖 Android 11+ 随机端口)
之前只扫 5555。Android 11+ "无线调试" 用 37000-44999 随机端口,
固定的 adb tcpip 也可改端口。新接口让扫描适配任意端口规格。

新增 parse_port_spec:解析端口规格字符串
  - 5555            单端口
  - "5555,5556"     逗号分隔
  - "37000-37010"   范围(最大 1024 个)
  - 混合格式与序列输入
  - 非法/越界 → 退化为默认 5555
  - 单个范围 > 1024 端口直接忽略,避免误扫整个端口段

scan_open_ports 重构:
  - 接受 ports 参数(list[int]),传 ports 时优先于旧 port=int
  - 返回 list[(ip, port)] 而不是 list[ip],按 (IP 数值序, port 升序) 稳定排序

discover_adb_devices 支持 ports 参数,按 (ip, port) 逐个 verify_adb_target

接入 GUI 与 webui:
  - gui_app.py 扫描对话框新增"端口"输入框 + 提示
  - gui_app.py 启动重连:上次端口非 5555 时把它一并扫描
  - web_gui.py /api/wifi/scan 接受 ports;/api/wifi/auto-reconnect 同上次端口逻辑

新增 13 个 parse_port_spec 单测 + 4 个 scan_open_ports 多端口测试 +
2 个 discover_adb_devices 多端口集成测试。
真机验证:6 端口 (5555 + 37000-37005) × 254 IP,~8.5s 扫完,
正确发现 192.168.5.2:5555 (PEPM00)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 01:02:48 +08:00
CodexandClaude Opus 4.7 4ab4504425 fix(cut_pic): 修截图路径错位 — pic 目录从 douyin/core/pic 改回项目根 pic
cut_pic 历史 bug:用 os.path.dirname(__file__) + "/pic" 推路径,
误指向 douyin/core/pic/(不存在),实际截图保存在 <project_root>/pic/。
日志中频繁出现"截图文件不存在: .../douyin/core/pic/screenshot.png"。

改为:
- 默认分支用 path_config.get_pic_dir() / get_screenshot_path()
- target 分支用 os.path.join(path_config.get_pic_dir(), target)

补 5 个回归测试覆盖:
- 源码不再含旧的 dirname-based 路径
- path_config 路径解析到 <project_root>/pic
- 截图缺失时 cut_pic 返回 False(重试 3 次后兜底)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-23 00:47:02 +08:00
CodexandClaude Opus 4.7 fb82213d53 refactor(underlying): 抽 _get_screenshot_direct 到 underlying_operations_pkg/screenshot_direct (2416 → 1930)
497 行的 ADB 截图实现(含 exec-out 主路径 + 多重兜底 + watchdog)整段抽到
underlying_operations_pkg/screenshot_direct.capture_screenshot_direct,
原方法保留 9 行 thin shim:

    def _get_screenshot_direct(self, device_id, path="pic"):
        from douyin.core.underlying_operations_pkg.screenshot_direct import (
            capture_screenshot_direct,
        )
        return capture_screenshot_direct(self, device_id, path)

净减 486 行。函数体过深的两层嵌套截图逻辑现在独立成模块,方便单独测试与改进。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:55:34 +08:00
CodexandClaude Opus 4.7 ffd048ffa5 refactor(fudai): 抽 run_once_basic 0.1 高价值预约检查到 helper (2079 → 1541)
新增 5 个 helper 到 run_once_basic_helpers.py:
- handle_reservation_check          0.1 预约检查主入口
- _maybe_clear_reservations_on_first_run  首次运行清空队列 + 状态文件
- _log_reservation_check_trigger    调试日志:检查触发条件
- _run_reservation_attend_window    队列满处理 / 抢占逻辑
- _log_reservation_attend_check     调试日志:第一个预约信息

净减 538 行重复嵌套样板。新增 7 个单元测试覆盖:
- 高价值未启用 / 队列空 → return False
- 首次运行清空队列
- 正常路径调 process_reservation_attend_window
- 队列满 → return True
- needswitch=False 走单间模式 + cleanup
- 等待开奖标志不阻断流程

至此 run_once_basic 总长 612 → 88 行(-86%),douyin_fudai.py
累计 4121 → 1541(-2580 行 / -63%),不再是项目最大文件。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:45:51 +08:00
CodexandClaude Opus 4.7 61cdf7b445 refactor(fudai): 抽 _handle_in_fudai_detail 步骤1 第二次打开分支 (2216 → 2079)
新增 handle_second_open_branch helper:
- 取 _last_fudai_detail_tuple;缺失/无效则重新读取(兜底)
- 有效缓存:从 countdown_tuple 提取 future_ts/原始秒数 + 设到 self
- 调 attend_choujiang:成功清标志 / 失败累加计数 / 异常 fall through

顺手修了一个 latent bug:first-open 抽出后 caller 还在用 step3_start /
skip / skip_reason 这些已不在作用域里的变量。改成从 self._last_fudai_detail_tuple
重新取 detail,去掉无意义的 step3_elapsed 日志,step4 的 skip 参数
直接传 (False, "") —— skip 已在 first-open 内部处理完。

净减 146 行嵌套样板。新增 6 个 second-open 单元测试覆盖:
- 缓存缺失重读 + fall through
- 短 tuple 触发重读
- attend 成功清标志清失败计数
- attend 失败累加计数
- attend 异常 fall through
- 缓存有效时正确设置 _current_fudai_future_ts

至此 _handle_in_fudai_detail 总长 506 → 215 行(-58%),
douyin_fudai.py 累计 4121 → 2079(-2042 行 / -50%)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:18:33 +08:00
CodexandClaude Opus 4.7 ca953cb4ba refactor(fudai): 抽 _handle_in_fudai_detail 步骤2+3 第一次打开分支 (2568 → 2216)
新增 5 个 helper 到 handle_detail_helpers.py:
- handle_first_open_branch       第一次打开主入口
- _validate_first_open_detail    数据验证失败处理
- _check_skip_and_handle         筛选检查 + 高价值预约 + 切房
- _try_high_value_reservation    高价值倒计时阈值判断(return/continue/still_skip)
- _handle_skip_filter            普通筛选不通过:关详情 + 切房
- _fallback_swipe_up             swipe_up_to_next_live 不存在时的兜底

净减 354 行嵌套样板代码。新增 8 个单元测试覆盖:
- detail 无效 / 短 tuple
- 数据验证失败
- 筛选通过保存数据
- 普通筛选不通过 + needswitch true/false
- 高价值阈值内立即参与
- 高价值阈值外记预约

至此 _handle_in_fudai_detail 总长 1010 → 506 行(-50%),
douyin_fudai.py 累计 4121 → 2216(-1905 行 / -46%)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 22:00:24 +08:00
CodexandClaude Opus 4.7 aeb51f73c7 chore(fudai): 清理 _handle_in_fudai_detail 死代码 + 4 处重复 cleanup
- 1 处 dead code:is_second_open 重复赋值(同一变量连读两次)
- 4 处内联"清除任务数量标志 + 嵌套 try"块用 _hd_helpers._clear_task_count_flag 替换

净减 50 行重复样板,2614 → 2568 行。
全套 1172 个测试通过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 21:35:38 +08:00
CodexandClaude Opus 4.7 0540610c75 refactor(fudai): 抽 _handle_in_fudai_detail last_status 检查到 helper (2872 → 2614)
新增 3 个 helper:
- check_last_status_branch:根据 _last_fudai_detail_status 路由 4 个状态
  (coupon_popup / watch_task / validation_failed / error)
- _clear_task_count_flag:清除 _fudai_detail_task_count_from_stage(多分支共用)
- _handle_error_status:error + reason=task_count_zero 时连续 3 次切直播间

净减 260 行重复样板代码。新增 9 个单元测试覆盖:
- 4 种已知 status 各自分支
- 未知/空 status 不触发
- task_count_zero 第 1 次仅累计、第 3 次强制切房 / needswitch=False 不切

至此 _handle_in_fudai_detail 总长 1010 → 752 行,
douyin_fudai.py 累计 4121 → 2614(-1507 行 / -37%)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 21:23:26 +08:00
CodexandClaude Opus 4.7 7b6dec820b refactor(fudai): 抽 _handle_in_fudai_detail 步骤3末尾两个小段 (2926 → 2872)
新增 2 个 helper:
- check_invalid_detail_fallback:兜底检查(content="" + value=0 → 视为无效详情)
- prepare_for_attend:记 attend_before_ts + 提取 future_ts + 重置 _detail_closed_by_attend

净减 54 行重复样板代码。新增 9 个单元测试覆盖:
- 空内容+0价值识别为无效
- 正常内容不触发兜底
- detail tuple 短或非 tuple 不抛
- prepare_for_attend 正确返回 attend_before_ts 和写入 future_ts

至此 _handle_in_fudai_detail 总长 1872 → 1010 行(-862 行 / -46%),
douyin_fudai.py 4121 → 2872(累计 -1249 行 / -30%)。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 21:16:06 +08:00
CodexandClaude Opus 4.7 8a975f2bf6 refactor(fudai): 抽 _handle_in_fudai_detail 步骤4 到 handle_detail_helpers (3174 → 2926)
新增 3 个 helper:
- step4_make_join_decision:参与决策入口(detail=None 短路 + 调 basic_join_decision)
- _handle_reservation_completion:参与成功是预约福袋时的锁定期处理 + 队列清理
- _close_detail_after_attend:根据 _detail_closed_by_attend 决定是否点 click_back

净减 251 行重复代码。新增 7 个 step4 单元测试覆盖:
- detail=None 短路
- join_decision 失败不设标志
- countdown 有效设标志 + 关详情
- attend 已关详情时跳过 click_back
- 预约福袋无其他预约 → 清锁定期
- 预约福袋有其他预约 → 设保护期
- countdown 已过期不设标志

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 21:09:24 +08:00
CodexandClaude Opus 4.7 cea3aced73 feat(web_gui): WebUI 启动时自动重连上次 WiFi 设备 + 智能匹配
新增 /api/wifi/auto-reconnect 端点,把桌面 GUI 的 _try_reconnect_last_wifi
逻辑搬到服务端:先 verify_adb_target 上次的 target → 失败则 discover_adb_devices
扫描 + pick_best_match 智能匹配。返回结构化 JSON 让前端渲染:

  action: noop | already_online | reconnected | matched | failed
  target / model / message / devices

webui/app.js DOMContentLoaded 末尾调用 tryAutoReconnectLastWifi(),
不阻塞页面加载。命中后自动刷新设备下拉并选中。

至此桌面 GUI 和 WebUI 在 WiFi 重连体验上完全对齐:换网段也能找回手机。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:53:23 +08:00
CodexandClaude Opus 4.7 5966f461c3 feat(wifi_adb): 启动重连失败时自动扫描子网 + 智能匹配
新增 pick_best_match(devs, last) 纯函数,按优先级匹配上次设备:
1. target 完全一致(IP 没换)
2. 同 model + 同 port(换 IP 但同一台手机)—— 多台同型号时返回 None 让用户选
3. 同主机段 + 同 port(弱兜底,仅唯一时返回)
4. 唯一一台 connected(扫到就一台时认定)

GUI _try_reconnect_last_wifi 流程升级:
- verify_adb_target 失败(不可达)→ 自动 discover_adb_devices 扫子网
- pick_best_match 命中 → 选中 + 更新 last_wifi_target
- 命中且 IP 已变 → 日志写"上次目标 X 已变 → 智能匹配到 Y(已更新记忆)"
- 没命中 → 列出候选 + 提示点'扫描 WiFi'手选

实际场景:换 WiFi 网段(家里 → 公司 / 192.168.1 → 192.168.5)后
GUI 启动时自动找回同一台手机,无需任何手动操作。

新增 15 个 pick_best_match 单元测试覆盖所有规则 + 边界。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:46:23 +08:00
CodexandClaude Opus 4.7 3d91764f56 feat(webui): WebUI 加"扫描 WiFi"按钮,对齐桌面 GUI
- index.html:WiFi ADB 操作行加"扫描 WiFi"按钮 + 扫描结果区域
- app.js:wifiScan() 调 /api/wifi/scan
  - 单个 connected:自动填回 IP,刷新设备
  - 多个候选:渲染列表,点击就填回 IP
  - unauthorized:提示需手机端授权
- 单击列表项 → 填 wifi_ip 输入框 + 刷新设备下拉

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:40:54 +08:00
CodexandClaude Opus 4.7 8c3a162deb feat(web_gui): WebGUI 对齐桌面 GUI 的 WiFi 扫描和 last_wifi_target 能力
新增 4 个端点:
- POST /api/wifi/scan       扫描局域网 ADB 设备
- GET  /api/wifi/last       查询上次连接记录
- POST /api/wifi/last       同上(POST 方便 fetch)
- POST /api/wifi/last/clear 清除记录

同步 connect / disconnect 路径行为:
- /api/wifi/connect 成功后写入 last_wifi_target(取设备型号)
- /api/wifi/disconnect 如果断的就是上次记住的设备 → 自动清除记录

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:33:22 +08:00
CodexandClaude Opus 4.7 b3a41db029 feat(wifi_adb): WiFi-ADB 设置对话框三个连接路径都记 last_wifi_target
补齐之前 main commit a71f6fa 漏的几处:
- "连接"按钮:成功后保存 ip:port + 设备型号到 last_wifi_target
- "自动连接"按钮:从 USB → WiFi 切换成功后保存
- "断开连接"按钮:如果断开的就是上次记住的 IP,清掉记录避免下次启动徒劳重试

行为现在统一:所有"连上一台 WiFi 设备"的入口都会更新记忆,所有"主动断开"
的入口都会清除记忆。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:21:24 +08:00
CodexandClaude Opus 4.7 a71f6faed0 feat(wifi_adb): 记住上次成功的 WiFi 设备,GUI 启动时自动重连
新增 gui/gui_core_pkg/config.py 三个 helper:
- get_last_wifi_target  / set_last_wifi_target / clear_last_wifi_target
配置以 last_wifi_target = {target, model, saved_at} 形式存在 config.json 顶层。

GUI 行为:
- "扫描 WiFi" 选中或自动连上一台 connected 设备 → 写入 last_wifi_target
- WiFi 选择对话框"使用选中"也写入
- 主窗口启动后延迟 300ms 后台尝试 verify_adb_target(last.target)
  - 已有设备:不打扰
  - 重连成功:自动设为当前设备
  - unauthorized:提示需手机端授权
  - 不可达:提示换网了,引导点'扫描 WiFi'

新增 12 个 last_wifi_target 单元测试覆盖读写/清除/损坏值/缺文件等场景。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:16:37 +08:00
CodexandClaude Opus 4.7 db7a78876b feat(gui): 主窗口加"扫描 WiFi"一键按钮
主窗口设备行的"刷新设备"按钮旁加"扫描 WiFi"按钮。后台线程扫描局域网,
按结果数智能处理:

- 0 个发现     → 日志提示
- 1 个 connected → 自动设为当前设备
- N 个 unauthorized → 提示需手机端授权
- 多个候选     → 弹简化版列表对话框让用户选

省去打开 WiFi-ADB 设置对话框的步骤,常见单机场景一键完成。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 20:09:01 +08:00
CodexandClaude Opus 4.7 e89393693b feat(wifi_adb): 加局域网 ADB 设备扫描发现
新增 gui/gui_core_pkg/wifi_adb_scan.py(356 行):
- get_local_subnet:从本机 WLAN 出口 IP 推 /24 子网
- parse_subnet_spec:解析 192.168.5.0/24 / 192.168.5.1-100 / 192.168.5.5 / 逗号组合
- probe_adb_port:并发 TCP 探测(默认 0.3s 超时,64 线程并发)
- verify_adb_target:对每个开放端口的 IP 调 adb connect 区分 connected / unauthorized / failed
- discover_adb_devices:主入口,端到端只需 1.5 秒扫完 /24

GUI(gui/gui_app.py)"扫描局域网"按钮加在 WiFi 设备操作区:
- 自动推子网(默认)+ 手动输入支持 CIDR / 范围 / 单 IP / 逗号
- 后台线程扫描,进度条 + 阶段提示
- 列表展示 IP / 状态 / 设备型号 / adb connect 输出,列表中手动选
- 选中已 connected 的设备 → 回填 IP 到主对话框
- unauthorized 设备明确提示需手机端授权

新增 25 个 wifi_adb_scan 单元测试。真机端到端验证通过:1.5s 扫完
192.168.5.0/24 子网,发现 192.168.5.2:5555(PEPM00)connected。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 19:59:19 +08:00
CodexandClaude Opus 4.7 23d370ae22 fix(wifi_adb): 修 3 处导致 WiFi-ADB 自动连接失败的解析 bug
1) get_device_ip 把 ip route 输出里的网段当 IP 返回
   原代码看到 "192.168.5.0/24 ... src 192.168.5.2" 时,扫到的第一个含 3 个点的字段是
   "192.168.5.0/24",结果用 0/24 当 IP 调 adb connect 必然失败。
   改成显式从 "src <ip>" 取,并优先 wlan 接口;加 ip addr show / ifconfig 兜底。

2) auto_connect_wifi_adb 顺序错误
   原代码先 tcpip 5555(让设备 adbd 重启、USB 链路断开)再 get_device_ip(需要 USB),
   USB 已断必然取不到 IP。改成先 get_device_ip 再 enable_wifi_adb 再 connect。

3) connect_wifi_adb 把"未授权 / 连接被拒"当成功
   adb connect 在 unauthorized / cannot connect / failed to authenticate 等场景下
   returncode 也是 0;以前只看 returncode + "connected" 子串,未授权也判成功。
   改成显式列出失败关键词,并对未授权给清晰的中文提示。

新增 20 个 wifi_adb 单元测试覆盖 3 处回归场景。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 19:32:04 +08:00
CodexandClaude Opus 4.7 a92cec4ff9 refactor(recovery): 抽 3 处桌面自救重复逻辑到 douyin/core/recovery 共享模块
新增 douyin/core/recovery.py(113 行):
- is_douyin_foreground(top_pkg): 统一判断前台是否抖音相关包
- recover_to_douyin(analyser, log=...): 桌面自救主入口(先 launch_package,失败回退点击)
- fallback_click_recovery(analyser, log=...): 旧的点击坐标自救兜底

3 处调用点收敛:
- fudai_modules/run_once_basic_helpers.handle_desktop_recovery:80 行 → 18 行
- douyin/other/douyin_yanghao.py: 3 段重复块(原 ~80 行 each)→ 单行调用

总计净减 -269 行重复代码。新增 13 个 recovery 单元测试 + 修测试 mock。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 19:20:29 +08:00
CodexandClaude Opus 4.7 4c1d95d4b5 feat(recovery): 桌面自救改用包名启动抖音,点击坐标降为兜底
当检测到不在抖音前台时,原先点击桌面图标 + 直播 + 进入直播间 3 步坐标的方式
依赖图标位置和分辨率,不同设备/桌面常常失败。改为优先调用 ADB 包名启动:

- underlying_operations 新增 launch_package(device_id, pkg):
  monkey -p <pkg> -c android.intent.category.LAUNCHER 1(主路径)
  失败回退到 am start -n <pkg>/<MainActivity>(多个常见 activity 兜底)
  默认按 com.ss.android.ugc.aweme / .lite / TikTok 顺序尝试

- 新增 is_douyin_foreground 便捷方法

- 改造 3 处自救点:
  fudai_modules/run_once_basic_helpers.py:handle_desktop_recovery
  douyin/other/douyin_yanghao.py(养号循环 + _yanghao_check_and_recover_from_desktop ×2)
  包名启动失败时仍走旧的点击逻辑作为兜底,向后兼容

新增 12 个单元测试覆盖 launch_package 主路径/兜底/失败和自救新行为。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 19:08:09 +08:00
CodexandClaude Opus 4.7 3aca02fae4 refactor(fudai): 抽 run_once_basic 2 段独立逻辑到 run_once_basic_helpers (3233 → 3174)
新增 2 个 helper:
- handle_just_recorded_reservation:刚记录预约后强制切换直播间
- handle_skip_stage_diagnosis:0.5 跳过阶段检测分支

新增 5 个单元测试。行为保持不变。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 18:37:18 +08:00
CodexandClaude Opus 4.7 695a84d8b5 refactor(fudai): 抽 _handle_in_fudai_detail 入口检查到 handle_detail_helpers (3294 → 3233)
抽出 2 个独立函数到 fudai_modules/handle_detail_helpers.py:
- log_entry_flags:进入方法时记录关键 flags
- handle_consecutive_failures_check:连续参与失败次数检查

新增 5 个单元测试覆盖阈值、needswitch 分支。行为保持不变。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 18:31:43 +08:00
CodexandClaude Opus 4.7 5802586b20 refactor(fudai): 拆 run_once_basic 6 段独立逻辑到 run_once_basic_helpers (4121 → 3294)
抽出 6 个独立函数到 fudai_modules/run_once_basic_helpers.py:
- handle_waiting_for_lottery_result:等待开奖期间持续 OCR 检测
- handle_no_attend_timeout:30 分钟未参与回到推荐页
- handle_desktop_recovery:桌面检测自救
- screenshot_and_diagnose:截图 + 阶段诊断
- handle_high_value_room_revisit:高价值房间重访
- dispatch_stage_branch:弹窗/详情/直播间/推荐页/开奖结果分发

新增 15 个单元测试覆盖各分支。run_once_basic 体积大幅瘦身但行为保持不变。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 18:22:17 +08:00
495 changed files with 86105 additions and 35563 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
+17
View File
@@ -60,6 +60,17 @@ git_lsremote_trace.txt
log_filter_result.txt
time_analysis_result.txt
# Test/diagnostic outputs
output/
artifacts/*
!artifacts/webui_checks/
artifacts/ocr_check/
artifacts/fudai_regression_runs/
artifacts/fudai_regression_samples/
artifacts/webui_checks/**/*.png
artifacts/webui_checks/**/*.txt
artifacts/webui_checks/**/*.json
# Local runtime state and generated caches
state/
pic/
@@ -84,6 +95,7 @@ temp/
# Local configuration and backups
config/*.json
!config/README.md
license.dat
*.bak
*.bak_*
*.backup
@@ -93,6 +105,7 @@ config/*.json
*~
# Generated tool reports and samples
*.spec
tools/coords_report*.csv
tools/*_report*.csv
tools/*_report*.csv.gz
@@ -103,6 +116,7 @@ tools/samples/
tools/*.zip
tools/*.tar.gz
tools/*.bundle
tools/tmp_pw_check.py
# Project-specific generated state
douyin/core/state/reservations.json
@@ -119,6 +133,9 @@ state/high_value_rooms.json
*.7z
*.bundle
# Local migration scratch notes
docs/json_migration_note.txt
# Node / frontend caches
node_modules/
npm-debug.log*
+41
View File
@@ -15,6 +15,47 @@
## [Unreleased]
## [V3.3.11] — 2026-06-29
## [V3.3.10] — 2026-06-29
## [V3.3.9] — 2026-06-28
### Fixed
- 自动更新差量包下载、校验或启动失败时自动回退完整安装包,避免旧版本反复卡在失败的 delta 更新上。
- 记录已启动的差量更新尝试;如果下次启动仍停留在旧版本,则跳过同一个 delta 并改用完整安装包。
### Added
- Dashboard 顶部新增“检查更新”按钮,可手动触发在线更新检查。
### Changed
- 自动更新默认启用;未配置更新地址时默认使用官方更新服务器,仍可通过配置或环境变量关闭。
## [V3.3.8] — 2026-06-28
### Fixed
- 修复部分荣耀/华为设备上 `adb exec-out screencap -p` 返回 `4294967295` 或损坏 PNG 后,截图链路未继续尝试 shell stdout 兜底的问题。
- 打包时收集 `paddlex` / `paddleocr` / Paddle / OpenCV / NumPy / PIL / pyclipper / shapely 运行依赖,避免新电脑上 OCR 初始化缺少 `_internal\paddlex\.version` 或相关二进制组件。
### Added
- Dashboard 新增“上传诊断日志”,客户端只打包有限大小的日志片段;服务端按卡密覆盖保存一份,便于远程排查问题。
## [V3.3.7] — 2026-06-28
### Changed
- Dashboard 首次启动未授权时锁定在“授权”页,验证卡密成功后再进入数据看板。
- WebGUI 未授权访问首页时先显示卡密验证门禁页,验证成功后再加载完整控制台。
### Fixed
- 保留运行接口的授权拦截,避免未输入卡密时通过接口直接启动运行。
## [V3.3.6] — 2026-06-27
## [V3.3.5] — 2026-06-27
## [V3.3.4] — 2026-06-26
### Added
- 引入完整的版本管理体系:
+235 -637
View File
@@ -1,707 +1,305 @@
# 抖音福袋挂机脚本
# 抖音自动化助手 - 数据看板版使用说明
<div align="center">
这是打包成 exe 后给普通用户使用的说明。正常使用时不需要安装 Python,也不需要打开源码文件。
**基于 ADB + OCR + 像素检测 + 模板匹配的抖音直播间福袋自动挂机工具**
## 文件说明
[![Version](https://img.shields.io/badge/version-V3.3.3-blue.svg)](douyin/core/version.py)
[![Python](https://img.shields.io/badge/python-3.10+-green.svg)](https://www.python.org/)
[![Platform](https://img.shields.io/badge/platform-Windows-lightgrey.svg)](https://www.microsoft.com/windows)
解压或安装后,主要会看到这些文件:
</div>
> ⚠️ **本工具仅供学习交流使用**。使用产生的任何后果(账号风控、数据丢失等)由使用者自行承担。完整免责条款见文末 [免责声明](#免责声明)。
---
## 📖 目录
- [项目简介](#项目简介)
- [核心功能](#核心功能)
- [技术架构](#技术架构)
- [环境要求与安装](#环境要求与安装)
- [快速开始](#快速开始)
- [详细配置说明](#详细配置说明)
- [使用指南](#使用指南)
- [工作原理](#工作原理)
- [代码结构](#代码结构)
- [测试](#测试)
- [开发指南](#开发指南)
- [故障排查](#故障排查)
- [常见问题](#常见问题)
- [版本更新日志](#版本更新日志)
- [贡献与反馈](#贡献与反馈)
- [免责声明](#免责声明)
---
## 项目简介
通过 ADB 连接安卓设备,结合像素检测 / 模板匹配 / OCR 三种技术识别抖音直播间状态,自动完成福袋发现、参与、领奖、人机验证、推荐页养号等操作。
适用场景:长时间挂机抢福袋、多账号管理、定时养号。**不适用**于商业用途。
更详细的内部技术资料:[`docs/完整技术文档.md`](docs/完整技术文档.md)、[`docs/archive/AI_PROJECT_SUMMARY.md`](docs/archive/AI_PROJECT_SUMMARY.md)(归档)。
---
## 核心功能
| # | 功能 | 说明 |
|---|------|------|
| 1 | **福袋检测** | 在直播间内通过模板匹配定位福袋图标,自动打开详情页 |
| 2 | **信息识别** | OCR 提取福袋内容、倒计时、价值(元)、参与人数 |
| 3 | **筛选参与** | 价值/人数/关键词三维筛选,命中黑白名单后决策是否参与 |
| 4 | **自动领奖** | 识别开奖结果,中奖后自动领取并处理订单确认页 |
| 5 | **高价值预约** | 价值 ≥ 阈值的福袋记录开奖时间,提前回退到目标直播间参与(需 `needswitch=true`) |
| 6 | **高价值回访** | 持久化记录高价值直播间,定时回访 |
| 7 | **推荐页养号** | 按概率点赞 / 收藏 / 评论,模拟真实用户行为 |
| 8 | **人机验证** | 自动处理滑块验证、图片点击、人脸识别(失败可重试) |
| 9 | **弹窗处理** | 自动关闭优惠券、购物红包等干扰弹窗 |
| 10 | **直播间切换** | 上划切换、N 次后回到首播、智能处理直播结束 |
| 11 | **超时保护** | 30 分钟未参与则自动返回推荐页重启流程,避免卡死 |
---
## 技术架构
### 核心技术栈
- **Python 3.10+** — 主语言
- **ADB**(Android Debug Bridge)— 设备控制
- **PaddleOCR**(>= 3.0.0)— OCR 文字识别
- **OpenCV** — 模板匹配 / 图像处理
- **Pillow / NumPy** — 图像 IO 与数值计算
- **tkinter + ttkbootstrap** — 桌面 GUI
- **内置 http.server** — Web GUI 服务
### 检测层次
| 技术 | 用途 | 速度 / 准确度 |
|------|------|---------------|
| 像素检测 | 弹窗背景色、按钮区域 | 极快 / 中 |
| 模板匹配(OpenCV) | 图标、按钮等 UI 元素 | 快 / 高 |
| OCR(PaddleOCR) | 文字识别(福袋内容、倒计时、人数) | 慢 / 高 |
| 阶段诊断 | 综合三种技术判断当前页面状态 | 可调 / 高 |
### 架构图
```
┌─────────────────────────────────────────┐
│ GUI / Web GUI / CLI(用户界面层) │
│ bin/gui_app.py / bin/webgui_launcher │
│ bin/run_cli.py │
└──────────────┬──────────────────────────┘
│
┌──────────────▼──────────────────────────┐
│ douyin/core/douyin_fudai.py │
│ class fudai_analyse(Mixin 组合) │
│ 核心调度器 - 主流程控制 │
└──────────────┬──────────────────────────┘
│
┌──────────┼──────────┐
│ │ │
┌───▼────┐ ┌───▼────┐ ┌──▼─────┐
│阶段诊断│ │福袋核心│ │弹窗处理│
│stage/ │ │fudai/ │ │handlers│
└────────┘ └────────┘ └────────┘
│ │ │
└──────────┼──────────┘
│
┌──────────────▼──────────────────────────┐
│ douyin/core/underlying_operations.py │
│ 底层 ADB / 截图 / OCR 封装 │
└──────────────┬──────────────────────────┘
│
┌──────────────▼──────────────────────────┐
│ douyin/core/path_config.py │
│ 统一路径配置(config / state / logs) │
└─────────────────────────────────────────┘
```text
DouyinGuajiGUI.exe 数据看板版主程序,优先打开这个
web_gui.exe Web 控制台服务,一般不用手动打开
run_cli.exe 后台运行程序,由主程序自动调用
assets/ 识别模板资源,不要删除
config/ 配置目录
logs/ 日志目录
pic/ 截图目录
state/ 运行状态目录
```
**设计要点**:
- **Mixin 组合**:`fudai_analyse` 把功能拆到 [`douyin/core/fudai_modules/`](douyin/core/fudai_modules) 各 Mixin
- **路径统一**:所有运行时路径通过 [`douyin/core/path_config.py`](douyin/core/path_config.py) 集中管理
- **日志分层**:统一日志 + 行为日志(`actions.log`)分离,便于性能分析
日常只需要双击:
---
## 环境要求与安装
### 系统要求
| 项 | 要求 |
|----|------|
| 操作系统 | Windows 10/11 (64-bit) |
| Python | 3.10–3.12(推荐 3.10) |
| 内存 | 至少 4 GB(推荐 8 GB+) |
| 存储 | 至少 2 GB 可用空间 |
| 安卓设备 | Android 5.0+,已开启 USB 调试 |
### 必需软件
1. **Python 3.10+** — [下载](https://www.python.org/downloads/),安装时勾选 *Add Python to PATH*
2. **ADB(platform-tools)** — [下载](https://developer.android.com/studio/releases/platform-tools),解压加入 PATH,验证 `adb version`
3. **抖音 APP** — 安装在已开启 USB 调试的安卓设备
### 安装步骤
```bash
# 1. 克隆仓库
git clone <repository-url>
cd douyi_guaji
# 2. 创建虚拟环境(推荐)
python -m venv .venv
.venv\Scripts\activate # Windows CMD
# .venv\Scripts\Activate.ps1 # Windows PowerShell
# 3. 安装核心依赖
pip install -r requirements.txt
# 如 paddlepaddle 安装失败,可指定清华源:
pip install "paddlepaddle>=3.0.0" -i https://pypi.tuna.tsinghua.edu.cn/simple
# GPU 版本(需 CUDA):
pip install "paddlepaddle-gpu>=3.0.0" -i https://pypi.tuna.tsinghua.edu.cn/simple
# 4. 验证
python --version
adb version
adb devices # 应能看到设备,状态为 "device"
```text
DouyinGuajiGUI.exe
```
### 设备配置
## 第一次使用
1. 进入「设置 → 关于手机」连续点击「版本号」7 次开启**开发者模式**
2. 在「开发者选项」中开启 **USB 调试**(部分机型还需开启 *USB 安装*)
3. USB 连接电脑,选择 *文件传输/MTP* 模式,**首次连接**手机会弹授权对话框,选择「允许」
4. 运行 `adb devices` 应输出 `<device-id> device`
1. 手机或模拟器开启 USB 调试,具体方法见下面“开启 ADB 调试”。
2. 用数据线连接电脑,手机弹出授权时选择允许。
3. 先在手机或模拟器里调出底部导航栏,具体方法见下面“调出底部导航栏”。
4. 双击 `DouyinGuajiGUI.exe`。
5. 在顶部设备下拉框选择设备。
6. 如果没有设备,点击“刷新设备”。
7. 进入“授权”页面,输入卡密并验证。
8. 回到“运行设置”“筛选设置”填写参数。
9. 点击底部“开始运行”。
---
## 开启 ADB 调试
## 快速开始
### 安卓手机
三种启动方式,按场景选择:
1. 打开手机“设置”。
2. 进入“关于手机”。
3. 连续点击“版本号”或“软件版本号”7 次,直到提示已进入开发者模式。
4. 返回设置首页,进入“系统”“更多设置”或“其他设置”。
5. 打开“开发者选项”。
6. 开启“USB 调试”。
7. 用数据线连接电脑。
8. 手机弹出“允许 USB 调试”时,勾选“始终允许使用这台计算机进行调试”,再点“允许”。
9. 回到软件,点击“刷新设备”。
### 方式一:桌面 GUI(推荐新手)
如果找不到入口,可以在手机设置顶部搜索:
```bash
python bin/gui_app.py
```text
开发者选项
USB 调试
```
1. 在「设备」下拉选择设备
2. 在「运行设置」/「筛选设置」配置参数
3. 点击「开始运行」,右侧日志窗口实时显示状态
4. 通过「截图」按钮查看实时截图,「停止」/「强制停止」终止运行
### 常见品牌路径
### 方式二:命令行(高级用户)
- 小米/红米:设置 -> 我的设备 -> 全部参数 -> 连点 MIUI 版本;然后设置 -> 更多设置 -> 开发者选项 -> USB 调试。
- 华为/荣耀:设置 -> 关于手机 -> 连点版本号;然后设置 -> 系统和更新 -> 开发人员选项 -> USB 调试。
- OPPO/一加:设置 -> 关于本机 -> 版本信息 -> 连点版本号;然后设置 -> 系统设置 -> 开发者选项 -> USB 调试。
- vivo/iQOO:设置 -> 系统管理 -> 关于手机 -> 连点软件版本号;然后设置 -> 系统管理 -> 开发者选项 -> USB 调试。
```bash
# 基本用法
python bin/run_cli.py --needswitch --wait-minutes 5
### 安卓模拟器
# 完整参数示例
python bin/run_cli.py \
--device-id MB75DEFQZHZTGMLJ \
--y-pianyi 0 \
--needswitch \
--wait-minutes 5 \
--min-prize-value-yuan 200.0 \
--min-participants 100 \
--skip-if-countdown-lt-seconds 5
1. 打开模拟器。
2. 进入模拟器的“设置中心”或右上角菜单。
3. 找到“ADB 调试”“Android 调试”或“开发者模式”。
4. 选择“开启”或“本地连接”。
5. 保存设置后重启模拟器。
6. 回到软件,点击“刷新设备”。
不同模拟器入口名字会略有不同,可以优先在模拟器设置里搜索:
```text
ADB
调试
开发者
```
| 常用参数 | 说明 |
|---------|------|
| `--device-id` | 设备 ID(省略则取第一个) |
| `--y-pianyi` | Y 偏移(-200~200,常用 -50~50) |
| `--needswitch` | 允许切换直播间 |
| `--wait-minutes` | 倒计时超过 N 分钟时切换直播间 |
| `--min-prize-value-yuan` | 最低奖品价值(元) |
| `--min-participants` | 最少参与人数 |
| `--skip-if-countdown-lt-seconds` | 跳过倒计时小于 N 秒的福袋 |
## 调出底部导航栏
### 方式三:Web GUI(远程控制)
自动化运行必须能看到底部返回、主页、多任务按钮。不要使用隐藏导航条或纯手势导航。
```bash
python bin/webgui_launcher.py
```
### 安卓手机
打开浏览器访问 `http://127.0.0.1:8000/`,通过页面配置参数、查看实时日志/截图,远程访问改用机器 IP。
1. 打开手机“设置”。
2. 搜索“系统导航方式”或“导航方式”。
3. 进入后选择“三键导航”“经典导航键”或“屏幕内三键导航”。
4. 回到桌面或抖音页面,确认屏幕底部能看到返回、主页、多任务按钮。
---
常见品牌路径:
## 详细配置说明
- 小米/红米:设置 -> 桌面 -> 系统导航方式 -> 经典导航键。
- 华为/荣耀:设置 -> 系统和更新 -> 系统导航方式 -> 屏幕内三键导航。
- OPPO/一加:设置 -> 系统设置 -> 系统导航方式 -> 虚拟按键。
- vivo/iQOO:设置 -> 系统导航 -> 导航键。
所有配置在 [`config/config.json`](config/config.json) 中,可通过 GUI 修改或直接编辑 JSON。运行时通过 `path_config.get_config_path()` 读取。
### 安卓模拟器
1. 打开模拟器设置。
2. 找到“导航栏”“虚拟按键”“系统导航”或“显示底部导航栏”。
3. 开启底部导航栏。
4. 如果模拟器底部按钮被隐藏,先把鼠标移到窗口底部,或在侧边工具栏里点“返回”“主页”按钮确认可用。
5. 回到抖音画面,确认底部能看到返回、主页、多任务按钮。
## 主界面怎么用
### 顶部区域
- 设备:选择当前要控制的手机或模拟器。
- 刷新设备:重新检测 ADB 设备。
- 扫描 WiFi:用于 WiFi ADB 连接。
- WiFi ADB:打开 WiFi 连接工具。
- Y偏移:点击位置有偏差时填写,普通文本输入即可。
- 截图+OCR:手动截图并识别当前画面。
- 保存配置:保存当前界面参数。
### 底部按钮
- 开始运行:启动自动化流程。
- 暂停/继续:临时暂停或恢复当前运行。
- 停止:正常停止。
- 强制停止:进程卡住时使用。
- 发送返回键:向手机发送一次返回键。
## 常用页面
### 数据看板
默认首页,主要看:
- 本次运行时间
- 总运行时间
- 中奖截图数量
- 预约队列
- 实时截图
### 运行设置
| 参数 | 类型 | 默认 | 说明 |
|------|------|------|------|
| `needswitch` | bool | `true` | 允许上划切换直播间 |
| `wait_minutes` | int | `5` | 倒计时超过该值(分钟)时切换(仅 `needswitch=true` 生效) |
| `skip_if_countdown_lt_seconds` | int | `5` | 倒计时小于该值时不参与(高价值仍可预约) |
| `reset_after_swipes_enabled` | bool | `true` | 启用「切换 N 次后回到首播」 |
| `reset_after_swipes` | int | `30` | 触发回到首播的切换次数 |
| `fudai_find_max_attempts` | int | `10` | 找福袋图标的最大重试次数 |
| `fudai_icon_retry_delay_seconds` | float | `0.6` | 找福袋图标的重试间隔(秒) |
| `fudai_icon_max_wait_seconds` | float | `5.0` | 找福袋图标的最大等待(秒) |
| `live_room_match_threshold` | float | `0.8` | 直播间检测阈值(0~1,越高越严格,建议 ≥ 0.8) |
| `stage_diag_max_time` | float | `15.0` | 阶段诊断最大耗时(秒) |
| `stage_diag_max_step_time` | float | `4.0` | 阶段诊断单步最大耗时(秒) |
| `no_attend_timeout_minutes` | float | `30.0` | 30 分钟超时保护:超过该值未成功参与则返回推荐页(0 = 禁用) |
设置运行方式,例如:
### 福袋筛选
- 是否允许切换直播间
- 运行时长
- 倒计时大于多少秒时跳过
- 连续无福袋退出阈值
| 参数 | 类型 | 默认 | 说明 |
|------|------|------|------|
| `min_prize_value_yuan` | float | `0.0` | 最低奖品价值(元),0 = 不启用 |
| `min_participants` | int | `0` | 最少参与人数,0 = 不启用 |
| `max_participants` | int | `0` | 最多参与人数,0 = 不启用 |
| `contains_want` | array | `[]` | 想要的关键词白名单 |
| `contains_not_want` | array | `[]` | 不想要的关键词黑名单 |
### 筛选设置
```json
{
"min_prize_value_yuan": 200.0,
"min_participants": 100,
"max_participants": 10000,
"contains_want": ["手机", "现金", "红包"],
"contains_not_want": ["袜子", "优惠券", "代金券"]
}
```
设置福袋筛选条件,例如:
### 高价值福袋预约
| 参数 | 类型 | 默认 | 说明 |
|------|------|------|------|
| `high_value_fudai_enabled` | bool | `true` | 启用预约功能 |
| `high_value_fudai_threshold_yuan` | float | `500.0` | 预约阈值(元),价值 ≥ 该值则预约 |
| `high_value_fudai_join_ahead_seconds` | int | `300` | 提前 N 秒返回直播间参与 |
| `high_value_fudai_max_swipe_back` | int | `35` | 最多回退次数(防止过远) |
| `high_value_fudai_max_reservations` | int | `3` | 最多同时预约数 |
| `high_value_fudai_after_action` | string | `"continue"` | 完成预约后:`stay`(停留)或 `continue`(继续抢) |
| `reservation_back_verify_enabled` | bool | `false` | 启用回退验证 |
| `reservation_back_swipe_delay` | float | `0.6` | 回退滑动延迟(秒) |
> **重要**:预约回退需 `needswitch=true`。单间模式下预约会在当前直播间自动识别参与,无需回退。
### 高价值直播间回访
| 参数 | 类型 | 默认 | 说明 |
|------|------|------|------|
| `high_value_room_revisit_enabled` | bool | `false` | 启用高价值直播间回访 |
| `high_value_room_revisit_only_current_run` | bool | `false` | 仅本次运行回访(true)或持久化(false) |
### 粉丝团
| 参数 | 类型 | 默认 | 说明 |
|------|------|------|------|
| `auto_join_fansclub` | bool | `true` | 自动加入粉丝团(**可能消耗钻石**) |
| `fansclub_fail_action` | string | `"switch"` | 加入失败后:`stay` 或 `switch` |
### 推荐页养号
养号参数较多(约 30 项),完整列表见 [`docs/完整技术文档.md`](docs/完整技术文档.md) 的「推荐页养号设置」段。常用:
| 参数 | 类型 | 默认 | 说明 |
|------|------|------|------|
| `yanghao_enabled` | bool | `false` | 启用养号 |
| `yanghao_enable_actions` | bool | `false` | 启用养号动作(点赞/收藏/评论) |
| `yanghao_recommend_duration_seconds` | int | `216` | 推荐页停留时长(秒) |
| `yanghao_recommend_interval_seconds` | int | `600` | 推荐页养号间隔(秒),0 = 不间隔 |
| `yanghao_like_prob` | float | `1.0` | 点赞概率 |
| `yanghao_fav_prob` | float | `0.85` | 收藏概率 |
| `yanghao_comment_prob` | float | `1.0` | 评论概率 |
### 静默时段
| 参数 | 类型 | 默认 | 说明 |
|------|------|------|------|
| `fudai_quiet_hours_enabled` | bool | `true` | 启用静默时段(不抢福袋,仍可养号) |
| `fudai_quiet_start_hour` | int | `2` | 起始小时(0–23) |
| `fudai_quiet_end_hour` | int | `6` | 结束小时(0–23) |
---
## 使用指南
### 首次使用
1. 通过 GUI 启动,便于观察日志
2. 调整 Y 偏移(通常 -50~50),通过「截图」核对点击位置
3. 设置较宽松的筛选条件,观察实际效果再收紧
4. 关注是否触发人机验证;频繁出现说明运行频率过高,应启用养号或缩短运行时段
### 日常建议
- **查日志**:[`logs/unified.log`](logs/) 总览、[`logs/actions.log`](logs/) 关键操作
- **稳定连接**:USB 3.0 + 不掉线手机,定期检查 `adb devices`
- **风控防御**:启用养号 + 配置静默时段;账号疑似限制立即停止并人工操作
### 高级用法
- **多账号**:每账号独立 `config/` 目录或通过 `--device-id` 区分
- **定时**:Windows 任务计划程序 + 静默时段
- **远程**:Web GUI 端口转发到外网(注意安全)
- **性能调优**:调小 OCR 区域、降低截图频率、用 GPU 版 PaddleOCR
---
## 工作原理
### 主流程
```
开始
│
├─> 初始化(加载配置、连接设备)
│
├─> 30 分钟超时检查
│ └─ 超时 → 返回推荐页面重新开始
│
├─> 阶段诊断(判断当前页面)
│ ├─> 直播间 → 检测福袋图标 → 打开详情页
│ ├─> 福袋详情页 → 读取信息 → 筛选 → 参与
│ ├─> 抽奖结果页 → 中奖领取 / 关闭弹窗
│ └─> 其他 → 导航回直播间
│
├─> 处理弹窗(优惠券、红包、人机验证)
│
└─> 循环执行
```
### 阶段诊断
按优先级判断当前页面:
1. **直播间检测**(最高优先级):模板匹配右上角关闭/心形图标,阈值默认 0.8
2. **像素检测**(并行):弹窗背景色、参与按钮红色、粉丝团红色等
3. **OCR 检测**(按需):识别推荐页 / 关注列表 / 直播列表 / 福袋详情等
4. **综合判断**:返回当前阶段(`IN_LIVE_ROOM` / `RECOMMEND_PAGE` / `FUDai_DETAIL` / `FUDai_RESULT` / ...)
### 福袋筛选
```
福袋信息
│
├─> 价值 < min_prize_value_yuan → 跳过
├─> 人数不在 [min_participants, max_participants] → 跳过
├─> 倒计时 < skip_if_countdown_lt_seconds → 不参与(高价值可预约)
├─> 命中 contains_not_want → 跳过
├─> contains_want 非空且未命中 → 跳过
└─> 全部通过 → 参与抽奖
```
- 最低价值
- 参与人数最小
- 参与人数最大
- 倒计时太短时跳过
- 粉丝团失败策略
### 高价值预约
1. **识别**:价值 ≥ `high_value_fudai_threshold_yuan` → 记录到 `douyin/core/state/reservations.json`
2. **继续**:不立即参与,继续切换直播间(需 `needswitch=true`)
3. **回退**:开奖前 `high_value_fudai_join_ahead_seconds` 秒,从状态文件加载,按直播间标题匹配回退
4. **持久化**:最多 `high_value_fudai_max_reservations` 个,超出丢弃最晚开奖的;重启后自动加载
用于价值较高、开奖时间较晚的福袋。
更详细:[`docs/预约系统详细流程.md`](docs/预约系统详细流程.md)。
常用项:
---
- 启用预约
- 价值阈值
- 提前参与秒数
- 最多记录数量
- 预约回退校验
## 代码结构
### 运行日志
显示完整运行输出。运行异常时优先看这里。
### 行为日志
显示更简洁的关键动作,例如:
- 进入直播间
- 识别福袋
- 点击参与
- 切换直播间
- 预约记录
- 中奖结果
### 截图预览
显示当前截图。识别不准时先看这里确认画面是否正常。
### 预约队列
显示已记录的预约福袋。该页面会自动刷新,首页里的预约队列也会自动更新。
### 统计信息
显示本次运行的数据统计,比日志更方便查看。
### 映射表
显示运行过程中记录的直播间位置和标题映射。可开启自动刷新。
## 推荐使用流程
1. 打开 `DouyinGuajiGUI.exe`。
2. 先把手机或模拟器底部导航栏调出来。
3. 刷新并选择设备。
4. 点击“截图+OCR”,确认截图能正常显示。
5. 在“筛选设置”填好最低价值、人数范围。
6. 如果要切换直播间,在“运行设置”开启允许切换直播间。
7. 如需高价值预约,在“高价值预约”开启预约并设置价值阈值。
8. 点击“保存配置”。
9. 点击“开始运行”。
10. 运行中观察“数据看板”“运行日志”“行为日志”。
11. 需要临时停一下时点“暂停/继续”,结束时点“停止”。
## 日志和截图位置
如果需要排查问题,可以打开这些文件:
```text
logs/unified.log 完整运行日志
logs/actions.log 关键行为日志
pic/screenshot.png 当前截图
pic/lottery/ 中奖截图
state/ 运行状态
```
<项目根>/
├── bin/ # 入口脚本
│ ├── run_cli.py # 命令行入口
│ ├── gui_app.py # 桌面 GUI launcher
│ ├── webgui_launcher.py # Web GUI launcher
│ └── manage_logs.py # 日志管理 CLI
├── douyin/ # 核心业务逻辑
│ ├── core/ # 核心调度
│ │ ├── douyin_fudai.py # fudai_analyse(Mixin 组合)
│ │ ├── douyin_main_flow.py # 主流程控制
│ │ ├── douyin_flow_control.py
│ │ ├── path_config.py # 路径配置
│ │ ├── underlying_operations.py # 底层 ADB/截图/OCR
│ │ ├── io_utils.py # 文件 IO 辅助
│ │ ├── version.py
│ │ └── fudai_modules/ # 7 个 Mixin
│ ├── detection/ # 像素 + 模板检测
│ ├── stage/ # 阶段诊断
│ ├── fudai/ # 福袋核心
│ │ └── core/ # detail_reader / filter / attend / coords / ...
│ ├── handlers/ # 截图 / 滑动 / 弹窗处理
│ ├── reservation/ # 预约状态文件 / 逻辑 / 回退校验
│ ├── logging/ # 9 个日志模块(unified / wrapper / action / ...)
│ ├── other/ # 养号 / 人机校验 / 高价值房间 / ...
│ └── utils/ # 配置 / 文本 / 时间 / OCR 预处理
├── operations/ # 兼容层:re-export 给老代码
├── gui/ # GUI 实现(桌面 + Web)
│ ├── gui_app.py / web_gui.py / gui_core.py
│ ├── components/ # 桌面 GUI 子组件
│ └── web_components/ # Web GUI 子组件
├── webui/ # Web GUI 前端(HTML/CSS/JS)
├── tools/ # 47 个开发/调试脚本(按 adb/coords/dev/diagnostics/logs 分组)
├── tests/ # pytest 单元/冒烟测试(242 用例)
├── docs/ # 项目文档
│ ├── 完整技术文档.md # 7000+ 行内部技术参考
│ └── archive/ # 已过时文档归档
├── config/config.json # 用户配置
├── assets/ # 模板图片(x.png / xin.png / like.png / fav.png 等)
├── pic/ # 运行时截图(.gitignored)
├── logs/ # 运行时日志(.gitignored)
└── state/ # 运行时状态(.gitignored)
```
### 核心模块速查
| 模块 / 文件 | 职责 |
|-------------|------|
| [`douyin/core/douyin_fudai.py`](douyin/core/douyin_fudai.py) | 主类 `fudai_analyse`,Mixin 组合,主入口 |
| [`douyin/core/path_config.py`](douyin/core/path_config.py) | 统一路径配置(config / state / logs / pic) |
| [`douyin/core/underlying_operations.py`](douyin/core/underlying_operations.py) | 底层 ADB/截图/OCR 封装 |
| [`douyin/stage/douyin_stage.py`](douyin/stage/douyin_stage.py) | 阶段诊断核心 |
| [`douyin/fudai/core/fudai_filter.py`](douyin/fudai/core/fudai_filter.py) | 福袋筛选决策(含黑白名单) |
| [`douyin/reservation/douyin_reservation.py`](douyin/reservation/douyin_reservation.py) | 预约状态文件原子读写 |
| [`douyin/logging/unified_logger.py`](douyin/logging/unified_logger.py) | MDC(Mapped Diagnostic Context)+ 装饰器 |
| [`gui/gui_app.py`](gui/gui_app.py) / [`gui/web_gui.py`](gui/web_gui.py) | 桌面 / Web GUI 实现 |
| [`bin/run_cli.py`](bin/run_cli.py) | 命令行入口(含参数解析、shim 加载) |
资源目录:
- [`assets/`](assets/) — 模板图片:`x.png`(关闭)、`xin.png`(心形)、`like.png`、`fav.png`、`desktop.png`
- `pic/` — 运行时截图(`screenshot.png` 是最新;`ocr/` 子目录为 OCR 区域示例)
- `logs/` — `unified.log`(全部)+ `actions.log`(关键操作)
- `state/` — `high_value_rooms.json`;预约状态实际写入 `douyin/core/state/reservations.json`
---
## 测试
`tests/` 是 pytest 风格的单元测试 + 业务冒烟,覆盖路径配置、文本解析、福袋筛选决策、logger helper、MDC 上下文、io_utils 等核心纯函数链路。**242 用例 / < 1 秒**,不依赖 ADB / 真实设备 / OCR 引擎。
```bash
pip install pytest
# 全量
pytest
# 单文件 / 单用例
pytest tests/test_filter_logging.py
pytest tests/test_path_config.py::TestSpecificPaths::test_reservations_path_in_douyin_core_state -v
# 跑较慢的性能对比脚本(需 paddleocr/easyocr/psutil)
pytest -m slow
```
测试约定:
- [`tests/conftest.py`](tests/conftest.py) 自动把项目根加入 `sys.path`
- 性能脚本用 `pytest.importorskip` 自动跳过缺失依赖
- 自定义 marker:`smoke`(业务关键链路)/ `slow`(慢测试);新增需先在 [`pyproject.toml`](pyproject.toml) 注册
---
## 开发指南
### 开发环境
```bash
# 创建并激活虚拟环境
python -m venv .venv
.venv\Scripts\activate
# 安装运行依赖 + 开发工具
pip install -r requirements.txt
pip install pytest black ruff mypy
```
### 代码规范
- **风格**:PEP 8;类名 `CamelCase`;函数/变量 `snake_case`;常量 `UPPER_SNAKE_CASE`
- **类型注解**:尽量加,特别是公共函数
- **注释**:默认不写;仅在 *为什么* 非显然时(隐藏约束、变通方案、会让读者意外的行为)添加一行
- **不写多行 docstring**:一行总结即可
### 工作流
1. **新功能** — 在 `douyin/<module>/` 创建模块;`douyin/core/douyin_fudai.py` 中调用;如需配置项,更新 `config/config.json` + GUI/WebUI 同步
2. **GUI 同步检查** — 运行 [`tools/diagnostics/check_web_gui_config_sync.py`](tools/diagnostics/check_web_gui_config_sync.py),确保桌面 GUI 与 WebUI 的配置 key 一致
3. **测试** — 修改纯函数 / 业务逻辑后补 [`tests/`](tests/) 用例,跑 `pytest`
4. **提交** — 提交信息中文,格式:`<类型>: <简短描述>`;类型有 `feat` / `fix` / `refactor` / `docs` / `chore` 等
### 调试技巧
- **业务日志**:`analyser._log_kv("分类", "消息", key=value)` 走统一日志体系
- **截图调试**:`analyser.operation.get_screenshot(self.device_id)` → 查看 `pic/screenshot.png`
- **GUI 即时截图**:桌面 GUI 「截图」按钮 → 实时截图 + OCR 结果
- **测试模式**:`python bin/run_cli.py --test-yanghao-flow` 单独跑养号流程
更多文档:[`docs/完整技术文档.md`](docs/完整技术文档.md)、[`docs/DEBUG_IMAGE_SYSTEM.md`](docs/DEBUG_IMAGE_SYSTEM.md)。
---
## 故障排查
### 设备连接
| 症状 | 处理 |
|------|------|
| `adb devices` 显示 `unauthorized` | 手机授权对话框选「允许」 |
| 显示 `offline` | 重新插拔 USB;`adb kill-server && adb start-server` |
| 列表为空 | 检查 USB 调试 / 数据线 / USB 接口;选择「文件传输/MTP」模式 |
### 识别错误
| 症状 | 处理 |
|------|------|
| 点击位置不准 | 调整 Y 偏移(`--y-pianyi`);查看 `pic/screenshot.png` |
| 找不到福袋图标 | 增加 `fudai_icon_max_wait_seconds`;确认 `assets/` 模板存在 |
| 阶段诊断错误 | 调整 `live_room_match_threshold`;查看 `pic/ocr/` 调试图片 |
### OCR
| 症状 | 处理 |
|------|------|
| OCR 失败 | 重装 PaddleOCR;确认截图清晰;检查识别区域配置 |
| OCR 慢 | 启用 GPU 版 PaddleOCR;调小识别区域;降低截图频率 |
### 风控
| 症状 | 处理 |
|------|------|
| 频繁人机验证 | 启用养号;缩短运行时段;调宽筛选条件 |
| 账号被限制 | **立即停止脚本**;手动操作账号恢复正常 |
### 性能
| 症状 | 处理 |
|------|------|
| CPU 高 | 降低截图频率;优化 OCR 区域;用 GPU 版 PaddleOCR |
| 内存高 | 限制日志文件大小;定期重启脚本 |
---
## 常见问题
**Q: 支持 iOS 设备吗?**
A: 不支持,iOS 需要越狱。
### 检测不到设备
**Q: 需要 Root 权限吗?**
A: 不需要,仅需 USB 调试。
1. 确认手机开启 USB 调试。
2. 重新插拔数据线。
3. 手机授权弹窗选择允许。
4. 点击主界面“刷新设备”。
**Q: 可以同时运行多个账号吗?**
A: 可以。每账号独立设备 + 独立 `config/` 目录,命令行用 `--device-id` 区分。
### 截图为空或不更新
**Q: 脚本会被检测吗?**
A: 任何自动化都有风控风险。建议:启用养号、合理配置静默时段、定期手动操作账号。
1. 先确认设备已连接。
2. 确认手机或模拟器底部导航栏已经调出。
3. 点击“截图+OCR”手动刷新。
4. 检查 `pic/screenshot.png` 是否生成。
5. 仍不正常时重启程序和设备。
**Q: 如何提高中奖率?**
A: 中奖率取决于福袋本身。可通过筛选小参与人数福袋 + 多账号并行提高总中奖期望。
### 点击位置不准
**Q: 脚本卡住怎么办?**
A: 查 `logs/unified.log` 确认卡在哪一步;用「截图」按钮看当前页面;点击「强制停止」;必要时重启脚本/设备。30 分钟超时保护会自动恢复。
先确认底部导航栏已经调出,再在顶部 `Y偏移` 输入框调整数值,然后再次截图确认。
**Q: 高价值预约不生效?**
A: 检查:
- `config.json` 中 `needswitch=true` 且 `high_value_fudai_enabled=true`
- `douyin/core/state/reservations.json` 中是否有预约数据
- 日志中搜 `[预约] run_once_basic:检查预约回退触发条件`
### 运行卡住
**Q: 如何更新脚本?**
A: 备份 `config/config.json` 与 `state/` 目录 → `git pull`(或重新下载)→ 检查 `config.json` 是否需要补新配置项。
1. 先点“停止”。
2. 如果没有反应,再点“强制停止”。
3. 查看 `logs/unified.log` 和 `logs/actions.log`。
---
### 预约队列没有内容
## 版本更新日志
只有识别到符合高价值预约条件的福袋后才会出现内容。请检查:
完整变更见 [CHANGELOG.md](CHANGELOG.md)(Keep a Changelog 格式)。
所有发布都打了 git tag,可以通过 `git tag -l` 查看,或访问 [git tags 页面](../../tags)。
1. 是否启用预约。
2. 价值阈值是否过高。
3. 是否允许切换直播间。
4. 运行日志里是否出现预约相关记录。
最近 3 个版本:
### 授权失败
### V3.3.3 (2025-12-28) — 当前
- ✨ 新增:30 分钟超时保护机制
- 🐛 修复:模板与截图路径配置统一,使用 [`path_config.py`](douyin/core/path_config.py)
- 🔧 优化:行为日志路径统一为 `path_config.get_actions_log_path()`
1. 检查网络是否正常。
2. 确认卡密没有复制多余空格。
3. 点击“刷新状态”后再验证。
4. 仍失败请联系发卡方。
### V3.3.2 (2025-12-25)
- 🐛 修复:预约回退功能不生效(`needswitch` 与 `self.reservations` 加载问题)
- 🔧 优化:每次 `run_once_basic` 自动从状态文件加载预约队列
## 不要删除的文件夹
### V3.3.1 (2025-12-14)
- ✨ 新增:直播间检测阈值可配置(`live_room_match_threshold`)
- ✨ 新增:福袋图标检测等待时间可配置
- 🔧 优化:阶段检测优先使用像素检测;合并阶段 1.5 与阶段 3 的 OCR
这些目录不要删除:
### 发布流程
新版本发布走 [`tools/dev/bump_version.py`](tools/dev/bump_version.py):
```bash
python tools/dev/bump_version.py patch # V3.3.3 → V3.3.4
python tools/dev/bump_version.py minor # V3.3.3 → V3.4.0
python tools/dev/bump_version.py major # V3.3.3 → V4.0.0
python tools/dev/bump_version.py --dry-run patch # 只看会改什么
```text
assets/
config/
webui/
```
脚本会自动同步 `version.py` / `pyproject.toml` / `CHANGELOG.md` 顶部并创建 git tag。
[`tests/test_version_consistency.py`](tests/test_version_consistency.py) 9 个用例守住三处版本号一致。
这些目录可以清理旧内容,但不建议删除目录本身:
---
## 贡献与反馈
### 提交 Issue
请包含:
- **标题**:一句话概述
- **环境**:操作系统、Python、ADB、设备型号
- **复现步骤**:最小复现命令 / 点击顺序
- **日志/截图**(可选但推荐):`logs/unified.log` 片段、错误截图
- **期望 vs 实际**
### 贡献 PR
```bash
# 1. fork + 新分支
git checkout -b fix/your-change
# 2. 改动 + 测试
pytest
# 3. 提交(中文,type: 描述)
git commit -m "fix: 修复 OCR 识别问题"
# 4. PR 描述写清变更细节、测试方法、影响范围
```text
logs/
pic/
state/
```
代码风格保持现有约定,避免大面积重构而不提前沟通。
## 更新版本
---
如果你拿到新的安装包:
## 免责声明
1. 先关闭正在运行的程序。
2. 备份旧目录里的 `config/` 和 `state/`。
3. 安装或解压新版本。
4. 如需保留旧配置,把备份的 `config/` 和 `state/` 放回新目录。
5. 重新打开 `DouyinGuajiGUI.exe`。
1. **本工具仅供学习交流使用**,请勿用于商业用途。
2. **使用本工具产生的任何后果由使用者自行承担**,包括但不限于:
- 账号被封禁或限制
- 数据丢失或泄露
- 设备损坏
- 其他法律风险
3. **请遵守抖音平台相关规则**,不要使用本工具进行违法违规操作。
4. **作者不对使用本工具造成的任何损失负责**。
5. **使用本工具即表示您已阅读并同意本免责声明**。
## 注意事项
---
## 许可
仓库当前未添加明确的开源许可文件(LICENSE)。如需对外发布或在项目中使用本代码,请先在 Issue 中联系作者或为仓库添加合适的许可证(MIT / Apache-2.0 / GPL-3.0 等)。
---
<div align="center">
**感谢使用抖音福袋挂机脚本**
如果这个项目对你有帮助,欢迎 ⭐
</div>
- 自动化运行期间不要手动频繁操作手机。
- 账号风控风险自行承担。
- 运行异常时先保存日志和截图,再重启程序。
- 如果杀毒软件提示拦截,请把程序目录加入信任后再试。
+32
View File
@@ -0,0 +1,32 @@
# WebUI 用户视角问题清单(2026-06-01)
## 已修复(本轮)
1. `/api/config` 布尔值字符串会被错误写入
- 现象:`"false"` 可能被当成 `true`。
- 修复:后端 `routes.py` 新增 `_coerce_bool`,前端 `config_form.js` 同步字面量解析。
2. 设备动作在无设备时存在未捕获 Promise 报错噪音
- 现象:点击“返回键”后可能触发全局 `pageerror`(虽有提示但会污染错误面板)。
- 修复:`runtime_device_actions.js` 的 `sendBackKey()` 增加局部 `try/catch`。
3. 预约/高价值列表中少量字段未统一做安全处理
- 现象:个别字符串字段直接插入模板字符串。
- 修复:`runtime_actions.js` 对 `future_str` 等补 `escapeHtml`,数值字段统一显式数值化。
4. WiFi 自动重连与扫描参数错误码语义不清
- 修复:
- 无 adb:`/api/wifi/auto-reconnect` 返回 `422`。
- `ports` 非法:`/api/wifi/scan` 返回 `400 invalid ports`。
- `probe_timeout` 非法继续返回 `400`。
## 仍可优化(下一批)
1. 移动端首屏头部信息密度偏高
- 证据:`mobile_home.png` 中操作按钮区占比较大,设备/状态卡阅读层级偏挤。
- 建议:在 `< 420px` 下把二级按钮折叠进更多菜单,保留“开始/停止/截图”主操作。
2. Tab 横向切换在自动化点击中偶发不可见状态
- 证据:Playwright 偶发 `runLogs` tab 点击超时(人工可复现概率低)。
- 建议:为 tab click 增加 `scrollIntoView` + `requestAnimationFrame` 后触发,提升自动化与低端机稳定性。
@@ -0,0 +1,84 @@
{
"url": "http://localhost:8001/",
"screenshots": [
"artifacts\\webui_checks\\20260601\\desktop_home.png",
"artifacts\\webui_checks\\20260601\\desktop_run_panel.png",
"artifacts\\webui_checks\\20260601\\desktop_stats_panel.png",
"artifacts\\webui_checks\\20260601\\desktop_monitor_panel.png",
"artifacts\\webui_checks\\20260601\\desktop_reservations_panel.png",
"artifacts\\webui_checks\\20260601\\desktop_runlogs_panel.png",
"artifacts\\webui_checks\\20260601\\desktop_actionlogs_panel.png",
"artifacts\\webui_checks\\20260601\\mobile_home.png",
"artifacts\\webui_checks\\20260601\\mobile_run_panel.png",
"artifacts\\webui_checks\\20260601\\mobile_stats_panel.png",
"artifacts\\webui_checks\\20260601\\mobile_monitor_panel.png",
"artifacts\\webui_checks\\20260601\\mobile_reservations_panel.png",
"artifacts\\webui_checks\\20260601\\mobile_runlogs_panel.png",
"artifacts\\webui_checks\\20260601\\mobile_actionlogs_panel.png"
],
"console_errors": [
{
"type": "error",
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
},
{
"type": "action",
"text": "click_failed .tabBtn[data-target=\"runLogs\"]: Locator.click: Timeout 3000ms exceeded.\nCall log:\n - waiting for locator(\".tabBtn[data-target=\\\"runLogs\\\"]\").first\n - locator resolved to <button role=\"tab\" type=\"button\" class=\"tabBtn\" data-target=\"runLogs\" aria-selected=\"false\">…</button>\n - attempting click action\n - waiting for element to be visible, enabled and stable\n - element is visible, enabled and stable\n - scrolling into view if needed\n - done scrolling\n - performing click action\n"
}
],
"page_errors": [
"未选择设备,且无法自动解析在线设备"
],
"checks": {
"desktop:has:btnStart": true,
"desktop:has:btnStop": true,
"desktop:has:btnForceStop": true,
"desktop:has:btnRefresh": true,
"desktop:has:btnScreenshot": true,
"desktop:has:btnBackKey": true,
"desktop:has:btnLoad": true,
"desktop:has:btnSave": true,
"desktop:has:device": true,
"desktop:has:btnWifiScan": true,
"desktop:has:wifiStatus": true,
"desktop:has:runLog": true,
"desktop:has:appConnText": true,
"desktop:has:appConnDot": true,
"desktop:has:reservationsContent": true,
"desktop:has:highValueRoomsContent": true,
"desktop:has:hv_expand_all": true,
"desktop:has:hv_collapse_all": true,
"desktop:conn_text": "已连接",
"desktop:body_box": {
"w": 1600,
"h": 1178.65625,
"scrollH": 1179
},
"desktop:overflow_controls": 0,
"mobile:has:btnStart": true,
"mobile:has:btnStop": true,
"mobile:has:btnForceStop": true,
"mobile:has:btnRefresh": true,
"mobile:has:btnScreenshot": true,
"mobile:has:btnBackKey": true,
"mobile:has:btnLoad": true,
"mobile:has:btnSave": true,
"mobile:has:device": true,
"mobile:has:btnWifiScan": true,
"mobile:has:wifiStatus": true,
"mobile:has:runLog": true,
"mobile:has:appConnText": true,
"mobile:has:appConnDot": true,
"mobile:has:reservationsContent": true,
"mobile:has:highValueRoomsContent": true,
"mobile:has:hv_expand_all": true,
"mobile:has:hv_collapse_all": true,
"mobile:conn_text": "已连接",
"mobile:body_box": {
"w": 390,
"h": 2102.875,
"scrollH": 2103
},
"mobile:overflow_controls": 1
}
}
@@ -0,0 +1,15 @@
{
"console_errors": [
{
"type": "error",
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
}
],
"page_errors": [],
"screenshots": [
"artifacts\\webui_checks\\20260601_port8002\\mobile_main.png"
],
"checks": {
"has_unhandled_error": false
}
}
@@ -0,0 +1,15 @@
{
"console_errors": [
{
"type": "error",
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
}
],
"page_errors": [],
"screenshots": [
"artifacts\\webui_checks\\20260601_port8003\\mobile_main.png"
],
"checks": {
"has_unhandled_error": false
}
}
@@ -0,0 +1,15 @@
{
"console_errors": [
{
"type": "error",
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
}
],
"page_errors": [],
"screenshots": [
"artifacts\\webui_checks\\20260601_postfix\\mobile_after_fix.png"
],
"checks": {
"has_unhandled_error": false
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 548 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

+2 -1
View File
@@ -8,10 +8,11 @@ import runpy
import sys
from pathlib import Path
from douyin.core import path_config
ROOT_DIR = Path(__file__).resolve().parent.parent
TARGET = ROOT_DIR / "gui" / "gui_app.py"
VENV_PYTHON = ROOT_DIR / ".venv" / "Scripts" / "python.exe"
VENV_PYTHON = Path(path_config.get_venv_python_path())
def _reexec_with_venv() -> None:
+179 -13
View File
@@ -4,6 +4,17 @@ import logging
import os
import shutil
import sys
import time
# ==== 将项目根目录加入 sys.path,确保后续所有 douyin.* 导入正常 ================
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if _BASE_DIR not in sys.path:
sys.path.insert(0, _BASE_DIR)
if __name__ == "__main__":
from douyin.updater.bootstrap import run_startup_update_check_early
run_startup_update_check_early(app_name="run_cli")
# 可选:全局参数/调用跟踪(仅在环境变量 PARAM_TRACK_ALL=1 时启用)
if os.environ.get("PARAM_TRACK_ALL") == "1":
@@ -47,10 +58,6 @@ except Exception as e:
# 如果需要从外部工作树加载兼容模块,可显式设置 EXTERNAL_DOUYIN_FUDAI_DIR。
# 默认只使用当前仓库内置实现,避免绑定到某台机器的 Cursor worktree 路径。
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 确保项目根在 sys.path 中(脚本从 bin/ 目录启动时)
if _BASE_DIR not in sys.path:
sys.path.insert(0, _BASE_DIR)
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "").strip()
@@ -75,7 +82,6 @@ def _load_local_shim(mod_name: str, rel_path: str) -> None:
# 1) 先加载本地 shim 模块,确保后续 import 优先使用这些实现
_load_local_shim("douyin_text_utils", "douyin/utils/douyin_text_utils.py")
_load_local_shim("douyin_swipe_ops", "douyin/handlers/douyin_swipe_ops.py")
# 2) 再把完整逻辑所在目录追加到 sys.path,供 `douyin_fudai` 等模块导入
@@ -90,17 +96,26 @@ except Exception as e:
logging.debug("外部模块路径配置失败: %s", e)
# 在导入 PaddleOCR 之前设置,避免每次启动都做连通性检查提示并抑制底层 glog/oneDNN 等噪音
# DISABLE_MODEL_SOURCE_CHECK: 跳过 PaddleOCR 的主机连通性检查(国内网络环境常卡)
# DISABLE_MODEL_SOURCE_CHECK/PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK: 跳过 PaddleOCR/PaddleX 主机连通性检查(国内网络环境常卡)
# GLOG_minloglevel: 2 -> ERROR 及以上,屏蔽 INFO/WARNING
# OMP_NUM_THREADS: 设为 1,避免 oneDNN 打印线程信息
os.environ.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True")
os.environ.setdefault("PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK", "1")
os.environ.setdefault("GLOG_minloglevel", "2")
os.environ.setdefault("OMP_NUM_THREADS", "1")
from douyin.core.douyin_fudai import fudai_analyse
from douyin.core import path_config
from douyin.license.license_manager import require_online_license_or_exit
def ensure_adb_in_path() -> None:
bundled_adb = path_config.find_bundled_adb()
if bundled_adb:
adb_dir = os.path.dirname(bundled_adb)
os.environ["PATH"] = adb_dir + os.pathsep + os.environ.get("PATH", "")
os.environ.setdefault("ADB_EXECUTABLE", bundled_adb)
return
if shutil.which("adb"):
return
localapp = os.environ.get("LOCALAPPDATA") or ""
@@ -125,6 +140,11 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
p.add_argument("--device-id", default="", help="ADB 设备 ID(为空则自动选择)")
p.add_argument("--y-pianyi", type=int, default=0, help="y 轴偏移(通常 -50~50)")
p.add_argument("--needswitch", action="store_true", help="是否允许上划切换直播间")
p.add_argument(
"--cold-start",
action="store_true",
help="启动本轮前 force-stop 并重新打开抖音(真机回归测试使用)",
)
p.add_argument(
"--wait-minutes",
type=int,
@@ -328,13 +348,135 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
default=None,
help="仅在 --yanghao-only 时有效:覆盖推荐页养号停留秒数",
)
p.add_argument(
"--reenter-live-entry-mode",
choices=["follow_list", "screen_center"],
default="screen_center",
help="重新进入直播间点击模式:follow_list=关注列表坐标,screen_center=屏幕中心坐标",
)
p.add_argument(
"--disable-regression-collection",
action="store_true",
help="禁用运行结束自动收集福袋回归测试素材",
)
p.add_argument(
"--regression-collection-max-images",
type=int,
default=500,
help="运行结束最多扫描本轮 debug capture 图片数(默认500,仅挑高价值小样本长期保留)",
)
p.add_argument(
"--regression-full-run-package",
action="store_true",
help="额外保留完整本轮回归包(日志、状态、debug/ocr 图片);默认只保留长期小样本池",
)
return p.parse_args(argv)
def _collect_regression_artifacts_if_enabled(
args: argparse.Namespace,
*,
run_started_at: float,
exit_code: int | None,
device_id: str,
) -> None:
if bool(getattr(args, "disable_regression_collection", False)):
return
try:
from douyin.testing.regression_collector import (
build_run_id,
collect_run_regression_artifacts,
)
max_images = int(getattr(args, "regression_collection_max_images", 500) or 500)
max_images = max(1, max_images)
max_ocr_images = max(80, min(max_images, int(max_images * 0.4)))
result = collect_run_regression_artifacts(
run_id=build_run_id("run_cli"),
started_at=run_started_at,
exit_code=exit_code,
device_id=device_id,
max_debug_images=max_images,
max_ocr_images=max_ocr_images,
full_run_package=bool(getattr(args, "regression_full_run_package", False)),
)
print(
"[REGRESSION] collected output_dir={} counts={}".format(
result.get("output_dir", ""),
result.get("counts", {}),
),
flush=True,
)
except Exception as e:
print("[REGRESSION] collect failed: {}".format(e), flush=True)
def _is_douyin_top_package(package_name: str) -> bool:
top_pkg = str(package_name or "")
return bool(top_pkg) and (
"aweme" in top_pkg
or "douyin" in top_pkg
or "com.ss.android.ugc" in top_pkg
or "musically" in top_pkg
)
def _cold_start_douyin_for_test(analyser: object, device_id: str) -> bool:
op = getattr(analyser, "operation", None)
if op is None or not device_id:
return False
packages = path_config.get_douyin_packages()
for pkg in packages:
pkg = str(pkg or "").strip()
if not pkg:
continue
try:
op._run_adb_shell(device_id, f"am force-stop {pkg}", timeout_seconds=3.0)
except Exception:
pass
try:
op.delay(1.5)
except Exception:
time.sleep(1.5)
launched_ok = False
launched_pkg = ""
try:
launched_ok, launched_pkg = op.launch_package(device_id, "", timeout_seconds=5.0)
except Exception as e:
print(f"[COLD-START] launch failed: {e}", flush=True)
try:
op.delay(2.5)
except Exception:
time.sleep(2.5)
top_pkg = ""
try:
top_pkg = op.get_top_package(device_id) or ""
except Exception:
top_pkg = ""
ok = bool(launched_ok) and _is_douyin_top_package(top_pkg or launched_pkg)
print(
"[COLD-START] force_stop={} launched={} pkg={} top_pkg={} result={}".format(
len(tuple(packages)),
bool(launched_ok),
launched_pkg,
top_pkg,
"OK" if ok else "FAIL",
),
flush=True,
)
return ok
def main(argv: list[str]) -> int:
require_online_license_or_exit()
ensure_adb_in_path()
args = parse_args(argv)
run_started_at = time.time()
# 让命令行输出更稳定(实时刷新 + UTF-8)
try:
@@ -609,6 +751,13 @@ def main(argv: list[str]) -> int:
except Exception:
pass
try:
analyser.reenter_live_entry_mode = str(
args.reenter_live_entry_mode or "screen_center"
).strip().lower()
except Exception:
analyser.reenter_live_entry_mode = "screen_center"
device_id = args.device_id.strip() if args.device_id else ""
if not device_id:
device_id = analyser.operation.select_device()
@@ -617,13 +766,30 @@ def main(argv: list[str]) -> int:
print("未检测到设备,退出。")
return 2
analyser.fudai_choujiang(
device_id=device_id,
y_pianyi=args.y_pianyi,
needswitch=bool(args.needswitch),
wait_minutes=int(args.wait_minutes),
)
return 0
if bool(getattr(args, "cold_start", False)):
if not _cold_start_douyin_for_test(analyser, device_id):
print("抖音冷启动失败或前台不是抖音,退出。")
return 4
exit_code = 0
try:
analyser.fudai_choujiang(
device_id=device_id,
y_pianyi=args.y_pianyi,
needswitch=bool(args.needswitch),
wait_minutes=int(args.wait_minutes),
)
except Exception:
exit_code = 1
raise
finally:
_collect_regression_artifacts_if_enabled(
args,
run_started_at=run_started_at,
exit_code=exit_code,
device_id=device_id,
)
return exit_code
if __name__ == "__main__":
+25
View File
@@ -0,0 +1,25 @@
from __future__ import annotations
import sys
from pathlib import Path
_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
run_startup_update_check_early(app_name="run_cli")
from bin.run_cli import main # noqa: E402
from douyin.core.version import print_version_banner # noqa: E402
if __name__ == "__main__":
try:
print_version_banner("run_cli")
except Exception:
pass
raise SystemExit(main(sys.argv[1:]))
+2 -1
View File
@@ -8,10 +8,11 @@ import runpy
import sys
from pathlib import Path
from douyin.core import path_config
ROOT_DIR = Path(__file__).resolve().parent.parent
TARGET = ROOT_DIR / "gui" / "webgui_launcher.py"
VENV_PYTHON = ROOT_DIR / ".venv" / "Scripts" / "python.exe"
VENV_PYTHON = Path(path_config.get_venv_python_path())
def _reexec_with_venv() -> None:
+36
View File
@@ -0,0 +1,36 @@
@echo off
setlocal
pushd "%~dp0" >nul 2>&1
if errorlevel 1 (
echo [ERROR] Failed to change to script directory.
exit /b 1
)
set "BOOTSTRAP_SCRIPT=bootstrap_deps.py"
if not exist "%BOOTSTRAP_SCRIPT%" (
echo [ERROR] Missing %BOOTSTRAP_SCRIPT% in project root.
popd >nul 2>&1
exit /b 1
)
where py >nul 2>&1
if not errorlevel 1 (
py -3 "%BOOTSTRAP_SCRIPT%" %*
set "EXIT_CODE=%ERRORLEVEL%"
goto :done
)
where python >nul 2>&1
if errorlevel 1 (
echo [ERROR] Python launcher not found. Install Python 3.10+ and add it to PATH.
popd >nul 2>&1
exit /b 1
)
python "%BOOTSTRAP_SCRIPT%" %*
set "EXIT_CODE=%ERRORLEVEL%"
:done
popd >nul 2>&1
exit /b %EXIT_CODE%
+239
View File
@@ -0,0 +1,239 @@
#!/usr/bin/env python3
"""
One-click dependency bootstrap for this repository.
Default behavior:
1. Create/update a virtual environment at .venv
2. Upgrade pip/setuptools/wheel in that environment
3. Install dependencies from requirements.txt
Examples:
python bootstrap_deps.py
python bootstrap_deps.py --minimal
python bootstrap_deps.py --no-venv
python bootstrap_deps.py --index-url https://pypi.tuna.tsinghua.edu.cn/simple
"""
from __future__ import annotations
import argparse
import shlex
import subprocess
import sys
from pathlib import Path
from typing import Iterable, Sequence
def _echo(message: str) -> None:
print(message, flush=True)
def _format_cmd(cmd: Sequence[str]) -> str:
return " ".join(shlex.quote(part) for part in cmd)
def _run(cmd: Sequence[str], *, cwd: Path, dry_run: bool = False) -> None:
_echo(f"$ {_format_cmd(cmd)}")
if dry_run:
return
subprocess.run(cmd, cwd=str(cwd), check=True)
def _resolve_requirements(repo_root: Path, args: argparse.Namespace) -> Path:
if args.requirements:
req = Path(args.requirements).expanduser()
if not req.is_absolute():
req = repo_root / req
else:
req_name = "requirements-minimal.txt" if args.minimal else "requirements.txt"
req = repo_root / req_name
return req.resolve()
def _resolve_venv_python(venv_dir: Path) -> Path:
candidates = (
venv_dir / "Scripts" / "python.exe",
venv_dir / "Scripts" / "python",
venv_dir / "bin" / "python",
)
for candidate in candidates:
if candidate.exists():
return candidate.resolve()
raise FileNotFoundError(
f"Could not find a Python executable in virtual environment: {venv_dir}"
)
def _build_pip_index_args(args: argparse.Namespace) -> list[str]:
pip_args: list[str] = []
if args.index_url:
pip_args += ["--index-url", args.index_url]
for item in args.extra_index_url:
pip_args += ["--extra-index-url", item]
for item in args.trusted_host:
pip_args += ["--trusted-host", item]
if args.no_cache_dir:
pip_args.append("--no-cache-dir")
if args.prefer_binary:
pip_args.append("--prefer-binary")
return pip_args
def _validate_python_version() -> None:
if sys.version_info < (3, 10):
raise RuntimeError(
f"Python 3.10+ is required. Current interpreter: {sys.version.split()[0]}"
)
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Bootstrap project dependencies in a migration-friendly way."
)
parser.add_argument(
"--venv-dir",
default=".venv",
help="Virtual environment directory (default: .venv).",
)
parser.add_argument(
"--no-venv",
action="store_true",
help="Install into the current Python environment instead of creating/using a venv.",
)
parser.add_argument(
"--python",
default="",
help="Python executable used to create the virtual environment.",
)
parser.add_argument(
"--minimal",
action="store_true",
help="Install requirements-minimal.txt instead of requirements.txt.",
)
parser.add_argument(
"--requirements",
default="",
help="Custom requirements file path (overrides --minimal).",
)
parser.add_argument(
"--skip-pip-upgrade",
action="store_true",
help="Skip upgrading pip/setuptools/wheel.",
)
parser.add_argument(
"--index-url",
default="",
help="Base package index URL for pip install.",
)
parser.add_argument(
"--extra-index-url",
action="append",
default=[],
help="Extra package index URL for pip install (repeatable).",
)
parser.add_argument(
"--trusted-host",
action="append",
default=[],
help="Trusted host passed to pip install (repeatable).",
)
parser.add_argument(
"--no-cache-dir",
action="store_true",
help="Pass --no-cache-dir to pip.",
)
parser.add_argument(
"--prefer-binary",
action="store_true",
help="Prefer binary wheels when possible.",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Print commands without executing them.",
)
return parser.parse_args()
def main() -> int:
_validate_python_version()
args = _parse_args()
repo_root = Path(__file__).resolve().parent
requirements_path = _resolve_requirements(repo_root, args)
if not requirements_path.exists():
raise FileNotFoundError(f"Requirements file not found: {requirements_path}")
if args.no_venv:
install_python = Path(sys.executable).resolve()
_echo(f"Using current interpreter: {install_python}")
else:
venv_dir = Path(args.venv_dir).expanduser()
if not venv_dir.is_absolute():
venv_dir = repo_root / venv_dir
creator_python = (args.python or sys.executable).strip()
if not _resolve_venv_python_if_exists(venv_dir):
_echo(f"Creating virtual environment: {venv_dir}")
_run([creator_python, "-m", "venv", str(venv_dir)], cwd=repo_root, dry_run=args.dry_run)
else:
_echo(f"Virtual environment already exists: {venv_dir}")
install_python = _resolve_venv_python(venv_dir)
_echo(f"Using virtual environment interpreter: {install_python}")
pip_base = [str(install_python), "-m", "pip"]
pip_index_args = _build_pip_index_args(args)
if not args.skip_pip_upgrade:
_echo("Upgrading pip, setuptools, and wheel...")
_run(
[*pip_base, "install", "--upgrade", "pip", "setuptools", "wheel", *pip_index_args],
cwd=repo_root,
dry_run=args.dry_run,
)
_echo(f"Installing dependencies from: {requirements_path}")
_run(
[*pip_base, "install", "-r", str(requirements_path), *pip_index_args],
cwd=repo_root,
dry_run=args.dry_run,
)
if not args.no_venv:
_echo("")
_echo("Done.")
if sys.platform.startswith("win"):
_echo(r"Activate with: .venv\Scripts\Activate.ps1")
else:
_echo("Activate with: source .venv/bin/activate")
else:
_echo("")
_echo("Done (installed into current interpreter).")
return 0
def _resolve_venv_python_if_exists(venv_dir: Path) -> Path | None:
candidates: Iterable[Path] = (
venv_dir / "Scripts" / "python.exe",
venv_dir / "Scripts" / "python",
venv_dir / "bin" / "python",
)
for candidate in candidates:
if candidate.exists():
return candidate.resolve()
return None
if __name__ == "__main__":
try:
raise SystemExit(main())
except subprocess.CalledProcessError as exc:
_echo("")
_echo(f"Command failed with exit code {exc.returncode}.")
raise SystemExit(exc.returncode)
except Exception as exc: # pragma: no cover - defensive entrypoint guard
_echo("")
_echo(f"Bootstrap failed: {exc}")
raise SystemExit(1)
+49
View File
@@ -14,6 +14,55 @@
- 建议在修改配置前备份原文件
- 配置文件使用 UTF-8 编码
## 自动更新配置
默认建议使用 HTTPS 且安装包与 manifest 同源:
```json
{
"auto_update": {
"enabled": true,
"manifest_url": "https://updates.example.com/douyin/update.json",
"fail_closed": true,
"require_sha256": true,
"require_https": true,
"allow_cross_origin": false
}
}
```
仅内网临时测试 `http://192.168.x.x/...` 时,才显式放宽:
```json
{
"auto_update": {
"enabled": true,
"manifest_url": "http://192.168.10.2:8000/update.json",
"require_https": false,
"allow_cross_origin": true
}
}
```
正式分发不要使用 HTTP;`sha256` 只能防安装包下载损坏,不能替代可信 manifest。
## 在线卡密激活配置
正式接入服务器后,在本地配置中增加:
```json
{
"license": {
"activation_url": "https://license.example.com/api/v1/activate",
"timeout_seconds": 10
}
}
```
未配置 `activation_url` 时,客户端仍只按旧逻辑安装 `DYGJ-` 离线授权码或完整
`license.dat` 内容。配置后,普通 `DG-` 卡密会请求服务器激活,服务器返回的签名授权
仍会先在本地验签,通过后才写入 `license.dat`。
+286 -12
View File
@@ -2,17 +2,31 @@
"needswitch": true,
"infinite_loop_enabled": true,
"wait_minutes": 5,
"min_prize_value_yuan": 300.0,
"auto_update": {
"enabled": false,
"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": 118,
"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": 500.0,
"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,
@@ -29,7 +43,7 @@
"yanghao_fallback_enter_live_x": 540,
"yanghao_fallback_enter_live_y": 1200,
"fudai_find_max_attempts": 99999,
"fudai_icon_max_wait_seconds": 6.5,
"fudai_icon_max_wait_seconds": 7.0,
"fudai_icon_retry_delay_seconds": 0.1,
"fudai_exit_after_misses": 7,
"enable_back_on_misses": false,
@@ -38,8 +52,29 @@
"fudai_detail_verified_wait_seconds": 0.2,
"fudai_detail_retry_delay_seconds": 0.5,
"fudai_detail_save_debug_images": true,
"fudai_disable_content_recognition": true,
"fudai_disable_task_recognition": 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,
@@ -158,9 +193,9 @@
"beautify_output": true,
"show_timestamps": true,
"show_execution_times": true,
"debug_detail_level": "detailed",
"debug_detail_level": "normal",
"error_detail_level": "full",
"action_log_format": "detailed",
"action_log_format": "concise",
"log_format_mode": "simple",
"stage_diag_verbose": true,
"color_output": true,
@@ -194,7 +229,7 @@
"monitor_critical_mb": 200.0
},
"debug_captures": {
"enabled": false,
"enabled": true,
"keep_days": 1,
"max_files": 1000,
"auto_cleanup": true,
@@ -210,7 +245,11 @@
"reservation_test_mode": false,
"swipe_duration_ms": 250,
"gui": {
"theme": "litera"
"theme": "litera",
"realtime_status": {
"refresh_interval_ms": 1000,
"tail_items": 50
}
},
"fansclub_click_delay": 0.6,
"fansclub_auto_join_wait_seconds": 5.0,
@@ -220,9 +259,244 @@
"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": 9999,
"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_up_end_y": 600,
"swipe_down_back_enabled": false,
"swipe_down_back_count": 3,
"log_unified_enabled": true,
"log_unified_path": "logs/unified.log",
"last_wifi_target": {
"target": "192.168.10.102:39783",
"model": "PEPM00",
"saved_at": 1782148222
},
"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
]
}
}
+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
}
}
+2
View File
@@ -6,6 +6,8 @@
### 入门与依赖
- **DEPENDENCY_GUIDE.md** - 依赖安装与版本说明
- **迁移部署指南.md** - 新电脑部署与手机端操作清单
- **deployment_quickstart.txt** - 极简迁移说明(优先一键部署 + 手机导航栏教程)
- **WiFi_ADB_使用指南.md** - WiFi ADB 连接指南
- **scrcpy_手动安装指南.md** - scrcpy 手动安装
- **核显GPU加速说明.md** - 核显 GPU 加速
@@ -0,0 +1,18 @@
# 福袋详情页 OCR 2.0 handoff
1. 目标:按 1080x2400 新福袋详情页更新 OCR 区域,保留 legacy,并支持 `auto/legacy/v2_0`。
2. 已新增字段开关:内容、价值、倒计时、任务、任务数量、按钮默认开;人数、直播间标题默认关。
3. 旧开关 `fudai_disable_content_recognition` / `fudai_disable_task_recognition` 仅作新开关缺省兜底。
4. 2.0 双任务 profile 在 `douyin/fudai/core/coords.py` 的 `DETAIL_UI_V2_0`。
5. 2.0 单任务下移 profile 在 `DETAIL_UI_V2_0_ONE_TASK`,按当前 ADB 截图微调。
6. 当前单任务标注图:`logs/fudai_detail_v2_regions_onetask_precise3.png`。
7. 当前 ADB 原图:`logs/fudai_detail_v2_current_20260602_234012.png`。
8. 单任务任务框已缩到左侧任务文案,避免混入右侧“未达成”。
9. 任务数量优先 OCR `(0/1)` / `(1/2)`,失败回退 legacy 像素检测。
10. debug 截图 extra_info 已包含 `ui_version`、`ocr_enabled`、`region_name` 等信息。
11. 桌面 GUI 与 Web GUI 已加入 UI 版本和所有 OCR 字段开关。
12. “参考价值”按实际价值解析,继续写 `prize_value_yuan`。
13. 验证日志:`logs/pytest_fudai_detail_v2_final4.log` PASS。
14. 验证日志:`logs/py_compile_fudai_detail_v2_final4.log` PASS。
15. 验证日志:`logs/web_gui_config_sync_fudai_v2_final4.log` PASS。
16. 验证日志:`logs/git_diff_check_fudai_v2_final4.log` PASS。
@@ -0,0 +1,239 @@
# 2026-06-02 全量代码审查进展
目标:对 `C:\Users\12742\Desktop\douyin_guaji-main` 做仓库级 code review,并对确认的高风险功能缺陷直接修复。
## 已确认并已修复
1. `gui/web_gui.py`
- `force_stop()` / `atexit` 会误杀同仓库其他 `run_cli.py` 进程。
- 已改为只清理当前 Web GUI 自己启动过的 PID。
2. `gui/webgui_launcher.py`
- `stop_old_processes()` 会按 `*web_gui.py*` 全局杀进程。
- 已改为限定当前仓库路径。
3. `gui/gui_core_pkg/config.py`
- 配置写入是浅 `update` + 直接覆盖,存在并发丢字段和半写风险。
- 已改为深合并 + 进程内锁 + `.tmp` + `os.replace()`。
4. `operations/screenshot_service.py`
- `start()` 在持锁状态下调用 `stop()`,设备切换时可能死锁。
- 已改为先释放锁再等待旧线程退出。
5. `gui/gui_core_pkg/wifi_adb.py`
- `disconnect_wifi_adb("ip:port")` 会拼成 `ip:port:5555`。
- 已修复为支持直接 `ip:port` 输入。
6. `gui/web_gui_pkg/routes.py`
- `/api/*` GET/POST、`/pic/*` 以及静态页都可被非本地来源访问。
- 已全部限制为 local-only。
7. `douyin/core/douyin_fudai.py`
- `_maybe_run_yanghao_during_run()` 注释说触发推荐页养号,实际只调用 `_yanghao_wait()`。
- 已改为真正调用 `_yanghao_recommend_flow()`。
8. `douyin/fudai/core/fudai_detail_orchestrator_pkg/read_with_retries.py`
- `read_once_callback` 参数未被真正使用。
- `status="ok"` 但 tuple 无效时会走未定义局部变量路径。
- `task_count_zero` 补救逻辑与 `read_once()` 返回的 `not_in_fudai_detail` 不一致。
- 已修复以上三点。
9. `douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py`
- 停止后台截图服务后未恢复。
- 复用阶段截图时不验证可读性,坏图会直接落到 `screenshot_failed`。
- 已补恢复逻辑和坏图自动 fresh screenshot。
10. `douyin/core/fudai_modules/handle_detail_*`
- first-open / second-open / 错误分支存在多处状态残留:
- first-open 可能误标 second-open
- second-open 重读终止状态后不清 flag
- second-open 重读失败后仍卡 second-open
- task_count_zero / not_in_fudai_detail 被消费后不清 `_last_fudai_detail_status/_extra`
- coupon/watch/validation_failed 被消费后不清 `_last_fudai_detail_status`
- 以上已逐项修复。
11. `douyin/detection/detection_pkg/finder.py`
- 命中后不写回 `last_fudai_x`。
- 非 1080 宽屏下历史坐标比较混用坐标系。
- `fudai_icon_max_wait_seconds=0` 时会 0 次检测直接退出。
- 已修复。
12. `douyin/detection/detection_pkg/finder_template_match.py`
- 模板兜底命中后不写回 `last_fudai_x`,与其他两条检测路径不一致。
- 已修复。
13. 导入链缺依赖即崩
- 已逐步把以下模块的顶层 `PIL` 依赖改成按需导入:
- `operations.__init__`
- `operations.screenshot_service`
- `douyin.detection.pixel._common`
- `douyin.detection.pixel.buttons`
- `douyin.detection.pixel.popups`
- `douyin.detection.pixel.stage`
- `douyin.detection.detection_pkg.detail`
- `douyin.detection.detection_pkg.finder`
- `douyin.fudai.core.fudai_debug_utils`
- `douyin.fudai.core.fudai_detail_coupon_detection`
- `douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once`
- `douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries`
- `douyin.core.douyin_fudai`
- `douyin.core.underlying_operations`
- 当前机器上已实证:
- `import operations`:PASS
- `import operations.screenshot_service`:PASS
- `import douyin.detection.douyin_detection`:PASS
- `import douyin.core.douyin_fudai`:PASS
14. `douyin/handlers/douyin_screenshot_handler.py`
- `save_step_screenshot()` 用 `dirname(__file__)` 锚到错误 `pic` 目录。
- 已改为统一使用 `path_config.get_pic_dir()`。
15. `douyin/core/fudai_modules/handle_detail_*`
- `check_invalid_detail_fallback()` 早退时不清 `_fudai_detail_first_read/_last_fudai_detail_tuple`。
- `handle_first_open_branch()` 的早退路径不清 first-open/缓存状态。
- `handle_second_open_branch()` 重读无效详情时不清 second-open 标志。
- 已修复。
16. `douyin/core/fudai_modules/handle_detail_helpers.py`
- 终止类状态(coupon/watch/validation_failed)消费后不清 `_last_fudai_detail_status`。
- task_count_zero / not_in_fudai_detail 错误被消费后不清 `_last_fudai_detail_status/_last_fudai_detail_extra`。
- 已修复。
17. `douyin/detection/detection_pkg/finder.py`
- `fudai_icon_max_wait_seconds=0` 时会 0 次检测直接退出。
- 旧实现还会把显式配置的 `0` 通过 `or 5.0` 偷偷退回默认值。
- 已修复为保留显式 `0`,并至少执行一轮即时检测。
18. `douyin/fudai/core/fudai_detail_coupon_detection.py`
- 顶层 `PIL` 依赖会继续阻塞 `douyin_fudai` 导入链。
- 已改为按需导入。
19. `douyin/detection/pixel/*`
- `popups.py` / `buttons.py` / `stage.py` / `_common.py` 顶层 `PIL` 依赖会阻塞 detection 导入链。
- 已改为按需导入。
20. `douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py`
- 第二次打开重读后若仍无有效 detail,会继续保留 second-open 状态。
- 已修复。
21. `douyin/core/fudai_modules/handle_detail_first_open.py`
- `branch_result == "return"` / 验证失败早退时,`_fudai_detail_first_read/_last_fudai_detail_tuple` 不清理。
- 已修复。
22. `douyin/core/fudai_modules/handle_detail_helpers.py`
- `check_invalid_detail_fallback()` 早退时不清 `_fudai_detail_first_read/_last_fudai_detail_tuple`。
- 已修复。
23. `douyin/detection/detection_pkg/finder_template_match.py`
- 模板兜底命中后只写 `last_find_fudai_time`,不写 `last_fudai_x`。
- 已修复。
24. `operations/screenshot_operations.py` / `douyin/core/underlying_operations_pkg/screenshot_direct.py`
- `target_pic` fallback 路径仍相对模块目录拼接。
- 已统一锚到 `<project_root>/target_pic`。
25. `operations/screenshot_operations.py`
- `_find_pic_path(..., for_reading=True)` 会把 `operations/` 当前目录作为图片搜索路径,可能误命中同名文件。
- 已修复为只搜索项目根 `pic/` 与 `target_pic/`。
26. `douyin/detection/pixel/stage.py`
- 并行阶段检测里实际调用了 popup/button helper,但文件头没导入,对应检测项运行时会静默掉成 False。
- 已补齐导入。
27. `douyin/core/douyin_flow_control_pkg/stage_handler.py`
- 直接调用 `find_and_open_fudai_detail()` 却未导入。
- 已修复。
28. `douyin/core/underlying_operations_pkg/countdown.py`
- 使用 `Optional` 但未导入。
- 已修复。
29. `douyin/core/fudai_modules/handle_detail_filter.py`
- 高价值预约分支里 `basic_join_decision()` 失败也会被当成“已记录预约并完成”。
- 已修复为只有真成功才消费该分支。
30. `douyin/reservation/reservation_logic/add.py` / `attend_window.py`
- 日志里的旧静态检查结果显示两处反复引用 `_RESERVATION_ERROR_UTILS_AVAILABLE`,但模块本身漏导入,属于确定性的 `NameError`/静态错误来源。
- 已补齐从 `reservation_logic._common` 的导入。
31. `gui/web_gui_pkg/request_parsing.py`
- `send_json()` 在客户端主动断开连接时会把正常断链打成 `ConnectionAbortedError` traceback,已在 `logs/web_gui_runtime.err.log` 中出现。
- 已改为对 `BrokenPipeError` / `ConnectionAbortedError` / `ConnectionResetError` 静默收口,不再把正常断链记成服务端异常。
32. `douyin/logging/douyin_logging_pkg/monitor.py`
- `logs` 中出现 `cannot import name 'start_log_monitor' from partially initialized module ... monitor`,根因是 `monitor.py` 顶层反向导入 `config.py`,同时模块导入末尾又主动调用 `configure_logging()`,形成循环导入。
- 已去掉 `monitor -> config` 的顶层依赖,以及 `monitor` 模块导入时的自动配置副作用,当前 `monitor/config/douyin_logging` 导入链已可直接通过。
33. `douyin/logging/action_logger.py`
- `ActionLogger.log_operation()` 之前只认 `elapsed`,会把调用方已经传进来的 `elapsed_seconds` 吞掉并重写成 `0.0`,导致 `actions.log` 大量出现假的 `耗时=0.00ms`。
- 已改为同时正确接受 `elapsed` / `elapsed_seconds`,只在确实有值时才写入耗时字段,日志耗时保真恢复正常。
34. `douyin/fudai/douyin_fudai_contain_impl.py`
- 重 OCR 分支里 `picked_heavy` 只在部分条件下赋值,后续却无条件读取,存在继续污染运行日志的局部变量边界风险。
- 已补默认初始化,避免该分支再出现这类局部变量异常。
35. `douyin/logging/douyin_logging_wrapper_pkg/simple.py`
- 行为日志桥接层之前只识别 `elapsed_ms` / `total_ms`,但 finder 一类日志大量传的是 `total_elapsed_ms`,导致这些本来已有总耗时的操作仍被桥接成缺失耗时或误导性 `0.00ms`。
- 已补 `total_elapsed_ms -> elapsed_seconds` 的统一映射,后续 `actions.log` 能更真实反映 finder 总耗时。
36. `douyin/logging/douyin_logging_wrapper_pkg/detailed.py`
- detailed 模式下的行为日志桥接也存在同样问题:只识别 `elapsed_ms` / `total_ms`,未覆盖 `total_elapsed_ms`,会让不同日志模式下的耗时记录不一致。
- 已与 simple 模式对齐,补上 `total_elapsed_ms` 识别。
37. `douyin/reservation/reservation_logic/attend_window.py`
- 运行时分支里仍残留一组高风险未定义符号:`cleanup_expired_reservations` 未导入,以及 `target_room_title / target_room_title_raw / target_content / target_value` 在成功回退分支会被直接使用。
- 已补齐导入与目标预约字段的本地初始化,避免这些分支在运行时直接 `NameError`。
38. `douyin/fudai/core/fudai_attend.py`
- `attend_choujiang()` 之前会在 5 秒有效期内无条件复用 `_fudai_button_status/_fudai_button_text`,没有校验缓存是否来自当前直播间,存在把上一个房间按钮状态误用到当前房间的风险。
- 已改为:5 秒内复用也必须满足 `current_room_pos == _fudai_button_room_pos`(或其中一方缺失),避免跨房间误复用按钮 OCR 缓存。
39. `douyin/reservation/douyin_reservation_handler_pkg/seek_room.py`
- 回退成功后会直接调用 `_dump_room_pos_map_to_state(analyser)`,但文件头之前没导入这个 helper,属于命中成功回退分支就可能触发的运行时 `NameError`。
- 已补从 `dump_state.py` 的显式导入,并加了最小导入回归验证。
40. `douyin/fudai/core/fudai_attend.py`
- 当 `room_pos` 不命中时,`attend_choujiang()` 之前只会从当前 `room_pos` 的映射表项回收 `button_text`,容易在房间位置漂移时直接掉到 `no_parallel_ocr_result`。
- 已补按 `current_room_title/current_room_title_raw` 匹配映射表标题的兜底回收路径,减少按钮 OCR 缓存因为位置漂移而失效。
41. `douyin/fudai/core/fudai_attend.py`
- `button_text_raw` 作为全局缓存之前会被直接信任,但它本身没有房间归属校验,存在把上一个直播间的裸按钮文本误用到当前直播间的风险。
- 已改为:只有确认 `_fudai_button_room_pos` 与当前 `room_pos` 同房间(或任一方缺失)时,才允许直接信任 `button_text_raw`。
42. `douyin/fudai/core/fudai_attend.py`
- “点击参与抽奖”分支里那两段调试 JSON 写盘之前完全裸奔,遇到不可 JSON 序列化对象时会直接把主流程打断。
- 已改为真正的 best-effort:写盘整体包裹在 `try/except` 中,并对关键字段做基础类型收敛,`json.dumps(..., default=str)` 不再让调试写盘反咬业务路径。
43. `douyin/fudai/douyin_fudai_contain_impl.py`
- 主并行 OCR 写按钮状态时会记录 `_fudai_button_room_pos`,但 fallback 并行 OCR 之前没传 `record_room_pos=True`,导致备用 OCR 成功后仍可能缺失房间归属信息,进而削弱后续跨房间缓存保护。
- 已补齐 fallback 路径的 `record_room_pos=True`,并加了最小回归验证。
44. `gui/components/wifi_adb_dialog.py`
- `toggle_maximize` 之前被错误定义在 `auto_connect_wifi()` 内部,但“放大/恢复”按钮是在外层直接绑定 `command=toggle_maximize`,属于打开对话框就可能命中的真作用域错误。
- 已把 `toggle_maximize` 提升到 `open_wifi_adb_dialog()` 同级作用域,并补了最小 smoke test 证明按钮命令可正常绑定。
## 仍建议继续深挖
1. `douyin/detection/detection_pkg/finder.py`
- 坏截图/半写图补拍恢复的一致性。
- 模板兜底与像素路径在日志、计时和状态清理上的一致性。
2. `douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py`
- 运行期截图/OCR异常回退的进一步收口。
## 仍未修复但已确认的风险
1. `config/config.json`
- 仍混有明显的本机运行态/本地偏好数据(如 `last_wifi_target`),不适合作为稳定仓库默认值。
- 因文件属于当前工作树活跃修改内容,未直接重写,避免覆盖用户现场状态。
2. `pyright`
- 仓库仍存在一批历史静态类型错误,当前没有被系统性清理。
3. `pytest`
- 当前环境缺 `pytest`,无法在本会话中把新增回归测试正式跑绿;目前主要依赖语法检查与轻量行为探针。
## 当前验证约束
1. 当前环境缺 `pytest`,不能直接在此会话里把新增测试跑绿。
2. 当前环境缺 `PIL` / OCR 相关依赖,但这反而帮助暴露了导入链的真实缺陷;多处“缺依赖即崩”的问题已被修复并通过轻量 import 探针验证。
@@ -0,0 +1,9 @@
# 2026-06-18 真机福袋诊断 handoff
- 设备:`192.168.10.100:45967`,前台为 `com.ss.android.ugc.aweme/.live.LivePlayActivity`。
- 已修 1:无福袋房间继承旧 `_current_fudai_content`,提交 `22e2ed1`,复测 `artifacts/live_fudai_flow_20260618_124737` 里无福袋位置 `2/3/6/8/9` 均为空内容。
- 已修 2:v2 双任务详情区域偏低,导致巴图 4999 福袋倒计时/内容裁剪到标题行;样本已保存到 `tests/fixtures/fudai_detail_v2_two_task_batu_4999_regions.png`。
- 已修 3:`0元带走¥999参考价值` 被价值校验器误判为 `value_raw_mismatch_parsed_value`。
- 复测证据:`artifacts/live_fudai_flow_20260618_130639` 中 13:10:20 识别 `【粉丝专享】左上角领取散热风`、`07:59`、`999元`,并写入预约,优惠券弹窗出现时日志为跳过福袋点击。
- 未充分覆盖:预约回退未进入实际执行窗口,日志均为 `时间窗口未到`;需后续更长轮验证。
- 待盯:关注列表当前可能直播间数量少或滑动未换房,短轮 `artifacts/live_fudai_flow_20260618_131658` 多次触发同房三连/回顶。
@@ -0,0 +1,16 @@
# 2026-06-18 gui_dashboard_app 新 UI 入口美化交接
- 范围:只改 `gui/dashboard_app` 新入口、`gui/gui_dashboard_app_entry.py` 入口关联和 `tools/gui` 导出工具。
- 旧入口:未改 `gui/gui_app.py`。
- 功能边界:以 20 页真实导出图为准,不新增/删除页面和功能。
- 页面数:`PAGES=20`。
- 视觉方向:浅色桌面 App、固定侧栏、顶部工具栏、底部运行栏、圆角按钮、轻量卡片、紧凑表格。
- 模块化:拆分为 `page_home/page_config/page_debug/page_data/page_registry/page_helpers/page_context`。
- 交互保留:刷新设备、扫描 WiFi、WiFi ADB、截图+OCR、保存配置、开始/停止/强制停止/返回键。
- 文本框保留:关键词、养号评论文案、爱心/收藏关键词切页不丢。
- 验证:`python -m py_compile` PASS。
- 验证:20 页 Tk 构建遍历 PASS。
- 验证:`git diff --check` PASS。
- 视觉核对包:`artifacts/gui_dashboard_ui_review_20260618_124233/index.html`。
- 视觉总览:`artifacts/gui_dashboard_ui_review_20260618_124233/contact-sheet.jpg`。
- 注意:`artifacts/` 为验收产物,未纳入提交。
+111
View File
@@ -0,0 +1,111 @@
Douyin Guaji - Quick Deployment (TXT)
=====================================
Purpose
-------
This is the simplified migration guide.
Computer-side setup is kept minimal because one-click deploy scripts are already provided.
1) Computer (minimal)
---------------------
Prerequisites:
- Windows 10/11
- Python 3.10+
- ADB (platform-tools) available in PATH
In project root, run:
bootstrap_deps.bat
Optional:
bootstrap_deps.bat --minimal
2) Phone required setup
-----------------------
2.1 Enable Developer options
- Open: Settings -> About phone
- Tap "Build number" 7 times
- Enter lock screen password if asked
2.2 Enable USB debugging
- Open: Settings -> Developer options
- Turn on:
- USB debugging
- (if available) USB debugging (Security settings) / USB installation
2.3 First USB authorization
- Connect phone to PC with USB cable
- Set USB mode to File Transfer (MTP)
- On phone popup "Allow USB debugging", tap Allow
- Verify on PC:
adb devices
Expected:
<device-id> device
If status is "unauthorized", replug cable and approve popup again.
3) How to show the bottom navigation bar on phone (detailed)
-------------------------------------------------------------
This section is for the Android system navigation bar (Back / Home / Recents).
Method A (standard Android path)
--------------------------------
1. Open Settings
2. Search "Navigation mode" (or "System navigation")
3. Open the result and switch to:
- 3-button navigation (shows bottom buttons), or
- Gesture navigation (shows gesture bar/hint on some devices)
Common path examples:
- Pixel / near-stock Android:
Settings -> System -> Navigation mode
- Some other ROMs:
Settings -> System -> Gestures -> Navigation mode
Method B (common brand paths)
-----------------------------
- Samsung:
Settings -> Display -> Navigation bar -> Buttons
- Xiaomi / Redmi / POCO (MIUI / HyperOS):
Settings -> Home screen -> System navigation -> Buttons
- OPPO / OnePlus (ColorOS / OxygenOS):
Settings -> System settings -> System navigation -> Virtual buttons
- vivo / iQOO:
Settings -> System navigation -> Navigation keys
- Huawei / Honor:
Settings -> System & updates -> System navigation -> Three-key navigation
If the bar still does not appear:
---------------------------------
1. Disable any "Full screen gestures" option
2. Disable app-level full screen mode for the current app
3. Reboot phone once after switching navigation mode
4. Use Settings search with keywords:
- navigation
- system navigation
- gesture
Temporary reveal tip:
---------------------
If an app is full-screen and hides controls, swipe up from the very bottom edge once.
On many devices this temporarily shows system navigation controls.
4) Quick run check
------------------
After dependencies are ready and ADB is authorized:
python bin/gui_app.py
Check:
- Device is visible in device selector
- Screenshot action works
- Start button can launch run loop
@@ -0,0 +1,272 @@
# 全量安全审计报告(2026-06-28)
## 结论摘要
本次审计覆盖客户端授权、自动更新、差量更新、服务端卡密/API、后台发布、WebGUI、本地打包、CI/CD 和仓库敏感信息暴露面。总体判断:
- 授权与更新主链路已有基础可信链:服务端签名授权/更新 manifest,客户端只内置公钥并校验 manifest 签名与文件 SHA256 后再执行更新。
- 当前最需要优先修的是服务端发布面与分发面:后台 token 权限过大、上传包一次性读入内存、下载包直出服务端。
- WebGUI 默认本机监听、POST 有 CSRF、未授权时拦截运行类接口,基础边界合理;但安全响应头和 CSP 仍缺失。
- 打包已包含 Cython/分发清单/新环境冒烟测试,但依赖安装仍是浮动版本,正式发布需要锁版本、记录 SBOM,并加入签名校验。
## 审计范围
- 服务端:`license_server/api.py`、`license_server/core.py`、`license_server/requirements.txt`、`license_server/docker-compose.yml`、`license_server/Dockerfile`
- 客户端授权:`douyin/license/license_manager.py`、`douyin/license/public_key.py`
- 自动更新:`douyin/updater/force_update.py`、`douyin/updater/bootstrap.py`、`tools/update_delta.py`
- WebGUI:`gui/web_gui.py`、`gui/web_gui_pkg/*`、`webui/**/*`
- 打包与 CI:`packaging/pyinstaller/build_windows.ps1`、`.github/workflows/windows-package-ci.yml`、`tools/ci/fresh_install_smoke.ps1`
- 仓库敏感信息:源代码、文档、测试、配置模板,排除 `artifacts/`、`dist/`、`build/`、`output/`、`logs/` 等生成物。
## 高风险
### H1. 后台发布权限仍集中在单个 admin token
证据:
- `license_server/api.py:118-139` 中 `_admin_allowed()` 接受三种管理员凭据:Session Cookie、`Bearer <token>`、Basic Auth 密码。
- `license_server/api.py:823-873` 的全量包和差量包发布接口只要通过管理员鉴权和 CSRF 即可发布更新。
影响:
- 一旦 `DYGJ_LICENSE_ADMIN_TOKEN` 泄露,攻击者可以发布全量安装包或差量包。
- 现有 manifest 签名能防止“客户端绕过服务端伪造更新”,但不能防止“拿到后台权限后用合法服务端签名发布恶意更新”。
建议:
- 立即轮换历史 admin token,清理桌面、聊天临时目录、部署机器 shell history 中的明文 token。
- 将“登录后台”和“发布更新”拆成两级权限:普通后台 token 不能发布更新,发布更新需要短时一次性 publish token 或 TOTP。
- 发布接口加 IP 白名单、审计日志、版本回滚记录和人工确认。
- 正式包必须做 Authenticode 签名,客户端启动安装器前校验发行者证书指纹。
### H2. 后台上传全量包/差量包会一次性读入内存
证据:
- `license_server/api.py:835` 对安装包执行 `content = await installer.read()`。
- `license_server/api.py:862` 对差量包执行 `content = await delta_file.read()`。
- `license_server/core.py:555-588` 的 `publish_update()` 接收完整 `bytes` 后写盘。
- `license_server/core.py:590-624` 的 `publish_delta_update()` 同样接收完整 `bytes` 后写盘。
影响:
- 大文件或异常 multipart 请求会直接放大服务端内存压力。
- 管理员误操作、token 泄露或代理层限流配置缺失时,容易造成授权服务器不可用。
建议:
- 上传接口加显式大小上限,例如全量包 500MB、差量包 200MB,超限立即拒绝。
- 改成流式写入临时文件,并边写边计算 SHA256。
- 反向代理加 `client_max_body_size` / request body size limit。
- 发布前校验文件类型、扩展名、hash、版本号和可执行文件签名。
### H3. 更新包下载由授权服务直接 `FileResponse` 暴露
证据:
- `license_server/api.py:681-698` 使用 `FileResponse` 直接返回全量包或差量包。
- `license_server/api.py:686-690` 已限制只能下载当前 manifest 允许的文件名,这是正向控制。
影响:
- 安装包/差量包通常较大,未加下载鉴权、限速或 CDN 时,服务端可被下载流量拖垮。
- Starlette `FileResponse` 是真实攻击面。外部公告显示,历史上 Starlette `FileResponse` Range 处理出现过 CPU DoS(CVE-2025-62727,修复于 0.49.1),multipart/form-data 也出现过内存 DoS(CVE-2024-47874,修复于 0.40.0)。
- 当前本机 Starlette 为 `1.3.1`,不落在上述受影响范围内;但生产环境如果不锁版本,仍存在依赖漂移和部署不可复现风险。
建议:
- 更新包放对象存储/CDN,授权服务只签发短期下载 URL。
- 服务端保留 manifest 和授权 API,不承担大文件分发。
- 若继续直出文件,固定 `starlette>=0.49.1`,并在依赖扫描中阻断已知 CVE。
## 中风险
### M1. 生产环境 Host header 仍依赖配置自觉
证据:
- `license_server/api.py:245-249`:未设置 `DYGJ_LICENSE_PUBLIC_BASE_URL` 时,manifest 下载 URL 从 `request.base_url` 推导。
- `license_server/api.py:484-499`:创建 FastAPI app 时未添加 `TrustedHostMiddleware`。
影响:
- 如果生产代理透传恶意 Host,且未配置 `DYGJ_LICENSE_PUBLIC_BASE_URL`,生成的 manifest 下载链接可能被 Host header 污染。
- 客户端有 HTTPS、同源、签名和 SHA256 校验,能降低恶意包执行风险;但错误下载源仍会造成更新失败或服务可用性问题。
建议:
- 生产环境强制要求 `DYGJ_LICENSE_PUBLIC_BASE_URL`,缺失即启动失败。
- 加 `TrustedHostMiddleware`,只允许正式域名和本地健康检查域名。
- 在部署文档中明确 Nginx/Cloudflare 的 Host 转发策略。
### M2. 管理后台 Cookie 默认未开启 Secure
证据:
- `license_server/api.py:495` 中 `DYGJ_LICENSE_SECURE_COOKIES` 默认值为 `False`。
- `license_server/api.py:706-712` 和 `license_server/api.py:733-740` 根据该开关设置 CSRF Cookie 和后台 Session Cookie 的 `secure`。
影响:
- 生产 HTTPS 场景如果忘记设置环境变量,后台 Cookie 不带 Secure 标记。
- `HttpOnly` 和 `SameSite=Lax` 已存在,风险主要来自生产配置遗漏。
建议:
- 生产模式默认 Secure=true,开发模式才允许关闭。
- 启动时检测 `DYGJ_LICENSE_PUBLIC_BASE_URL` 为 `https://` 时强制 Secure Cookie。
### M3. 客户端执行安装器前缺少 Authenticode 校验
证据:
- `douyin/updater/force_update.py:143-158` 会校验 manifest 签名。
- `douyin/updater/force_update.py:556-566` 校验安装包 SHA256 后直接构造命令并启动安装器。
- 当前未看到对 Windows Authenticode 签名、发行者证书指纹或时间戳的校验。
影响:
- SHA256 只能证明“下载到的文件与签名 manifest 中声明一致”。
- 如果服务端私钥或发布后台被攻破,攻击者仍可能发布一个“合法签名 manifest + 恶意 exe”。
建议:
- 正式发布包使用 Authenticode 签名。
- 客户端在 `launch_installer()` 前验证 exe 签名主体和证书指纹。
- CI/CD 记录签名证书指纹、安装包 SHA256 和 SBOM。
### M4. 差量更新应用脚本缺少二次解包后校验
证据:
- `douyin/updater/force_update.py:318-356` 下载后会校验差量包 manifest、文件路径和每个文件 SHA256。
- `douyin/updater/force_update.py:434-463` 真正应用更新时,PowerShell `Expand-Archive` 后直接按 manifest 删除/复制文件。
影响:
- 主进程校验和应用更新是两个阶段,中间若本地文件被替换,应用脚本不会再次校验。
- 对普通用户机器来说攻击门槛较高,但对本地恶意软件或被篡改的更新目录仍是风险点。
建议:
- 在 PowerShell 应用脚本里二次校验 delta zip SHA256,解包后再校验 manifest 中每个文件 SHA256。
- 应用前将 `$root`、`$work`、目标路径做规范化并确认都在安装目录内。
### M5. WebGUI 缺少安全响应头和 CSP
证据:
- `gui/web_gui_pkg/static_handler.py:67-73` 只设置 `Content-Type`、`Content-Length`、`Cache-Control`、`ETag`。
- `gui/web_gui_pkg/routes.py:161-169` GET API 仅允许本机访问并暴露 CSRF token。
- `gui/web_gui_pkg/routes.py:389-399` POST API 有本机限制、CSRF 校验和授权门禁。
影响:
- WebGUI 默认 `127.0.0.1` 监听,且 POST 有 CSRF,基础边界是好的。
- 但没有 `Content-Security-Policy`、`X-Content-Type-Options`、`Referrer-Policy` 等安全头;一旦未来某个日志/接口字段进入 DOM 时漏转义,XSS 的后果会扩大到本机控制面。
建议:
- 给 HTML/JS 响应加安全头:`X-Content-Type-Options: nosniff`、`Referrer-Policy: no-referrer`、最小 CSP。
- 逐步减少内联脚本,或者使用 nonce/hash CSP。
## 低风险与观察项
### L1. 前端使用 `innerHTML` 较多,但核心动态数据大多已转义
证据:
- `webui/js/dom_utils.js:83-90` 提供 `escapeHtml()`。
- `webui/js/runtime_actions.js:318-325`、`360-372`、`441-454` 对直播间、内容、原因等 API 字段使用 `escapeHtml()`。
- `webui/js/dashboard_renderers.js:65-110` 对榜单 key、中奖内容、时间和值做了转义。
- `license_server/api.py:667` 的兑换页把 `data.card_key` 拼入 `innerHTML`,卡密格式由服务端生成,当前风险较低。
建议:
- 新增 ESLint/简单 grep 门禁:所有拼接 API 数据的 `innerHTML` 必须经过 `escapeHtml()` 或改用 `textContent`。
- 兑换页成功展示卡密可改为创建 `code` 节点并设置 `textContent`。
### L2. CI/CD 依赖安装未锁定 hash
证据:
- `.github/workflows/windows-package-ci.yml:42-44` 使用 `pip install -r requirements.txt` 和未固定的 `pyinstaller cython setuptools wheel`。
- `packaging/pyinstaller/build_windows.ps1:31-38` 本地打包也会安装浮动版本依赖。
- `license_server/requirements.txt:1-4` 使用 `>=` 范围。
影响:
- 复用缓存打包时结果可能随 PyPI 最新版本变化。
- 安全修复会自动进来,但也可能引入供应链回归或打包不一致。
建议:
- 增加 `requirements-lock.txt` / `constraints.txt`,正式打包用锁定版本。
- CI 增加 `pip-audit` 或 GitHub Dependabot,发现高危 CVE 直接失败。
- 发布产物附带 SBOM、SHA256 和构建日志。
### L3. 仓库未发现真实私钥明文,但历史 token 文档仍提示需要清理本机副本
证据:
- 敏感信息扫描未发现真实生产私钥 PEM;测试私钥仅在 `tests/` 中使用。
- `license_server/api.py:86-93` 生产私钥从环境变量或服务器文件读取。
- 旧审计文档中记录过桌面存在多个 admin token 明文副本,需要按运维动作清理。
建议:
- 本机和服务器执行 token 文件清理,并确认 `.gitignore` 覆盖 `secrets/`、`*.pem`、`admin_token*.txt`。
- 把生产 secret 全部放服务器 secret 管理或部署平台环境变量,不放桌面、微信临时目录和仓库。
## 已有保护点
- 授权文件签名:`license_server/core.py:872-889` 服务端签名授权,客户端使用公钥验签。
- 机器码只保存 hash:`douyin/license/license_manager.py:66-76` 本机指纹 hash 化。
- 在线复核:`douyin/license/license_manager.py:260-340` 使用服务器状态复核本地授权。
- 更新 manifest 签名:`license_server/core.py:656-658` 服务端签名,`douyin/updater/force_update.py:143-158` 客户端验签。
- 更新下载约束:`douyin/updater/force_update.py:212-237` 要求 HTTPS 和同源,除非配置允许跨源。
- 更新文件完整性:`douyin/updater/force_update.py:547-563` 校验全量包 SHA256,`318-356` 校验差量包路径和文件 SHA256。
- WebGUI 本机限制与 CSRF:`gui/web_gui_pkg/routes.py:57-62`、`389-399`。
- 首次授权门禁:`gui/web_gui.py:912-918` 未授权时不直接进入运行态,`tools/ci/fresh_install_smoke.ps1:180-239` 已覆盖新环境授权门禁冒烟。
- 打包分发清单:`packaging/pyinstaller/build_windows.ps1:55-63` 默认 Cython/PyArmor staging,`270-287` 执行 distribution manifest 检查。
## 依赖与外部公告核对
本机当前版本:
- `fastapi==0.137.2`
- `starlette==1.3.1`
- `uvicorn==0.49.0`
- `python-multipart==0.0.32`
- `cryptography==47.0.0`
- `PyInstaller==6.12.0`
外部公告核对:
- Starlette multipart/form-data DoS:GHSA-f96h-pmfr-66vw / CVE-2024-47874,Starlette `0.40.0` 修复。
- Starlette FileResponse Range DoS:GHSA-7f5h-v6xp-fcq8 / CVE-2025-62727,Starlette `0.49.1` 修复。
- 当前本机 Starlette `1.3.1` 高于上述修复版本;生产仍建议锁版本并加入自动漏洞扫描。
## 修复优先级
1. 轮换 admin token,清理本机和服务器明文 token,后台发布增加二次授权。
2. 上传接口改流式写入并加大小限制,反向代理同步限流。
3. 更新包改 CDN/对象存储分发,授权服务只发短期 URL。
4. 正式包 Authenticode 签名,客户端校验证书指纹后再启动安装器。
5. 生产强制 `DYGJ_LICENSE_PUBLIC_BASE_URL`、`TrustedHostMiddleware`、Secure Cookie。
6. WebGUI 加安全响应头和 CSP,继续收敛 `innerHTML`。
7. CI/CD 增加锁版本、SBOM、pip-audit/Dependabot。
## 本次验证
- `git status --short --branch`:工作区除用户本地 `config/config.json` 外无其他未提交改动。
- 静态证据扫描:授权、服务端 API、更新、WebGUI、打包、CI 均完成。
- 敏感信息扫描:未发现生产私钥 PEM;扫描到的 `secret` 主要位于测试用例和历史审计文档。
- 依赖版本核对:本机 Starlette/FastAPI 版本高于已核对 Starlette DoS 修复版本。
## 参考资料
- GitHub Advisory:Starlette multipart/form-data DoS,GHSA-f96h-pmfr-66vw,https://github.com/advisories/GHSA-f96h-pmfr-66vw
- GitHub Advisory:Starlette FileResponse Range DoS,GHSA-7f5h-v6xp-fcq8,https://github.com/advisories/GHSA-7f5h-v6xp-fcq8
- Starlette Release Notes,https://www.starlette.io/release-notes/
- Starlette Responses 文档:`FileResponse` 支持 Range 请求,https://www.starlette.io/responses/
@@ -0,0 +1,228 @@
# 全量安全审查报告
日期:2026-06-23
审查方式:结合 `security-best-practices`、`security-threat-model`、`code-review-and-quality` 思路,对客户端、本地 Web GUI、卡密服务端、自动更新、打包分发和 Git/配置暴露面做静态审查与最小运行验证。
## 结论
当前版本已经具备一批关键安全地基:客户端默认走 `https://dy.absfan.cn`,自动更新 manifest 有签名和安装包 sha256 校验;卡密服务使用服务端时间和 SQLite 参数化查询;后台登录使用 HttpOnly 会话 cookie 与 CSRF;本地 Web GUI 默认只监听 `127.0.0.1`;当前 tracked 文件未发现服务器真实 IP、私钥或管理员 token 明文。
但仍有 5 个需要优先处理的风险:
- P0:Git 历史提交里仍可检索到服务器源站 IP 字面量,若仓库外发或公开,历史会继续泄露源站。
- P1:服务端限流信任客户端传入的 `x-forwarded-for`,可能被绕过并造成 rate-limit bucket 增长。
- P1:后台登录未接入限流/锁定;同时仍保留 Bearer/Basic token 后门入口,公网后台暴露时爆破面偏大。
- P1:后台发布更新时一次性 `await installer.read()` 读取上传文件,缺少上传大小限制,可能导致内存或磁盘 DoS。
- P1:本地 Web GUI 虽默认本机监听,但一旦配置成 `0.0.0.0`,WiFi ADB、启动/停止、日志读取等接口没有二次认证。
## 范围与资产
核心资产:
- 卡密数据库、激活记录、审计记录。
- 服务端私钥、管理员 token、更新安装包、更新 manifest。
- 客户端内置公钥、授权文件、本地配置。
- 本地 Web GUI 对 ADB、设备、日志和运行进程的控制能力。
主要入口:
- 公网:`/api/v1/activate`、`/api/v1/verify_license`、`/api/v1/update/manifest`、`/api/v1/update/download/{filename}`、`/admin/*`。
- 本机:`/api/wifi/*`、`/api/config`、日志/运行控制相关 Web GUI 接口。
- 分发:PyInstaller/安装包、自动更新下载的 EXE。
## 已有安全控制
- 客户端默认更新地址是 `https://dy.absfan.cn/api/v1/update/manifest`。
- 自动更新默认要求 manifest 签名,安装包 URL 默认同源,安装包下载后做 sha256 校验。
- 服务端 license 和 update manifest 使用 Ed25519 签名。
- SQLite 操作使用参数化 SQL,未看到直接字符串拼接 SQL 的主路径。
- 后台登录成功后写入 HttpOnly、SameSite=Lax 的 session cookie,后台写操作有 CSRF token。
- 卡密校验以服务器端激活记录和服务端时间为准,客户端本地时间不能直接绕过在线校验。
- 本地 Web GUI 默认监听 `127.0.0.1:8000`,不是默认公网暴露。
- 当前 tracked 文件扫描未发现真实源站 IP、服务器密码、管理员 token、私钥 PEM。
## 发现与建议
### P0-1 Git 历史仍包含源站 IP
证据:
- 当前 tracked 文件未命中真实源站 IP、管理员 token 或私钥。
- `git log --all -S` 仍能在历史提交中找到源站 IP 字面量,涉及提交包括 `25876bd`、`0efdc83`、`5c7d341`、`cb74a23` 等。
影响:
- 即使当前代码改成域名,仓库被发给别人或推到公开仓库时,历史仍会暴露源站。
- 攻击者可绕过域名层防护,直接打源站端口或做扫描。
建议:
- 若仓库已经外发或公开:立即做 Git 历史改写,清除源站 IP、旧 server 默认值和任何敏感片段,然后 force push。
- 同步轮换公网源站或至少限制源站只接受可信代理/防火墙来源。
- 报告、文档、提交信息里后续只写域名或 `[REDACTED_ORIGIN]`。
### P1-1 限流信任 `x-forwarded-for`
证据:
- `license_server/api.py:182-185` 使用请求头 `x-forwarded-for` 第一段作为限流 key。
- `_rate_limited` 对 activate、verify_license 生效,但 bucket key 由该 header 决定。
影响:
- 如果反代/CDN 未强制覆盖该 header,客户端可以伪造不同 IP 绕过限流。
- 大量伪造 header 会让 `rate_limit_buckets` 增长,形成内存型 DoS。
建议:
- 只在请求来自可信代理 IP 时读取 `x-forwarded-for`,否则使用 `request.client.host`。
- 增加 bucket 总量上限和周期性清理。
- 部署层确保反代覆盖而不是透传用户自带的 XFF。
### P1-2 后台登录缺少限流/锁定,且保留多种 token 入口
证据:
- `/admin/login` 在 `license_server/api.py:492-497` 直接比较 token,失败返回 403,未调用 `_rate_limited`。
- `_admin_allowed` 在 `license_server/api.py:88-109` 同时接受 session cookie、Bearer token、Basic auth。
影响:
- 公网后台可被持续爆破或撞库,尤其管理员 token 如果不够长会变成高风险。
- Bearer/Basic 让 token 更容易出现在代理日志、浏览器插件、命令历史或误贴日志中。
建议:
- 给 `/admin/login` 加 IP + 用户维度限流、指数退避和失败审计。
- 默认禁用 Basic auth;Bearer token 仅保留给受控 CLI,或通过环境变量显式开启。
- 管理员 token 要求至少 32 字节随机值,并增加启动时弱 token 检查。
### P1-3 更新发布上传无大小限制
证据:
- `license_server/api.py:586-606` 中 `UploadFile` 直接 `await installer.read()`,随后写入发布目录。
- 未见文件大小、后缀白名单、Content-Length 上限或流式落盘控制。
影响:
- 管理员误操作、token 泄露或 CSRF 以外的后台入口被利用时,可以上传超大文件导致内存、磁盘或进程不可用。
- 更新发布链路是高权限供应链入口,风险高于普通文件上传。
建议:
- 增加最大上传大小,例如 300 MB 或按实际安装包体积上限配置。
- 使用流式写临时文件,边读边计算 sha256,超限立即中断并删除临时文件。
- 限制后缀为 `.exe`,发布前校验 Windows Authenticode 签名或至少校验内部版本号。
### P1-4 本地 Web GUI 非 localhost 暴露时缺少认证
证据:
- 默认监听 `127.0.0.1`:`douyin/core/path_config.py:31`。
- 环境变量或配置可覆盖 host:`douyin/core/path_config.py:96-103`。
- Web GUI 暴露 WiFi ADB 启用、连接、断开、扫描和自动重连:`gui/web_gui_pkg/routes.py:717-824`、`863-940`。
影响:
- 默认本机使用问题不大。
- 如果用户为了局域网访问改成 `0.0.0.0`,同网段其他人可未授权控制 ADB 连接、扫描局域网、读取部分状态或影响挂机运行。
建议:
- 当 host 不是 localhost 时强制启用 Web GUI token。
- 对 `/api/wifi/*`、运行控制、配置写入、日志读取加认证。
- UI 上显示“当前监听地址”和“局域网暴露风险”。
### P2-1 HTTPS 开关默认逻辑不够稳
证据:
- 默认 manifest URL 是 HTTPS:`douyin/updater/force_update.py:31`。
- frozen 默认 manifest 下 `require_https` 默认值为 `not using_default_manifest`,即默认 false:`douyin/updater/force_update.py:192-195`。
- 同时默认签名是开启的。
影响:
- 当前域名是 HTTPS,实际链路可用。
- 但“默认 manifest 不强制 HTTPS”的逻辑容易在以后改默认地址时退化,签名不能完全替代传输层保护。
建议:
- `require_https` 默认始终为 true,除非显式开发环境关闭。
- 对自动更新增加环境分层:dev 可放宽,release 必须 HTTPS + signed manifest + sha256。
### P2-2 license 和 update manifest 共用签名密钥
证据:
- `license_server/core.py:444-446` 提供通用 `sign_payload`。
- license 文档签名在 `license_server/core.py:626-644`,update manifest 也由同一服务私钥签名。
影响:
- 单一私钥泄露会同时影响授权文件与更新供应链。
- 后续密钥轮换时两个系统耦合,恢复复杂。
建议:
- 分离 license signing key 与 update signing key。
- 客户端分别内置 license public key 和 update public key,支持 key id 与滚动轮换。
### P2-3 依赖版本没有锁定
证据:
- `requirements.txt` 多数依赖使用 `>=`,例如 `Pillow>=9.0.0`、`opencv-python>=4.5.0`、`cryptography>=41.0.0`。
影响:
- 构建复现性弱,新版本依赖可能引入兼容问题或供应链风险。
建议:
- 为 release 打包生成锁定文件,例如 `requirements-lock.txt` 或 `pip-tools` 输出。
- CI/打包只使用锁定依赖,开发环境可继续宽松。
### P2-4 shell 调用需要继续收敛
证据:
- 聚焦扫描显示存在若干 `subprocess.run`/`Popen`,多数 ADB 调用为列表参数。
- 仍存在少量 `shell=True` 或 `/bin/sh -c` 用法,主要用于平台命令探测或 ADB 降级路径。
影响:
- 如果参数未来从 UI 或配置直通,可能扩大命令注入风险。
建议:
- 对所有 `shell=True` 建立 allowlist,逐个替换成 list 参数。
- 对确实需要 shell 的命令增加注释和单元测试覆盖。
## 验证
已执行:
- `python -m pytest tests/test_license_server_api.py tests/test_license_server_core.py tests/test_license_manager.py tests/test_auto_update.py tests/test_web_gui_routes_logic.py -q`
- 结果:PASS。
- 日志:`artifacts/security_audit_tests.log`。
公网最小验证:
- `https://dy.absfan.cn/api/v1/health` 返回 `{"ok": true, "service": "douyin-license-server"}`。
- `https://dy.absfan.cn/api/v1/update/manifest` 返回 `enabled=false`、`version=0.0.0`,并包含签名字段。
当前 secret 扫描:
- tracked 文件未发现真实源站 IP、私钥 PEM、管理员 token、服务器密码明文。
- Git 历史仍包含源站 IP,需要单独处理。
## 建议修复顺序
1. 先修服务端 P1:可信代理 IP/XFF、后台登录限流、上传大小限制、Secure cookie。
2. 再修本地 P1:Web GUI 非 localhost 强制 token,敏感接口鉴权。
3. 然后做 P0 历史清理:确认仓库是否已外发/公开,必要时 history rewrite + force push + 源站访问限制。
4. 最后做供应链增强:分离签名密钥、release 依赖锁定、自动更新 HTTPS 强制。
@@ -0,0 +1,43 @@
# 兑换链接安全复核 2026-06-24
## 结论
本次复核对象是闲鱼自动发货兑换链路:
- `POST /api/v1/redeem/external/create`
- `GET /redeem`
- `GET /redeem/{token}` 兼容旧链接
- `POST /api/v1/redeem/claim`
线上域名:`https://dy.absfan.cn`。
## 已验证
- 外部创建接口必须使用 `Authorization: Bearer <DYGJ_LICENSE_EXTERNAL_API_TOKEN>`。
- 外部创建接口只返回 `claim_url`,不返回真实 `DG-` 卡密。
- 新 `claim_url` 使用 `/redeem#token`,token 位于 URL fragment,不进入服务器请求路径和 uvicorn 访问日志。
- 兑换接口只允许同一 token 成功兑换一次;重复兑换返回 `409 already_redeemed`。
- 并发兑换已用 SQLite `BEGIN IMMEDIATE` 加写锁,测试确认只会生成一张卡。
- `/docs` 和 `/openapi.json` 线上返回 `404`。
- 未授权创建返回 `403`,坏参数返回 `400`。
- 兑换后的卡密可正常走 `/api/v1/activate`,授权文件可继续走 `/api/v1/verify_license`。
## 修复项
- 修复同一兑换 token 并发兑换可能生成多张卡的问题。
- 为公开兑换接口增加限流:`REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS`。
- 为外部创建接口鉴权失败增加独立限流:`EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS`。
- 新生成兑换链接改为 `/redeem#token`,降低访问日志泄露 token 的概率。
## 验证证据
- 本地回归:`artifacts/redeem_security_full_tests_20260624.log`,结果 `PASS`。
- 本地语法:`python -m py_compile license_server/core.py license_server/api.py douyin/license/license_manager.py`,结果 `PASS`。
- 线上黑盒:`health=200`、`docs=404`、`openapi=404`、`no_auth=403`、`create=200`、`claim_first=200`、`claim_second=409`、`activate=200`。
- 线上日志确认:`GET /redeem HTTP/1.1`,未记录 `/redeem/{token}`。
## 剩余建议
- `DYGJ_LICENSE_EXTERNAL_API_TOKEN` 应定期轮换,且只配置在自动发货服务器侧。
- 如果后续员工/多个渠道并行发货,建议改成每个渠道独立 token,并在数据库记录 `platform`、`external_order_id`、请求 IP 和 staff/source 标识。
- 如果订单量增大,建议在 1Panel/OpenResty 层再加 IP 级限流。
@@ -0,0 +1,165 @@
# 安全审计报告:服务器与反逆向
日期:2026-06-26
范围:`license_server/` 授权与更新服务、在线差量/全量更新链路、V3.3.4 发布包反逆向与分发内容。
## 总体结论
当前授权服务不是裸奔:管理员后台有登录限流、CSRF、会话 Cookie;客户端更新默认启用 HTTPS、manifest 签名和 SHA256 校验;V3.3.4 发布包通过了分发清单检查,核心逻辑已有 Cython `.pyd` 编译层。
但最值得优先处理的风险有两个:管理员 token 暴露后可直接发布任意 EXE 更新;更新安装包上传/下载缺少大文件资源控制。反逆向方面,现在属于“提高脚本级拆包成本”,还不是强对抗级保护。
## P1:必须优先处理
### 1. 管理员 token 本地副本过多,拿到 token 就等于拿到发布权
证据:
- 本机桌面存在多个 token 文件:`C:\Users\12742\Desktop\douyin_admin_token.txt`、`C:\Users\12742\Desktop\douyin_admin_token_open.txt`、`C:\Users\12742\Desktop\douyin_admin_token_可打开.txt`。
- 管理员鉴权使用单一 token:`license_server/api.py:101`、`license_server/api.py:118-135`。
- 发布更新接口在管理员鉴权后直接接受 EXE 并写入 manifest:`license_server/api.py:795-818`、`license_server/core.py:532-562`。
影响:
- 本机恶意软件、聊天软件临时目录泄露、误传文件,都可能让攻击者发布恶意更新。
- 因客户端会信任服务端签名的 manifest,服务器发布权比普通卡密权限高很多。
建议:
- 立刻轮换 `DYGJ_LICENSE_ADMIN_TOKEN`,删除桌面和聊天临时目录里的 token 明文副本。
- 管理后台改为“短期会话 + 二次确认发布 + 可选 TOTP/一次性发布口令”。
- 管理发布接口限制来源 IP,至少只允许固定办公 IP 或 VPN。
- 发布动作记录操作者、IP、文件 SHA256、版本号,并保留不可覆盖审计日志。
### 2. 更新包上传一次性读入内存,缺少大小上限和流式写入
证据:
- `license_server/api.py:809` 使用 `await installer.read()` 一次性读完整上传文件。
- `license_server/core.py:537` 接收 `bytes`,`license_server/core.py:550` 直接 `write_bytes(content)`。
- 当前正式安装包约 214 MB,已经是大对象。
影响:
- 管理 token 被盗或后台被滥用时,可以上传超大文件造成内存/磁盘 DoS。
- 即使没有被盗,误传错误文件也会把服务打满。
建议:
- 服务端增加最大上传大小,例如 300 MB 或 500 MB,超限立即拒绝。
- 改成分块读取、边写临时文件、边计算 SHA256,完成后再原子重命名。
- Nginx/Caddy/Cloudflare 层设置请求体大小限制和上传超时。
### 3. 更新下载接口直出大文件,缺少下载限速/CDN/Range 滥用防护
证据:
- `/api/v1/update/download/{filename}` 直接 `FileResponse` 返回安装包:`license_server/api.py:658-672`。
- 已验证下载端点支持 Range,正式包体积约 214 MB。
影响:
- 任意公网客户端都能拉取大文件,容易被刷带宽。
- Range/并发下载可以把授权服务和更新服务一起拖慢。
建议:
- 安装包放对象存储或 CDN,授权服务只签 manifest,不直接扛大文件流量。
- 给下载接口加 IP 限流、并发限制、带宽限制。
- 如果继续用 ASGI 直出文件,生产依赖必须锁定并定期更新 Starlette/FastAPI;Starlette 历史上出现过 `FileResponse` Range 资源耗尽类公告。
## P2:建议加固
### 4. 生产环境缺少强制 Host 白名单
证据:
- `_public_base_url()` 未配置 `DYGJ_LICENSE_PUBLIC_BASE_URL` 时会回退到 `request.base_url`:`license_server/api.py:245-249`。
- 当前代码没有看到 `TrustedHostMiddleware` 或等价 Host 白名单。
影响:
- 如果生产环境漏配 `DYGJ_LICENSE_PUBLIC_BASE_URL`,错误 Host 头可能影响兑换链接或更新 URL 生成。
建议:
- 生产强制配置 `DYGJ_LICENSE_PUBLIC_BASE_URL=https://dy.absfan.cn`。
- 增加 `TrustedHostMiddleware`,只允许 `dy.absfan.cn` 和必要内网域名。
### 5. Cookie secure 默认关闭,生产 HTTPS 容易误配置
证据:
- `DYGJ_LICENSE_SECURE_COOKIES` 默认值为 `False`:`license_server/api.py:472`。
- CSRF 和后台 session cookie 都依赖该状态设置 `secure`:`license_server/api.py:680-686`、`license_server/api.py:707-711`。
影响:
- HTTPS 生产环境如果忘记设置环境变量,后台 Cookie 不会带 Secure 标记。
建议:
- 生产默认改为 Secure,只有本地开发显式关闭。
- README 和部署脚本强制检查该环境变量。
### 6. 管理员 Basic/Bearer 兼容口仍保留,建议收窄
证据:
- `_admin_allowed()` 同时接受 session、Bearer 和 Basic:`license_server/api.py:122-135`。
影响:
- Header token 适合脚本,但也更容易进入命令历史、代理日志或调试日志。
- 增加后台鉴权路径,后续维护更难保证所有入口策略一致。
建议:
- 默认只保留网页登录 session;CLI 发布单独走短期一次性 token。
- 如果必须保留 Bearer,限制到内网/VPN,并要求 CSRF 或发布专用 nonce。
### 7. 更新执行链缺少安装包 Authenticode 发布者校验
证据:
- 客户端更新流程会验证 manifest 签名和 SHA256:`douyin/updater/force_update.py:347-378`。
- 通过后直接启动下载的 installer:`douyin/updater/force_update.py:380-381`。
影响:
- 当前信任根主要是服务端 manifest 私钥和后台发布权。
- 一旦服务器私钥或发布权泄露,客户端无法再用 Windows 发布者签名做第二道拦截。
建议:
- 给正式安装包做 Authenticode 代码签名。
- 客户端启动安装器前校验签名发布者或证书指纹。
### 8. 服务器依赖没有锁定精确版本
证据:
- `license_server/requirements.txt` 使用 `fastapi>=0.124.0`、`uvicorn[standard]>=0.38.0`、`cryptography>=41.0.0`。
- 当前本机运行版本:FastAPI `0.137.2`,Starlette `1.3.1`。
影响:
- 生产重装时可能拿到未经本项目验证的新版本,也可能因为旧环境没有升级而继续运行旧版本。
建议:
- 为服务器单独生成锁定文件,例如 `requirements-server.lock.txt`。
- 发布服务端时记录 `pip freeze` 和镜像 digest。
## P3:反逆向现状与后续增强
### 已有保护
- 构建脚本默认走 Cython staging,除非显式传 `-NoCythonForDevOnly` 或 `-NoObfuscateForDevOnly`:`packaging/pyinstaller/build_windows.ps1:4-6`、`packaging/pyinstaller/build_windows.ps1:54-61`。
- 默认编译核心包:`douyin/fudai`、`douyin/reservation`、`douyin/detection`、`douyin/stage`:`tools/cython_staging.py:16-21`。
- 发布包分发清单阻止项目源码、日志、调试图和多余文件混入:`tools/distribution_manifest.py:120-155`。
- V3.3.4 发布目录检查通过:`logs/security_dist_manifest_check_2026-06-26.log`。
- V3.3.4 发布目录未发现项目核心 `.py` 源码混入;核心路径下 `.pyd` 数量为 93。
- 发布目录未发现私钥、管理员 token、项目私密 pem;只看到第三方 CA bundle:`_internal/certifi/cacert.pem`。
### 仍然薄弱
- GUI 与 WebUI 代码按当前策略仍更多是普通 PyInstaller/PYZ 层,不能按强混淆理解。
- Python/Cython `.pyd` 可以被逆向分析,只是成本高于纯 `.py`。
- 客户端公钥是公开的,这是正确设计;但协议、接口、版本更新逻辑仍能被静态分析。
- 没有运行时完整性校验、调试器检测、虚拟机/注入检测或关键路径反篡改。
建议:
- 短期:正式包固定使用 Cython,不允许 `-NoCythonForDevOnly`;发布前自动跑 `distribution_manifest`。
- 中期:把授权校验、更新校验、核心策略判断也纳入 Cython 或商业混淆。
- 中期:增加运行时自校验,例如关键 `.pyd`/EXE 哈希校验和异常上报。
- 长期:核心逻辑尽量服务端化,客户端只保留必要执行逻辑;反逆向不能替代服务端风控。
## 已验证通过项
- 管理员登录有限流:`license_server/api.py:693-700`。
- 后台修改类表单有 CSRF 校验:`license_server/api.py:805-807`,创建/解绑/禁用也有同类校验。
- 授权激活/验证/兑换接口有限流:`license_server/api.py:486-512`、`license_server/api.py:561-588`。
- 服务端私钥没有内置到客户端;客户端只包含公钥:`douyin/license/public_key.py:1-9`。
- 发布包分发清单 PASS:`logs/security_dist_manifest_check_2026-06-26.log`。
## 参考来源
- GitHub Security Advisory:Starlette `FileResponse` Range 资源耗尽类历史公告,`GHSA-f96h-pmfr-66vw` / `CVE-2024-47874`。
- Starlette 官方文档:`TrustedHostMiddleware` 用于限制 Host header。
@@ -0,0 +1,462 @@
# 拆分 gui/gui_app.py 实施计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 把 `gui/gui_app.py`(5476 行)中内聚的 `main()` 闭包逐段抽到 `gui/components/*` 子模块,主文件持续瘦身,GUI 行为不变。
**Architecture:** 每个候选段抽到独立模块,改造为顶层函数,通过显式参数(回调 + 必要的 widgets/Vars/路径)接收依赖。每抽完一段独立 commit + push。
**Tech Stack:** Python 3.10+, tkinter / ttkbootstrap, pytest
**Spec:** `docs/superpowers/specs/2026-05-30-split-gui-app-design.md`
---
## 抽取顺序
按 spec 优先级:P1 → P2 → P3 → P4 → P5 → P6。每个任务独立可停。
P1 包括两个紧耦合段(`open_wifi_adb_dialog` 845 行 + `open_scan_dialog` 200 行)。
---
## Task 1: 抽 `open_scan_dialog` 到 `components/wifi_adb_scan_dialog.py`
**Files:**
- Create: `gui/components/wifi_adb_scan_dialog.py`
- Modify: `gui/gui_app.py:539-742` (删除原闭包) + 改 `gui/gui_app.py:1088-1093`(`open_scan_dialog` 调用点)
**理由先抽这个:** `open_scan_dialog` 已经是显式参数形式,不依赖 `main()` 任何捕获变量,迁移最简单。先做它能熟悉抽取流程,降 ~200 行。
- [ ] **Step 1: 读完整段确认依赖**
```bash
# 看 539-742 完整段
```
确认 `open_scan_dialog` 仅依赖参数 `parent, adb_exe_local, ip_var, on_line_local, refresh_cb` 和模块级 import(`tk`, `ttk`, `discover_adb_devices`, `get_local_subnet`, `pick_best_match`, `verify_adb_target` 等)。
- [ ] **Step 2: 创建新模块**
写 `gui/components/wifi_adb_scan_dialog.py`,把 539-742 的整段函数原样复制为 `open_scan_dialog`,加 `from __future__ import annotations` 与所有需要的 import。
- [ ] **Step 3: 修改 `gui_app.py`,替换调用点**
在 `gui_app.py` 顶部 import 新模块:
```python
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
```
删除 539-742 的原 `def open_scan_dialog(...)` 定义。
- [ ] **Step 4: 验证语法**
```bash
python -m py_compile gui/gui_app.py gui/components/wifi_adb_scan_dialog.py
```
Expected: 无输出(成功)
- [ ] **Step 5: 跑测试**
```bash
pytest -x
```
Expected: 全部 PASS
- [ ] **Step 6: 行数核对 + commit**
```bash
wc -l gui/gui_app.py
git status --short
git add gui/gui_app.py gui/components/wifi_adb_scan_dialog.py
git commit -m "refactor(gui): 抽 open_scan_dialog 到 components/wifi_adb_scan_dialog (5476 → <new>)"
git push
```
---
## Task 2: 抽 `open_wifi_adb_dialog` 到 `components/wifi_adb_dialog.py`
**Files:**
- Create: `gui/components/wifi_adb_dialog.py`
- Modify: `gui/gui_app.py:743-1111` (删除原闭包,改 `wifi_adb_btn` 的 command)
**依赖分析(已完成):**
模块级(已 import,直接用):
- `list_adb_devices`, `enable_wifi_adb`, `connect_wifi_adb`, `disconnect_wifi_adb`, `auto_connect_wifi_adb`, `get_device_ip`, `get_connected_wifi_devices`(from `gui.gui_core`)
- `set_last_wifi_target`, `get_last_wifi_target`, `clear_last_wifi_target`(from `gui.gui_core_pkg`)
- `verify_adb_target`, `query_device_model`(from `gui.gui_core_pkg.wifi_adb_scan`)
`main()` 局部(必须传):
- `root: tk.Misc`(父窗口,用于 `tk.Toplevel(root)`)
- `adb_exe: str`
- `on_line: Callable[[str], None]`
- `refresh_devices: Callable[[], None]`
- `open_scan_dialog`(Task 1 完成后已为顶层函数,直接 import)
自递归(三处 `dialog.destroy(); open_wifi_adb_dialog()`):
改造为传入自己的引用 —— 用一个内部函数 `_reopen()` 闭包捕获参数,或参数化 `parent`/`adb_exe` 后直接再调用顶层函数。**采用方案 B:把 `open_wifi_adb_dialog` 改成顶层函数,签名带所有依赖,自递归直接调用自己。**
- [ ] **Step 1: 创建新模块骨架**
```python
# gui/components/wifi_adb_dialog.py
from __future__ import annotations
import re
import threading
import tkinter as tk
from tkinter import ttk
from tkinter.constants import LEFT, W, X
from typing import Callable
from gui.gui_core import (
auto_connect_wifi_adb,
connect_wifi_adb,
disconnect_wifi_adb,
enable_wifi_adb,
get_connected_wifi_devices,
get_device_ip,
list_adb_devices,
)
from gui.gui_core_pkg import (
clear_last_wifi_target,
get_last_wifi_target,
set_last_wifi_target,
)
from gui.gui_core_pkg.wifi_adb_scan import query_device_model
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
def open_wifi_adb_dialog(
root: tk.Misc,
*,
adb_exe: str,
on_line: Callable[[str], None],
refresh_devices: Callable[[], None],
) -> None:
"""打开 WiFi ADB 设置对话框。
从 gui_app.main 抽出,显式接收依赖。
"""
# ... (Step 2 复制原 743-1111 函数体,把对外部名字的引用替换为参数)
```
- [ ] **Step 2: 复制函数体并替换闭包变量引用**
把 `gui_app.py:743-1111`(从 `def open_wifi_adb_dialog():` 内 body 开始,到 `info_label.pack(...)` 结束)整段复制进新函数体,缩进调整 4 → 4(已经一致,只是去掉外层 `def main()` 这一层)。
把三处自递归改为带参数的:
```python
# 原: open_wifi_adb_dialog()
# 改: open_wifi_adb_dialog(root, adb_exe=adb_exe, on_line=on_line, refresh_devices=refresh_devices)
```
把对 `open_scan_dialog` 的引用保留为 module-import 形式:
```python
# 原:
# command=lambda: open_scan_dialog(dialog, adb_exe, ip_var, on_line, refresh_device_lists)
# 不变(因为已 import 顶层 open_scan_dialog)
```
注意 `toggle_maximize`、`refresh_device_lists` 是嵌套闭包,保持原样不抽 —— 它们捕获的是对话框内 widgets,只在对话框内用。
- [ ] **Step 3: 改 `gui_app.py`,删原闭包,改按钮 command**
在 `gui_app.py` 顶部加:
```python
from gui.components.wifi_adb_dialog import open_wifi_adb_dialog as _open_wifi_adb_dialog
```
删除 743-1111 的原嵌套 `def open_wifi_adb_dialog():` 整段。
把 1113 行的按钮 command 改为:
```python
wifi_adb_btn = ttk.Button(
top,
text="WiFi ADB",
command=lambda: _open_wifi_adb_dialog(
root,
adb_exe=adb_exe,
on_line=on_line,
refresh_devices=refresh_devices,
),
)
```
- [ ] **Step 4: 验证语法**
```bash
python -m py_compile gui/gui_app.py gui/components/wifi_adb_dialog.py
```
Expected: 无输出
- [ ] **Step 5: 跑测试**
```bash
pytest -x
```
Expected: 全部 PASS
- [ ] **Step 6: 行数核对 + commit**
```bash
wc -l gui/gui_app.py
git status --short
git add gui/gui_app.py gui/components/wifi_adb_dialog.py
git commit -m "refactor(gui): 抽 open_wifi_adb_dialog 到 components/wifi_adb_dialog (<old> → <new>)"
git push
```
---
## Task 3: 评估 P2(`load_config_to_ui` + `save_ui_to_config`)
P2 在 spec 里被标记为高风险(100+ Var)。只有 Task 1+2 完成且测试稳定时才做。
- [ ] **Step 1: 数 Var 数量**
```bash
grep -nE "^\s+[a-zA-Z_]+_var = " gui/gui_app.py | wc -l
```
如果数量 ≥ 50,跳过 Task 3,直接进 Task 4。
如果 < 50,继续。
- [ ] **Step 2: 如果继续,设计 dataclass 聚合 Var**
读 2748-3402 列出所有用到的 Var,定义:
```python
# gui/components/config_io.py
@dataclass
class ConfigVars:
y_var: tk.IntVar
needswitch_var: tk.BooleanVar
# ... 全部
```
抽出函数:
```python
def load_config_to_ui(vars_: ConfigVars, *, on_line: Callable[[str], None]) -> None: ...
def save_ui_to_config(vars_: ConfigVars, *, on_line: Callable[[str], None]) -> None: ...
```
实施步骤参考 Task 2 的 Step 1-6。
如果改动量过大或测试卡住,**回滚并跳过 P2**。
---
## Task 4: 抽 `refresh_reservations` 到 `components/reservations_view.py`
**Files:**
- Create: `gui/components/reservations_view.py`
- Modify: `gui/gui_app.py:4530-4805` (删原闭包),改调用点
- [ ] **Step 1: 列出依赖**
读 4530-4805,记录捕获的 widgets(主要是 `reservations_tree: ttk.Treeview`)、状态变量、回调。
- [ ] **Step 2: 创建模块,函数签名**
```python
# gui/components/reservations_view.py
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from typing import Callable
def refresh_reservations(
tree: ttk.Treeview,
*,
on_line: Callable[[str], None] = lambda _msg: None,
) -> None:
"""刷新预约 Tab 的 Treeview。"""
# body 来自原 4530-4805
```
依赖里如果有路径(`get_logs_dir` 之类)直接 import,不需要传参。
- [ ] **Step 3: 修改 `gui_app.py`**
```python
from gui.components.reservations_view import refresh_reservations as _refresh_reservations_impl
# 原 def refresh_reservations(): ... 改为:
def refresh_reservations():
_refresh_reservations_impl(reservations_tree, on_line=on_line)
```
保留薄包装 `def refresh_reservations()`,因为 `auto_refresh_reservations` 等地方仍以闭包形式调用它。
- [ ] **Step 4: 验证 + 测试 + commit**
```bash
python -m py_compile gui/gui_app.py gui/components/reservations_view.py
pytest -x
wc -l gui/gui_app.py
git add gui/gui_app.py gui/components/reservations_view.py
git commit -m "refactor(gui): 抽 refresh_reservations 到 components/reservations_view (<old> → <new>)"
git push
```
---
## Task 5: 抽 `refresh_high_value_rooms` 到 `components/high_value_view.py`
**Files:**
- Create: `gui/components/high_value_view.py`
- Modify: `gui/gui_app.py:4805-5085`
- [ ] **Step 1: 列出依赖**
读 4805-5085,记录捕获的 widgets(主要是 `high_value_rooms_tree: ttk.Treeview`)、状态变量、回调。
- [ ] **Step 2: 创建模块,函数签名**
```python
# gui/components/high_value_view.py
from __future__ import annotations
import tkinter as tk
from tkinter import ttk
from typing import Callable
def refresh_high_value_rooms(
tree: ttk.Treeview,
*,
on_line: Callable[[str], None] = lambda _msg: None,
) -> None:
"""刷新高价值房间 Tab 的 Treeview。"""
# body 来自原 4805-5085
```
依赖里如果有路径(`get_logs_dir` 之类)直接 import,不需要传参。
- [ ] **Step 3: 修改 `gui_app.py`**
```python
from gui.components.high_value_view import refresh_high_value_rooms as _refresh_high_value_rooms_impl
# 原 def refresh_high_value_rooms(): ... 改为薄包装:
def refresh_high_value_rooms():
_refresh_high_value_rooms_impl(high_value_rooms_tree, on_line=on_line)
```
- [ ] **Step 4: 验证 + 测试 + commit**
```bash
python -m py_compile gui/gui_app.py gui/components/high_value_view.py
pytest -x
wc -l gui/gui_app.py
git add gui/gui_app.py gui/components/high_value_view.py
git commit -m "refactor(gui): 抽 refresh_high_value_rooms 到 components/high_value_view (<old> → <new>)"
git push
```
---
## Task 6: 抽 `do_screenshot` + `_bind_screenshot_button` 到 `components/screenshot_action.py`
**Files:**
- Create: `gui/components/screenshot_action.py`
- Modify: `gui/gui_app.py:3402-3651`
- [ ] **Step 1: 列出依赖**
读 3402-3651。`do_screenshot` 依赖:`adb_exe`、状态 Label、图片预览刷新回调、ADB 截图工具函数。
- [ ] **Step 2-4: 抽出,签名:**
```python
def do_screenshot(
*,
adb_exe: str,
on_line: Callable[[str], None],
on_done: Callable[[str], None], # 截图保存路径
status_label: ttk.Label | None = None,
) -> None:
...
def bind_screenshot_button(
btn: ttk.Button,
*,
adb_exe: str,
on_line: Callable[[str], None],
on_done: Callable[[str], None],
status_label: ttk.Label | None = None,
) -> None:
btn.configure(command=lambda: do_screenshot(
adb_exe=adb_exe, on_line=on_line, on_done=on_done, status_label=status_label
))
```
调用点同 Task 4。
commit msg: `refactor(gui): 抽 do_screenshot 到 components/screenshot_action (<old> → <new>)`
---
## Task 7: 抽 `refresh_actions_log` + 搜索栏 到 `components/actions_log_view.py`
**Files:**
- Create: `gui/components/actions_log_view.py`
- Modify: `gui/gui_app.py:4845-5070`
- [ ] **Step 1: 列出依赖**
读 4845-5070。包含:`configure_actions_log_colors`、`refresh_actions_log`、几个搜索方法 `search_in_actions_log`/`search_next_in_actions`/`search_prev_in_actions`/`clear_search_in_actions`/`on_actions_search_entry_key`。
- [ ] **Step 2-4: 设计**
设计成 1 个 `setup_actions_log_view(text_widget, search_entry, ...)` 一次性绑定所有,或者保留几个独立函数都接收 `text_widget` 参数。优先后者(更小步)。
签名:
```python
def configure_actions_log_colors(text_widget: tk.Text) -> None: ...
def refresh_actions_log(text_widget: tk.Text, *, on_line: Callable[[str], None]) -> None: ...
def search_in_actions_log(text_widget: tk.Text, search_entry: ttk.Entry, *, direction: int = 1) -> None: ...
```
`gui_app.py` 里保留薄包装让原闭包调用模式不变。
commit msg: `refactor(gui): 抽 actions_log 视图相关到 components/actions_log_view (<old> → <new>)`
---
## Task 8: 评估停止条件 + 收尾
- [ ] **Step 1: 检查停止条件**
```bash
wc -l gui/gui_app.py
```
满足以下任一即停:
1. ≤ 3000 行
2. 行数下降 < 50
3. 下一段需传 ≥ 50 个独立依赖
- [ ] **Step 2: 如果停止,写收尾说明**
如果停止,在 `docs/superpowers/specs/2026-05-30-split-gui-app-design.md` 末尾追加 `## Outcome` 段:列出实际抽出的模块、行数变化、未做的项。
```bash
git add docs/superpowers/specs/2026-05-30-split-gui-app-design.md
git commit -m "docs(specs): 补充 gui_app 拆分实际成果"
git push
```
- [ ] **Step 3: 报告**
总结输出给用户:
- 起始行数:5476
- 当前行数:`<X>`
- 抽出的模块列表
- pytest 状态
- 是否还有未抽的候选(可作为下一轮)
---
## 关键约束(每个 Task 都要遵守)
1. **AGENTS.md**:每个 Task 都要 commit + push,只 stage 本任务实际改的文件,不混入用户已有改动。
2. **不改行为**:抽取是纯重构,不修 bug、不优化性能、不删功能。
3. **失败回滚**:若 pytest 失败且修复需改 ≥ 2 个非目标文件,`git reset --hard HEAD~1`(本任务的 commit 还没 push),回到上一 Task 报告问题。
4. **每个 Task 验证后再开下一个**:不批量做。
5. **手工 smoke 推迟到批次末尾**:本计划的 pytest 不覆盖 GUI 交互(项目测试有意写得轻),抽取属纯重构,逻辑保持一致。每个 Task 完成后,在 Task 8 的收尾报告里提示用户:「请启动 GUI 跑一遍受影响功能(WiFi 对话框 / 预约 Tab / 高价值房间 / 截图按钮 / 操作日志 Tab),确认无回归。」用户 smoke 后若发现问题,定位到具体 Task 的 commit 回滚。
@@ -0,0 +1,982 @@
# Split WebUI Large Files Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Continue the large-file split after `gui/gui_app.py` by modularizing the WebUI frontend and, only after the frontend is stable, splitting the Web GUI Python server.
**Architecture:** Keep the current static WebUI behavior intact while moving code into focused `webui/js/*` and `webui/css/*` files. Each task changes one responsibility, preserves global names needed by `DOMContentLoaded`, runs focused tests, commits, and pushes before the next task.
**Tech Stack:** Plain HTML/CSS/JavaScript, Python `http.server`, pytest, browser smoke test for UI changes.
---
## Current Evidence
From the current worktree on 2026-05-31:
| File | Lines | Role |
|---|---:|---|
| `webui/styles.css` | 3745 | WebUI visual system, layout, panels, logs, responsive rules |
| `webui/app.js` | 2512 | WebUI constants, state, API calls, rendering, polling, event wiring |
| `gui/web_gui.py` | 1663 | local HTTP server, runner, API routes, static file serving |
| `webui/index.html` | 1232 | WebUI DOM structure and config bindings |
`gui/gui_app.py` is already down to about 130 lines and should not be the next split target. The next target is the WebUI bundle.
## Stop Conditions
Stop this plan and write an outcome note when any one is true:
1. `webui/app.js` is below 700 lines and `webui/styles.css` is below 1400 lines.
2. The next split would require changing more than 3 of the large files in one task.
3. Browser smoke finds a visual or runtime regression that cannot be fixed inside the current task boundary.
4. Tests fail and the fix would require behavior changes outside the current responsibility.
## Verification Commands
Run these after every JavaScript or HTML task:
```powershell
python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
```
Expected:
```text
py_compile: exit code 0
pytest: all selected tests PASS
```
Run these after every CSS or visual task:
```powershell
python -m py_compile gui/web_gui.py > logs\webui_split_py_compile.log 2>&1
pytest tests/test_webgui.py -q > logs\pytest_webui_split.log 2>&1
```
Expected:
```text
py_compile: exit code 0
pytest: all selected tests PASS
```
For frontend visual changes, also start the Web GUI and inspect it in a browser:
```powershell
python gui\web_gui.py
```
Expected browser checks:
- `/` loads without a blank page.
- Console has no module load errors, syntax errors, or missing function errors.
- Header buttons, tabs, logs panel, reservations panel, high-value panel, screenshot preview, and footer remain visible without overlap at desktop width.
- At mobile width, command buttons wrap and panels remain readable.
## Static Loading Decision
The current page loads:
```html
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
<script src="app.js?v=console-20260520-theme-v35"></script>
```
Use classic scripts for the first JavaScript split instead of ES modules. This avoids a broad initialization rewrite and keeps inline event expectations simple. New scripts must be loaded before `app.js` if `app.js` depends on them.
For CSS, use multiple `<link rel="stylesheet">` tags. Keep `styles.css` as the compatibility shell until the end of the CSS split.
---
## Task 1: Add WebUI Static Asset Structure
**Files:**
- Create: `webui/js/README.md`
- Create: `webui/css/README.md`
- Modify: `webui/index.html`
- [ ] **Step 1: Create asset directory docs**
Create `webui/js/README.md`:
```markdown
# WebUI JavaScript modules
Classic browser scripts loaded by `webui/index.html`.
Load order matters:
1. `constants.js`
2. `dom.js`
3. `api.js`
4. focused feature scripts
5. `app.js`
Keep behavior-preserving splits small. Do not introduce a build step unless a later plan explicitly replaces this static layout.
```
Create `webui/css/README.md`:
```markdown
# WebUI CSS modules
Plain CSS files loaded by `webui/index.html`.
Recommended order:
1. `tokens.css`
2. `base.css`
3. `layout.css`
4. `components.css`
5. focused panel or feature CSS
6. `styles.css` compatibility remainder
Keep selectors stable so existing HTML and JavaScript continue to work.
```
- [ ] **Step 2: Add no-op load anchors to `index.html`**
Insert comments around the existing assets:
```html
<!-- WebUI CSS modules are loaded before the compatibility remainder. -->
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
```
```html
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
<script src="app.js?v=console-20260520-theme-v35"></script>
```
- [ ] **Step 3: Verify**
Run:
```powershell
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
```
Expected: selected tests PASS.
- [ ] **Step 4: Commit and push**
```powershell
git add webui/index.html webui/js/README.md webui/css/README.md
git commit -m "refactor(webui): add static module split structure"
git push
```
---
## Task 2: Extract JavaScript Constants and Copy
**Files:**
- Create: `webui/js/constants.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `constants.js`**
Move these top-level constants from `app.js` into `webui/js/constants.js` unchanged:
```javascript
const UI_LIMITS = Object.freeze({
runLogMaxLines: 50000,
runLogMaxChars: 200000,
actionsLogMaxLines: 5000,
scrollBottomThresholdPx: 5,
screenshotPollMs: 1500,
logPollMs: 800,
statsPollMs: 1200,
});
const UI_CLASS = Object.freeze({
busy: "isBusy",
clickable: "isClickable",
collapsed: "isCollapsed",
listCollapsed: "isListCollapsed",
reservationHeader: "reservationHeader",
reservationBody: "reservationBody",
reservationsList: "reservationsList",
shotEmpty: "isShotEmpty",
statusRunning: "statusRunning",
statusIdle: "statusIdle",
statusError: "statusError",
});
const RUN_TONE = Object.freeze({
running: "running",
idle: "idle",
error: "error",
});
```
Also move `UI_COPY`, `TIMELINE_SERIES_KEYS`, `TIMELINE_LAYOUT`, `TIMELINE_STROKES`, and `DEFAULTS` unchanged.
- [ ] **Step 2: Remove moved constants from `app.js`**
Delete only the moved constant declarations from `webui/app.js`. Keep state variables such as `logIdx`, `pollTimer`, `runLogBuffer`, and `deviceOverviewState` in `app.js` for now.
- [ ] **Step 3: Load `constants.js` before `app.js`**
Change the bottom of `webui/index.html` to:
```html
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
<script src="js/constants.js?v=console-20260531-split-1"></script>
<script src="app.js?v=console-20260531-split-1"></script>
```
- [ ] **Step 4: Verify**
Run:
```powershell
python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
```
Expected: both PASS.
- [ ] **Step 5: Browser smoke**
Start:
```powershell
python gui\web_gui.py
```
Open `http://127.0.0.1:8765/` or the printed local URL. Confirm console has no `UI_LIMITS is not defined`, `DEFAULTS is not defined`, or `fmtDuration is not defined` errors.
- [ ] **Step 6: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/constants.js
git commit -m "refactor(webui): extract frontend constants"
git push
```
---
## Task 3: Extract DOM and Formatting Helpers
**Files:**
- Create: `webui/js/dom_utils.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `dom_utils.js`**
Move these functions from `app.js` into `webui/js/dom_utils.js` unchanged:
```javascript
function $(id)
function setTextIfExists(id, text)
function clearEl(el)
function escapeHtml(s)
function fmtTime(ts)
function fmtNum(v)
function fmtDuration(seconds)
```
When implementing, copy the exact current function declarations and bodies from `webui/app.js`.
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete the moved function declarations only. Do not move UI initialization functions yet.
- [ ] **Step 3: Load `dom_utils.js` after `constants.js`**
```html
<script src="js/constants.js?v=console-20260531-split-2"></script>
<script src="js/dom_utils.js?v=console-20260531-split-2"></script>
<script src="app.js?v=console-20260531-split-2"></script>
```
- [ ] **Step 4: Verify and smoke**
Run the standard JavaScript verification commands. In browser console, confirm no `$ is not defined`, `fmtDuration is not defined`, or `escapeHtml is not defined` errors.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/dom_utils.js
git commit -m "refactor(webui): extract DOM and format helpers"
git push
```
---
## Task 4: Extract API Client Helpers
**Files:**
- Create: `webui/js/api_client.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `api_client.js`**
Move these functions and state from `app.js` into `webui/js/api_client.js` unchanged:
```javascript
let _apiFailStreak = 0;
const _apiFailThreshold = 2;
let _csrfToken = null;
function setConnState(state)
function notifyApiOk()
function notifyApiFail()
async function apiGet(path)
async function getCsrfToken()
async function apiPost(path, body)
```
When implementing, copy the exact current function declarations and bodies from `webui/app.js`.
- [ ] **Step 2: Remove moved declarations from `app.js`**
Delete only the moved declarations. Keep feature-level functions such as `refreshDevices`, `startRun`, `pollLogs`, and `pollStats` in `app.js`.
- [ ] **Step 3: Load `api_client.js` after `dom_utils.js`**
```html
<script src="js/constants.js?v=console-20260531-split-3"></script>
<script src="js/dom_utils.js?v=console-20260531-split-3"></script>
<script src="js/api_client.js?v=console-20260531-split-3"></script>
<script src="app.js?v=console-20260531-split-3"></script>
```
- [ ] **Step 4: Verify and smoke**
Run the standard JavaScript verification commands. In browser, click refresh devices and load config. Confirm API state footer updates and no `apiGet is not defined` or CSRF errors appear.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/api_client.js
git commit -m "refactor(webui): extract API client helpers"
git push
```
---
## Task 5: Extract Log View Behavior
**Files:**
- Create: `webui/js/log_views.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `log_views.js`**
Move the log rendering and search functions from `app.js` into `webui/js/log_views.js`:
```javascript
function classifyLogLine(line)
function renderLogLineNode(line)
function appendLog(lines)
function renderRunLog()
function appendRunLogLines(lines)
async function fetchActionsLog()
function renderActionsLog()
```
Keep these shared state variables in `app.js` for this task:
```javascript
let runLogBuffer = [];
let runLogFilter = "";
let runLogMode = "filter";
let runSearchResultsBuffer = [];
let runSearchActive = false;
let actionsLogBuffer = [];
let actionsLogFilter = "";
```
Because classic scripts share global scope, `log_views.js` can keep using these names.
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete only the moved function declarations.
- [ ] **Step 3: Load `log_views.js` before `app.js`**
```html
<script src="js/constants.js?v=console-20260531-split-4"></script>
<script src="js/dom_utils.js?v=console-20260531-split-4"></script>
<script src="js/api_client.js?v=console-20260531-split-4"></script>
<script src="js/log_views.js?v=console-20260531-split-4"></script>
<script src="app.js?v=console-20260531-split-4"></script>
```
- [ ] **Step 4: Verify and smoke**
Run the standard JavaScript verification commands. In browser, check the run log filter/search and action log refresh.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/log_views.js
git commit -m "refactor(webui): extract log view behavior"
git push
```
---
## Task 6: Extract Dashboard Renderers
**Files:**
- Create: `webui/js/dashboard_renderers.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `dashboard_renderers.js`**
Move these renderer functions from `app.js` into `webui/js/dashboard_renderers.js`:
```javascript
function renderBars(containerId, dataMap, labelMap)
function renderTopContent(containerId, items)
function renderWinsTable(containerId, wins)
function renderTimeline(containerId, timeline)
function renderOverviewSparkline(svgId, timeline)
```
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete only the moved renderer declarations.
- [ ] **Step 3: Load `dashboard_renderers.js` before `app.js`**
```html
<script src="js/dashboard_renderers.js?v=console-20260531-split-5"></script>
<script src="app.js?v=console-20260531-split-5"></script>
```
Keep all earlier module script tags before `dashboard_renderers.js`.
- [ ] **Step 4: Verify and smoke**
Run standard JavaScript verification. In browser, confirm stats charts, timeline tooltip, top content table, and wins table still render.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/dashboard_renderers.js
git commit -m "refactor(webui): extract dashboard renderers"
git push
```
---
## Task 7: Extract Config Form Binding
**Files:**
- Create: `webui/js/config_form.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `config_form.js`**
Move these config-related functions from `app.js` into `webui/js/config_form.js`:
```javascript
function getConfigBoundElements()
function syncMirrorFields()
function getConfigValue(cfg, key)
function coerceValue(type, raw, isCheckbox)
function applyConfigToUI(cfg)
function collectConfigFromUI()
async function loadConfig()
async function saveConfig()
```
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete only the moved config declarations.
- [ ] **Step 3: Load `config_form.js` before `app.js`**
```html
<script src="js/config_form.js?v=console-20260531-split-6"></script>
<script src="app.js?v=console-20260531-split-6"></script>
```
Keep all earlier module script tags before `config_form.js`.
- [ ] **Step 4: Verify and smoke**
Run standard JavaScript verification and `pytest tests/test_gui_webui_sync.py -q`. In browser, load config, change one harmless UI field, save, reload, and confirm no config-binding error appears.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/config_form.js
git commit -m "refactor(webui): extract config form bindings"
git push
```
---
## Task 8: Extract Polling and Device Actions
**Files:**
- Create: `webui/js/runtime_actions.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Create `runtime_actions.js`**
Move these functions from `app.js` into `webui/js/runtime_actions.js`:
```javascript
async function refreshDevices()
function decorateDeviceSelect()
function selectedDeviceId()
async function postDeviceAction(path, body, successPrefix)
async function forceStopRun()
async function sendBackKey()
async function wifiEnable()
async function wifiConnect()
async function wifiDisconnect()
async function tryAutoReconnectLastWifi()
async function wifiScan()
async function startRun()
async function testYanghao()
async function testComment()
async function stopRun()
async function pollLogs()
async function pollReservations()
async function pollHighValueRooms()
async function pollStats()
function startPolling()
function startStatsPolling()
```
Keep `DOMContentLoaded` event wiring in `app.js`.
- [ ] **Step 2: Remove moved functions from `app.js`**
Delete only the moved runtime declarations.
- [ ] **Step 3: Load `runtime_actions.js` before `app.js`**
```html
<script src="js/runtime_actions.js?v=console-20260531-split-7"></script>
<script src="app.js?v=console-20260531-split-7"></script>
```
Keep all earlier module script tags before `runtime_actions.js`.
- [ ] **Step 4: Verify and smoke**
Run standard JavaScript verification. In browser, click refresh devices, load config, start/stop if safe, refresh action log, and switch through all panels.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/runtime_actions.js
git commit -m "refactor(webui): extract runtime actions and polling"
git push
```
---
## Task 9: Reduce `app.js` to Initialization Glue
**Files:**
- Create: `webui/js/ui_init.js`
- Modify: `webui/app.js`
- Modify: `webui/index.html`
- [ ] **Step 1: Move UI initialization helpers**
Move these functions into `webui/js/ui_init.js`:
```javascript
function initTheme()
function ensureToastContainer()
function toast(message, kind = "info", { duration = 3500 } = {})
function initConfigSearch()
function initFooter()
function attachCopyButtons()
function initKeyboardShortcuts()
function initHeaderScroll()
function initShotFullscreen()
function applyKbdHints()
function initStickySectionShadow()
function initShortcutsHelp()
function updateTabBadge(target, count)
function startReservationsCountdownTick()
function initTabs()
function attachNumberSteppers()
function pollShot()
function startShotPolling()
function setButtonBusy(id, busy)
function setRunOverview(state, meta, tone)
function updateDeviceOverview()
```
- [ ] **Step 2: Keep `app.js` as bootstrapping only**
After this task, `app.js` should contain:
```javascript
window.addEventListener("DOMContentLoaded", async () => {
initTheme();
initTabs();
initConfigSearch();
initFooter();
attachCopyButtons();
initShotFullscreen();
initHeaderScroll();
initKeyboardShortcuts();
initShortcutsHelp();
initStickySectionShadow();
attachNumberSteppers();
applyKbdHints();
syncMirrorFields();
await refreshDevices();
await loadConfig();
startPolling();
startStatsPolling();
startShotPolling();
startReservationsCountdownTick();
pollLogs();
pollStats();
pollShot();
pollReservations();
pollHighValueRooms();
});
```
During implementation, preserve the existing event listener bindings from the current `DOMContentLoaded` body. If the current body wires buttons or inputs, keep those bindings in `app.js` or move them into a clearly named `bindAppEvents()` function in `ui_init.js`.
- [ ] **Step 3: Verify and smoke**
Run standard JavaScript verification. Browser smoke must cover initial load, tabs, theme, footer, shortcuts overlay, screenshot preview, logs, and config load/save.
- [ ] **Step 4: Commit and push**
```powershell
git add webui/index.html webui/app.js webui/js/ui_init.js
git commit -m "refactor(webui): reduce app script to initialization glue"
git push
```
---
## Task 10: Split CSS Tokens and Base Rules
**Files:**
- Create: `webui/css/tokens.css`
- Create: `webui/css/base.css`
- Modify: `webui/styles.css`
- Modify: `webui/index.html`
- [ ] **Step 1: Extract theme tokens**
Move these ranges from `styles.css` into `webui/css/tokens.css`:
- `:root { ... }` light theme token block
- `:root[data-theme="dark"] { ... }` dark theme token block
- reduced-motion token or global animation defaults that are pure variables
Do not rename variables.
- [ ] **Step 2: Extract base element rules**
Move base reset and generic element rules into `webui/css/base.css`:
- `*`, `html`, `body`
- `button`, `input`, `select`, `textarea`
- generic focus-visible rules
- global scrollbar rules
- generic utility classes that are not tied to one panel
- [ ] **Step 3: Load extracted CSS before `styles.css`**
```html
<!-- WebUI CSS modules are loaded before the compatibility remainder. -->
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-1" />
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-1" />
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-1" />
```
- [ ] **Step 4: Verify and smoke**
Run CSS verification commands. Browser smoke must compare light and dark theme basics, header, buttons, forms, and scrollbars.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/styles.css webui/css/tokens.css webui/css/base.css
git commit -m "refactor(webui): extract CSS tokens and base rules"
git push
```
---
## Task 11: Split CSS Layout and Shared Components
**Files:**
- Create: `webui/css/layout.css`
- Create: `webui/css/components.css`
- Modify: `webui/styles.css`
- Modify: `webui/index.html`
- [ ] **Step 1: Extract layout rules**
Move app shell, header, workspace, panel grid, and footer layout rules into `layout.css`. Include responsive `@media` rules that only affect those layout selectors.
- [ ] **Step 2: Extract shared component rules**
Move shared button, card, tab, field, table, tooltip, toast, skeleton, and shortcut overlay rules into `components.css`. Include related `@media` and `prefers-reduced-motion` blocks when they directly belong to those selectors.
- [ ] **Step 3: Load CSS in stable order**
```html
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-2" />
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-2" />
<link rel="stylesheet" href="css/layout.css?v=console-20260531-split-css-2" />
<link rel="stylesheet" href="css/components.css?v=console-20260531-split-css-2" />
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-2" />
```
- [ ] **Step 4: Verify and smoke**
Run CSS verification. Browser smoke must check desktop and mobile layout, tabs, cards, buttons, toast, tooltip, and shortcuts overlay.
- [ ] **Step 5: Commit and push**
```powershell
git add webui/index.html webui/styles.css webui/css/layout.css webui/css/components.css
git commit -m "refactor(webui): extract CSS layout and shared components"
git push
```
---
## Task 12: Split CSS Feature Panels
**Files:**
- Create: `webui/css/panels.css`
- Create: `webui/css/logs.css`
- Create: `webui/css/charts.css`
- Modify: `webui/styles.css`
- Modify: `webui/index.html`
- [ ] **Step 1: Extract panel-specific styles**
Move screenshot preview, reservations, high-value room, realtime status, and panel-specific content rules into `panels.css`.
- [ ] **Step 2: Extract log styles**
Move run log, action log, log line classification, log search, and log scrollbar rules into `logs.css`.
- [ ] **Step 3: Extract chart/table styles**
Move chart blocks, timeline tooltip, bar rows, top content table, wins table, and related table rows into `charts.css`.
- [ ] **Step 4: Load CSS in stable order**
```html
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/layout.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/components.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/panels.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/logs.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="css/charts.css?v=console-20260531-split-css-3" />
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-3" />
```
- [ ] **Step 5: Verify and smoke**
Run CSS verification. Browser smoke must check screenshot preview, reservations, high-value room list, log panels, charts, and mobile wrapping.
- [ ] **Step 6: Commit and push**
```powershell
git add webui/index.html webui/styles.css webui/css/panels.css webui/css/logs.css webui/css/charts.css
git commit -m "refactor(webui): extract CSS feature panels"
git push
```
---
## Task 13: Decide Whether to Split `index.html`
**Files:**
- Modify: `webui/index.html`
- Optional create: `webui/partials/README.md`
- [ ] **Step 1: Recount file sizes**
Run:
```powershell
rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize
```
- [ ] **Step 2: Keep `index.html` intact unless it is still above 1000 lines**
If `index.html` is at or below 1000 lines, do not split it in this plan. HTML partial loading would require server or build changes and is not needed yet.
If `index.html` remains above 1000 lines and the team wants smaller HTML files, write a separate spec before changing runtime behavior. That spec must choose one of:
- server-side partial injection in `gui/web_gui.py`
- client-side fetch of static partials
- build-time HTML generation
- [ ] **Step 3: Commit only if docs are added**
If `webui/partials/README.md` is created:
```powershell
git add webui/partials/README.md
git commit -m "docs(webui): record HTML partial split decision"
git push
```
---
## Task 14: Split `gui/web_gui.py` Only After Frontend Is Stable
**Files:**
- Create: `gui/web_gui_pkg/static_handler.py`
- Create: `gui/web_gui_pkg/request_parsing.py`
- Create: `gui/web_gui_pkg/routes.py`
- Modify: `gui/web_gui.py`
- Test: `tests/test_webgui.py`
- [ ] **Step 1: Extract request parsing helpers**
Move `_send_json` and `_read_json` behavior into functions that still receive the `Handler` instance:
```python
def send_json(handler: BaseHTTPRequestHandler, obj: object, 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)))
handler.end_headers()
handler.wfile.write(data)
```
```python
def read_json(handler: BaseHTTPRequestHandler) -> dict:
n = int(handler.headers.get("Content-Length") or 0)
raw = handler.rfile.read(n) if n > 0 else b"{}"
try:
value = json.loads(raw.decode("utf-8"))
except Exception:
return {}
return value if isinstance(value, dict) else {}
```
Keep `Handler._send_json` and `Handler._read_json` as thin wrappers at first.
- [ ] **Step 2: Extract static file serving**
Move `_serve_static` into `gui/web_gui_pkg/static_handler.py`:
```python
def serve_static(
handler: BaseHTTPRequestHandler,
*,
webui_dir: str,
rel_path: str,
log_error: Callable[[str], None],
) -> None:
# paste current Handler._serve_static body and replace:
# self -> handler
# WEBUI_DIR -> webui_dir
# _wg_log(...) -> log_error(...)
```
Keep `Handler._serve_static` as:
```python
def _serve_static(self, rel_path: str) -> None:
serve_static(
self,
webui_dir=WEBUI_DIR,
rel_path=rel_path,
log_error=lambda msg: _wg_log(msg, level="ERROR"),
)
```
- [ ] **Step 3: Verify**
Run:
```powershell
python -m py_compile gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py > logs\web_gui_split_py_compile.log 2>&1
pytest tests/test_webgui.py -q > logs\pytest_web_gui_split.log 2>&1
```
Expected: PASS.
- [ ] **Step 4: Commit and push**
```powershell
git add gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py tests/test_webgui.py
git commit -m "refactor(webgui): extract request and static helpers"
git push
```
---
## Task 15: Final Outcome Note
**Files:**
- Modify: this plan file
- [ ] **Step 1: Record final sizes**
Run:
```powershell
rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize
```
- [ ] **Step 2: Append outcome**
Append:
```markdown
## Outcome
- `webui/app.js`: 2512 -> actual final line count
- `webui/styles.css`: 3745 -> actual final line count
- `webui/index.html`: 1232 -> actual final line count
- `gui/web_gui.py`: 1663 -> actual final line count
- Extracted JS modules: actual module filenames
- Extracted CSS modules: actual module filenames
- Verification: exact pytest log path and browser smoke result
- Remaining large files: actual top remaining files from the final size command
```
- [ ] **Step 3: Commit and push**
```powershell
git add docs/superpowers/plans/2026-05-31-split-webui-large-files.md
git commit -m "docs(webui): record large-file split outcome"
git push
```
---
## Execution Notes
- Do not batch tasks. Each task must pass verification, commit, and push before starting the next one.
- Keep query-string versions in `index.html` synchronized across all WebUI assets touched in a task.
- Do not introduce a frontend build step in this plan.
- Do not convert to ES modules until the classic-script split is complete and browser smoke is clean.
- For JavaScript moves, copy exact function bodies first, verify, then optionally do tiny cleanup in a separate commit.
- For CSS moves, preserve selector order unless the moved file load order proves an equivalent cascade.
- Project rule: only stage files changed by the current task.
@@ -0,0 +1,89 @@
# 2026-06-01 大文件继续拆分计划(续)
## 当前状态(更新于本轮)
- 已完成:
- `gui/web_gui.py` 路由壳化,主体路由下沉到 `gui/web_gui_pkg/routes.py`
- `douyin/core/fudai_modules/run_once_basic_helpers.py` 中预约检查与状态写盘逻辑下沉到 `run_once_basic_reservation.py`
- `douyin/core/douyin_fudai.py` 中 `_handle_in_fudai_detail` / `_handle_live_room_has_or_not_fudai` 下沉到 `fudai_modules/live_room_handlers.py`
- `douyin/core/underlying_operations.py` 中 `get_screenshot` 下沉到 `underlying_operations_pkg/screenshot_pipeline.py`
- `douyin/fudai/douyin_fudai_core_legacy.py` 壳化完成,核心实现转移到 `douyin/fudai/douyin_fudai_contain_impl.py`
- `douyin/fudai/douyin_fudai_contain_impl.py` 内部 helper 下沉到 `douyin/fudai/douyin_fudai_core_pkg/contain_helpers.py`(轻重 OCR 分流判定、参与人数提取等)
- `douyin/fudai/douyin_fudai_contain_impl.py` 主并行/备用并行共用的按钮状态判定与回写逻辑下沉到 `douyin/fudai/douyin_fudai_core_pkg/button_state.py`
- `douyin/fudai/douyin_fudai_contain_impl.py` 主并行/备用并行共用的并行任务提交与结果收集骨架下沉到 `douyin/fudai/douyin_fudai_core_pkg/parallel_exec.py`
- `douyin/fudai/douyin_fudai_contain_impl.py` 主并行/备用并行共用的任务列表观看任务检测分支下沉到 `douyin/fudai/douyin_fudai_core_pkg/watch_task.py`
- `douyin/fudai/douyin_fudai_contain_impl.py` 原始内容/清理后内容观看任务检测分支下沉到 `douyin/fudai/douyin_fudai_core_pkg/watch_task.py`
- `douyin/fudai/douyin_fudai_contain_impl.py` 倒计时数字提取与校验分支下沉到 `douyin/fudai/douyin_fudai_core_pkg/countdown_parse.py`
- `douyin/core/douyin_fudai.py` 的 `_capture_roi_screenshot` 与 `_match_icon_template` 下沉到 `douyin/handlers/douyin_screenshot_handler.py`
- `douyin/core/douyin_fudai.py` 的 `fudai_choujiang` 运行循环(定时/无限模式 + 结束日志)下沉到 `douyin/core/fudai_modules/fudai_run_loop.py`
- `douyin/core/douyin_fudai.py` 的 `run_once_basic` 前置段(启动日志/养号触发/标题记录)下沉到 `run_once_basic_helpers.run_once_basic_prelude`
- `douyin/core/douyin_fudai.py` 的 `run_once_basic` 预约后阶段处理段下沉到 `run_once_basic_helpers.run_once_basic_post_reservation`
- `douyin/core/underlying_operations.py` 的输入法/文本输入链路下沉到 `douyin/core/underlying_operations_pkg/text_input.py`(`input_text` / `paste_text_at` / ADBKeyboard 广播与 IME 切换等),主类保留薄转发
- `douyin/core/fudai_modules/run_once_basic_helpers.py` 的阶段链路下沉到 `douyin/core/fudai_modules/run_once_basic_stage.py`(`screenshot_and_diagnose` / `handle_desktop_recovery` / `handle_high_value_room_revisit`),主 helper 保留薄转发
- `douyin/core/fudai_modules/run_once_basic_helpers.py` 的粉丝团处理段下沉到 `douyin/core/fudai_modules/run_once_basic_fansclub.py`(`_handle_fansclub_join`),主 helper 保留薄转发
- `douyin/core/fudai_modules/handle_detail_helpers.py` 的筛选与高价值预约段下沉到 `douyin/core/fudai_modules/handle_detail_filter.py`(`_check_skip_and_handle` / `_try_high_value_reservation` / `_handle_skip_filter` / `_fallback_swipe_up`),主 helper 保留薄转发
- `douyin/core/fudai_modules/handle_detail_helpers.py` 的首开详情分支下沉到 `douyin/core/fudai_modules/handle_detail_first_open.py`(`handle_first_open_branch` / `_validate_first_open_detail`),主 helper 保留薄转发
- `douyin/core/fudai_modules/handle_detail_helpers.py` 的二次打开与预约完成收尾下沉到 `douyin/core/fudai_modules/handle_detail_second_open.py`(`handle_second_open_branch` / `_handle_reservation_completion`),主 helper 保留薄转发
- `douyin/stage/douyin_stage.py` 的步骤0并行像素检测下沉到 `douyin/stage/douyin_stage_handler_pkg/pixel_parallel.py`(`run_parallel_pixel_detection`),主诊断流程保留汇总与分支调度
- `douyin/stage/douyin_stage.py` 的弹窗OCR兜底与最终阶段收尾下沉到 `douyin/stage/douyin_stage_handler_pkg/finalize_stage.py`(`finalize_stage_after_pixel`),主诊断流程保留前序分支与统一调用
- `douyin/stage/douyin_stage.py` 的“邀你抢红包”OCR检测段下沉到 `douyin/stage/douyin_stage_handler_pkg/ocr_redpacket.py`(`detect_invite_redpacket_via_ocr`),主诊断流程保留统一调用与返回分发
- `douyin/core/underlying_operations.py` 的 UIAutomator 交互段下沉到 `douyin/core/underlying_operations_pkg/ui_automator.py`(`_uiautomator_dump` / `tap_by_text` / `tap_close_icon`),主类保留薄转发
- `douyin/core/underlying_operations.py` 的前台包检测与应用拉起链路下沉到 `douyin/core/underlying_operations_pkg/foreground.py`(`get_top_package` / `launch_package` / `is_douyin_foreground`),主类保留薄转发
- `gui/web_gui.py` 的 ProcRunner 状态读取与测试入口段下沉到 `gui/web_gui_pkg/proc_runner_ops.py`(`get_reservations` / `get_high_value_rooms` / `send_back_key` / `start_test_yanghao` / `start_test_comment`),主类保留薄转发
- `gui/web_gui.py` 的 ProcRunner 统计聚合段下沉到 `gui/web_gui_pkg/proc_runner_stats.py`(`get_stats`),主类保留薄转发
- `webui/css/components.css` 的 Overlay/Toast 样式拆分到 `webui/css/components_overlays.css` 与 `webui/css/components_toast.css`,并在 `webui/index.html` 追加模块化样式引用,主 `components.css` 保留其余组件样式
- `webui/index.html` 的监控/预约/日志面板与页脚区块下沉到 `webui/js/panel_templates.js`,页面改为挂载点注入(保留原 DOM id/class),主 `index.html` 继续瘦身
- `webui/index.html` 的头部命令条与状态概览区块下沉到 `webui/js/top_templates.js`,页面改为挂载点注入(保留原 DOM id/class),主 `index.html` 继续瘦身
- `douyin/reservation/reservation_logic/attend_window.py` 的“已参与过滤/无效时间过滤/动态提前量计算/目标快照日志”下沉到 `douyin/reservation/reservation_logic/attend_window_helpers.py`,主流程保留编排与分支顺序
- `webui/js/runtime_actions.js` 的设备动作与测试动作下沉到 `webui/js/runtime_device_actions.js`(`selectedDeviceId` / `postDeviceAction` / `wifi*` / `forceStopRun` / `testYanghao` / `testComment`),`index.html` 已补充脚本加载顺序
- `douyin/stage/douyin_stage_handler_pkg/check_live.py` 的分数选择策略与结果日志汇总下沉到 `douyin/stage/douyin_stage_handler_pkg/check_live_score.py`,主流程保留模板匹配编排
- `gui/components/config_io.py` 的文本域读写与 debug/logging 配置映射下沉到 `gui/components/config_io_helpers.py`,主流程保留编排与配置字段回写顺序
- `douyin/handlers/screenshot_manager/save_image.py` 的调试保存开关读取、保存重试机制、标注绘制逻辑下沉到 `douyin/handlers/screenshot_manager/save_image_helpers.py`(`is_debug_captures_enabled` / `save_image_with_retry` / `annotate_debug_image`),主入口保留编排与异常处理
- `tools/coords/region_selector.py` 的菜单构建、快捷键绑定、画布事件绑定与拖放注册下沉到 `tools/coords/region_selector_ui.py`(`setup_menu` / `bind_canvas_events` / `setup_dnd`),主类保留业务状态与事件处理
- `douyin/fudai/douyin_fudai_contain_impl.py` 的后处理聚合逻辑下沉到 `douyin/fudai/douyin_fudai_core_pkg/contain_postprocess.py`(进房耗时日志、价值OCR校验、标题写回、房间映射落盘),主流程保留编排与返回值
- `gui/gui_core_pkg/stats_log_parser.py` 的重复正则提取与数值转换下沉到 `gui/gui_core_pkg/stats_log_parser_helpers.py`(`search_group` / `search_group_any` / `parse_int_value` / `parse_float_value` / `set_meta_*_if_match`),主解析流程保留业务事件判定
- `douyin/reservation/reservation_logic/attend_window.py` 的尾段日志逻辑下沉到 `attend_window_helpers.py`(`log_back_failed_keep_queue` / `log_attend_window_result`),主流程保留回退决策与状态编排
- `webui/index.html` 的 `keywords + debug` 配置面板下沉到 `webui/js/config_panel_templates.js`,页面改为 `configPanelTemplatesMount` 挂载点注入并补充脚本加载顺序(保留原 id/data-key,行为兼容)
- `tools/coords/simple_region_selector.py` 的菜单/快捷键/画布绑定下沉到 `tools/coords/simple_region_selector_ui.py`(`setup_menu_and_shortcuts` / `bind_canvas_events`),主类保留图像处理与多边形分析流程
- 当前 Top 大文件(源码):
1. `webui/index.html` 53.7KB(本轮从 71.0KB 降到 53.7KB,已低于 65KB 目标)
2. `douyin/other/douyin_yanghao.py` 29.8KB
3. `webui/css/components.css` 29.7KB
4. `douyin/fudai/douyin_fudai_finder_pkg/detector.py` 29.4KB
5. `douyin/core/douyin_fudai.py` 29.0KB
6. `douyin/reservation/reservation_logic/attend_window.py` 28.8KB(已从 35.5KB 降到 28.8KB)
7. `gui/web_gui_pkg/stats_log_parser.py` 28.7KB
8. `douyin/stage/douyin_stage_handler_pkg/check_live.py` 28.6KB
9. `gui/gui_core_pkg/stats_log_parser.py` 28.4KB(已从 30.3KB 降到 28.4KB)
10. `webui/js/ui_init.js` 27.8KB
11. `webui/js/runtime_actions.js` 27.1KB
## 下一轮拆分顺序(建议)
1. `douyin/fudai/douyin_fudai_finder_pkg/detector.py`
- 抽离模板匹配与阈值/回退逻辑,降低单函数复杂度。
2. `gui/web_gui_pkg/stats_log_parser.py`
- 参照 gui_core 侧 helper 化,统一正则提取与类型转换入口。
3. `douyin/reservation/reservation_logic/attend_window.py`
- 继续抽离中段“锁定期判断 + 同预约分支”中的日志与状态更新子流程。
4. `douyin/other/douyin_yanghao.py`
- 抽离坐标/概率配置读取与动作执行分发,降低主流程长度与分支复杂度。
5. `webui/js/ui_init.js`
- 分离面板切换、搜索过滤与快捷键初始化,进一步降低单文件复杂度。
## 验证口径
- 每次拆分后必须执行:
- `python -m py_compile <改动的py文件>`
- 如本机 `pytest` 可用,再跑相关最小测试集
- 由于当前 shell 环境缺少 pytest,测试日志需保留:
- `logs/pytest_*.log`
## 硬编码治理并行策略
- 优先治理“环境迁移敏感”的硬编码:
- host/port(已收敛到 `net_config`,继续排查其它入口)
- 本地路径、固定命令、默认端口
- 处理方式:
- 新增集中配置读取函数
- 原调用点只保留薄封装,避免每处单独拼环境变量
@@ -0,0 +1,244 @@
# 拆分 gui/gui_app.py 设计文档
## 背景
`gui/gui_app.py` 当前 5476 行,几乎全部代码都嵌在单个 `main()` 函数里,
内含 50+ 个闭包,捕获大量 widgets 和 tkinter Var。文件已经被多轮抽取过:
- `5649 → 5537`:`ThreadSafeLogWriter` → `components/log_writer`
- `5539 → 5370`:`_open_realtime_viewer_impl` → `components/realtime_viewer`
- `6339 → 5634`:`refresh_stats` 字符串格式化 → `components/stats_formatter`
继续按相同思路把内聚闭包抽到 `gui/components/*`,主文件继续瘦身。
## 目标
迭代式抽取 `gui/gui_app.py` 中的内聚闭包,主文件越变越小,
**不改变任何 GUI 运行行为**。
### 成功标准
1. `gui/gui_app.py` 行数显著下降(目标:≤ 3000 行;继续视边际收益决定是否再抽)
2. `pytest` 全绿
3. 每次抽取产生一个独立 commit,保持小步可回滚
4. GUI 启动 + 主要交互路径无回归(手工 smoke:启动 GUI、打开 WiFi 对话框、加载配置、截图、查看日志)
### 非目标
- 不重构 GUI 整体架构(不引入 MVC/MVVM)
- 不改变 `gui_app.py` 对外暴露的入口(`main()`、`format_gui_log_line()`)
- 不优化性能、不修 bug(除非抽取过程中发现)
- 不动 `gui/web_gui.py`(属于下一轮独立 spec)
## 抽取候选清单
按「行数 × 边界清晰度」排序(行数粗略统计):
| 优先级 | 闭包 | 行范围 | 行数 | 目标文件 | 主要依赖 |
|---|---|---|---|---|---|
| P1 | `open_wifi_adb_dialog` | 743-1588 | 845 | `components/wifi_adb_dialog.py` | ADB 工具 + 几个回调 |
| P2 | `load_config_to_ui` + `save_ui_to_config` | 2748-3402 | 654 | `components/config_io.py` | 100+ tkinter Var(需聚合)|
| P3 | `refresh_reservations` | 4530-4805 | 275 | `components/reservations_view.py` | 1-2 个 Treeview + 路径 |
| P4 | `refresh_high_value_rooms` | 4805-5085 | ~280 | `components/high_value_view.py` | 1 个 Treeview + 路径 |
| P5 | `do_screenshot` + `_bind_screenshot_button` | 3402-3651 | 249 | `components/screenshot_action.py` | ADB exe + 路径 + 状态 Label |
| P6 | `refresh_actions_log` + 搜索栏 | 4892-5070 | ~178 | `components/actions_log_view.py` | Text widget + 路径 |
**估算**:完整抽完 P1-P6 约减 2480 行 → 主文件 ~3000 行。
若 P2 风险评估后觉得不值得做,可跳过,仍能减约 1830 行 → ~3650 行。
## 抽取模式(每轮通用)
每个候选段按以下步骤处理:
### 1. 摸清依赖
读完整段代码,列出:
- 捕获的 `main()` 局部变量(widgets / Vars / 路径 / 状态)
- 调用的 `main()` 内其它闭包(回调)
- 调用的 module-level 函数 / 项目其它模块函数
### 2. 设计签名
把闭包改造为顶层函数:
```python
# components/<feature>.py
def <feature_action>(
parent: tk.Misc, # 父窗口或容器
*,
deps: <FeatureDeps>, # 依赖注入容器
on_line: Callable[[str], None], # 日志回调
...
) -> <return-type>:
"""..."""
```
依赖容器优先用 `dataclass`(命名参数太多时):
```python
@dataclass
class <FeatureDeps>:
adb_exe: str
ip_var: tk.StringVar
refresh_devices: Callable[[], None]
# ...
```
### 3. 抽取 + 注入
- 在 `gui/components/<feature>.py` 写新函数
- 在 `gui_app.py` 原位置:删旧闭包,import 新函数,传依赖调用
### 4. 验证
```bash
pytest # 全部通过
python -m py_compile gui/gui_app.py gui/components/<feature>.py
# 手工 smoke:启动 GUI 走一遍受影响功能
```
### 5. 提交
按 AGENTS.md 规则:
- `git status` 检查只改了预期文件
- `git add` 具体路径,不用 `-A`
- commit 消息格式参考历史:`refactor(gui): 抽 <feature> 到 components/<file> (<旧行数> → <新行数>)`
- `git push`
## 风险
| 风险 | 缓解 |
|---|---|
| 闭包捕获 Var 漏传 → 配置项静默丢失 | P2 用 `dataclass` 聚合 Var 引用;先写完整测试再改 |
| GUI 交互回归(按钮回调失效等) | 每轮手工 smoke;优先抽边界清晰的 P1/P5 验证流程 |
| `mainloop` / `after()` 调度跨闭包失效 | 显式把 `root` 或 `tk_widget.after` 当依赖传入 |
| import 循环(components → gui_app) | components/* 不允许 import gui_app;只接收依赖参数 |
## 停止条件
满足任一即停手,向用户报告本轮成果:
1. `gui_app.py` ≤ 3000 行
2. 下一个候选段需要传 ≥ 50 个独立依赖(信号:应该先把 widgets 聚成一个 `UiState`,那是另一个 spec)
3. 抽取后 `gui_app.py` 行数下降 < 50(边际收益太小)
4. 某轮抽取后 pytest 失败且修复需要改动多个非目标文件(信号:风险扩散,停下复盘)
## 实现顺序
按 P1 → P2 → P3 → P4 → P5 → P6,每段独立 commit。
P2 视 P1 完成后情况评估(如果 P1 已经把主文件压到很小,P2 可推迟)。
## 测试策略
- **现有 pytest**:每轮必须保持全绿(不需要为抽取新增单测,因为是纯重构)
- **手工 smoke**(每轮都要走一遍受影响路径):
- P1:启动 → 打开 "WiFi ADB" 对话框 → 扫描设备 → 连接
- P2:启动 → 修改若干配置项 → 关闭 → 重启 → 检查配置已保存
- P3/P4:启动 → 切到「预约」/「高价值房间」Tab → 验证刷新
- P5:启动 → 截图按钮 → 检查图片落盘
- P6:启动 → 切到「操作日志」Tab → 搜索
## Out of Scope
- `gui/web_gui.py`(1810 行)—— 下一轮独立 spec
- `douyin/core/*` 几个 1000+ 行业务文件 —— 下一轮独立 spec
- 引入新的 GUI 框架或异步模式
- 单元测试覆盖率提升
## Outcome(2026-05-30 实施完成)
**起始**:5476 行
**结束**:178 行
**降幅**:5298 行(-96.7%)
**新增模块**:54 个 component 文件
### 主文件最终结构(178 行)
```
imports 45 行 (gui_core / 14 个 components / stdlib)
warnings 抑制 / format_gui_log_line 18 行
def main(): ~115 行
setup_root_window
setup_log_pipeline ← (queue + ThreadSafeLogWriter + on_line + Runner)
setup_top_device_bar ← (设备选择 + WiFi 工具)
build_config_vars ← (127 个 tk Var)
setup_left_config_area ← (PanedWindow + 7 配置 Tab + load/save IO)
setup_right_main_area ← (Notebook + 9 Tab + actions + pump_logs)
setup_top_buttons ← (保存配置 + 截图+OCR)
setup_periodic_refreshers ← (启动延迟 + 周期刷新)
setup_close_handler ← (WM_DELETE_WINDOW)
refresh_devices() / mainloop()
```
### 抽取阶段总结
实施分 4 个阶段:
**阶段 1:闭包/视图抽取(5476 → 3590 行,-34%)**
把 `main()` 内的内聚闭包和视图刷新函数抽到独立模块。共 17 个模块:
wifi_adb_scan_dialog / wifi_adb_dialog / reservations_view / high_value_view /
screenshot_action / actions_log_view / wifi_adb_pick_dialog / wifi_adb_reconnect /
ocr_results_view / log_pump / win_record_view / preview_view /
wifi_adb_one_click_scan / run_log_view / text_search /
logging_config_io / run_params_builder。
**阶段 2:Var 聚合 + Tab UI(3590 → 1373 行,-44% → -75%)**
- `config_io.py`(load/save 640 行 → 1 个模块)用 dict-of-vars 模式
- `build_config_vars()` 工厂集中创建 127 个 tk Var
- 7 个 Tab UI(debug / logging / yanghao / reservation / run / filter / realtime)抽
到独立 `setup_*_tab(parent, vars_=_vars_)`,直接接受 vars 全集
**阶段 3:右侧 Tab + 工具栏 + 模板复用(1373 → 519 行,-75% → -90.5%)**
- log_search_toolbar / actions_log_toolbar 用 dataclass + handles 返回
- win_record_tab / preview_tab / log_tab 整段抽出
- simple_tabs.py 提供 setup_simple_text_tab / setup_text_tab_with_refresh /
setup_stats_tab / setup_actions_log_tab / setup_ocr_results_tab 复用模板
- main_notebook / action_buttons / top_buttons / top_device_bar /
log_pipeline / periodic_refreshers / log_text_colors / keywords_tab 全部抽出
**阶段 4:聚合层 + 死代码清理(519 → 178 行,-90.5% → -96.7%)**
最后阶段把 main() 里剩余的"装配脉络"打包成更高层组件,清理失效的导入和死注释:
- `setup_root_window`: ttkbootstrap fallback + root window
- `setup_left_config_area`: PanedWindow 布局 + 7 配置 Tab + load/save IO
- `setup_right_main_area`: Notebook + 9 Tab + actions + pump_logs
- 删除 125 个无用的 _vars_ unpack(只保留 y_var/gui_theme_var)
- 死注释清理 / 重复 import / 冗余 dict 字面量(_config_io_vars 复用 _vars_ 全集)
- 重复 lambda 去重(theme_getter / _open_realtime_viewer)
### 抽取模式(54 个 components 按用途分类)
| 类型 | 模块 |
|---|---|
| WiFi ADB(6 个) | wifi_adb_scan_dialog / wifi_adb_dialog / wifi_adb_pick_dialog / wifi_adb_reconnect / wifi_adb_one_click_scan / top_device_bar |
| Tab 视图(8 个) | reservations_view / high_value_view / actions_log_view / ocr_results_view / win_record_view / preview_view / run_log_view / log_pump |
| Tab UI 容器(13 个) | run_tab / filter_tab / reservation_tab / yanghao_tab / debug_tab / logging_tab / keywords_tab / log_tab / preview_tab / win_record_tab / realtime_tab / simple_tabs / main_notebook |
| 工具栏(2 个) | log_search_toolbar / actions_log_toolbar |
| 配色 / 状态(3 个) | log_text_colors / text_search / screenshot_action |
| 配置序列化(4 个) | logging_config_io / run_params_builder / config_io / config_vars |
| 顶部 / 底部按钮(2 个) | top_buttons / action_buttons |
| 系统调度(2 个) | log_pipeline / periodic_refreshers |
| 高层聚合(3 个) | root_window / left_config_area / right_main_area |
| 已有共用(11 个) | log_writer / log_viewer / log_color_config / mapping_table / mapping_utils / device_selector / actions_log_viewer / error_log_viewer / realtime_viewer / stats_formatter / __init__ |
### 验证
- 每轮抽取后 `pytest` 全绿(1374 passed),包括 `test_gui_app_smoke.py` 启动 smoke 和
`test_gui_webui_sync.py` GUI/WebUI 配置 key 同步检查。
- 共 7 次 pytest 失败均能定位修复(具体错误参见各次 commit message):
- `_preview_view` 在 `update_image_list` 之前被引用
- `enable_ocr_mode1_var` 因含数字未被正则替换(2 次)
- `BOTH` 常量 / `ScrolledText` import 缺失
- sync 工具锚点失效 → 让工具改读 `config_io.py` + `realtime_tab.py`
- `image_var` 在 `setup_top_buttons` 调用时还没创建 → 调整顺序
- 未做手工 GUI smoke(建议用户启动 GUI 走一遍 WiFi 对话框 / 各 Tab,确认无回归)。
### 停止原因
主文件已从 5476 → 178(-96.7%)。当前 main() 是清晰的"装配胶水":每个 setup_*
调用对应一个明确的功能区。继续抽要么打散这个装配脉络,要么把整个 main 改造成
`GuiApp` 类(MVC/MVVM),都属于另一个 spec。`pytest` 1374 全绿。
+97
View File
@@ -0,0 +1,97 @@
# 迁移部署指南(简版)
## 1. 电脑端(最少步骤)
1. 安装 `Python 3.10+`
2. 安装 `ADB`(platform-tools)并加入 PATH
3. 拉代码:
```powershell
git clone https://git.simgreek.com/simgreek/douyi_guaji_main.git
cd douyin_guaji-main
```
4. 一键部署依赖:
```powershell
bootstrap_deps.bat
```
可选:
```powershell
bootstrap_deps.bat --minimal
bootstrap_deps.bat --index-url https://pypi.tuna.tsinghua.edu.cn/simple
```
---
## 2. 手机端必须操作
### 2.1 开启开发者选项
1. `设置 -> 关于手机`
2. 连续点击“版本号”7次
### 2.2 开启 USB 调试
1. `设置 -> 开发者选项`
2. 开启:
- `USB 调试`
- (部分机型)`USB 调试(安全设置)` / `USB 安装`
### 2.3 首次授权
1. 手机 USB 连接电脑,模式选“文件传输/MTP”
2. 手机弹出“允许 USB 调试”时点击“允许”
3. 电脑执行:
```powershell
adb devices
```
看到 `<device-id> device` 即成功。
如果是 `unauthorized`,重新插线并重新允许授权。
---
## 3. 手机底部导航栏怎么调出(详细)
目标:显示底部“返回/主页/多任务”按钮。
### 方法 A(通用)
1. 打开设置
2. 搜索:`System navigation` 或 `Navigation mode`
3. 选择:`3-button navigation`(三键导航)
常见路径:
- `Settings -> System -> Gestures -> System navigation`
- 或 `Settings -> System -> Navigation mode`
### 方法 B(品牌常见路径)
- Samsung:`设置 -> 显示 -> 导航条 -> 按钮`
- Xiaomi/Redmi/POCO:`设置 -> 桌面 -> 系统导航方式 -> 经典导航键`
- OPPO/OnePlus:`设置 -> 系统设置 -> 系统导航方式 -> 虚拟按键`
- vivo/iQOO:`设置 -> 系统导航 -> 导航键`
- Huawei/Honor:`设置 -> 系统和更新 -> 系统导航方式 -> 屏幕内三键导航`
### 还是没显示时
1. 关闭“全面屏手势/全屏手势”
2. 退出当前全屏 App 后再切换
3. 切换后重启手机一次
临时调出:从屏幕最底部向上轻划一次(很多机型会临时显示系统导航控件)。
---
## 4. 可选迁移配置
如果要保留你原来的策略和状态,再复制这些文件:
1. `config/config.json`
2. `state/high_value_rooms.json`
3. `douyin/core/state/reservations.json`
+61
View File
@@ -0,0 +1,61 @@
迁移部署指南(简版,TXT)
==========================
1. 电脑端(最少步骤)
---------------------
1)安装 Python 3.10+
2)安装 ADB(platform-tools)并加入 PATH
3)拉取代码:
git clone https://git.simgreek.com/simgreek/douyi_guaji_main.git
cd douyin_guaji-main
4)一键部署依赖:
bootstrap_deps.bat
可选参数:
bootstrap_deps.bat --minimal
bootstrap_deps.bat --index-url https://pypi.tuna.tsinghua.edu.cn/simple
2. 手机端必须操作
------------------
2.1 开启开发者选项
1)设置 -> 关于手机
2)连续点击“版本号”7次
2.2 开启 USB 调试
1)设置 -> 开发者选项
2)开启:
- USB 调试
- (部分机型)USB 调试(安全设置)/ USB 安装
2.3 首次授权
1)手机 USB 连接电脑,模式选“文件传输/MTP”
2)手机弹出“允许 USB 调试”时点击“允许”
3)电脑执行:
adb devices
看到:
<device-id> device
即成功。
如果显示 unauthorized,重新插线并重新允许授权。
3. 手机底部导航栏怎么调出(详细)
----------------------------------
目标:显示底部“返回/主页/多任务”按钮。
方法 A(通用)
1)打开设置
2)搜索:System navigation 或 Navigation mode(系统导航/导航方式)
3)选择:3-button navigation(三键导航)
常见路径:
- Settings -> System -> Gestures -> System navigation
- 或 Settings -> System -> Navigation mode
方法 B(品牌常见路径)
- Samsung:设置 -> 显示 -> 导航条 -> 按钮
- Xiaomi/Redmi/POCO:设置 -> 桌面 -> 系统导航方式 -> 经典导航键
- OPPO/OnePlus:设置 -> 系统设置 -> 系统导航方式 -> 虚拟按键
- vivo/iQOO:设置 -> 系统导航 -> 导航键
- Huawei/Honor:设置 -> 系统和更新 -> 系统导航方式 -> 屏幕内三键导航
还是没显示时
1)关闭“全面屏手势/全屏手势”
2)退出当前全屏 App 后再切换
3)切换后重启手机一次
临时调出:
从屏幕最底部向上轻划一次(很多机型会临时显示系统导航控件)。
4. 可选迁移配置
---------------
如果要保留原来的策略和状态,手动复制:
1)config/config.json
2)state/high_value_rooms.json
3)douyin/core/state/reservations.json
@@ -8,11 +8,131 @@ from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, List, Optional, Tuple
from typing import Any, Callable, Optional
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
def _emit_flow_flag(analyser: Any, flag: str, status: str, **extra) -> None:
try:
payload = {
"flag": str(flag or ""),
"status": str(status or ""),
"run_id": str(getattr(analyser, "_run_id", "") or ""),
}
payload.update(extra or {})
analyser._log_kv("流程标志", f"[FLOW_FLAG] {flag}:{status}", **payload)
except Exception:
pass
def _log_detail_open_verdict(analyser: Any, verdict: str, **extra) -> None:
"""固定日志:点击福袋后的第一层详情页验证结果。"""
try:
analyser._log_kv(
"详情验证",
f"[DETAIL_OPEN_VERDICT] {verdict}",
verdict=str(verdict or ""),
**(extra or {}),
)
except Exception:
pass
def _detail_probe_after_click(analyser: Any) -> dict[str, Any]:
"""Lightweight detail evidence produced by stage diagnosis, without extra OCR."""
task_count = getattr(analyser, "_fudai_detail_task_count_from_stage", None)
try:
task_count_int = int(task_count or 0)
except Exception:
task_count_int = 0
screenshot_ready = bool(getattr(analyser, "_screenshot_ready_for_ocr", False))
probe_result = "detail_likely" if (task_count_int > 0 or screenshot_ready) else "not_enough_evidence"
return {
"task_count_from_stage": task_count_int,
"screenshot_ready_for_ocr": screenshot_ready,
"detail_probe_result": probe_result,
"detail_probe_confident": bool(task_count_int > 0 or screenshot_ready),
}
def _close_wrong_fudai_target(
analyser: Any,
device_id: str,
*,
stage: str,
reason: str,
click_x: int | None = None,
click_y: int | None = None,
) -> None:
"""Close a non-detail page opened by a risky fudai candidate click."""
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:关闭疑似误入口,准备同直播间重试福袋",
stage=str(stage or ""),
reason=str(reason or ""),
decision="close_wrong_target_before_retry",
)
except Exception:
pass
stage_text = str(stage or "")
if stage_text in ("IN_LIVE_ROOM", "UNKNOWN", ""):
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:误入口仍处于直播间,不执行关闭点击或返回键",
stage=stage_text,
decision="skip_close_action_same_live_room",
)
except Exception:
pass
else:
try:
analyser.operation.click_back(device_id)
except Exception:
try:
analyser.operation.back(device_id)
except Exception:
pass
try:
analyser.operation.delay(0.7)
except Exception:
time.sleep(0.7)
try:
setattr(
analyser,
"_allow_fudai_click_after_wrong_target_until_ts",
time.time() + 3.0,
)
if click_x is not None:
setattr(analyser, "_last_wrong_fudai_click_x", int(click_x))
if click_y is not None:
setattr(analyser, "_last_wrong_fudai_click_y", int(click_y))
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:误入口已关闭,允许同房重试绕过一次优惠券预检",
click_x=click_x,
click_y=click_y,
decision="allow_retry_after_wrong_target",
)
except Exception:
pass
try:
analyser.operation.get_screenshot(device_id, use_service=False)
except Exception:
pass
for attr, value in (
("last_fudai_x", 0),
("_last_fudai_confirm_failure", None),
("_screenshot_ready_for_ocr", False),
("_fudai_detail_task_count_from_stage", 0),
):
try:
setattr(analyser, attr, value)
except Exception:
pass
def find_and_open_fudai_detail(
@@ -20,8 +140,24 @@ def find_and_open_fudai_detail(
stage: Any = "",
seen: Any = "",
func_start_time: float | None = None,
max_wait_seconds: float | None = None,
):
"""主实现:检测福袋图标并点击打开详情页。"""
effective_max_wait_seconds = float(
(
max_wait_seconds
if max_wait_seconds is not None
else getattr(analyser, "fudai_icon_max_wait_seconds", 5.0)
)
or 5.0
)
_emit_flow_flag(
analyser,
"fudai_find_open",
"start",
room_pos=int(getattr(analyser, "room_pos", 0) or 0),
max_wait_seconds=effective_max_wait_seconds,
)
if func_start_time is None:
func_start_time = time.time()
@@ -49,16 +185,13 @@ def find_and_open_fudai_detail(
# 1. 利用像素检测福袋图标的 X 坐标(1080 基准)
# 在配置的最大等待时间内重复检测福袋图标
max_wait_seconds = float(
getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0
)
max_wait_seconds = effective_max_wait_seconds
retry_delay_seconds = float(
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
)
start_time = time.time()
x = False
while (time.time() - start_time) < max_wait_seconds:
# 在调用检测函数之前,检查是否还有足够的时间
elapsed = time.time() - start_time
@@ -248,6 +381,13 @@ def find_and_open_fudai_detail(
except Exception:
# 容错:如果处理计数或配置读取出错,忽略并继续返回 False
pass
_emit_flow_flag(
analyser,
"fudai_find_open",
"not_found",
max_wait_seconds=max_wait_seconds,
elapsed_seconds=round(time.time() - start_time, 2),
)
return False
# 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度)
@@ -292,9 +432,12 @@ def find_and_open_fudai_detail(
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
img = Image.open(screenshot_path)
img.load()
pic_rgb_full = img.convert("RGB")
_raw = Image.open(screenshot_path)
try:
_raw.load()
pic_rgb_full = _raw.convert("RGB")
finally:
_raw.close()
try:
box_r = 30
coord_box = (
@@ -341,6 +484,10 @@ def find_and_open_fudai_detail(
"流程",
"find_and_open_fudai_detail:点击后固定等待",
wait_seconds=wait_seconds,
click_x=click_x,
click_y=click_y,
fudai_x=int(x or 0),
room_pos=int(getattr(analyser, "room_pos", 0) or 0),
)
except Exception:
pass
@@ -359,6 +506,10 @@ def find_and_open_fudai_detail(
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后截图文件不存在,无法验证",
decision="fail_no_after_click_screenshot",
click_x=click_x,
click_y=click_y,
screenshot_path=pic_path,
)
except Exception:
pass
@@ -376,22 +527,44 @@ def find_and_open_fudai_detail(
else:
stage, reason = result
try:
probe = _detail_probe_after_click(analyser)
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测",
stage=stage,
reason=reason,
click_x=click_x,
click_y=click_y,
wait_seconds=wait_seconds,
decision=(
"success_stage_detail"
if stage == "FUDai_DETAIL"
else "needs_detail_probe"
),
**probe,
)
except Exception:
pass
if stage == "FUDai_DETAIL":
_log_detail_open_verdict(
analyser,
"detail_recognized",
stage=stage,
reason=str(reason or ""),
task_count_from_stage=getattr(
analyser, "_fudai_detail_task_count_from_stage", None
),
)
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测确认在福袋详情页",
stage=stage,
reason=reason,
click_x=click_x,
click_y=click_y,
decision="success",
)
except Exception:
pass
@@ -438,14 +611,126 @@ def find_and_open_fudai_detail(
)
except Exception:
pass
_emit_flow_flag(
analyser,
"fudai_find_open",
"open_success",
stage=stage,
reason=str(reason or ""),
)
return True
else:
probe = _detail_probe_after_click(analyser)
if probe.get("detail_probe_confident"):
_log_detail_open_verdict(
analyser,
"stage_false_negative_detail_likely",
stage=stage,
reason=str(reason or ""),
click_x=click_x,
click_y=click_y,
**probe,
)
try:
analyser._log_kv(
"诊断",
"点击后阶段检测=非详情,但详情轻量探测命中,疑似阶段误判,按已打开详情继续",
stage=stage,
reason=reason,
click_x=click_x,
click_y=click_y,
decision="continue_as_detail",
**probe,
)
except Exception:
pass
try:
setattr(analyser, "_consecutive_no_fudai_count", 0)
except Exception:
pass
elapsed = time.time() - func_start_time
analyser._log_kv(
"流程",
"find_and_open_fudai_detail完成(轻量探测确认详情)",
elapsed_seconds=round(elapsed, 2),
stage=stage,
reason=str(reason or ""),
)
_emit_flow_flag(
analyser,
"fudai_find_open",
"open_success_by_probe",
stage=stage,
reason=str(reason or ""),
**probe,
)
return True
_log_detail_open_verdict(
analyser,
"detail_not_recognized",
stage=stage,
reason=str(reason or ""),
click_x=click_x,
click_y=click_y,
**probe,
)
try:
candidate_warning = getattr(analyser, "_last_fudai_candidate_warning", {})
except Exception:
candidate_warning = {}
try:
retry_depth = int(getattr(analyser, "_fudai_wrong_target_retry_depth", 0) or 0)
except Exception:
retry_depth = 0
if retry_depth < 1:
_log_detail_open_verdict(
analyser,
"wrong_target_retry_same_room",
stage=stage,
reason=str(reason or ""),
click_x=click_x,
click_y=click_y,
candidate_warning=candidate_warning,
**probe,
)
_close_wrong_fudai_target(
analyser,
device_id,
stage=str(stage or ""),
reason=str(reason or ""),
click_x=click_x,
click_y=click_y,
)
try:
setattr(analyser, "_fudai_wrong_target_retry_depth", retry_depth + 1)
except Exception:
pass
try:
return bool(
find_and_open_fudai_detail(
analyser,
stage=stage,
seen=seen,
func_start_time=func_start_time,
)
)
finally:
try:
setattr(analyser, "_fudai_wrong_target_retry_depth", retry_depth)
except Exception:
pass
try:
analyser._log_kv(
"流程",
"find_and_open_fudai_detail:点击后阶段检测未在福袋详情页,可能误点击",
stage=stage,
reason=reason,
click_x=click_x,
click_y=click_y,
decision="misclick_close_detail_area",
**probe,
)
except Exception:
pass
@@ -480,6 +765,10 @@ def find_and_open_fudai_detail(
"流程",
"find_and_open_fudai_detail完成(误点击)",
elapsed_seconds=round(elapsed, 2),
stage=stage,
reason=str(reason or ""),
click_x=click_x,
click_y=click_y,
)
try:
analyser._log_kv(
@@ -492,8 +781,23 @@ def find_and_open_fudai_detail(
)
except Exception:
pass
_emit_flow_flag(
analyser,
"fudai_find_open",
"open_misclick",
stage=stage,
reason=str(reason or ""),
)
return False
except Exception as e:
_log_detail_open_verdict(
analyser,
"detail_stage_exception",
error=str(e),
task_count_from_stage=getattr(
analyser, "_fudai_detail_task_count_from_stage", None
),
)
try:
analyser._log_kv(
"流程",
@@ -508,6 +812,12 @@ def find_and_open_fudai_detail(
"find_and_open_fudai_detail完成(阶段检测异常)",
elapsed_seconds=round(elapsed, 2),
)
_emit_flow_flag(
analyser,
"fudai_find_open",
"open_stage_exception",
error=str(e),
)
return False
except Exception:
try:
@@ -530,6 +840,7 @@ def find_and_open_fudai_detail(
"find_and_open_fudai_detail完成(兜底失败)",
elapsed_seconds=round(elapsed, 2),
)
_emit_flow_flag(analyser, "fudai_find_open", "fallback_failed")
return False
return False
@@ -5,13 +5,8 @@ handle_no_fudai_situation:在直播间未识别到福袋时做简单的等待
from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, List, Optional, Tuple
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
from typing import Any, Callable, List, Optional
def handle_no_fudai_situation(
@@ -5,14 +5,10 @@ handle_stage_after_diagnosis:记录当前阶段信息(暂不做复杂跳转
"""
from __future__ import annotations
import logging
import os
import time
from typing import Any, Callable, List, Optional, Tuple
from typing import Any
from douyin.core import path_config
from douyin.detection.douyin_detection import check_have_fudai_with_ready_screenshot
from douyin.fudai.douyin_fudai_core import should_skip_fudai_by_config
from .find_open import find_and_open_fudai_detail
def handle_stage_after_diagnosis(
+142 -507
View File
@@ -16,17 +16,11 @@ import time
import subprocess
import logging
# Optional heavy dependencies used in image processing; Pylance may not have them in analysis env
from PIL import Image # type: ignore[import]
import numpy as np # type: ignore[import]
from douyin.core.underlying_operations import underlying_operations
from douyin.stage import douyin_stage
from douyin.detection import douyin_detection
from douyin.fudai import douyin_fudai_detail
from douyin.fudai import douyin_fudai_core
from douyin.core import douyin_flow_control # pylint: disable=redefined-outer-name
from douyin.other import douyin_live_room
from douyin.reservation import (
douyin_reservation_logic,
@@ -39,9 +33,6 @@ from douyin.handlers import douyin_popup_handler
from douyin.handlers import douyin_swipe_handler
from douyin.reservation import douyin_reservation_handler
from douyin.stage import douyin_stage_handler
from douyin.core.fudai_modules import fudai_run_blocks
from douyin.core.fudai_modules import fudai_detail_blocks
from douyin.core.fudai_modules import fudai_image_helpers
class fudai_analyse:
@@ -119,242 +110,9 @@ class fudai_analyse:
douyin_logging.configure_logging()
except Exception:
pass
self._forced_reservation_detail = None
self._forced_reservation_fudai_x = None
# 进入直播间后诊断与阶段流转所需的一些状态
self._last_diag_stage: str = "INIT"
self._last_diag_seen: str = "-"
self._last_diag_ts: float = 0.0
# 30分钟超时相关:记录最后一次成功参与福袋的时间
self._last_successful_attend_ts: float = 0.0
self._no_attend_timeout_minutes: float = (
30.0 # 30分钟没有参与成功则返回推荐页面(可通过config.json配置)
)
self._run_start_ts: float = (
time.time()
) # 记录运行开始时间,用于从未成功参与时的超时检查
# 预约状态上次写盘时间(初始化以避免 attribute-defined-outside-init 警告)
self._reservations_state_last_write_ts: float = 0.0
self.last_fudai_x: int = 0 # 上次检测到的福袋图标X坐标(用于优化搜索)
# 与配置相关的核心字段(只初始化最关键的几项,其余保持默认)
self.contains_not_want: list[str] = []
self.contains_want: list[str] = []
self.min_prize_value_yuan: float = 0.0
self.min_participants: int = 0
self.max_participants: int = 0
self.skip_if_countdown_gt_seconds: int = 900
self.skip_if_countdown_lt_seconds: int = 0 # 倒计时小于该秒数则不参与
self.no_fudai_watchdog_enabled: bool = False
# 福袋图标检测节流相关默认值
# 实际识别到福袋一般需要 4–6 秒,这里取中间值 5 秒作为默认上限,具体值可在 GUI / config.json 中调整
# 注意:已改为使用时间限制(fudai_icon_max_wait_seconds),不再使用尝试次数限制
self.fudai_icon_retry_delay_seconds: float = 0.6
self.fudai_icon_max_wait_seconds: float = 5.0
# 连续未找到福袋超过此阈值后,自动按返回键退出直播间(默认999999=禁用)
self.fudai_exit_after_misses: int = 999999
# 是否启用自动返回键退出(默认False=禁用)
self.enable_back_on_misses: bool = False
# 点击福袋图标后等待详情页加载的时间(秒)
self.fudai_click_wait_seconds: float = 1.0
# 切换直播间后等待阶段诊断的时间(秒)
self.switch_room_wait_after_stage_diag_seconds: float = 7.0
# 滑动速度(毫秒),影响滑动持续时间,值越大滑动越慢
self.swipe_duration_ms: int = 600
# fudai_find_max_attempts 已废弃,保留仅为兼容性,实际不再使用
self.fudai_find_max_attempts: int = 10
# 优化查找器相关配置
self.fudai_finder_optimized_enabled: bool = True # 默认启用优化查找器
self.fudai_click_verify_enabled: bool = True # 点击后验证是否成功打开详情页
self.fudai_find_max_retries: int = 3 # 最大重试次数
self.screenshot_diagnose_min_interval_seconds: float = 8.0
# 开奖页面检测红色占比阈值(0.0~1.0)
self.lucky_draw_red_ratio_threshold: float = 0.9
# 优惠券模板匹配阈值(0.0~1.0,默认0.75)
self.coupon_template_match_threshold: float = 0.75
# 参与按钮红色占比阈值(0.0~1.0,默认0.25)
self.attend_button_red_ratio_threshold: float = 0.25
# 粉丝团加入红色占比阈值(0.0~1.0,默认0.25)
self.fansclub_join_red_ratio_threshold: float = 0.25
# 直播间检测阈值(模板匹配阈值,0.0~1.0,默认0.8)
self.live_room_match_threshold: float = 0.8
# 福袋模板匹配开关(默认关闭)
self.fudai_template_match_enabled: bool = False
# 福袋模板匹配阈值(0.0~1.0,默认0.7)
self.fudai_template_match_threshold: float = 0.7
# —— 高价值福袋 / 预约相关配置(从原 fudai1 精简迁移) ——
# 是否启用“高价值福袋预约参与”
self.high_value_fudai_enabled: bool = False
# 高价值阈值(元)
self.high_value_fudai_threshold_yuan: float = 500.0
# 提前参与秒数:开奖前 N 秒回到该直播间并参与
self.high_value_fudai_join_ahead_seconds: int = 100
# 从当前位置最多回滑多少次以回到预约直播间
self.high_value_fudai_max_swipe_back: int = 35
# 同时记录的最大预约数量
self.high_value_fudai_max_reservations: int = 3
# 完成某个预约福袋后的动作:stay=停留当前直播间;continue=继续执行抢福袋
self.high_value_fudai_after_action: str = "continue"
self.high_value_fudai_after_stay_seconds: int = 120
# 开奖前轮询时间(秒,默认10.0)
self.high_value_fudai_poll_before_seconds: float = 10.0
# 高价值直播间"回访"相关(当前仅保留配置,不在本地版强制启用复杂逻辑)
self.high_value_room_revisit_enabled: bool = False
self.high_value_room_revisit_only_current_run: bool = False
self.high_value_room_revisit_min_interval_seconds: int = 300
self.high_value_room_revisit_max_per_run: int = 5
self.high_value_room_revisit_min_prize_value: float = 0.0
self.high_value_room_revisit_max_age_days: int = 30
# 粉丝团相关配置
self.auto_join_fansclub: bool = False # 是否自动加入粉丝团
self.fansclub_fail_action: str = (
"stay" # 粉丝团失败策略:stay=停留,switch=切换
)
# 预约回退相关
self.reservation_back_verify_enabled: bool = True # 默认启用回退校验
# 未做回退校验时的快速回滑延迟(秒)
self.reservation_back_swipe_delay: float = 0.6
# 滑动次数重置相关
self.reset_after_swipes_enabled: bool = False # 由 Web/CLI 显式开关
self.reset_after_swipes: int = 10 # 达到阈值次数后回退,需启用开关后生效
# 意外返回桌面自救相关
self.desktop_icon_x: int = 153 # 桌面图标 X 坐标(默认值)
self.desktop_icon_y: int = 260 # 桌面图标 Y 坐标(默认值)
self.yanghao_fallback_live_x: int = 540 # 养号备用直播按钮 X 坐标
self.yanghao_fallback_live_y: int = 2000 # 养号备用直播按钮 Y 坐标
self.yanghao_fallback_enter_live_x: int = 540 # 养号备用进入直播间 X 坐标
self.yanghao_fallback_enter_live_y: int = 1200 # 养号备用进入直播间 Y 坐标
# 推荐页养号默认配置(若 config.json 未设置则使用这些默认值)
self.yanghao_enabled: bool = True
self.yanghao_enable_actions: bool = True
self.yanghao_step_screenshot: bool = False
self.yanghao_recommend_duration_seconds: int = 60
self.yanghao_recommend_interval_seconds: int = 0
self.yanghao_like_prob: float = 0.15
self.yanghao_fav_prob: float = 0.05
self.yanghao_comment_prob: float = 0.0
self.yanghao_dwell_on_action_min_seconds: float = 5.0
self.yanghao_dwell_on_action_max_seconds: float = 30.0
self.yanghao_icon_roi_size: int = 180
# 调整默认阈值为 0.70(更宽松,减少漏检)
self.yanghao_icon_match_threshold: float = 0.70
self.yanghao_like_roi_scale: float = 1.5
self.yanghao_fav_roi_scale: float = 1.5
self.yanghao_like_icon_match_threshold: float | None = None
self.yanghao_fav_icon_match_threshold: float | None = None
# icon 坐标(基于 1080x2400)
self.yanghao_like_icon_x: int = 0
self.yanghao_like_icon_y: int = 0
self.yanghao_fav_icon_x: int = 0
self.yanghao_fav_icon_y: int = 0
# roi 偏移
self.yanghao_like_roi_offset_x: int = 0
self.yanghao_like_roi_offset_y: int = 0
self.yanghao_fav_roi_offset_x: int = 0
self.yanghao_fav_roi_offset_y: int = 0
# 评论相关默认坐标与文案列表
# 最近一次触发推荐页养号的时间戳(用于定时触发)
self._last_yanghao_ts: float = 0.0
self.yanghao_comment_btn_x: int = 0
self.yanghao_comment_btn_y: int = 0
self.yanghao_comment_input_x: int = 0
self.yanghao_comment_input_y: int = 0
self.yanghao_comment_send_x: int = 0
self.yanghao_comment_send_y: int = 0
self.yanghao_comment_close_x: int = 0
self.yanghao_comment_close_y: int = 0
self.yanghao_comment_texts: list[str] = []
# —— 预约运行时状态(单次运行内有效) ——
# 高价值福袋预约队列
self.reservations: list[dict[str, Any]] = []
# 标记是否是第一次运行 run_once_basic(用于刷新预约队列)
self._first_run_once_basic: bool = True
# 当前"直播间位置"计数:上划 +1,下滑 -1(仅在本次连续切换过程中有效)
self.room_pos: int = 0
# 回退到预约直播间后,在该时间戳前不允许上划离开
self.reservation_focus_until_ts: float = 0.0
# 当前是否还有"完成某个预约后的后续动作"待执行
self.reservation_after_action_pending: bool = False
# 达到"无福袋切换阈值"后,是否在处理完预约后回到列表第一个直播间
self.reset_to_list_after_reservations: bool = False
# 队列满时是否已回退到最早开奖的预约直播间等待
self.queue_full_waiting_at_earliest: bool = False
# 预约队列状态文件(供 WebGUI / 其他进程查看)
try:
from douyin.core import path_config as _pc
self._reservations_state_path: str = _pc.get_reservations_path()
except Exception:
self._reservations_state_path = os.path.join(
os.path.dirname(__file__), "state", "reservations.json"
)
# 运行时直播间标题和位置映射表(用于回退校验)
# 格式:{room_pos: {"title": str, "title_raw": str, "has_fudai": bool, "fudai_content": str, "fudai_detail": Any}}
self._room_pos_to_title_map: dict[int, dict[str, Any]] = {}
# 每次重新运行时丢弃磁盘上旧的映射表,确保只记录本次运行的结果。
# 同时尝试删除旧的导出文件(JSON/CSV/MD),以避免 GUI 在未写入新数据前显示过期内容。
try:
state_dir = os.path.dirname(self._reservations_state_path)
state_path = os.path.join(state_dir, "room_pos_map.json")
csv_path = os.path.join(state_dir, "room_pos_map.csv")
md_path = os.path.join(state_dir, "room_pos_map.md")
for p in (state_path, csv_path, md_path):
try:
if os.path.exists(p):
os.remove(p)
except Exception:
pass
except Exception:
pass
# 已记录统计的福袋跟踪(避免同一个直播间同一个福袋重复记录统计)
self._recorded_fudai_stats: set[tuple[str, str]] = (
set()
) # (room_title, fudai_content)
# 运行时状态标志(避免在外部定义属性的警告)
self.needswitch: bool | None = (
None # 是否允许切换直播间,将从配置文件加载,默认 True
)
self._waiting_for_lottery_result: bool = False # 是否正在等待开奖结果
self._current_attending_reservation_fudai: bool = (
False # 当前正在参与的是否为预约福袋
)
self._skip_stage_diagnosis_and_find_fudai: bool = False # 跳过阶段诊断标志
self._just_switched_room: bool = False # 是否刚刚切换了直播间
# 高价值房间重访相关状态
self._last_high_value_revisit_ts: float = (
time.time()
) # 最后一次重访时间戳,初始化为当前时间避免启动后立即重访
self._current_run_revisit_count: int = 0 # 本次运行的重访次数
self._current_run_high_value_rooms: list[dict[str, Any]] = (
[]
) # 本次运行发现的高价值房间
self._last_fudai_detail_tuple: Optional[Tuple[Any, ...]] = (
None # 上次读取的福袋详情
)
self._current_fudai_future_ts: float = 0.0 # 当前福袋的开奖时间戳
self._current_fudai_content: str = "" # 当前福袋的内容标识
self._fudai_detail_first_read: bool = False # 是否第一次读取福袋详情
self._fudai_detail_consecutive_failures: int = 0 # 连续失败次数
self._detail_closed_by_attend: bool = False # 详情页是否由参与操作关闭
self._lottery_result_expected_ts: float = 0.0 # 开奖结果预期时间戳
self._lottery_wait_start_ts: float = 0.0 # 开始等待开奖的时间戳
# 应用所有"配置默认值 + 运行时状态字段初始化"
from douyin.core.fudai_modules.init_helpers import apply_fudai_defaults
apply_fudai_defaults(self)
# 初次加载配置
self.load_config()
@@ -372,12 +130,14 @@ class fudai_analyse:
self, target_title, target_title_raw
)
def _record_room_title_and_pos(self) -> None:
def _record_room_title_and_pos(self) -> bool:
"""记录当前直播间的标题和位置到运行时映射表。
用于预约回退校验时验证位置信息。
"""
douyin_reservation_handler.ReservationHandler.record_room_title_and_pos(self)
return bool(
douyin_reservation_handler.ReservationHandler.record_room_title_and_pos(self)
)
def click(self, x: int, y: int) -> None:
"""兼容原版 fudai_analyse.click:转发到底层 operation.click。"""
@@ -553,7 +313,7 @@ class fudai_analyse:
self._last_yanghao_ts = now
seconds = int(getattr(self, "yanghao_recommend_duration_seconds", 60) or 60)
try:
self._yanghao_wait(seconds)
self._yanghao_recommend_flow(seconds)
except Exception:
pass
except Exception:
@@ -569,7 +329,29 @@ class fudai_analyse:
) -> None:
"""兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。"""
# 程序启动时清理旧截图文件,避免复用过期的截图
fudai_run_blocks.cleanup_old_screenshot_at_startup(self)
try:
from douyin.core import path_config
import os
pic_path = path_config.get_screenshot_path()
if os.path.exists(pic_path):
os.remove(pic_path)
self._log_kv(
"启动",
"清理旧截图文件,避免复用过期截图",
path=pic_path,
log_type="SCREENSHOT",
)
except Exception as e:
try:
self._log_kv(
"启动",
f"清理旧截图文件失败 - {str(e)}",
level="WARNING",
error=str(e),
)
except Exception:
pass
# DEBUG: 记录函数入口
try:
@@ -589,20 +371,78 @@ class fudai_analyse:
try:
self.needswitch = bool(needswitch)
except Exception:
# 兜底:若赋值失败,则保持原有行为(默认允许切换)
self.needswitch = True
# 获取设备分辨率(带重试 + 默认回退)
self.resolution_ratio_x, self.resolution_ratio_y = (
fudai_run_blocks.resolve_device_resolution(self, max_attempts=5)
)
# 尝试获取设备分辨率;若设备未连接则重试数次再回退到默认分辨率
resolved = False
if self.device_id:
for attempt in range(5):
try:
rx, ry = self.operation.get_device_resolution(self.device_id)
self.resolution_ratio_x = int(rx or 1080)
self.resolution_ratio_y = int(ry or 2400)
resolved = True
break
except Exception as e:
try:
self._log_kv(
"截图",
"获取分辨率失败,重试中",
attempt=attempt + 1,
error=str(e),
)
except Exception:
logging.warning(
f"[DEBUG] get_device_resolution attempt {attempt+1} failed: {e}"
)
time.sleep(1.0)
if not resolved:
# 回退到默认分辨率
try:
self._log_kv("截图", "使用默认分辨率回退", width=1080, height=2400)
except Exception:
pass
self.resolution_ratio_x, self.resolution_ratio_y = 1080, 2400
# 记录运行开始
from datetime import datetime
start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
fudai_run_blocks.write_actions_log_separator(
f"{start_time} - [GUI] - [运行] 程序开始运行"
)
try:
try:
from douyin.core import path_config as _pc
actions_log_path = _pc.get_actions_log_path()
except Exception:
# 兜底:path_config 不可用时退化(不会推到 douyin/core/logs,沿用 PROJECT_ROOT/logs)
actions_log_path = os.path.join(
os.path.dirname(__file__), "..", "..", "logs", "actions.log"
)
actions_log_path = os.path.normpath(actions_log_path)
log_dir = os.path.dirname(actions_log_path)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
with open(
actions_log_path, "a", encoding="utf-8-sig", errors="replace"
) as f:
f.write("=" * 80 + "\n")
f.write(f"{start_time} - [GUI] - [运行] 程序开始运行\n")
f.flush()
except Exception:
pass
# 捕获并记录未被捕获的异常以便排查立即退出问题
try:
# 原有后续逻辑继续...
pass
except Exception as top_exc:
try:
self._log_kv(
"ERROR", "fudai_choujiang top-level exception", error=str(top_exc)
)
except Exception:
import traceback
traceback.print_exc()
raise
# 暂时禁用流式截图,使用直接截图模式
self._log_kv("截图服务", "暂时禁用流式截图,使用直接截图模式")
@@ -616,10 +456,12 @@ class fudai_analyse:
)
# 基础循环:在限定时间内反复执行单轮逻辑
# 如果 wait_minutes <= 0,则无限循环运行
from douyin.core.fudai_modules import fudai_run_loop as _run_loop
if wait_minutes and wait_minutes > 0:
fudai_run_blocks.run_basic_loop_with_timeout(self, int(wait_minutes))
_run_loop.run_timed_loop(self, int(wait_minutes))
else:
fudai_run_blocks.run_basic_loop_forever(self)
_run_loop.run_infinite_loop(self)
# ========== 阶段诊断 ==========
def _diagnose_stage_from_current_screen(
@@ -682,19 +524,16 @@ class fudai_analyse:
def _capture_roi_screenshot(
self, label: str, sx: int, sy: int, size: int, screenshot_path: str = None
) -> str:
"""捕获以 (sx,sy) 为中心,边长为 size 的 ROI 截图,保存到 `pic/` 并返回路径。
返回 ROI 图片路径(绝对路径),失败返回空字符串。
"""
return fudai_image_helpers.capture_roi_screenshot(
"""捕获以 (sx,sy) 为中心的 ROI 截图。"""
return douyin_screenshot_handler.ScreenshotHandler.capture_roi_screenshot(
self, label, sx, sy, size, screenshot_path
)
def _match_icon_template(
self, roi_path: str, template_path: str, threshold: float | None = None
) -> Tuple[bool, float]:
"""对比 ROI 与模板,返回 (detected: bool, score: float)。"""
return fudai_image_helpers.match_icon_template(
"""对比 ROI 与模板,返回 (detected, score)。"""
return douyin_screenshot_handler.ScreenshotHandler.match_icon_template(
self, roi_path, template_path, threshold
)
@@ -750,96 +589,48 @@ class fudai_analyse:
# use module-level `douyin_reservation_logic` imported at top
start_time = time.time()
self._log_kv("流程", "run_once_basic开始", start_timestamp=start_time)
# 在主循环开始时检查是否需要定时触发推荐页养号
try:
self._maybe_run_yanghao_during_run()
except Exception:
pass
# 尝试记录当前直播间的标题与位置,确保所有直播间(不限福袋)都被采集到运行时映射表
# 但如果刚刚切换直播间,避免重复记录(切换前已记录)
try:
just_switched = getattr(self, "_just_switched_room", False)
if not just_switched:
self._record_room_title_and_pos()
else:
self._log_kv(
"预约",
"[预约] 刚刚切换直播间,跳过重复记录标题",
reason="avoid_duplicate_after_switch",
)
except Exception:
pass
# 直接参与标志已移除,相关旧逻辑已清理,继续按正常流程执行
# 0. 如果正在等待开奖:不在此期间检查并抢占其他预约,避免放弃当前正在参加的直播间
if fudai_run_blocks.handle_waiting_for_lottery_result(self, start_time):
from douyin.core.fudai_modules import run_once_basic_helpers as _ronce_helpers
_ronce_helpers.run_once_basic_prelude(self, start_time)
if _ronce_helpers.handle_waiting_for_lottery_result(self, start_time):
return
# 0. 检查30分钟超时:如果30分钟没有成功参与福袋,则返回推荐页面并重新进入直播间
if fudai_run_blocks.handle_no_attend_timeout(self, start_time):
if _ronce_helpers.handle_no_attend_timeout(self, start_time):
return
# 0.1. 若启用高价值预约:先处理"是否需要回退到预约直播间"
try:
reservation_check_start = time.time()
self._log_kv("预约", "开始预约检查", timestamp=reservation_check_start)
# 每次开始运行时丢弃旧的预约队列,不加载状态文件
fudai_run_blocks.maybe_clear_reservation_queue_on_first_run(self)
high_value_enabled = getattr(self, "high_value_fudai_enabled", False)
reservations_list = getattr(self, "reservations", None)
reservations_count = len(reservations_list) if reservations_list else 0
# 添加详细的调试日志,确认预约回退逻辑的触发条件
fudai_run_blocks.log_reservation_trigger_check(
self, high_value_enabled, reservations_list, reservations_count
)
if fudai_run_blocks.process_high_value_reservation_check(
self, start_time, high_value_enabled, reservations_list
):
if _ronce_helpers.handle_reservation_pipeline(self, start_time):
return
if getattr(self, "_current_attending_reservation_fudai", False):
if not getattr(self, "reservations", None):
try:
self._log_kv(
"预约",
"[预约] run_once_basic:预约直参状态残留但队列为空,清除状态并回到正常流程",
reason="stale_direct_attend_without_reservations",
)
except Exception:
pass
try:
self._current_attending_reservation_fudai = False
self.reservation_after_action_pending = False
self.reservation_focus_until_ts = 0.0
except Exception:
pass
_ronce_helpers.run_once_basic_post_reservation(self, start_time)
return
except Exception:
pass
# 检查是否刚刚记录了预约,如果是,强制切换直播间,避免在同一直播间循环
if fudai_run_blocks.handle_just_recorded_reservation(self, start_time):
return
# 预约检查耗时记录
reservation_elapsed = time.time() - reservation_check_start
self._log_kv("预约", f"预约检查完成,耗时: {reservation_elapsed:.3f}s")
# 0.5. 检查是否需要跳过阶段检测,直接查找福袋(点击参与抽奖后)
if fudai_run_blocks.handle_skip_stage_diagnosis(self, start_time):
return
# 1. 截图 + 阶段诊断
ok, screenshot_elapsed = fudai_run_blocks.take_screenshot_with_retries(
self, start_time, max_retries=3
)
if not ok:
return
stage, seen = fudai_run_blocks.diagnose_stage_with_logging(
self, start_time, screenshot_elapsed
)
# 1.5. 检测是否意外返回桌面(不在抖音前台),若是则尝试恢复
if fudai_run_blocks.handle_desktop_recovery(self):
return
# 2. 诊断后分支(弹窗检测已合并到阶段诊断中)
# 2.0. 高价值房间重访检查(在处理其他状态之前)
if fudai_run_blocks.handle_high_value_room_revisit(self, start_time):
return
# 处理 stage 分发
if fudai_run_blocks.dispatch_stage(self, stage, seen, start_time):
try:
self._log_kv(
"预约",
"[预约] run_once_basic:预约回退已就绪,切换到直接参与流程",
)
except Exception:
pass
self._handle_reservation_direct_attend()
return
_ronce_helpers.run_once_basic_post_reservation(self, start_time)
def _check_lottery_result_by_ocr(self) -> Optional[str]:
"""通过OCR识别开奖结果按钮区域,返回识别到的文本类型。"""
@@ -919,166 +710,10 @@ class fudai_analyse:
# pylint: disable=too-many-nested-blocks
def _handle_in_fudai_detail(self) -> None:
"""已经在福袋详情页:只跑详情识别 + 是否参与的基础逻辑。"""
start_time = time.time()
fudai_detail_blocks.log_entry_flags(self)
# 注意:点击参与抽奖后会自动关闭详情页,下次循环会跳过阶段检测直接查找福袋
# 检查连续参与失败次数,避免卡死
if fudai_detail_blocks.handle_too_many_consecutive_failures(self):
return
# 步骤1:检查是否是第二次打开福袋详情
step1_start = time.time()
if fudai_detail_blocks.handle_second_open_attend(self, start_time, step1_start):
return
is_second_open = getattr(self, "_fudai_detail_first_read", False)
if is_second_open:
# 第二次打开但 handle_second_open_attend 返回 False(无详情数据需要重读,
# 或参与函数抛错),落入第一次打开路径继续处理
detail = fudai_detail_blocks.reread_detail_for_second_open_fallthrough(self)
skip = False
skip_reason = ""
else:
detail, should_return, skip, skip_reason = (
fudai_detail_blocks.perform_first_open_read_validate_filter(
self, start_time
)
)
if should_return:
return
# 检查是否是优惠券弹窗、观看任务或识别错误:如果检测到,应该直接跳过,不继续处理
if fudai_detail_blocks.handle_status_based_early_return(self, start_time):
return
if fudai_detail_blocks.handle_task_count_zero_error(self, start_time):
return
# 如果成功读取,重置失败计数
try:
self._fudai_detail_consecutive_failures = 0
except Exception:
pass
# 额外验证:使用验证函数检查数据合理性
if fudai_detail_blocks.handle_extra_validation(self, detail, start_time):
return
# 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误
if fudai_detail_blocks.handle_invalid_detail_fallback(self, detail, start_time):
return
# 记录参与前的状态
attend_before_ts = getattr(self, "_last_successful_attend_ts", 0.0) or 0.0
# 记录当前福袋的 future_ts,供 attend_choujiang 使用
fudai_detail_blocks.extract_future_ts_from_detail(self, detail)
# 重置详情关闭标志
try:
self._detail_closed_by_attend = False
except Exception:
pass
# 步骤4:参与决策
step4_start = time.time()
# 执行参与决策
if detail is None:
if fudai_detail_blocks.handle_detail_is_none(self, start_time):
return
join_result = douyin_fudai_core.basic_join_decision(
self, detail, (skip, skip_reason)
)
# 检查是否参与成功:如果 _last_successful_attend_ts 刚刚更新,说明参与成功
if fudai_detail_blocks.handle_attend_success_post_processing(
self, detail, attend_before_ts, start_time, step4_start, join_result
):
return
from douyin.core.fudai_modules.live_room_handlers import handle_in_fudai_detail as _impl
return _impl(self)
def _handle_live_room_has_or_not_fudai(self) -> None:
"""在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定"继续找/切换/养号"."""
start_time = time.time()
# 设置当前参与的福袋类型为高价值福袋(非预约)
self._current_attending_reservation_fudai = False
# 先检查是否已经在福袋详情页(可能阶段诊断没有正确识别)
# 如果已验证过详情页但任务数为0,说明详情页正在加载,不应该再次查找福袋
try:
already_verified = bool(
getattr(self, "_fudai_detail_verified", False) or False
)
if already_verified:
try:
self._log_kv(
"流程",
"_handle_live_room_has_or_not_fudai:已验证过详情页,直接处理详情,不查找福袋",
)
except Exception:
pass
# 直接调用详情处理逻辑,不查找福袋
self._handle_in_fudai_detail()
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_live_room_has_or_not_fudai完成(已验证详情页)",
elapsed_seconds=round(elapsed, 2),
)
return
except Exception:
pass
# 检查是否在锁定期内,且时间窗口未到,避免重复打开福袋详情
if fudai_detail_blocks.should_skip_search_in_lock_period(self, start_time):
return
room_pos_ref: List[int] = [0]
opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
if not opened:
# 无福袋,交给 flow_control 的“无福袋处理”逻辑
# 根据配置决定是否允许切换直播间(needswitch=False 时只等待不切房)
try:
need_switch_config = bool(getattr(self, "needswitch", True))
except Exception:
need_switch_config = True
wait_times_ref = [0]
swipe_times_ref = [0]
reservation_focus_until_ts_ref = [0.0]
reset_to_list_after_reservations_ref = [False]
douyin_flow_control.handle_no_fudai_situation(
self,
x=0,
swipe_times=0,
wait_times_ref=wait_times_ref,
needswitch=need_switch_config,
reservation_focus_until_ts=0.0,
reservations=[],
room_pos=room_pos_ref[0],
post_switch_delay_s=1.5,
swipe_up_switch_callback=self.swipe_up_to_next_live,
swipe_down_back_callback=lambda: None,
sort_reservations_callback=lambda: None,
clear_reservations_callback=lambda: None,
write_state_callback=lambda: None,
back_to_list_callback=lambda: None,
into_list_callback=lambda: None,
reservation_focus_until_ts_ref=reservation_focus_until_ts_ref,
reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref,
swipe_times_ref=swipe_times_ref,
)
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_live_room_has_or_not_fudai完成(无福袋)",
elapsed_seconds=round(elapsed, 2),
)
return
# 成功打开详情:调用同一套详情处理逻辑
self._handle_in_fudai_detail()
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_live_room_has_or_not_fudai完成(成功打开详情)",
elapsed_seconds=round(elapsed, 2),
)
"""在直播间:寻找福袋图标;有则点开详情,无则交给 flow_control 决定继续策略。"""
from douyin.core.fudai_modules.live_room_handlers import handle_live_room_has_or_not_fudai as _impl
return _impl(self)
-6
View File
@@ -10,9 +10,6 @@ from .fudai_popup_handler import PopupHandlerMixin
from .fudai_lottery_result import LotteryResultMixin
from .fudai_room_utils import RoomUtilsMixin
from .fudai_main_logic import MainLogicMixin
from . import fudai_run_blocks
from . import fudai_detail_blocks
from . import fudai_image_helpers
__all__ = [
"BaseFudaiMixin",
@@ -23,7 +20,4 @@ __all__ = [
"LotteryResultMixin",
"RoomUtilsMixin",
"MainLogicMixin",
"fudai_run_blocks",
"fudai_detail_blocks",
"fudai_image_helpers",
]
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,91 @@
"""douyin/core/fudai_modules/fudai_device_control - 共享 ADB 设备操作
抽出 handle_detail_helpers 中重复 2 次的兜底 swipe 逻辑:
- _handle_error_status (L266-318)
- _fallback_swipe_up (L1187-1239)
两处都做"没有 swipe_up_to_next_live 时直接 ADB shell input swipe,失败再回退到
operation.swipe"。提到这里统一管理。
"""
from __future__ import annotations
import os
import subprocess
from typing import Any
def fallback_swipe_up_via_adb(self: Any) -> None:
"""没有 swipe_up_to_next_live 时用 ADB shell input swipe 兜底切换直播间。
流程:
1. 按 self.resolution_ratio_x/y(默认 1080x2400)计算起止坐标
2. 优先调用 self.operation._adb_path() 获取 adb 路径
3. 直接 subprocess.run ADB shell input swipe
4. 任何异常 → 回退到 self.operation.swipe(...)
主要用于 _handle_error_status 的"连续 task_count_zero≥3 强制切房"分支
和 _fallback_swipe_up 的"没有 swipe_up_to_next_live 时兜底"。
"""
try:
rx = int(getattr(self, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(self, "resolution_ratio_y", 2400) or 2400)
except Exception:
rx, ry = 1080, 2400
start_x = 540 * rx // 1080
start_y = 1200 * ry // 2400
end_x = 540 * rx // 1080
end_y = 600 * ry // 2400
try:
if hasattr(self.operation, "_adb_path"):
adb_cmd = self.operation._adb_path()
else:
adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb"
if adb_cmd.startswith('"') and adb_cmd.endswith('"'):
adb_cmd = adb_cmd[1:-1]
cmd = [
adb_cmd,
"-s",
str(self.device_id),
"shell",
"input",
"swipe",
str(int(start_x)),
str(int(start_y)),
str(int(end_x)),
str(int(end_y)),
"300",
]
subprocess.run(
cmd,
timeout=5.0,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
except Exception:
# 回退到 operation.swipe
self.operation.swipe(
self.device_id,
start_x,
start_y,
end_x,
end_y,
300,
)
def swipe_up_or_fallback(self: Any) -> None:
"""优先调 self.swipe_up_to_next_live(),否则走 fallback_swipe_up_via_adb 兜底。
替代 handle_detail_helpers 中 L266-318 的内联兜底实现。
"""
try:
if hasattr(self, "swipe_up_to_next_live"):
self.swipe_up_to_next_live()
return
except Exception:
pass
fallback_swipe_up_via_adb(self)
@@ -1,279 +0,0 @@
"""douyin_fudai 实例方法的辅助函数(图片/截图等)。
把 fudai_analyse 里相对独立的图片处理逻辑抽出来,便于单测与复用。
"""
from __future__ import annotations
import io
import logging
import os
import time
from typing import Any, Optional
from PIL import Image # type: ignore[import]
_LOGGER = logging.getLogger("douyin.core.fudai_modules.fudai_image_helpers")
def _read_screenshot_with_validation(
analyser: Any, pic_path: str, max_attempts: int = 6
) -> Optional[bytes]:
"""以原子方式读取截图字节,最多重试 max_attempts 次。
每次读取后用 PNG 头/IEND 尾 + PIL.verify 做基本校验,避免读到半写入文件。
返回完整字节,或 None(多次重试仍未读到完整文件)。
"""
data: Optional[bytes] = None
for _attempt in range(max_attempts):
try:
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
except Exception:
pass
if not os.path.exists(pic_path):
time.sleep(0.08)
continue
sz = os.path.getsize(pic_path)
if sz < 1024:
time.sleep(0.08)
continue
with open(pic_path, "rb") as f:
data = f.read()
if not data or not data.startswith(b"\x89PNG"):
data = None
time.sleep(0.08)
continue
if b"IEND" not in data[-512:]:
data = None
time.sleep(0.08)
continue
try:
img_test = Image.open(io.BytesIO(data))
img_test.verify()
except Exception:
data = None
time.sleep(0.08)
continue
break
except Exception:
data = None
time.sleep(0.08)
return data
def _open_image_or_retry(
analyser: Any, data: bytes, pic_path: str
) -> Optional[Image.Image]:
"""先用 data 解析图片;失败则尝试重新读取一次 pic_path 再解析。"""
from PIL import UnidentifiedImageError # type: ignore[import]
try:
img = Image.open(io.BytesIO(data))
img.load()
return img
except UnidentifiedImageError:
return None
except Exception:
pass
try:
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
except Exception:
pass
with open(pic_path, "rb") as f:
data2 = f.read()
if (
data2
and data2.startswith(b"\x89PNG")
and b"IEND" in data2[-512:]
):
try:
img = Image.open(io.BytesIO(data2))
img.load()
return img
except Exception:
return None
return None
except Exception:
return None
def capture_roi_screenshot(
analyser: Any,
label: str,
sx: int,
sy: int,
size: int,
screenshot_path: Optional[str] = None,
) -> str:
"""捕获以 (sx,sy) 为中心、边长为 size 的 ROI 截图,保存到 ``pic/`` 并返回路径。
返回 ROI 图片路径(绝对路径),失败返回空字符串。
"""
try:
from douyin.core import path_config
if screenshot_path is None:
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
except Exception:
pass
pic_path = path_config.get_screenshot_path()
else:
pic_path = screenshot_path
if not os.path.exists(pic_path):
return ""
half = int(size // 2)
left = int(max(0, sx - half))
top = int(max(0, sy - half))
right = int(sx + half)
bottom = int(sy + half)
data = _read_screenshot_with_validation(analyser, pic_path)
if not data:
return ""
img = _open_image_or_retry(analyser, data, pic_path)
if img is None:
return ""
w, h = img.size
left = max(0, min(left, w - 1))
top = max(0, min(top, h - 1))
right = max(1, min(right, w))
bottom = max(1, min(bottom, h))
roi = img.crop((left, top, right, bottom))
out_dir = path_config.get_pic_dir()
os.makedirs(out_dir, exist_ok=True)
fname = (
f"roi_{label}_{getattr(analyser, '_run_id', 'run')}_{int(time.time())}.png"
)
out_path = os.path.join(out_dir, fname)
roi.save(out_path)
return out_path
except Exception:
try:
analyser._log_kv(
"截图",
"_capture_roi_screenshot 失败",
label=label,
sx=sx,
sy=sy,
size=size,
)
except Exception:
pass
return ""
def _correlation_score(a_flat, b_flat) -> float:
"""计算两个等长 1D 数组的归一化相关系数(去均值后点积/范数乘积)。"""
import numpy as np
a = a_flat - a_flat.mean()
b = b_flat - b_flat.mean()
denom = np.linalg.norm(a) * np.linalg.norm(b)
if denom <= 1e-6:
return -1.0
return float(np.dot(a, b) / denom)
def _sliding_search_best_score(roi_gray, tpl_gray) -> float:
"""以 step ≈ 模板边长 // 6 的步长在 ROI 中滑动搜索最佳相关系数。"""
ih, iw = roi_gray.shape
th, tw = tpl_gray.shape
best = -1.0
step_y = max(1, th // 6)
step_x = max(1, tw // 6)
for y in range(0, ih - th + 1, step_y):
for x in range(0, iw - tw + 1, step_x):
window = roi_gray[y : y + th, x : x + tw]
score = _correlation_score(window.flatten(), tpl_gray.flatten())
if score > best:
best = score
return best
def match_icon_template(
analyser: Any,
roi_path: str,
template_path: str,
threshold: Optional[float] = None,
):
"""对比 ROI 与模板,返回 (detected: bool, score: float)。
使用 PIL + numpy 计算归一化相关系数作为匹配分数(-1..1)。
threshold 不传时使用 analyser.yanghao_icon_match_threshold(默认 0.70)。
出错或文件缺失返回 (False, 0.0)。
"""
import numpy as np
try:
if not roi_path or not os.path.exists(roi_path):
return False, 0.0
if not template_path or not os.path.exists(template_path):
return False, 0.0
roi_img = Image.open(roi_path).convert("RGB")
tpl_img = Image.open(template_path).convert("RGB")
rw, rh = roi_img.size
tw, th = tpl_img.size
if tw > rw or th > rh:
scale = min(rw / tw, rh / th, 1.0)
new_w = max(1, int(tw * scale))
new_h = max(1, int(th * scale))
tpl_img = tpl_img.resize((new_w, new_h), Image.Resampling.LANCZOS)
tw, th = tpl_img.size
roi_gray = np.asarray(roi_img.convert("L"), dtype=np.float32)
tpl_gray = np.asarray(tpl_img.convert("L"), dtype=np.float32)
used_thr = (
float(threshold)
if threshold is not None
else float(getattr(analyser, "yanghao_icon_match_threshold", 0.70) or 0.70)
)
# 同尺寸:直接计算
if roi_gray.shape == tpl_gray.shape:
score = _correlation_score(roi_gray.flatten(), tpl_gray.flatten())
return bool(score >= used_thr), float(score)
# 模板小于 ROI:先尝试中心裁剪比对,分数足够好直接返回
ih, iw = roi_gray.shape
th, tw = tpl_gray.shape
if ih >= th and iw >= tw:
cy = ih // 2 - th // 2
cx = iw // 2 - tw // 2
cy = max(0, min(cy, ih - th))
cx = max(0, min(cx, iw - tw))
window = roi_gray[cy : cy + th, cx : cx + tw]
score = _correlation_score(window.flatten(), tpl_gray.flatten())
if score >= 0.55:
return bool(score >= used_thr), float(score)
# 退回到滑动搜索
best = _sliding_search_best_score(roi_gray, tpl_gray)
if best < -0.5:
return False, 0.0
return bool(best >= used_thr), float(best)
except Exception:
try:
analyser._log_kv(
"检测",
"_match_icon_template 异常",
roi_path=roi_path,
template_path=template_path,
)
except Exception:
pass
return False, 0.0
@@ -27,13 +27,15 @@ class RoomUtilsMixin:
self, target_title, target_title_raw
)
def _record_room_title_and_pos(self) -> None:
def _record_room_title_and_pos(self) -> bool:
"""记录当前直播间的标题和位置到运行时映射表。
用于预约回退校验时验证位置信息。
"""
from douyin.reservation import douyin_reservation_handler
douyin_reservation_handler.ReservationHandler.record_room_title_and_pos(self)
return bool(
douyin_reservation_handler.ReservationHandler.record_room_title_and_pos(self)
)
def _seek_reservation_room(self, item: dict[str, Any]) -> bool:
"""根据预约记录里的 pos_seen 与当前 room_pos 进行回退,靠近目标直播间。
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,95 @@
"""fudai_choujiang 运行循环辅助逻辑。"""
from __future__ import annotations
import os
import time
from datetime import datetime
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..douyin_fudai import fudai_analyse
def _append_actions_end_log(reason_text: str) -> None:
"""写入 actions.log 的运行结束记录。"""
try:
from douyin.core import path_config as _pc
actions_log_path = _pc.get_actions_log_path()
except Exception:
actions_log_path = os.path.normpath(
os.path.join(os.path.dirname(__file__), "..", "..", "..", "logs", "actions.log")
)
try:
log_dir = os.path.dirname(actions_log_path)
if log_dir:
os.makedirs(log_dir, exist_ok=True)
end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
with open(actions_log_path, "a", encoding="utf-8-sig", errors="replace") as f:
f.write("=" * 80 + "\n")
f.write(f"{end_time} - [GUI] - [运行] 程序运行结束({reason_text})\n")
f.flush()
except Exception:
pass
def _run_once_with_recover(self: "fudai_analyse") -> bool:
"""执行单轮 run_once_basic;返回 True 表示继续,False 表示中断退出。"""
try:
self.run_once_basic()
return True
except KeyboardInterrupt:
try:
self._log_kv("循环", "收到中断信号,退出循环")
except Exception:
pass
_append_actions_end_log("中断退出")
return False
except Exception as exc:
try:
self._log_kv(
"循环",
"run_once_basic 异常",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
try:
self.operation.delay(2.0)
except Exception:
time.sleep(2.0)
return True
def run_timed_loop(self: "fudai_analyse", wait_minutes: int) -> None:
"""定时运行模式。"""
end_ts = time.time() + int(wait_minutes) * 60
while time.time() < end_ts:
ok = _run_once_with_recover(self)
if not ok:
raise KeyboardInterrupt()
try:
self.operation.delay(1.0)
except Exception:
time.sleep(1.0)
_append_actions_end_log("时间到")
def run_infinite_loop(self: "fudai_analyse") -> None:
"""无限循环运行模式。"""
try:
self._log_kv("循环", "进入无限循环模式(wait_minutes <= 0)")
except Exception:
pass
while True:
ok = _run_once_with_recover(self)
if not ok:
raise KeyboardInterrupt()
try:
self.operation.delay(1.0)
except Exception:
time.sleep(1.0)
@@ -0,0 +1,255 @@
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..douyin_fudai import fudai_analyse
def check_skip_and_handle(
self: "fudai_analyse", detail, step2_start: float, start_time: float
) -> str:
"""筛选检查 + 高价值预约 + 筛选不通过切房。"""
from douyin.fudai import douyin_fudai_core
try:
skip, skip_reason = douyin_fudai_core.should_skip_fudai_by_config(self, detail)
except Exception as e:
try:
self._log_kv("流程", "_handle_in_fudai_detail:筛选检查异常", error=str(e))
except Exception:
pass
return "continue"
if not skip:
return "continue"
high_value_result = try_high_value_reservation(self, detail, skip, skip_reason, start_time)
if high_value_result == "return":
return "return"
if high_value_result == "continue":
return "continue"
return handle_skip_filter(self, skip_reason, start_time, detail=detail)
def try_high_value_reservation(
self: "fudai_analyse", detail, skip: bool, skip_reason: str, start_time: float
) -> str:
"""高价值倒计时筛选处理。"""
import time
from douyin.fudai import douyin_fudai_core
try:
prize_value_yuan = 0.0
countdown_tuple = None
if isinstance(detail, tuple) and len(detail) >= 6:
_, _, _, _, prize_value_yuan, countdown_tuple = detail
high_value_enabled = bool(getattr(self, "high_value_fudai_enabled", False))
high_value_threshold = float(
getattr(self, "high_value_fudai_threshold_yuan", 500.0) or 500.0
)
is_high_value = (
high_value_enabled
and prize_value_yuan > 0
and prize_value_yuan >= high_value_threshold
and isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 2
and float(countdown_tuple[1] or 0.0) > 0.0
)
if not (is_high_value and skip_reason.startswith("countdown_gt_")):
return "still_skip"
remain_seconds = None
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
try:
now = time.time()
cd_start = float(countdown_tuple[0] or 0.0)
cd_end = float(countdown_tuple[1] or 0.0)
if cd_start > 0 and cd_end > cd_start:
remain_seconds = float(cd_end - now)
except Exception:
pass
join_ahead_seconds = int(getattr(self, "high_value_fudai_join_ahead_seconds", 100) or 120)
if remain_seconds is not None and remain_seconds <= join_ahead_seconds:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:倒计时大于阈值,但剩余秒数在预约参与阈值内,立即参与",
reason=skip_reason,
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
remain_seconds=int(remain_seconds),
join_ahead_threshold=join_ahead_seconds,
)
except Exception:
pass
return "continue"
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:倒计时大于阈值,但价值达到高价值阈值,记录预约",
reason=skip_reason,
value_yuan=prize_value_yuan,
threshold=high_value_threshold,
remain_seconds=(int(remain_seconds) if remain_seconds is not None else None),
join_ahead_threshold=join_ahead_seconds,
level="DEBUG",
)
except Exception:
pass
reservation_recorded = False
try:
reservation_recorded = bool(douyin_fudai_core.basic_join_decision(self, detail))
except Exception as e:
try:
self._log_kv("流程", "_handle_in_fudai_detail:记录预约时出错", error=str(e))
except Exception:
pass
reservation_recorded = False
if not reservation_recorded:
return "still_skip"
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(记录预约)", elapsed_seconds=round(elapsed, 2))
return "return"
except Exception as e:
try:
self._log_kv("流程", "_handle_in_fudai_detail:高价值检查异常", error=str(e))
except Exception:
pass
return "still_skip"
def _summarize_detail_for_skip(detail) -> dict:
info = {
"fudai_content": "",
"prize_value_yuan": None,
"remain_seconds": None,
"lottery_result_expected_ts": None,
}
try:
if isinstance(detail, tuple):
if len(detail) >= 1:
info["fudai_content"] = str(detail[0] or "")[:60]
if len(detail) >= 5:
try:
info["prize_value_yuan"] = float(detail[4] or 0.0)
except Exception:
info["prize_value_yuan"] = None
if len(detail) >= 6:
countdown_tuple = detail[5]
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
import time
future_ts = float(countdown_tuple[1] or 0.0)
info["lottery_result_expected_ts"] = future_ts if future_ts > 0 else None
if future_ts > 0:
info["remain_seconds"] = max(0, int(future_ts - time.time()))
except Exception:
pass
return info
def handle_skip_filter(
self: "fudai_analyse",
skip_reason: str,
start_time: float,
detail=None,
) -> str:
"""普通筛选不通过:关详情 + 按需切直播间。返回 return。"""
import time
from douyin.fudai import douyin_fudai_detail
is_countdown_zero = str(skip_reason or "").strip() == "countdown_zero"
try:
detail_info = _summarize_detail_for_skip(detail)
self._log_kv(
"筛选",
"_handle_in_fudai_detail:筛选不通过,确认未发送参与点击",
decision="skip_without_attend",
skip_reason=skip_reason,
attend_click_sent=False,
waiting_for_lottery=bool(getattr(self, "_waiting_for_lottery_result", False)),
button_status=str(getattr(self, "_fudai_button_status", "") or ""),
button_text=str(getattr(self, "_fudai_button_text", "") or ""),
**detail_info,
)
except Exception:
pass
try:
self._log_kv("流程", "_handle_in_fudai_detail:第一次打开时筛选不通过,直接跳过", skip_reason=skip_reason)
except Exception:
pass
if is_countdown_zero:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:倒计时归零,关闭详情页",
skip_reason=skip_reason,
)
except Exception:
pass
try:
douyin_fudai_detail.close_fudai_detail(self)
except Exception:
pass
else:
try:
douyin_fudai_detail.close_fudai_detail(self)
except Exception:
pass
try:
needswitch = bool(getattr(self, "needswitch", True))
except Exception:
needswitch = True
if needswitch and not is_countdown_zero:
try:
self._log_kv("流程", "_handle_in_fudai_detail:筛选不通过后切换直播间", skip_reason=skip_reason)
except Exception:
pass
try:
if hasattr(self, "swipe_up_to_next_live"):
self.swipe_up_to_next_live()
else:
fallback_swipe_up(self)
except Exception:
pass
_clear_task_count_flag(self)
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(筛选不通过)", elapsed_seconds=round(elapsed, 2))
return "return"
def fallback_swipe_up(self: "fudai_analyse") -> None:
"""没有 swipe_up_to_next_live 时的兜底 swipe。"""
from douyin.core.fudai_modules.fudai_device_control import fallback_swipe_up_via_adb
fallback_swipe_up_via_adb(self)
def _clear_task_count_flag(self: "fudai_analyse") -> None:
"""清除任务数量标志。"""
try:
self._fudai_detail_task_count_from_stage = None
try:
self._log_kv(
"福袋详情",
"_handle_in_fudai_detail:清除任务数量标志",
log_type="DEBUG",
)
except Exception:
pass
except Exception:
pass
@@ -0,0 +1,128 @@
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..douyin_fudai import fudai_analyse
def handle_first_open_branch(self: "fudai_analyse", start_time: float) -> bool:
"""第一次打开福袋详情分支。"""
from douyin.fudai import douyin_fudai_detail
from .handle_detail_filter import check_skip_and_handle
step2_start = __import__("time").time()
detail = douyin_fudai_detail.read_fudai_detail_with_retries(
self,
fudai_x=0,
read_once_callback=douyin_fudai_detail.read_fudai_detail_once,
close_detail_callback=douyin_fudai_detail.close_fudai_detail,
ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open,
)
if not (detail and isinstance(detail, tuple) and len(detail) >= 6):
try:
self._log_kv("流程", "_handle_in_fudai_detail:第一次打开时详情数据无效,跳过")
except Exception:
pass
return True
if validate_first_open_detail(self, detail, step2_start, start_time):
return True
branch_result = check_skip_and_handle(self, detail, step2_start, start_time)
if branch_result == "return":
try:
self._fudai_detail_first_read = False
self._last_fudai_detail_tuple = None
except Exception:
pass
return True
try:
current_status = str(getattr(self, "_last_fudai_detail_status", "") or "")
if current_status not in {"coupon_popup", "watch_task", "validation_failed", "error"}:
self._last_fudai_detail_tuple = detail
self._fudai_detail_first_read = True
if detail and isinstance(detail, tuple) and len(detail) >= 1:
self._current_fudai_content = str(detail[0] if detail[0] else "")
self._log_kv(
"流程",
"_handle_in_fudai_detail:福袋详情识别成功",
fudai_content=(detail[0] if len(detail) > 0 else "")[:50],
prize_value_yuan=float(detail[4] if len(detail) > 4 else 0.0),
)
except Exception:
pass
return False
def validate_first_open_detail(
self: "fudai_analyse", detail, step2_start: float, start_time: float
) -> bool:
"""第一次打开详情的数据验证。"""
import time
from douyin.fudai import douyin_fudai_detail
try:
is_valid, reason = douyin_fudai_detail.validate_fudai_detail(detail, self)
except Exception:
return False
if is_valid:
return False
actionable = {"可以参与", "需要加入粉丝团", "需要评论", "需要观看", "已参与"}
button_status = getattr(self, "_fudai_button_status", None)
if button_status in actionable:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:数据验证失败但按钮可操作,继续参与",
validation_reason=reason,
button_status=button_status,
)
except Exception:
pass
return False
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:第一次打开时数据验证失败,跳过",
validation_reason=reason,
)
except Exception:
pass
try:
douyin_fudai_detail.close_fudai_detail(self)
except Exception:
pass
try:
self._fudai_detail_first_read = False
self._last_fudai_detail_tuple = None
except Exception:
pass
step2_elapsed = (time.time() - step2_start) * 1000
self._log_kv("详情处理", "步骤2[读取福袋详情]-完成", 总耗时毫秒=step2_elapsed)
_clear_task_count_flag(self)
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_in_fudai_detail完成(数据验证失败)", elapsed_seconds=round(elapsed, 2))
return True
def _clear_task_count_flag(self: "fudai_analyse") -> None:
try:
self._fudai_detail_task_count_from_stage = None
try:
self._log_kv(
"福袋详情",
"_handle_in_fudai_detail:清除任务数量标志",
log_type="DEBUG",
)
except Exception:
pass
except Exception:
pass
@@ -0,0 +1,653 @@
"""_handle_in_fudai_detail 辅助逻辑
把 _handle_in_fudai_detail 的若干独立段落抽出来,保持原语义和日志不变。
helper 返回 True 表示主流程应当结束本轮(caller `return`)。
"""
from __future__ import annotations
import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..douyin_fudai import fudai_analyse
def log_entry_flags(self: "fudai_analyse") -> None:
"""记录进入 _handle_in_fudai_detail 时的关键 flags。"""
try:
self._log_kv(
"诊断",
"进入 _handle_in_fudai_detail:记录当前关键 flags",
reservation_after_action_pending=bool(
getattr(self, "reservation_after_action_pending", False)
),
reservation_focus_until_ts=float(
getattr(self, "reservation_focus_until_ts", 0.0) or 0.0
),
waiting_for_lottery=bool(
getattr(self, "_waiting_for_lottery_result", False)
),
room_pos=int(getattr(self, "room_pos", 0) or 0),
)
except Exception:
pass
def handle_consecutive_failures_check(self: "fudai_analyse") -> bool:
"""检查连续参与失败次数。
超过阈值则关闭详情页 + 按需切换直播间 + 重置计数器,并返回 True
表示 caller 应当 `return`。
返回 False 表示尚未达到阈值,继续后续步骤。
"""
consecutive_failures = getattr(self, "_consecutive_attend_failures", 0)
max_consecutive_failures = 5
if consecutive_failures < max_consecutive_failures:
return False
from douyin.fudai import douyin_fudai_detail
try:
self._log_kv(
"参与",
"_handle_in_fudai_detail:连续参与失败次数过多,跳过此福袋",
consecutive_failures=consecutive_failures,
max_allowed=max_consecutive_failures,
)
except Exception:
pass
# 关闭详情页,避免卡死
try:
douyin_fudai_detail.close_fudai_detail(self)
except Exception:
pass
# 连续失败过多时,按需切换直播间
try:
needswitch = bool(getattr(self, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:连续参与失败过多,切换直播间",
)
except Exception:
pass
try:
self.swipe_up_to_next_live()
except Exception:
pass
else:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:连续参与失败过多,单间模式不切换",
)
except Exception:
pass
# 重置计数器,避免影响后续直播间
try:
self._consecutive_attend_failures = 0
except Exception:
pass
return True
def check_last_status_branch(
self: "fudai_analyse", start_time: float
) -> bool:
"""检查 self._last_fudai_detail_status,对 4 种已知状态做相应处理。
支持的状态:
- coupon_popup 检测到优惠券弹窗
- watch_task 检测到"观看 X 分钟"任务
- validation_failed 数据验证失败
- error 其他错误(特别处理 task_count_zero 子情况:连续 3 次强制切直播间)
返回 True 表示已处理某状态,caller 应当 `return`;
返回 False 表示状态正常或不在已知列表,继续后续步骤。
"""
import os
import subprocess
import time
from douyin.fudai import douyin_fudai_detail
try:
last_status = getattr(self, "_last_fudai_detail_status", "")
except Exception:
last_status = ""
if last_status == "coupon_popup":
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:检测到优惠券弹窗,已关闭,跳过后续处理",
)
except Exception:
pass
_clear_task_count_flag(self)
try:
self._last_fudai_detail_status = ""
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(优惠券弹窗)",
elapsed_seconds=round(elapsed, 2),
)
return True
if last_status == "watch_task":
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:检测到'观看X分钟'任务,已在OCR阶段跳过,无需后续处理",
)
except Exception:
pass
_clear_task_count_flag(self)
try:
self._last_fudai_detail_status = ""
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(观看任务)",
elapsed_seconds=round(elapsed, 2),
)
return True
if last_status == "validation_failed":
# 按钮状态为可操作时,即使验证失败也继续走参与流程
_ACTIONABLE_BUTTON_STATUSES = {
"可以参与",
"需要加入粉丝团",
"需要评论",
"需要观看",
"已参与",
}
button_status = getattr(self, "_fudai_button_status", None)
if button_status in _ACTIONABLE_BUTTON_STATUSES:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:验证失败但按钮可操作,继续参与",
button_status=button_status,
)
except Exception:
pass
return False
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:福袋详情数据验证失败,识别出错,跳过后续处理",
)
except Exception:
pass
_clear_task_count_flag(self)
try:
self._last_fudai_detail_status = ""
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(验证失败)",
elapsed_seconds=round(elapsed, 2),
)
return True
if last_status == "error":
return _handle_error_status(self, start_time)
# 未知 / 空状态 → 继续后续步骤
return False
def _clear_task_count_flag(self: "fudai_analyse") -> None:
"""清除任务数量标志,多个 last_status 分支都用到。"""
try:
self._fudai_detail_task_count_from_stage = None
try:
self._log_kv(
"福袋详情",
"_handle_in_fudai_detail:清除任务数量标志",
log_type="DEBUG",
)
except Exception:
pass
except Exception:
pass
def _handle_error_status(self: "fudai_analyse", start_time: float) -> bool:
"""last_status == "error" 时的处理。
特殊子情况:task_count_zero。连续 3 次时强制关详情 + 切直播间避免卡死。
其它 error 不在此函数处理,返回 False。
"""
import os
import subprocess
import time
from douyin.fudai import douyin_fudai_detail
try:
last_extra = getattr(self, "_last_fudai_detail_extra", {})
if not (
isinstance(last_extra, dict)
and last_extra.get("reason") in {"task_count_zero", "not_in_fudai_detail"}
):
return False
# 累加连续失败计数
consecutive_failures = (
getattr(self, "_fudai_detail_consecutive_failures", 0) or 0
)
consecutive_failures += 1
try:
self._fudai_detail_consecutive_failures = consecutive_failures
except Exception:
pass
# 连续失败 < 3:仅记录并返回
if consecutive_failures < 3:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:检测到任务数量为0,跳过后续处理",
consecutive_failures=consecutive_failures,
)
except Exception:
pass
_clear_task_count_flag(self)
try:
self._last_fudai_detail_status = ""
self._last_fudai_detail_extra = {}
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(任务数量为0)",
elapsed_seconds=round(elapsed, 2),
)
return True
# 连续失败 >= 3:强制关详情 + 切直播间
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:连续3次识别到任务数量为0,强制关闭详情页并切换直播间,避免卡死",
consecutive_failures=consecutive_failures,
)
except Exception:
pass
try:
douyin_fudai_detail.close_fudai_detail(self)
self.operation.delay(0.5)
except Exception:
pass
try:
needswitch = bool(getattr(self, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
try:
from douyin.core.fudai_modules.fudai_device_control import (
swipe_up_or_fallback,
)
swipe_up_or_fallback(self)
self.operation.delay(0.5)
except Exception:
pass
# 重置失败计数 + 清除任务数量标志
try:
self._fudai_detail_consecutive_failures = 0
except Exception:
pass
_clear_task_count_flag(self)
try:
self._last_fudai_detail_status = ""
self._last_fudai_detail_extra = {}
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(连续失败)",
elapsed_seconds=round(elapsed, 2),
)
return True
except Exception:
return False
def check_invalid_detail_fallback(
self: "fudai_analyse", detail, start_time: float
) -> bool:
"""兜底检查:detail 内容为空且价值为 0 → 视为无效详情(优惠券或识别错误)。
返回 True 表示已识别为无效详情、清理标志并 log,caller 应当 `return`;
返回 False 表示详情看起来正常,继续后续步骤。
"""
import time
try:
if isinstance(detail, tuple) and len(detail) >= 5:
content = str(detail[0] or "")
try:
prize_value_yuan = float(detail[4] or 0.0)
except (TypeError, ValueError):
prize_value_yuan = 0.0
if not content and prize_value_yuan == 0.0:
# 按钮状态为可操作时,即使详情为空也继续走参与流程
_ACTIONABLE_BUTTON_STATUSES = {
"可以参与",
"需要加入粉丝团",
"需要评论",
"需要观看",
"已参与",
}
button_status = getattr(self, "_fudai_button_status", None)
if button_status in _ACTIONABLE_BUTTON_STATUSES:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:详情为空但按钮可操作,继续参与",
button_status=button_status,
)
except Exception:
pass
return False
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理",
content=content,
prize_value_yuan=prize_value_yuan,
)
except Exception:
pass
# 清除任务数量标志
try:
self._fudai_detail_task_count_from_stage = None
try:
self._log_kv(
"福袋详情",
"_handle_in_fudai_detail:清除任务数量标志",
log_type="DEBUG",
)
except Exception:
pass
except Exception:
pass
try:
self._fudai_detail_first_read = False
self._last_fudai_detail_tuple = None
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(无效详情)",
elapsed_seconds=round(elapsed, 2),
)
return True
except Exception:
pass
return False
def prepare_for_attend(self: "fudai_analyse", detail) -> float:
"""步骤3 末尾:记录参与前状态、提取 future_ts、重置标志。
返回 attend_before_ts —— 给 step4 用来对比 _last_successful_attend_ts
判断是否参与成功。
"""
from typing import Any, Tuple, cast
attend_before_ts = getattr(self, "_last_successful_attend_ts", 0.0) or 0.0
# 记录当前福袋的 future_ts,供 attend_choujiang 使用
countdown_tuple = None
try:
if isinstance(detail, tuple) and len(detail) >= 6:
d_cast: Tuple[Any, ...] = cast(Tuple[Any, ...], detail)
countdown_tuple = d_cast[5]
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2:
future_ts = float(countdown_tuple[1] or 0.0)
if future_ts > 0:
self._current_fudai_future_ts = future_ts
except Exception:
pass
# 重置详情关闭标志
try:
self._detail_closed_by_attend = False
except Exception:
pass
return attend_before_ts
def step4_make_join_decision(
self: "fudai_analyse",
detail,
skip: bool,
skip_reason: str,
attend_before_ts: float,
start_time: float,
) -> None:
"""步骤4:参与决策 + 等待开奖标志设置 + 预约清理 + 关闭详情页。
本函数总是消费完后返回(caller 即 _handle_in_fudai_detail 在调用本函数后
也是方法末尾,不需要再判断返回值)。
"""
import time
from typing import Any, Tuple, cast
from douyin.fudai import douyin_fudai_core
from douyin.reservation import douyin_reservation_logic
step4_start = time.time()
if detail is None:
try:
self._log_kv("参与", "详情数据为 None,无法执行参与决策")
except Exception:
pass
# 清除任务数量标志
try:
self._fudai_detail_task_count_from_stage = None
try:
self._log_kv(
"福袋详情",
"_handle_in_fudai_detail:清除任务数量标志",
log_type="DEBUG",
)
except Exception:
pass
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(详情为None)",
elapsed_seconds=round(elapsed, 2),
)
return
join_result = douyin_fudai_core.basic_join_decision(
self, detail
)
# 检查是否参与成功:如果 _last_successful_attend_ts 刚刚更新,说明参与成功
attend_after_ts = getattr(self, "_last_successful_attend_ts", 0.0) or 0.0
if not (join_result and attend_after_ts > attend_before_ts):
return
# 参与成功,设置等待开奖标志
try:
# 从 detail 中提取倒计时信息
countdown_tuple = None
remain_seconds = 0
future_timestamp = 0.0
if isinstance(detail, tuple) and len(detail) >= 6:
d_cast: Tuple[Any, ...] = cast(Tuple[Any, ...], detail)
countdown_tuple = d_cast[5]
if isinstance(countdown_tuple, tuple) and len(countdown_tuple) >= 2:
# countdown_tuple[1] 是 countdown_end(开奖时间戳)
future_timestamp = float(countdown_tuple[1] or 0.0)
# 计算剩余秒数:结束时间戳 - 当前时间
current_time = time.time()
if future_timestamp > current_time:
remain_seconds = int(future_timestamp - current_time)
if remain_seconds > 0:
try:
current_prize_value = float(detail[4] or 0.0)
except Exception:
current_prize_value = 0.0
# 设置等待开奖标志和预期开奖时间
self._waiting_for_lottery_result = True
self._lottery_result_expected_ts = future_timestamp
self._lottery_wait_start_ts = time.time()
self._lottery_wait_prize_value_yuan = current_prize_value
self._log_kv(
"参与",
"参与成功,设置等待开奖标志,停止其他行为",
remain_seconds=remain_seconds,
future_ts=int(future_timestamp),
prize_value_yuan=current_prize_value,
)
# 检查是否是预约福袋,如果是处理锁定期和移除预约
_handle_reservation_completion(self, future_timestamp)
# 关闭详情页,返回直播间等待开奖
_close_detail_after_attend(self)
# 清除第一次读取标志,下次打开新福袋时重新识别
try:
self._fudai_detail_first_read = False
self._last_fudai_detail_tuple = None
except Exception:
pass
# 清除任务数量标志
try:
self._fudai_detail_task_count_from_stage = None
try:
self._log_kv(
"福袋详情",
"_handle_in_fudai_detail:清除任务数量标志",
log_type="DEBUG",
)
except Exception:
pass
except Exception:
pass
# 步骤4结束计时
step4_elapsed = (time.time() - step4_start) * 1000
self._log_kv(
"详情处理", "步骤4[参与决策]-完成", 总耗时毫秒=step4_elapsed
)
return
else:
self._log_kv("参与", "参与成功但无法获取倒计时,跳过等待")
except Exception as e:
self._log_kv("参与", "设置等待开奖标志时出错", error=str(e))
def _handle_reservation_completion(
self: "fudai_analyse", future_timestamp: float
) -> None:
from .handle_detail_second_open import handle_reservation_completion as _impl
return _impl(self, future_timestamp)
def _close_detail_after_attend(self: "fudai_analyse") -> None:
"""参与成功后关闭详情页(如果 attend_choujiang 还没关)。"""
detail_already_closed = getattr(self, "_detail_closed_by_attend", False)
if not detail_already_closed:
try:
self.operation.click_back(self.device_id)
self.operation.delay(1.0)
self._log_kv("参与", "已关闭详情页,返回直播间等待开奖")
except Exception:
pass
else:
try:
self._log_kv(
"参与",
"详情页已由 attend_choujiang 关闭,跳过返回键点击",
)
except Exception:
pass
# ============================================================
# handle_first_open_branch —— 步骤2 + 步骤3 完整分支
# ============================================================
def handle_second_open_branch(
self: "fudai_analyse", start_time: float, step1_start: float
) -> bool:
from .handle_detail_second_open import handle_second_open_branch as _impl
return _impl(self, start_time, step1_start)
def handle_first_open_branch(
self: "fudai_analyse", start_time: float
) -> bool:
from .handle_detail_first_open import handle_first_open_branch as _impl
return _impl(self, start_time)
def _validate_first_open_detail(
self: "fudai_analyse", detail, step2_start: float, start_time: float
) -> bool:
from .handle_detail_first_open import validate_first_open_detail as _impl
return _impl(self, detail, step2_start, start_time)
def _check_skip_and_handle(
self: "fudai_analyse", detail, step2_start: float, start_time: float
) -> str:
from .handle_detail_filter import check_skip_and_handle as _impl
return _impl(self, detail, step2_start, start_time)
def _try_high_value_reservation(
self: "fudai_analyse", detail, skip: bool, skip_reason: str, start_time: float
) -> str:
from .handle_detail_filter import try_high_value_reservation as _impl
return _impl(self, detail, skip, skip_reason, start_time)
def _handle_skip_filter(
self: "fudai_analyse", skip_reason: str, start_time: float, detail=None
) -> str:
from .handle_detail_filter import handle_skip_filter as _impl
return _impl(self, skip_reason, start_time, detail=detail)
def _fallback_swipe_up(self: "fudai_analyse") -> None:
from .handle_detail_filter import fallback_swipe_up as _impl
return _impl(self)
@@ -0,0 +1,225 @@
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..douyin_fudai import fudai_analyse
def handle_reservation_completion(
self: "fudai_analyse", future_timestamp: float
) -> None:
"""参与成功是预约福袋时:处理锁定期 + 移除已完成的预约。"""
import time
from douyin.reservation import douyin_reservation_logic
try:
if not getattr(self, "reservation_after_action_pending", False):
return
try:
self._log_kv(
"预约",
"[预约] 参与成功,处理锁定期并移除预约",
future_ts=int(future_timestamp),
current_focus_until=int(getattr(self, "reservation_focus_until_ts", 0)),
)
except Exception:
pass
has_other_reservations = False
if hasattr(self, "reservations") and self.reservations:
for r in self.reservations:
try:
r_ft = float(r.get("future_ts") or 0.0)
if r_ft > 0 and abs(r_ft - future_timestamp) >= 5.0:
has_other_reservations = True
break
except Exception:
continue
if has_other_reservations:
protection_until = time.time() + 10.0
self.reservation_focus_until_ts = max(
self.reservation_focus_until_ts, protection_until
)
try:
self._log_kv(
"预约",
"[预约] 参与成功,设置保护期确保依次参与",
protection_seconds=10,
new_focus_until=int(self.reservation_focus_until_ts),
remaining_reservations=len(
[r for r in self.reservations if float(r.get("future_ts", 0)) > 0]
),
)
except Exception:
pass
else:
self.reservation_focus_until_ts = 0.0
try:
self._log_kv(
"预约",
"[预约] 参与成功,清除锁定期(无其他预约)",
future_ts=int(future_timestamp),
)
except Exception:
pass
self.reservation_after_action_pending = False
if hasattr(self, "reservations") and self.reservations:
reservations_to_remove = []
for idx, r in enumerate(self.reservations):
try:
r_ft = float(r.get("future_ts") or 0.0)
if r_ft > 0 and abs(r_ft - future_timestamp) < 5.0:
reservations_to_remove.append(idx)
except Exception:
continue
for idx in reversed(reservations_to_remove):
try:
removed = self.reservations.pop(idx)
try:
self._log_kv(
"预约",
"[预约] 已从队列中移除已完成的预约",
future_ts=int(removed.get("future_ts", 0)),
content=str(removed.get("content", ""))[:50],
)
except Exception:
pass
except Exception:
pass
if self.reservations:
try:
douyin_reservation_logic._sort_reservations_inplace(self.reservations)
except Exception:
pass
except Exception as e:
try:
self._log_kv("预约", "[预约] 清除锁定期和移除预约时出错", error=str(e))
except Exception:
pass
def handle_second_open_branch(
self: "fudai_analyse", start_time: float, step1_start: float
) -> bool:
"""步骤1:第二次打开福袋详情,直接点击参与(跳过验证和内容识别)。"""
import time
from typing import Any, Tuple
from douyin.fudai import douyin_fudai_core, douyin_fudai_detail
try:
self._log_kv("流程", "_handle_in_fudai_detail:第二次打开,直接点击参与,跳过验证和内容识别")
except Exception:
pass
detail = getattr(self, "_last_fudai_detail_tuple", None)
if detail is None or not isinstance(detail, tuple) or len(detail) < 6:
try:
self._log_kv("流程", "_handle_in_fudai_detail:未找到第一次读取的详情数据,重新读取")
except Exception:
pass
detail = douyin_fudai_detail.read_fudai_detail_with_retries(
self,
fudai_x=0,
read_once_callback=douyin_fudai_detail.read_fudai_detail_once,
close_detail_callback=douyin_fudai_detail.close_fudai_detail,
ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open,
)
if detail and isinstance(detail, tuple) and len(detail) >= 6:
current_status = str(getattr(self, "_last_fudai_detail_status", "") or "")
if current_status not in {"coupon_popup", "watch_task", "validation_failed", "error"}:
self._last_fudai_detail_tuple = detail
detail_t: Tuple[Any, ...] = tuple(detail)
self._current_fudai_content = detail_t[0] if len(detail_t) > 0 else ""
else:
try:
self._fudai_detail_first_read = False
except Exception:
pass
try:
current_status = str(getattr(self, "_last_fudai_detail_status", "") or "")
if current_status in {"coupon_popup", "watch_task", "validation_failed", "error"}:
self._fudai_detail_first_read = False
except Exception:
pass
return False
try:
if detail is not None and isinstance(detail, tuple) and len(detail) >= 6:
detail_t = tuple(detail)
countdown_tuple = detail_t[5]
if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 3:
future_ts = float(countdown_tuple[1] or 0.0)
original_seconds = countdown_tuple[2]
if future_ts > 0:
self._current_fudai_future_ts = future_ts
self._current_fudai_content = detail_t[0] if len(detail_t) > 0 else ""
remain_seconds = (
max(0, int(original_seconds or 0))
if original_seconds is not None
else int(future_ts - time.time())
)
self._log_kv(
"参与",
"第二次打开:使用第一次的倒计时信息",
future_ts=int(future_ts),
remain_seconds=remain_seconds,
original_seconds=(int(original_seconds or 0) if original_seconds is not None else None),
)
except Exception as e:
try:
self._log_kv("参与", "第二次打开:设置倒计时信息时出错", error=str(e))
except Exception:
pass
try:
attend_result = douyin_fudai_core.attend_choujiang(self)
if attend_result:
self._log_kv("参与", "第二次打开:直接点击参与成功", result="参与成功")
self._consecutive_attend_failures = 0
else:
self._log_kv("参与", "第二次打开:直接点击参与失败", result="参与失败")
self._consecutive_attend_failures = getattr(self, "_consecutive_attend_failures", 0) + 1
try:
self._fudai_detail_first_read = False
self._last_fudai_detail_tuple = None
except Exception:
pass
_clear_task_count_flag(self)
step1_elapsed = (time.time() - step1_start) * 1000
self._log_kv("详情处理", "步骤1[检查是否第二次打开]-完成", 总耗时毫秒=step1_elapsed)
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(第二次打开直接参与)",
elapsed_seconds=round(elapsed, 2),
attend_result=attend_result,
)
return True
except Exception as e:
self._log_kv("参与", "第二次打开:直接点击参与异常", error=str(e))
return False
def _clear_task_count_flag(self: "fudai_analyse") -> None:
try:
self._fudai_detail_task_count_from_stage = None
try:
self._log_kv("福袋详情", "_handle_in_fudai_detail:清除任务数量标志", log_type="DEBUG")
except Exception:
pass
except Exception:
pass
+326
View File
@@ -0,0 +1,326 @@
"""douyin/core/fudai_modules/init_helpers - fudai_analyse 配置默认值与运行时状态初始化
把 fudai_analyse.__init__ 中"配置字段默认值 + 运行时状态字段初始化 + 状态文件
路径解析"的整段抽出来。原 __init__ 保留:设备/分辨率、operation 实例、日志系统
初始化、_run_id、_log_kv 等需要早期就绪的核心字段。
入口:apply_fudai_defaults(self) 一次性把所有"普通字段默认值"应用到实例。
"""
from __future__ import annotations
import json
import os
import time
from typing import Any, Optional, Tuple
def apply_fudai_defaults(self: Any) -> None:
"""把 fudai_analyse 实例的所有配置默认值 + 运行时状态字段一次性初始化。
依赖前提(必须由 caller 在调用前已设置):
- self.operation, self.device_id, self.y_pianyi
- self.resolution_ratio_x, self.resolution_ratio_y
- self._log_kv 等日志相关字段
本函数不调用 load_config(让 caller 决定时机)。
"""
self._forced_reservation_detail = None
self._forced_reservation_fudai_x = None
# 进入直播间后诊断与阶段流转所需的一些状态
self._last_diag_stage = "INIT"
self._last_diag_seen = "-"
self._last_diag_ts = 0.0
# 30 分钟超时相关:记录最后一次成功参与福袋的时间
self._last_successful_attend_ts = 0.0
self._no_attend_timeout_minutes = 30.0
self._run_start_ts = time.time()
# 预约状态上次写盘时间(初始化以避免 attribute-defined-outside-init 警告)
self._reservations_state_last_write_ts = 0.0
self.last_fudai_x = 0 # 上次检测到的福袋图标 X 坐标(用于优化搜索)
# 与配置相关的核心字段
self.contains_not_want = []
self.contains_want = []
self.min_prize_value_yuan = 0.0
self.min_participants = 0
self.max_participants = 0
self.skip_if_countdown_gt_seconds = 900
self.skip_if_countdown_lt_seconds = 0
self.no_fudai_watchdog_enabled = False
# 福袋图标检测节流相关默认值
self.fudai_icon_retry_delay_seconds = 0.6
self.fudai_icon_max_wait_seconds = 5.0
self.fudai_exit_after_misses = 999999
self.enable_back_on_misses = False
self.fudai_click_wait_seconds = 1.0
self.switch_room_wait_after_stage_diag_seconds = 7.0
self.swipe_duration_ms = 600
self.fudai_find_max_attempts = 10 # 已废弃,保留兼容性
# 优化查找器相关配置
self.fudai_finder_optimized_enabled = True
self.fudai_click_verify_enabled = True
self.fudai_find_max_retries = 3
self.screenshot_diagnose_min_interval_seconds = 8.0
self.lucky_draw_red_ratio_threshold = 0.9
self.coupon_template_match_threshold = 0.75
self.attend_button_red_ratio_threshold = 0.25
self.fansclub_join_red_ratio_threshold = 0.25
self.live_room_match_threshold = 0.8
self.fudai_detail_body_bluepurple_threshold = 0.45
self.fudai_detail_body_dark_threshold = 0.35
self.fudai_task_status_template_threshold = 0.26
self.fudai_template_match_enabled = False
self.fudai_template_match_threshold = 0.7
self.fudai_detail_ui_mode = "auto"
self.fudai_detail_ocr_content_enabled = True
self.fudai_detail_ocr_value_enabled = True
self.fudai_detail_ocr_countdown_enabled = True
self.fudai_detail_ocr_task_enabled = True
self.fudai_detail_ocr_task_count_enabled = True
self.fudai_detail_ocr_button_enabled = True
self.fudai_detail_ocr_participants_enabled = False
self.fudai_detail_ocr_live_title_enabled = True
self.fudai_detail_task_ocr_in_critical_path_enabled = False
self.fudai_detail_countdown_full_ocr_in_critical_path_enabled = False
self.fudai_detail_info_line_ocr_in_critical_path_enabled = False
self.fudai_detail_ocr_workers = 1
self.pixel_detect_fudai_icon_enabled = True
self.pixel_detect_coupon_popup_enabled = True
self.pixel_detect_shopping_redpacket_enabled = True
self.pixel_detect_lottery_result_enabled = True
self.pixel_detect_attend_button_enabled = True
self.pixel_detect_fansclub_join_enabled = True
self.pixel_detect_fudai_detail_enabled = True
self.pixel_detect_live_room_enabled = True
self.ocr_lottery_result_enabled = True
self.ocr_coupon_popup_enabled = True
self.ocr_shopping_redpacket_enabled = False
self.ocr_stage_page_enabled = True
# 高价值福袋 / 预约相关配置
self.high_value_fudai_enabled = False
self.high_value_fudai_threshold_yuan = 500.0
self.high_value_fudai_join_ahead_seconds = 100
self.high_value_fudai_max_swipe_back = 35
self.high_value_fudai_max_reservations = 3
self.high_value_fudai_after_action = "continue"
self.high_value_fudai_after_stay_seconds = 120
self.high_value_fudai_poll_before_seconds = 10.0
# 高价值直播间"回访"相关
self.high_value_room_revisit_enabled = False
self.high_value_room_revisit_only_current_run = False
self.high_value_room_revisit_min_interval_seconds = 300
self.high_value_room_revisit_max_per_run = 5
self.high_value_room_revisit_min_prize_value = 0.0
self.high_value_room_revisit_max_age_days = 30
# 粉丝团相关配置
self.auto_join_fansclub = False
self.fansclub_fail_action = "stay"
# 预约回退相关
self.reservation_back_verify_enabled = True
self.reservation_back_swipe_delay = 0.6
# 滑动次数重置相关
self.reset_after_swipes_enabled = False
self.reset_after_swipes = 10
# 意外返回桌面自救相关(坐标兜底,主路径已改用 launch_package 包名启动)
self.desktop_icon_x = 153
self.desktop_icon_y = 260
self.yanghao_fallback_live_x = 540
self.yanghao_fallback_live_y = 2000
self.yanghao_fallback_enter_live_x = 540
self.yanghao_fallback_enter_live_y = 1200
# 重新进入直播间点击模式:
# - follow_list: 使用关注列表入口坐标
# - screen_center: 使用屏幕中心坐标
self.reenter_live_entry_mode = "follow_list"
# 推荐页养号默认配置
_apply_yanghao_defaults(self)
# 预约运行时状态(单次运行内有效)
self.reservations = []
self._first_run_once_basic = True
self.room_pos = 0
self.reservation_focus_until_ts = 0.0
self.reservation_after_action_pending = False
self.reset_to_list_after_reservations = False
self.queue_full_waiting_at_earliest = False
# 预约队列状态文件 + 清理映射表导出文件
_resolve_reservations_state_path(self)
_clear_runtime_state_files_on_start(self)
# 已记录统计的福袋跟踪
self._recorded_fudai_stats = set()
# 运行时状态标志
self.needswitch = None
self._waiting_for_lottery_result = False
self._current_attending_reservation_fudai = False
self._skip_stage_diagnosis_and_find_fudai = False
self._just_switched_room = False
# 高价值房间重访相关状态
self._last_high_value_revisit_ts = time.time()
self._current_run_revisit_count = 0
self._current_run_high_value_rooms = []
self._last_fudai_detail_tuple = None
self._current_fudai_future_ts = 0.0
self._current_fudai_content = ""
self._fudai_detail_first_read = False
self._fudai_detail_consecutive_failures = 0
self._detail_closed_by_attend = False
self._lottery_result_expected_ts = 0.0
self._lottery_wait_prize_value_yuan = 0.0
self._lottery_wait_start_ts = 0.0
def _apply_yanghao_defaults(self: Any) -> None:
"""推荐页养号相关默认配置。"""
self.yanghao_enabled = True
self.yanghao_enable_actions = True
self.yanghao_step_screenshot = False
self.yanghao_recommend_duration_seconds = 60
self.yanghao_recommend_interval_seconds = 0
self.yanghao_like_prob = 0.15
self.yanghao_fav_prob = 0.05
self.yanghao_comment_prob = 0.0
self.yanghao_dwell_on_action_min_seconds = 5.0
self.yanghao_dwell_on_action_max_seconds = 30.0
self.yanghao_icon_roi_size = 180
self.yanghao_icon_match_threshold = 0.70
self.yanghao_like_roi_scale = 1.5
self.yanghao_fav_roi_scale = 1.5
self.yanghao_like_icon_match_threshold = None
self.yanghao_fav_icon_match_threshold = None
self.yanghao_like_icon_x = 0
self.yanghao_like_icon_y = 0
self.yanghao_fav_icon_x = 0
self.yanghao_fav_icon_y = 0
self.yanghao_like_roi_offset_x = 0
self.yanghao_like_roi_offset_y = 0
self.yanghao_fav_roi_offset_x = 0
self.yanghao_fav_roi_offset_y = 0
self._last_yanghao_ts = 0.0
self.yanghao_comment_btn_x = 0
self.yanghao_comment_btn_y = 0
self.yanghao_comment_input_x = 0
self.yanghao_comment_input_y = 0
self.yanghao_comment_send_x = 0
self.yanghao_comment_send_y = 0
self.yanghao_comment_close_x = 0
self.yanghao_comment_close_y = 0
self.yanghao_comment_texts = []
def _resolve_reservations_state_path(self: Any) -> None:
"""通过 path_config 解析预约状态文件路径,失败时退化到相对兜底。"""
try:
from douyin.core import path_config as _pc
self._reservations_state_path = _pc.get_reservations_path()
except Exception:
# 兜底:path_config 不可用时退到相对路径,与 douyin/core/state/ 一致
self._reservations_state_path = os.path.normpath(
os.path.join(os.path.dirname(__file__), "..", "state", "reservations.json")
)
# 运行时直播间标题/位置映射表(清空后存)
self._room_pos_to_title_map = {}
def _cleanup_old_room_pos_map_files(self: Any) -> None:
"""兼容旧入口:每次启动写入空映射表,避免 GUI 显示过期内容。"""
_write_empty_room_pos_map_state(self, reason="startup_clear")
def _clear_runtime_state_files_on_start(self: Any) -> None:
"""新运行实例启动时清空运行态预约队列和映射表状态文件。"""
try:
self.reservations = []
self.reservation_focus_until_ts = 0.0
self.reservation_after_action_pending = False
self.queue_full_waiting_at_earliest = False
self.reset_to_list_after_reservations = False
except Exception:
pass
try:
state_path = getattr(self, "_reservations_state_path", None)
if state_path:
from douyin.reservation.douyin_reservation import write_reservations_state
write_reservations_state(
state_path=state_path,
reservations=[],
room_pos=0,
current_room_title="",
current_room_title_raw="",
reason="startup_clear",
analyser=self,
)
except Exception as exc:
try:
self._log_kv(
"预约",
"[预约] 启动时清空预约状态文件失败",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
_write_empty_room_pos_map_state(self, reason="startup_clear")
def _write_empty_room_pos_map_state(self: Any, *, reason: str) -> None:
"""写入空的 room_pos_map 三件套,避免新一轮启动时暴露旧映射。"""
try:
state_dir = os.path.dirname(self._reservations_state_path)
os.makedirs(state_dir, exist_ok=True)
json_path = os.path.join(state_dir, "room_pos_map.json")
csv_path = os.path.join(state_dir, "room_pos_map.csv")
md_path = os.path.join(state_dir, "room_pos_map.md")
data = {
"_meta": {
"source": json_path,
"generated_ts": int(time.time()),
"run_id": getattr(self, "_run_id", ""),
"reason": str(reason or ""),
}
}
tmp_json = json_path + ".tmp"
with open(tmp_json, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.write("\n")
os.replace(tmp_json, json_path)
tmp_csv = csv_path + ".tmp"
with open(tmp_csv, "w", encoding="utf-8", newline="") as f:
f.write("pos,title,title_raw,has_fudai,fudai_content\n")
os.replace(tmp_csv, csv_path)
tmp_md = md_path + ".tmp"
with open(tmp_md, "w", encoding="utf-8") as f:
f.write("| pos | title | title_raw | has_fudai | fudai_content |\n")
f.write("| --- | --- | --- | --- | --- |\n")
f.write("| - | 暂无映射 | - | - | - |\n")
os.replace(tmp_md, md_path)
except Exception as exc:
try:
self._log_kv(
"映射表",
"启动时清空映射表状态文件失败",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
pass
@@ -0,0 +1,190 @@
"""直播间/福袋详情处理逻辑下沉模块。"""
from __future__ import annotations
import time
from typing import TYPE_CHECKING, List
from douyin.core import douyin_flow_control
from douyin.fudai import douyin_fudai_detail
if TYPE_CHECKING:
from ..douyin_fudai import fudai_analyse
def handle_in_fudai_detail(self: "fudai_analyse") -> None:
from douyin.core.fudai_modules import handle_detail_helpers as _hd_helpers
start_time = time.time()
_hd_helpers.log_entry_flags(self)
if _hd_helpers.handle_consecutive_failures_check(self):
return
step1_start = time.time()
is_second_open = getattr(self, "_fudai_detail_first_read", False)
if is_second_open:
if _hd_helpers.handle_second_open_branch(self, start_time, step1_start):
return
else:
if _hd_helpers.handle_first_open_branch(self, start_time):
return
if _hd_helpers.check_last_status_branch(self, start_time):
return
detail = getattr(self, "_last_fudai_detail_tuple", None)
try:
self._fudai_detail_consecutive_failures = 0
except Exception:
pass
try:
if detail is None:
try:
self._log_kv("福袋详情", "详情数据为 None,跳过验证")
except Exception:
pass
else:
is_valid, reason = douyin_fudai_detail.validate_fudai_detail(detail, self)
if not is_valid:
actionable = {"可以参与", "需要加入粉丝团", "需要评论", "需要观看", "已参与"}
btn_st = getattr(self, "_fudai_button_status", None)
if btn_st in actionable:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:验证失败但按钮可操作,继续参与",
validation_reason=reason,
button_status=btn_st,
)
except Exception:
pass
else:
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:福袋详情数据验证失败,识别出错",
validation_reason=reason,
)
except Exception:
pass
douyin_fudai_detail.close_fudai_detail(self)
_hd_helpers._clear_task_count_flag(self)
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(验证失败)",
elapsed_seconds=round(elapsed, 2),
)
return
except Exception:
pass
if _hd_helpers.check_invalid_detail_fallback(self, detail, start_time):
return
attend_before_ts = _hd_helpers.prepare_for_attend(self, detail)
_hd_helpers.step4_make_join_decision(self, detail, False, "", attend_before_ts, start_time)
def handle_live_room_has_or_not_fudai(self: "fudai_analyse") -> None:
start_time = time.time()
self._current_attending_reservation_fudai = False
try:
already_verified = bool(getattr(self, "_fudai_detail_verified", False) or False)
if already_verified:
try:
self._log_kv("流程", "_handle_live_room_has_or_not_fudai:已验证过详情页,直接处理详情,不查找福袋")
except Exception:
pass
self._handle_in_fudai_detail()
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_live_room_has_or_not_fudai完成(已验证详情页)", elapsed_seconds=round(elapsed, 2))
return
except Exception:
pass
try:
now_ts = time.time()
focus_until = float(getattr(self, "reservation_focus_until_ts", 0.0) or 0.0)
queue_full_waiting = bool(getattr(self, "queue_full_waiting_at_earliest", False) or False)
if focus_until > 0 and now_ts < focus_until and queue_full_waiting:
if self.reservations and len(self.reservations) > 0:
earliest = self.reservations[0]
try:
ft = float(earliest.get("future_ts") or 0.0)
if ft > 0:
join_ahead = float(getattr(self, "high_value_fudai_join_ahead_seconds", 100) or 120)
time_window_start_ts = ft - join_ahead
if now_ts < time_window_start_ts:
try:
self._log_kv(
"预约",
"[预约] 锁定期内时间窗口未到,避免重复打开福袋详情",
focus_until=int(focus_until),
now_ts=int(now_ts),
time_window_start=int(time_window_start_ts),
remain_seconds=int(time_window_start_ts - now_ts),
)
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_live_room_has_or_not_fudai完成(锁定期内时间窗口未到)",
elapsed_seconds=round(elapsed, 2),
)
return
except Exception:
pass
except Exception:
pass
room_pos_ref: List[int] = [0]
opened = douyin_flow_control.find_and_open_fudai_detail(self, room_pos_ref)
if not opened:
try:
self._current_fudai_content = ""
self._last_fudai_detail_tuple = None
self._fudai_detail_first_read = False
except Exception:
pass
try:
need_switch_config = bool(getattr(self, "needswitch", True))
except Exception:
need_switch_config = True
wait_times_ref = [0]
swipe_times_ref = [0]
reservation_focus_until_ts_ref = [0.0]
reset_to_list_after_reservations_ref = [False]
douyin_flow_control.handle_no_fudai_situation(
self,
x=0,
swipe_times=0,
wait_times_ref=wait_times_ref,
needswitch=need_switch_config,
reservation_focus_until_ts=0.0,
reservations=[],
room_pos=room_pos_ref[0],
post_switch_delay_s=1.5,
swipe_up_switch_callback=self.swipe_up_to_next_live,
swipe_down_back_callback=lambda: None,
sort_reservations_callback=lambda: None,
clear_reservations_callback=lambda: None,
write_state_callback=lambda: None,
back_to_list_callback=lambda: None,
into_list_callback=lambda: None,
reservation_focus_until_ts_ref=reservation_focus_until_ts_ref,
reset_to_list_after_reservations_ref=reset_to_list_after_reservations_ref,
swipe_times_ref=swipe_times_ref,
)
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_live_room_has_or_not_fudai完成(无福袋)", elapsed_seconds=round(elapsed, 2))
return
self._handle_in_fudai_detail()
elapsed = time.time() - start_time
self._log_kv("流程", "_handle_live_room_has_or_not_fudai完成(成功打开详情)", elapsed_seconds=round(elapsed, 2))
@@ -0,0 +1,144 @@
from __future__ import annotations
import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..douyin_fudai import fudai_analyse
def handle_fansclub_join(self: "fudai_analyse", start_time: float) -> None:
"""FANSCLUB_JOIN 阶段处理:参与按钮 + 预设位置点击 + 关闭详情。"""
self._log_kv("粉丝团处理", "检测到粉丝团加入按钮,开始处理")
try:
attend_x = int(543 * self.resolution_ratio_x // 1080)
attend_y = int(2070 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, attend_x, attend_y)
self._log_kv(
"粉丝团处理",
"先点击参与按钮",
x=attend_x,
y=attend_y,
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
)
self.operation.delay(0.5)
preset_x = int(527 * self.resolution_ratio_x // 1080)
preset_y = int(567 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, preset_x, preset_y)
self._log_kv(
"粉丝团处理",
"第一次点击预设位置",
x=preset_x,
y=preset_y,
base_x=527,
base_y=567,
)
self.operation.delay(0.5)
self.operation.click(self.device_id, preset_x, preset_y)
self._log_kv(
"粉丝团处理",
"第二次点击预设位置",
x=preset_x,
y=preset_y,
base_x=527,
base_y=567,
)
self.operation.delay(1.0)
close_x = int(500 * self.resolution_ratio_x // 1080)
close_y = int(470 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, close_x, close_y)
self._log_kv(
"粉丝团处理",
"关闭详情页",
x=close_x,
y=close_y,
base_x=500,
base_y=470,
)
self.operation.delay(1.0)
except Exception as exc:
self._log_kv("粉丝团处理", "处理粉丝团加入失败", error=str(exc))
if getattr(self, "auto_join_fansclub", False):
self._log_kv("粉丝团处理", "已启用自动加入粉丝团,等待页面加载")
self.operation.delay(1.0)
try:
stage_after, _ = self._diagnose_stage_from_current_screen()
if stage_after == "FANSCLUB_JOIN":
preset_x = int(527 * self.resolution_ratio_x // 1080)
preset_y = int(567 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, preset_x, preset_y)
self._log_kv(
"粉丝团处理",
"仍在粉丝团加入页,再次第一次点击",
x=preset_x,
y=preset_y,
base_x=527,
base_y=567,
)
self.operation.delay(0.5)
self.operation.click(self.device_id, preset_x, preset_y)
self._log_kv(
"粉丝团处理",
"仍在粉丝团加入页,再次第二次点击",
x=preset_x,
y=preset_y,
base_x=527,
base_y=567,
)
self.operation.delay(2.0)
try:
return_x = int(527 * self.resolution_ratio_x // 1080)
return_y = int(567 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, return_x, return_y)
self._log_kv(
"粉丝团处理",
"加入粉丝团成功后,点击返回直播间",
x=return_x,
y=return_y,
base_x=527,
base_y=567,
)
self.operation.delay(1.0)
except Exception as exc_inner:
self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(exc_inner))
except Exception:
pass
else:
self._log_kv("粉丝团处理", "未启用自动加入粉丝团,等待手动确认", wait_seconds=15)
self.operation.delay(15.0)
try:
return_x = int(527 * self.resolution_ratio_x // 1080)
return_y = int(567 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, return_x, return_y)
self._log_kv(
"粉丝团处理",
"加入粉丝团成功后,点击返回直播间",
x=return_x,
y=return_y,
base_x=527,
base_y=567,
)
self.operation.delay(1.0)
except Exception as exc_inner2:
self._log_kv("粉丝团处理", "点击返回直播间失败", error=str(exc_inner2))
self.operation.delay(0.5)
fansclub_fail_action = getattr(self, "fansclub_fail_action", "stay")
if fansclub_fail_action == "switch":
self._log_kv("粉丝团处理", "粉丝团失败策略为switch,切换直播间")
try:
self.swipe_up_to_next_live()
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(处理粉丝团)", elapsed_seconds=round(elapsed, 2))
@@ -0,0 +1,693 @@
"""run_once_basic 辅助逻辑
把 run_once_basic 的若干独立段落(等待开奖、30 分钟超时检查等)抽出来,
保持原 douyin_fudai.run_once_basic 的语义和日志不变。
Each helper returns True 表示主流程应当结束本轮(caller `return`),
返回 False 表示继续走 run_once_basic 后续步骤。
"""
from __future__ import annotations
import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..douyin_fudai import fudai_analyse
def _emit_flow_flag(self: "fudai_analyse", flag: str, status: str, **extra) -> None:
"""输出统一流程标志,便于按关键节点检索整条福袋流程。"""
try:
payload = {
"flag": str(flag or ""),
"status": str(status or ""),
"run_id": str(getattr(self, "_run_id", "") or ""),
}
payload.update(extra or {})
self._log_kv("流程标志", f"[FLOW_FLAG] {flag}:{status}", **payload)
except Exception:
pass
def handle_waiting_for_lottery_result(self: "fudai_analyse", start_time: float) -> bool:
"""0. 等待开奖期间持续 OCR 检测开奖结果。
返回 True 表示 caller 应当 `return`(已在本函数中处理完毕本轮逻辑);
返回 False 表示当前没在等待开奖、或异常分支应当继续走 run_once_basic 后续步骤。
"""
if not getattr(self, "_waiting_for_lottery_result", False):
return False
wait_lottery_start = time.time()
try:
future_ts = getattr(self, "_lottery_result_expected_ts", 0.0) or 0.0
current_ts = time.time()
# 从设置等待标志后开始持续检测,最多等待开奖时间+10秒
timeout_ts = future_ts + 10.0
if current_ts >= timeout_ts:
self._waiting_for_lottery_result = False
self._current_attending_reservation_fudai = False
self._lottery_wait_prize_value_yuan = 0.0
timeout_seconds = int(current_ts - future_ts)
self._log_kv(
"参与",
f"等待开奖超时(超过开奖时间{timeout_seconds}秒),清除等待标志,继续执行其他操作",
超时秒数=timeout_seconds,
等待开奖总耗时=round(time.time() - wait_lottery_start, 2),
)
# 超时分支不 return,让外层继续后续步骤
return False
# 持续 OCR 检测开奖结果
wait_start_ts = getattr(self, "_lottery_wait_start_ts", future_ts)
passed_seconds = int(current_ts - wait_start_ts)
self._log_kv(
"参与",
f"等待开奖结果中,持续OCR检测,已等待{passed_seconds}秒",
已等待秒数=passed_seconds,
)
deadline_ts = timeout_ts
attempt = 0
consecutive_none = 0
interval = 0.5
while time.time() <= deadline_ts:
attempt += 1
loop_start = time.time()
try:
try:
screenshot_start = time.time()
self.operation.get_screenshot(self.device_id)
self._log_kv(
"截图",
"等待开奖期间截图",
elapsed_seconds=round(time.time() - screenshot_start, 2),
)
except Exception:
pass
ocr_start = time.time()
result = self._check_lottery_result_by_ocr()
self._log_kv(
"OCR",
"等待开奖期间OCR检测",
elapsed_seconds=round(time.time() - ocr_start, 2),
)
except Exception as e:
result = None
try:
self._log_kv(
"参与",
"等待开奖期间OCR检测出错,继续重试",
error=str(e),
)
except Exception:
pass
if result:
self._waiting_for_lottery_result = False
self._current_attending_reservation_fudai = False
self._lottery_wait_prize_value_yuan = 0.0
try:
self._log_kv(
"参与",
"等待期间检测到开奖结果,开始处理",
attempt=attempt,
等待开奖总耗时=round(time.time() - wait_lottery_start, 2),
)
except Exception:
pass
self._handle_lottery_result_by_ocr(result)
elapsed = time.time() - start_time
try:
self._log_kv(
"流程",
"run_once_basic完成(等待开奖期间处理结果)",
elapsed_seconds=round(elapsed, 2),
)
except Exception:
pass
return True
consecutive_none += 1
now_ts_inner = time.time()
remain_to_deadline = int(max(0, deadline_ts - now_ts_inner))
try:
self._log_kv(
"参与",
"等待开奖连续检测:未识别到结果",
attempt=attempt,
remain_seconds=remain_to_deadline,
单次检测耗时=round(time.time() - loop_start, 2),
)
except Exception:
pass
spent = time.time() - loop_start
to_sleep = max(0.0, interval - spent)
if to_sleep > 0:
if time.time() + to_sleep > deadline_ts:
break
self.operation.delay(to_sleep)
self._waiting_for_lottery_result = False
self._current_attending_reservation_fudai = False
self._lottery_wait_prize_value_yuan = 0.0
try:
self._log_kv(
"参与",
"等待开奖连续检测结束:未识别到开奖结果,清除等待标志",
attempts=attempt,
consecutive_none=consecutive_none,
等待开奖总耗时=round(time.time() - wait_lottery_start, 2),
)
except Exception:
pass
try:
needswitch = bool(getattr(self, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
try:
self._log_kv(
"开奖结果",
"处理完开奖结果,切换直播间找新福袋",
color="RED",
)
except Exception:
pass
self.swipe_up_to_next_live()
elapsed = time.time() - start_time
try:
self._log_kv(
"流程",
"run_once_basic完成(等待开奖期间处理结果)",
elapsed_seconds=round(elapsed, 2),
)
except Exception:
pass
return True
except Exception as exc:
self._log_kv("参与", "等待开奖检测时出错", error=str(exc))
self._waiting_for_lottery_result = False
self._current_attending_reservation_fudai = False
self._lottery_wait_prize_value_yuan = 0.0
return False
def handle_no_attend_timeout(self: "fudai_analyse", start_time: float) -> bool:
"""0. 30 分钟未参与福袋超时检查,超时则回到推荐页面再进入直播间。
返回 True 表示 caller 应当 `return`;返回 False 表示未触发超时,继续后续步骤。
"""
try:
last_attend_ts = float(
getattr(self, "_last_successful_attend_ts", 0.0) or 0.0
)
timeout_minutes = float(
getattr(self, "_no_attend_timeout_minutes", 30.0) or 30.0
)
current_ts = time.time()
run_start_ts = float(
getattr(self, "_run_start_ts", current_ts) or current_ts
)
# 如果成功参与过,检查距离最后一次成功参与是否超过 timeout_minutes
if last_attend_ts > 0:
elapsed_minutes = (current_ts - last_attend_ts) / 60.0
if elapsed_minutes >= timeout_minutes:
try:
self._log_kv(
"超时",
"30分钟未参与成功福袋,返回推荐页面重新进入直播间",
last_attend_minutes_ago=round(elapsed_minutes, 1),
)
except Exception:
pass
self._return_to_recommend_and_reenter_live()
# 重置最后成功参与时间,避免立即再次触发
try:
self._last_successful_attend_ts = current_ts
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(30分钟超时处理)",
elapsed_seconds=round(elapsed, 2),
)
return True
else:
# 从未成功参与过,检查运行时间
elapsed_minutes = (current_ts - run_start_ts) / 60.0
if elapsed_minutes >= timeout_minutes:
try:
self._log_kv(
"超时",
f"运行{round(elapsed_minutes, 1)}分钟仍未参与成功福袋,返回推荐页面重新进入直播间",
run_minutes=round(elapsed_minutes, 1),
)
except Exception:
pass
self._return_to_recommend_and_reenter_live()
# 重置运行开始时间已移至 _return_to_recommend_and_reenter_live() 方法中
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(30分钟超时处理)",
elapsed_seconds=round(elapsed, 2),
)
return True
except Exception as exc:
try:
self._log_kv("超时", "检查30分钟超时时出错", error=str(exc))
except Exception:
pass
return False
def run_once_basic_prelude(self: "fudai_analyse", start_time: float) -> None:
"""run_once_basic 前置逻辑:启动日志、养号触发、直播间标题记录。"""
self._log_kv("流程", "run_once_basic开始", start_timestamp=start_time)
_emit_flow_flag(
self,
"run_once_basic",
"start",
room_pos=int(getattr(self, "room_pos", 0) or 0),
wait_minutes=int(getattr(self, "wait_minutes", 0) or 0),
needswitch=bool(getattr(self, "needswitch", True)),
)
# 在主循环开始时检查是否需要定时触发推荐页养号
try:
self._maybe_run_yanghao_during_run()
except Exception:
pass
# 尝试记录当前直播间的标题与位置,确保所有直播间(不限福袋)都被采集到运行时映射表
# 但如果刚刚切换直播间,避免重复记录(切换前已记录)
try:
just_switched = getattr(self, "_just_switched_room", False)
if not just_switched:
self._record_room_title_and_pos()
else:
self._log_kv(
"预约",
"[预约] 刚刚切换直播间,跳过重复记录标题",
reason="avoid_duplicate_after_switch",
)
except Exception:
pass
def handle_desktop_recovery(self: "fudai_analyse") -> bool:
from .run_once_basic_stage import handle_desktop_recovery as _impl
return _impl(self)
def screenshot_and_diagnose(
self: "fudai_analyse",
start_time: float,
):
from .run_once_basic_stage import screenshot_and_diagnose as _impl
return _impl(self, start_time)
def handle_high_value_room_revisit(self: "fudai_analyse", start_time: float) -> bool:
from .run_once_basic_stage import handle_high_value_room_revisit as _impl
return _impl(self, start_time)
def dispatch_stage_branch(
self: "fudai_analyse",
stage: str,
seen,
start_time: float,
) -> None:
"""根据阶段诊断结果分发处理:弹窗 / 详情页 / 直播间 / 推荐页 / 开奖结果 / 其他。
本函数总是消费完一轮分发后返回;caller 不需要判断返回值——run_once_basic
在调用本函数后即结束本轮(原本各分支后面也没有更多代码)。
"""
_emit_flow_flag(
self,
"stage_dispatch",
"enter",
stage=str(stage or ""),
)
# 处理弹窗阶段
if stage == "COUPON_POPUP":
# 优惠券弹窗:按返回键关闭
self._log_kv("弹窗处理", "检测到优惠券弹窗,按返回键关闭")
try:
self.operation.click_back(self.device_id)
self.operation.delay(0.5)
self._log_kv("弹窗处理", "已按返回键关闭优惠券弹窗")
except Exception as e:
self._log_kv("弹窗处理", "按返回键关闭优惠券弹窗失败", error=str(e))
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(处理优惠券弹窗)",
elapsed_seconds=round(elapsed, 2),
)
return
elif stage == "SHOPPING_REDPACKET_POPUP":
# 购物红包弹窗:点击关闭按钮
self._log_kv("弹窗处理", "检测到购物红包弹窗,点击关闭按钮")
try:
close_x = int(530 * self.resolution_ratio_x // 1080)
close_y = int(1647 * self.resolution_ratio_y // 2400)
self.operation.click(self.device_id, close_x, close_y)
self.operation.delay(0.5)
self._log_kv("弹窗处理", "已点击购物红包关闭按钮", x=close_x, y=close_y)
except Exception as e:
self._log_kv("弹窗处理", "点击购物红包关闭按钮失败", error=str(e))
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(处理购物红包弹窗)",
elapsed_seconds=round(elapsed, 2),
)
return
elif stage == "FANSCLUB_JOIN":
_handle_fansclub_join(self, start_time)
return
elif stage == "FUDai_DETAIL":
try:
self._log_kv(
"预约",
"[预约] 检测到福袋详情页,按正常详情流程处理",
stage=stage,
)
except Exception:
pass
self._handle_in_fudai_detail()
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(处理福袋详情)",
elapsed_seconds=round(elapsed, 2),
)
elif stage in ("IN_LIVE_ROOM", "LIVE_OR_UNKNOWN"):
try:
self._log_kv(
"预约",
"[预约] 检测到直播间,按正常直播间流程处理",
stage=stage,
)
except Exception:
pass
# 在直播间:如果刚刚切换了直播间,等待福袋加载
just_switched = getattr(self, "_just_switched_room", False)
if just_switched:
try:
self._just_switched_room = False
wait_seconds = float(
getattr(self, "switch_room_wait_after_stage_diag_seconds", 7.0)
or 7.0
)
if wait_seconds > 0:
self._log_kv(
"流程",
"切换直播间后,阶段检测完成,等待福袋加载",
wait_seconds=wait_seconds,
)
self.operation.delay(wait_seconds)
except Exception as e:
try:
self._just_switched_room = False
self._log_kv("流程", "等待福袋加载时出错", error=str(e))
except Exception:
pass
# 在直播间:寻找福袋图标并尝试点开
fudai_search_start = time.time()
self._handle_live_room_has_or_not_fudai()
fudai_search_elapsed = time.time() - fudai_search_start
self._log_kv("福袋查找", f"福袋查找完成,耗时: {fudai_search_elapsed:.3f}s")
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(处理直播间)",
elapsed_seconds=round(elapsed, 2),
)
elif stage in ("RECOMMEND_PAGE", "FOLLOW_LIST", "LIVE_LIST"):
# 处理推荐/关注/直播列表页:回到直播间或切换
if stage == "RECOMMEND_PAGE":
self._log_kv(
"流程",
"检测到推荐页面,点击进入直播页并进入直播间",
stage=stage,
seen=seen,
)
try:
from douyin.handlers.live_tab_ocr import (
click_live_tab_on_recommend_page,
)
live_tab_x, live_tab_y, live_tab_method = (
click_live_tab_on_recommend_page(self)
)
self._log_kv(
"流程",
"点击进入直播页",
x=live_tab_x,
y=live_tab_y,
method=live_tab_method,
)
self.operation.delay(self.FOLLOW_TAB_CLICK_DELAY)
# 点击进入直播间位置(支持模式切换:关注列表坐标/屏幕中心),连点两次
try:
from douyin.handlers import douyin_swipe_handler
enter_live_x, enter_live_y, entry_mode = (
douyin_swipe_handler.SwipeHandler.resolve_reenter_live_click_point(
self
)
)
except Exception:
enter_live_x = int(103 * self.resolution_ratio_x // 1080)
enter_live_y = int(382 * self.resolution_ratio_y // 2400)
entry_mode = "follow_list"
self.operation.click(self.device_id, enter_live_x, enter_live_y)
self.operation.delay(self.ENTER_LIVE_CLICK_DELAY)
try:
self.operation.delay(
getattr(self, "RETURN_STEP_DELAY_SECONDS", 0.8)
)
except Exception:
self.operation.delay(0.8)
self.operation.click(self.device_id, enter_live_x, enter_live_y)
self._log_kv(
"流程",
"点击进入直播间位置(entry_mode={})".format(entry_mode),
x=enter_live_x,
y=enter_live_y,
次数=2,
entry_mode=entry_mode,
)
try:
self.operation.delay(
getattr(self, "RETURN_STEP_DELAY_SECONDS", 0.8)
)
except Exception:
self.operation.delay(0.8)
self.operation.delay(self.ENTER_LIVE_FINAL_DELAY)
except Exception as e:
self._log_kv("流程", "处理推荐页面时出错", error=str(e))
try:
self.operation.click_back(self.device_id)
self.operation.delay(1.0)
except Exception:
pass
else:
# 其他列表页:使用原有逻辑
from douyin.other import douyin_live_room
douyin_live_room.reflash_zhibo(self)
elif stage == "FUDai_RESULT":
# 抽奖结果弹窗:处理开奖结果(使用OCR识别,不使用阶段诊断)
self._waiting_for_lottery_result = False
self._current_attending_reservation_fudai = False
self._log_kv("开奖结果", "检测到抽奖结果弹窗,使用OCR识别处理")
lottery_ocr_start = time.time()
result = self._check_lottery_result_by_ocr()
if result:
self._handle_lottery_result_by_ocr(result)
else:
# OCR识别失败,使用返回键关闭
try:
self.operation.click_back(self.device_id)
self.operation.delay(0.5)
self.swipe_up_to_next_live()
except Exception:
pass
lottery_ocr_elapsed = time.time() - lottery_ocr_start
self._log_kv("开奖结果", f"OCR处理完成,耗时: {lottery_ocr_elapsed:.3f}s")
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(处理开奖结果)",
elapsed_seconds=round(elapsed, 2),
)
return
elif stage in ("LIVE_CLOSED",):
# 直播结束:下滑/切下一个
self._log_kv("阶段", "当前直播已结束,尝试切换下一个")
self.swipe_up_to_next_live()
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(直播结束)",
elapsed_seconds=round(elapsed, 2),
)
else:
# 未识别出特殊阶段:尽量保持原地,交给上层循环
elapsed = time.time() - start_time
self._log_kv(
"阶段",
"未匹配到特定阶段",
stage=stage,
elapsed_seconds=round(elapsed, 2),
)
def _handle_fansclub_join(self: "fudai_analyse", start_time: float) -> None:
from .run_once_basic_fansclub import handle_fansclub_join as _impl
return _impl(self, start_time)
def handle_just_recorded_reservation(self: "fudai_analyse", start_time: float) -> bool:
"""检查 _just_recorded_reservation 标志,若刚记录了预约则强制切换直播间。
返回 True 表示已切换并应当 `return`;False 表示未触发,继续后续步骤。
"""
try:
just_recorded = getattr(self, "_just_recorded_reservation", False)
if not just_recorded:
return False
self._just_recorded_reservation = False # 清除标志
try:
self._log_kv(
"预约",
"[预约] 刚刚记录预约,继续在新直播间搜索福袋",
)
except Exception:
pass
try:
needswitch_cfg = bool(getattr(self, "needswitch", True))
except Exception:
needswitch_cfg = True
if needswitch_cfg:
try:
self.swipe_up_to_next_live()
except Exception as exc:
try:
self._log_kv(
"预约",
"[预约] 执行上滑切换失败",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
else:
try:
self._log_kv(
"预约",
"[预约] just_recorded_reservation 触发,但 needswitch=False,未切换",
)
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(记录预约后切换直播间)",
elapsed_seconds=round(elapsed, 2),
)
return True
except Exception:
return False
def handle_skip_stage_diagnosis(self: "fudai_analyse", start_time: float) -> bool:
"""0.5 跳过阶段检测:点击参与抽奖后直接查找福袋。
返回 True 表示已处理并应当 `return`;False 表示标志未设置,继续后续步骤。
"""
skip_stage_diagnosis = getattr(
self, "_skip_stage_diagnosis_and_find_fudai", False
)
if not skip_stage_diagnosis:
return False
try:
self._skip_stage_diagnosis_and_find_fudai = False
self._log_kv("流程", "点击参与抽奖后,跳过阶段检测,直接查找福袋")
except Exception:
pass
self._handle_live_room_has_or_not_fudai()
elapsed = time.time() - start_time
self._log_kv(
"流程",
"run_once_basic完成(跳过阶段检测)",
elapsed_seconds=round(elapsed, 2),
)
return True
def handle_reservation_check(self: "fudai_analyse", start_time: float) -> bool:
"""0.1 高价值预约检查:清空队列 / 处理队列已满 / 调 process_reservation_attend_window。
返回 True 表示有 return-out 出口被触发,caller 应当 `return`;
返回 False 表示走完所有逻辑后继续执行后续步骤。
"""
from .run_once_basic_reservation import handle_reservation_check as _impl
return _impl(self, start_time)
def run_once_basic_post_reservation(self: "fudai_analyse", start_time: float) -> None:
"""run_once_basic 在预约检查之后的阶段处理总流程。"""
# 0.5. 检查是否需要跳过阶段检测,直接查找福袋(点击参与抽奖后)
if handle_skip_stage_diagnosis(self, start_time):
return
# 1. 截图 + 阶段诊断
diag = screenshot_and_diagnose(self, start_time)
if diag is None:
return
stage, seen = diag
# 1.5. 检测是否意外返回桌面(不在抖音前台),若是则尝试恢复
if handle_desktop_recovery(self):
return
# 2.0. 高价值房间重访检查(在处理其他状态之前)
if handle_high_value_room_revisit(self, start_time):
return
# 处理弹窗 / 详情 / 直播间 / 推荐页 / 开奖结果 / 直播结束 阶段分发
dispatch_stage_branch(self, stage, seen, start_time)
def handle_reservation_pipeline(self: "fudai_analyse", start_time: float) -> bool:
"""run_once_basic 的预约处理聚合管线。"""
reservation_check_start = time.time()
if handle_reservation_check(self, start_time):
return True
if handle_just_recorded_reservation(self, start_time):
return True
reservation_elapsed = time.time() - reservation_check_start
self._log_kv("预约", f"预约检查完成,耗时: {reservation_elapsed:.3f}s")
return False
@@ -0,0 +1,601 @@
"""run_once_basic 预约检查相关辅助逻辑。"""
from __future__ import annotations
import json
import os
import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..douyin_fudai import fudai_analyse
def _safe_float_attr(obj, name: str, default: float) -> float:
try:
value = getattr(obj, name, default)
if not isinstance(value, (int, float, str)):
return float(default)
return float(value if value is not None else default)
except Exception:
return float(default)
def _safe_int_attr(obj, name: str, default: int) -> int:
try:
value = getattr(obj, name, default)
if not isinstance(value, (int, float, str)):
return int(default)
return int(value if value is not None else default)
except Exception:
return int(default)
def handle_reservation_check(self: "fudai_analyse", start_time: float) -> bool:
"""0.1 高价值预约检查:清空队列 / 处理队列已满 / 调 process_reservation_attend_window。"""
try:
reservation_check_start = time.time()
self._log_kv("预约", "开始预约检查", timestamp=reservation_check_start)
_maybe_clear_reservations_on_first_run(self)
high_value_enabled = getattr(self, "high_value_fudai_enabled", False)
reservations_list = getattr(self, "reservations", None)
reservations_count = len(reservations_list) if reservations_list else 0
_log_reservation_check_trigger(
self, high_value_enabled, reservations_list, reservations_count
)
if not high_value_enabled:
try:
self._log_kv(
"预约",
"[预约] 预约功能未启用(high_value_fudai_enabled=False),跳过预约回退检查",
)
except Exception:
pass
elif not reservations_list or reservations_count == 0:
try:
self._log_kv(
"预约",
"[预约] 预约队列为空,跳过预约回退检查",
reservations_is_none=(reservations_list is None),
reservations_count=reservations_count,
)
except Exception:
pass
if not (high_value_enabled and reservations_list):
return False
return _run_reservation_attend_window(self, start_time)
except Exception:
return False
def _maybe_clear_reservations_on_first_run(self: "fudai_analyse") -> None:
try:
is_first_run = getattr(self, "_first_run_once_basic", True)
old_reservations_count = 0
try:
old_reservations_count = (
len(self.reservations)
if hasattr(self, "reservations") and self.reservations
else 0
)
except Exception:
pass
if is_first_run:
try:
self._log_kv(
"预约",
"[预约] 第一次运行:丢弃旧的预约队列,不加载状态文件",
old_reservations_count=old_reservations_count,
)
except Exception:
pass
try:
before_clear = (
len(self.reservations)
if hasattr(self, "reservations") and self.reservations
else 0
)
self.reservations = []
after_clear = len(self.reservations) if hasattr(self, "reservations") else 0
try:
state_path = getattr(self, "_reservations_state_path", None)
if state_path:
from douyin.reservation.douyin_reservation import write_reservations_state
write_reservations_state(
state_path=state_path,
reservations=[],
room_pos=0,
current_room_title="",
current_room_title_raw="",
reason="startup_clear",
)
try:
self._log_kv(
"预约",
"[预约] 已清空预约队列并更新状态文件",
before_clear=before_clear,
after_clear=after_clear,
)
except Exception:
pass
except Exception as exc:
try:
self._log_kv(
"预约",
"[预约] 清空状态文件时出错",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
except Exception as exc:
try:
if hasattr(self, "reservations"):
self.reservations = []
self._log_kv(
"预约",
"[预约] 清空预约队列时出错,已尝试直接设置",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
try:
self._first_run_once_basic = False
except Exception:
pass
else:
try:
current_count = (
len(self.reservations)
if hasattr(self, "reservations") and self.reservations
else 0
)
self._log_kv(
"预约",
"[预约] 非第一次运行,保持当前预约队列",
reservations_count=current_count,
is_first_run=False,
)
except Exception:
pass
except Exception as exc:
try:
self._log_kv(
"预约",
"[预约] 初始化预约队列时出错",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
def _log_reservation_check_trigger(
self: "fudai_analyse",
high_value_enabled: bool,
reservations_list,
reservations_count: int,
) -> None:
try:
from datetime import datetime as _dt
reservations_detail = []
if reservations_list:
for idx, r in enumerate(reservations_list[:3]):
try:
ft = float(r.get("future_ts") or 0)
ft_str = _dt.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效"
reservations_detail.append(
{
"index": idx,
"future_ts": int(ft) if ft > 0 else 0,
"future_str": ft_str,
"value": float(r.get("prize_value_yuan", 0)),
"pos_seen": int(r.get("pos_seen", 0)),
}
)
except Exception:
pass
self._log_kv(
"预约",
"[预约] run_once_basic:检查预约回退触发条件",
high_value_enabled=high_value_enabled,
reservations_count=reservations_count,
reservations_is_none=(reservations_list is None),
will_check_reservations=bool(high_value_enabled and reservations_list),
reservations_detail=reservations_detail,
)
except Exception:
pass
def _run_reservation_attend_window(self: "fudai_analyse", start_time: float) -> bool:
from douyin.reservation import douyin_reservation_logic
def _swipe_down_once() -> None:
self.swipe_down_back_from_live()
def _sort_reservations() -> None:
douyin_reservation_logic._sort_reservations_inplace(self.reservations) # type: ignore[attr-defined]
def _write_state() -> None:
_write_reservations_state(self)
focus_ref = [float(self.reservation_focus_until_ts or 0.0)]
after_action_ref = [bool(self.reservation_after_action_pending or False)]
def _seek_reservation_room(item: dict) -> bool:
try:
return bool(self._seek_reservation_room(item, operation_type="预约"))
except Exception:
return False
if getattr(self, "_waiting_for_lottery_result", False):
if not _should_allow_reservation_preempt_waiting_lottery(self):
return False
max_reservations = _safe_int_attr(self, "high_value_fudai_max_reservations", 3)
if len(self.reservations) >= max_reservations and not self.queue_full_waiting_at_earliest:
waiting = douyin_reservation_logic.handle_queue_full_wait_at_earliest(
analyser=self,
reservations=self.reservations,
room_pos=int(getattr(self, "room_pos", 0) or 0),
reservation_focus_until_ts_ref=focus_ref,
reservation_back_swipe_delay_s=_safe_float_attr(self, "reservation_back_swipe_delay", 0.6),
swipe_down_back_callback=_swipe_down_once,
seek_reservation_room_callback=_seek_reservation_room,
sort_reservations_callback=_sort_reservations,
write_state_callback=_write_state,
)
if waiting:
self.queue_full_waiting_at_earliest = True
if focus_ref:
self.reservation_focus_until_ts = float(focus_ref[0] or 0.0)
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(预约队列满等待)", elapsed_seconds=round(elapsed, 2))
return True
if getattr(self, "_current_attending_reservation_fudai", False):
try:
self._log_kv(
"预约",
"[预约] 正在参与预约福袋,跳过预约回退检查,避免被其他预约打断",
current_attending_reservation=True,
)
except Exception:
pass
if self.queue_full_waiting_at_earliest and not self.reservations:
try:
self._log_kv("预约", "[预约] 所有预约已完成,重置到第一个直播间")
except Exception:
pass
self.queue_full_waiting_at_earliest = False
self.reservation_focus_until_ts = 0.0
try:
current_pos = int(getattr(self, "room_pos", 0) or 0)
back_times = min(abs(current_pos), 100)
if back_times > 0:
for _ in range(back_times):
_swipe_down_once()
self.operation.delay(0.6)
self.room_pos = 0
if hasattr(self, "_swipe_times"):
self._swipe_times = 0
try:
self._log_kv("预约", "[预约] 已回退到第一个直播间", back_times=back_times)
except Exception:
pass
except Exception:
pass
return True
try:
needswitch_cfg = bool(getattr(self, "needswitch", True))
except Exception:
needswitch_cfg = True
_log_reservation_attend_check(self, needswitch_cfg)
if needswitch_cfg:
try:
self._log_kv(
"预约",
"[预约] 多间模式:开始调用 process_reservation_attend_window",
reservations_count=(len(self.reservations) if self.reservations else 0),
room_pos=int(getattr(self, "room_pos", 0) or 0),
)
except Exception:
pass
preempted = douyin_reservation_logic.process_reservation_attend_window(
analyser=self,
reservations=self.reservations,
room_pos=int(getattr(self, "room_pos", 0) or 0),
reservation_focus_until_ts_ref=focus_ref,
reservation_after_action_pending_ref=after_action_ref,
reservation_back_swipe_delay_s=_safe_float_attr(self, "reservation_back_swipe_delay", 0.6),
swipe_down_back_callback=_swipe_down_once,
seek_reservation_room_callback=_seek_reservation_room,
sort_reservations_callback=_sort_reservations,
write_state_callback=_write_state,
)
try:
self._log_kv(
"预约",
"[预约] process_reservation_attend_window 返回结果",
preempted=preempted,
focus_until=(int(focus_ref[0]) if focus_ref and focus_ref[0] > 0 else 0),
)
except Exception:
pass
if focus_ref:
self.reservation_focus_until_ts = float(focus_ref[0] or 0.0)
if after_action_ref:
self.reservation_after_action_pending = bool(after_action_ref[0])
if preempted:
self._current_attending_reservation_fudai = True
elif not bool(getattr(self, "reservation_after_action_pending", False)):
if getattr(self, "_current_attending_reservation_fudai", False):
try:
self._log_kv(
"预约",
"[预约] 回退窗口未触发,清除旧的直接参与状态",
reason="attend_window_not_preempted_and_no_pending_action",
)
except Exception:
pass
self._current_attending_reservation_fudai = False
else:
try:
self._log_kv(
"预约",
"[预约] 单间模式(needswitch=False):不执行预约回退,预约会在当前直播间自动识别和参与",
reservations_count=(len(self.reservations) if self.reservations else 0),
)
douyin_reservation_logic.cleanup_expired_reservations(self, self.reservations, _write_state)
except Exception as exc:
try:
self._log_kv("预约", "[预约] 单间模式下清理过期预约时出错", error=str(exc))
except Exception:
pass
return False
def _should_allow_reservation_preempt_waiting_lottery(self: "fudai_analyse") -> bool:
"""等待开奖期间只允许明显更高价值的预约抢占。"""
try:
current_value = float(getattr(self, "_lottery_wait_prize_value_yuan", 0.0) or 0.0)
except Exception:
current_value = 0.0
try:
current_future_ts = float(getattr(self, "_lottery_result_expected_ts", 0.0) or 0.0)
except Exception:
current_future_ts = 0.0
try:
reservations = list(getattr(self, "reservations", []) or [])
except Exception:
reservations = []
if not reservations:
try:
self._log_kv(
"预约",
"[预约] 正在等待开奖,预约队列为空,跳过预约回退检查",
waiting_for_lottery=True,
current_wait_value=current_value,
current_future_ts=int(current_future_ts) if current_future_ts > 0 else 0,
)
except Exception:
pass
return False
now_ts = time.time()
try:
poll_before = _safe_float_attr(self, "high_value_fudai_poll_before_seconds", 10.0)
except Exception:
poll_before = 10.0
join_ahead = _safe_float_attr(self, "high_value_fudai_join_ahead_seconds", 100.0)
swipe_delay = _safe_float_attr(self, "reservation_back_swipe_delay", 0.6)
try:
room_pos = int(getattr(self, "room_pos", 0) or 0)
except Exception:
room_pos = 0
try:
from douyin.reservation.reservation_logic.attend_window_helpers import compute_dynamic_ahead
from douyin.reservation.reservation_logic.helpers import (
_select_reservation_target_for_window,
)
def _dynamic_ahead_for_item(item: dict) -> float:
dynamic_ahead, _est = compute_dynamic_ahead(
self,
item,
room_pos,
swipe_delay,
join_ahead,
)
return dynamic_ahead
selected_idx, target = _select_reservation_target_for_window(
reservations,
now_ts,
_dynamic_ahead_for_item,
poll_before,
)
except Exception:
selected_idx, target = 0, reservations[0]
try:
target_future_ts = float(target.get("future_ts") or 0.0)
except Exception:
target_future_ts = 0.0
try:
target_value = float(target.get("prize_value_yuan") or 0.0)
except Exception:
target_value = 0.0
# 若选择器没有命中当前窗口,会返回队头;此时不要用未来预约打断等待开奖。
in_window = False
try:
from douyin.reservation.reservation_logic.attend_window_helpers import compute_dynamic_ahead
dynamic_ahead, _est = compute_dynamic_ahead(
self,
target,
room_pos,
swipe_delay,
join_ahead,
)
in_window = (target_future_ts > 0) and (
now_ts >= target_future_ts - max(0.0, dynamic_ahead)
) and (now_ts <= target_future_ts + max(0.0, poll_before))
except Exception:
in_window = False
if not in_window:
try:
self._log_kv(
"预约",
"[预约] 正在等待开奖,预约未到参与窗口,跳过预约回退检查",
waiting_for_lottery=True,
current_wait_value=current_value,
target_value=target_value,
target_future_ts=int(target_future_ts) if target_future_ts > 0 else 0,
decision="skip_reservation_back",
reason="waiting_lottery_target_window_not_reached",
)
except Exception:
pass
return False
if target_value <= current_value:
try:
self._log_kv(
"预约",
"[预约] 正在等待开奖,当前已参与福袋价值不低于预约,跳过预约回退检查",
waiting_for_lottery=True,
current_wait_value=current_value,
current_future_ts=int(current_future_ts) if current_future_ts > 0 else 0,
target_value=target_value,
target_future_ts=int(target_future_ts) if target_future_ts > 0 else 0,
selected_index=int(selected_idx),
decision="skip_reservation_back",
reason="waiting_lottery_current_value_ge_target",
)
except Exception:
pass
return False
try:
self._log_kv(
"预约",
"[预约] 正在等待开奖,但预约价值更高,允许抢占当前等待",
waiting_for_lottery=True,
current_wait_value=current_value,
current_future_ts=int(current_future_ts) if current_future_ts > 0 else 0,
target_value=target_value,
target_future_ts=int(target_future_ts) if target_future_ts > 0 else 0,
selected_index=int(selected_idx),
decision="allow_reservation_back",
reason="waiting_lottery_target_value_gt_current",
)
except Exception:
pass
return True
def _write_reservations_state(self: "fudai_analyse") -> None:
from datetime import datetime
try:
now_ts = time.time()
last_ts = float(getattr(self, "_reservations_state_last_write_ts", 0.0) or 0.0)
if (now_ts - last_ts) < 1.0:
return
self._reservations_state_last_write_ts = now_ts
os.makedirs(os.path.dirname(self._reservations_state_path), exist_ok=True)
items = []
for r in self.reservations or []:
try:
ft = float(r.get("future_ts") or 0)
except Exception:
ft = 0.0
try:
ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft else ""
except Exception:
ft_str = str(r.get("future_str", ""))
items.append(
{
"prize_value_yuan": float(r.get("prize_value_yuan") or 0),
"content": str(r.get("content") or ""),
"future_ts": ft,
"future_str": ft_str,
"pos_seen": int(r.get("pos_seen") or 0),
"room_title": str(r.get("room_title", "") or ""),
"room_title_raw": str(r.get("room_title_raw", "") or ""),
"created_ts": float(r.get("created_ts") or 0),
}
)
data = {
"updated_ts": time.time(),
"reason": "process_reservation",
"room_pos": int(getattr(self, "room_pos", 0) or 0),
"current_room_title": str(getattr(self, "current_room_title", "") or ""),
"current_room_title_raw": str(getattr(self, "current_room_title_raw", "") or ""),
"reservations": items,
}
with open(self._reservations_state_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception as exc:
try:
self._log_kv("预约", "写入预约队列状态文件失败", error=str(exc), error_type=type(exc).__name__)
except Exception:
pass
def _log_reservation_attend_check(self: "fudai_analyse", needswitch_cfg: bool) -> None:
try:
from datetime import datetime as _dt
first_reservation_info = {}
if self.reservations and len(self.reservations) > 0:
first_r = self.reservations[0]
try:
ft = float(first_r.get("future_ts") or 0)
now_ts = time.time()
ft_str = _dt.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 else "无效"
remain_seconds = int(ft - now_ts) if ft > 0 else 0
first_reservation_info = {
"future_ts": int(ft) if ft > 0 else 0,
"future_str": ft_str,
"value": float(first_r.get("prize_value_yuan", 0)),
"pos_seen": int(first_r.get("pos_seen", 0)),
"remain_seconds": remain_seconds,
"current_room_pos": int(getattr(self, "room_pos", 0) or 0),
}
except Exception:
pass
self._log_kv(
"预约",
"[预约] run_once_basic:检查预约回退条件",
needswitch_cfg=needswitch_cfg,
reservations_count=(len(self.reservations) if self.reservations else 0),
first_reservation=first_reservation_info,
)
except Exception:
pass
@@ -0,0 +1,177 @@
from __future__ import annotations
import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..douyin_fudai import fudai_analyse
def handle_desktop_recovery(self: "fudai_analyse") -> bool:
"""桌面检测自救:若不在抖音前台则恢复并结束本轮。
说明:
- 这里不能在函数内再次调用 ``run_once_basic``;
- 否则会形成递归重入,出现同一进程内多层主流程并发推进,
导致偶发“连续切换两次直播间”等异常行为。
"""
from douyin.core import recovery as _recovery
try:
top_pkg = ""
try:
top_pkg = self.operation.get_top_package(self.device_id) or ""
self._log_kv("自救", "桌面检测:获取前台包名", top_pkg=top_pkg)
except Exception as exc:
top_pkg = ""
self._log_kv("自救", "桌面检测:获取前台包名失败", error=str(exc))
if top_pkg and not _recovery.is_douyin_foreground(top_pkg):
self._log_kv("自救", "桌面检测:检测到不在抖音前台", top_pkg=top_pkg, is_douyin=False)
try:
self._log_kv("自救", "发现前台包不在抖音,尝试通过包名启动抖音", top_pkg=top_pkg)
_recovery.recover_to_douyin(self, log=lambda msg: self._log_kv("自救", msg))
try:
self._log_kv(
"流程",
"run_once_basic:自救完成,结束本轮并由外层循环进入下一轮",
)
except Exception:
pass
return True
except Exception as exc2:
try:
self._log_kv("自救", "恢复失败", error=str(exc2), error_type=type(exc2).__name__)
except Exception:
pass
except Exception as exc:
try:
self._log_kv("自救", "桌面检测异常", error=str(exc), error_type=type(exc).__name__)
except Exception:
pass
return False
def screenshot_and_diagnose(self: "fudai_analyse", start_time: float):
"""截图 + 阶段诊断;失败时返回 None。"""
screenshot_start = time.time()
max_screenshot_retries = 3
ok = False
for retry in range(max_screenshot_retries):
ok = self.operation.get_screenshot(self.device_id, use_service=False)
if ok:
break
if retry < max_screenshot_retries - 1:
self._log_kv(
"截图",
f"截图失败,重试中 ({retry + 1}/{max_screenshot_retries})",
retry=retry + 1,
max_retries=max_screenshot_retries,
)
try:
self.operation.delay(1.0)
except Exception:
time.sleep(1.0)
screenshot_elapsed = time.time() - screenshot_start
if not ok:
elapsed = time.time() - start_time
self._log_kv(
"截图",
"获取截图失败(多次重试后仍失败)",
ok=0,
retries=max_screenshot_retries,
elapsed_seconds=round(elapsed, 2),
screenshot_elapsed_seconds=round(screenshot_elapsed, 2),
reservation_after_action_pending=bool(getattr(self, "reservation_after_action_pending", False)),
reservation_focus_until_ts=float(getattr(self, "reservation_focus_until_ts", 0.0) or 0.0),
waiting_for_lottery=bool(getattr(self, "_waiting_for_lottery_result", False)),
room_pos=int(getattr(self, "room_pos", 0) or 0),
suggestion="检查设备连接状态和ADB服务",
)
return None
try:
self._log_kv(
"阶段诊断",
"调用阶段诊断-前置检查",
trigger_reason="run_once_basic_initial",
fudai_detail_task_count_from_stage=getattr(self, "_fudai_detail_task_count_from_stage", None),
screenshot_ready_for_ocr=bool(getattr(self, "_screenshot_ready_for_ocr", False)),
)
except Exception:
pass
stage, seen = self._diagnose_stage_from_current_screen(trigger_reason="run_once_basic_initial")
self._last_diag_stage = stage
self._last_diag_seen = seen
self._last_diag_ts = time.time()
elapsed = time.time() - start_time
self._log_kv(
"截图",
"截图+阶段诊断",
stage=stage,
seen=seen,
elapsed_seconds=round(elapsed, 2),
screenshot_elapsed_seconds=round(screenshot_elapsed, 2),
)
return stage, seen
def handle_high_value_room_revisit(self: "fudai_analyse", start_time: float) -> bool:
"""高价值房间重访检查。返回 True 表示重访成功并应结束本轮。"""
try:
revisit_enabled = bool(getattr(self, "high_value_room_revisit_enabled", False))
only_current_run = bool(getattr(self, "high_value_room_revisit_only_current_run", False))
if not revisit_enabled:
return False
from douyin.other import douyin_high_value_room
should_revisit = douyin_high_value_room.should_trigger_revisit(
analyser=self,
revisit_enabled=revisit_enabled,
only_current_run=only_current_run,
min_interval_seconds=getattr(self, "high_value_room_revisit_min_interval_seconds", 300),
max_revisit_per_run=getattr(self, "high_value_room_revisit_max_per_run", 5),
)
if not should_revisit:
return False
candidates = douyin_high_value_room.get_revisit_candidates(
analyser=self,
only_current_run=only_current_run,
min_prize_value=getattr(self, "high_value_room_revisit_min_prize_value", 0.0),
max_age_days=getattr(self, "high_value_room_revisit_max_age_days", 30),
)
if not candidates:
return False
target_room = candidates[0]
self._log_kv(
"高价值房间",
"[重访] 触发高价值房间重访",
target_room_title=target_room.get("room_title", "")[:30],
max_prize_value=target_room.get("max_prize_value_yuan", 0),
candidates_count=len(candidates),
)
revisit_success = douyin_high_value_room.execute_room_revisit(analyser=self, target_room=target_room)
if revisit_success:
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(高价值房间重访成功)", elapsed_seconds=round(elapsed, 2))
return True
self._log_kv("高价值房间", "[重访] 高价值房间重访失败,继续正常流程")
except Exception as exc:
try:
self._log_kv(
"高价值房间",
"[重访] 高价值房间重访检查异常",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
return False
@@ -0,0 +1,161 @@
from __future__ import annotations
import time
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ..douyin_fudai import fudai_analyse
def handle_waiting_for_lottery_result(self: "fudai_analyse", start_time: float) -> bool:
if not getattr(self, "_waiting_for_lottery_result", False):
return False
wait_lottery_start = time.time()
try:
future_ts = getattr(self, "_lottery_result_expected_ts", 0.0) or 0.0
current_ts = time.time()
timeout_ts = future_ts + 10.0
if current_ts >= timeout_ts:
self._waiting_for_lottery_result = False
self._current_attending_reservation_fudai = False
timeout_seconds = int(current_ts - future_ts)
self._log_kv(
"参与",
f"等待开奖超时(超过开奖时间{timeout_seconds}秒),清除等待标志,继续执行其他操作",
超时秒数=timeout_seconds,
等待开奖总耗时=round(time.time() - wait_lottery_start, 2),
)
return False
wait_start_ts = getattr(self, "_lottery_wait_start_ts", future_ts)
passed_seconds = int(current_ts - wait_start_ts)
self._log_kv("参与", f"等待开奖结果中,持续OCR检测,已等待{passed_seconds}秒", 已等待秒数=passed_seconds)
deadline_ts = timeout_ts
attempt = 0
consecutive_none = 0
interval = 0.5
while time.time() <= deadline_ts:
attempt += 1
loop_start = time.time()
try:
try:
screenshot_start = time.time()
self.operation.get_screenshot(self.device_id)
self._log_kv("截图", "等待开奖期间截图", elapsed_seconds=round(time.time() - screenshot_start, 2))
except Exception:
pass
ocr_start = time.time()
result = self._check_lottery_result_by_ocr()
self._log_kv("OCR", "等待开奖期间OCR检测", elapsed_seconds=round(time.time() - ocr_start, 2))
except Exception as e:
result = None
try:
self._log_kv("参与", "等待开奖期间OCR检测出错,继续重试", error=str(e))
except Exception:
pass
if result:
self._waiting_for_lottery_result = False
self._current_attending_reservation_fudai = False
try:
self._log_kv("参与", "等待期间检测到开奖结果,开始处理", attempt=attempt, 等待开奖总耗时=round(time.time() - wait_lottery_start, 2))
except Exception:
pass
self._handle_lottery_result_by_ocr(result)
elapsed = time.time() - start_time
try:
self._log_kv("流程", "run_once_basic完成(等待开奖期间处理结果)", elapsed_seconds=round(elapsed, 2))
except Exception:
pass
return True
consecutive_none += 1
now_ts_inner = time.time()
remain_to_deadline = int(max(0, deadline_ts - now_ts_inner))
try:
self._log_kv("参与", "等待开奖连续检测:未识别到结果", attempt=attempt, remain_seconds=remain_to_deadline, 单次检测耗时=round(time.time() - loop_start, 2))
except Exception:
pass
spent = time.time() - loop_start
to_sleep = max(0.0, interval - spent)
if to_sleep > 0:
if time.time() + to_sleep > deadline_ts:
break
self.operation.delay(to_sleep)
self._waiting_for_lottery_result = False
self._current_attending_reservation_fudai = False
try:
self._log_kv("参与", "等待开奖连续检测结束:未识别到开奖结果,清除等待标志", attempts=attempt, consecutive_none=consecutive_none, 等待开奖总耗时=round(time.time() - wait_lottery_start, 2))
except Exception:
pass
try:
needswitch = bool(getattr(self, "needswitch", True))
except Exception:
needswitch = True
if needswitch:
try:
self._log_kv("开奖结果", "处理完开奖结果,切换直播间找新福袋", color="RED")
except Exception:
pass
self.swipe_up_to_next_live()
elapsed = time.time() - start_time
try:
self._log_kv("流程", "run_once_basic完成(等待开奖期间处理结果)", elapsed_seconds=round(elapsed, 2))
except Exception:
pass
return True
except Exception as exc:
self._log_kv("参与", "等待开奖检测时出错", error=str(exc))
self._waiting_for_lottery_result = False
self._current_attending_reservation_fudai = False
return False
def handle_no_attend_timeout(self: "fudai_analyse", start_time: float) -> bool:
try:
last_attend_ts = float(getattr(self, "_last_successful_attend_ts", 0.0) or 0.0)
timeout_minutes = float(getattr(self, "_no_attend_timeout_minutes", 30.0) or 30.0)
current_ts = time.time()
run_start_ts = float(getattr(self, "_run_start_ts", current_ts) or current_ts)
if last_attend_ts > 0:
elapsed_minutes = (current_ts - last_attend_ts) / 60.0
if elapsed_minutes >= timeout_minutes:
try:
self._log_kv("超时", "30分钟未参与成功福袋,返回推荐页面重新进入直播间", last_attend_minutes_ago=round(elapsed_minutes, 1))
except Exception:
pass
self._return_to_recommend_and_reenter_live()
try:
self._last_successful_attend_ts = current_ts
except Exception:
pass
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(30分钟超时处理)", elapsed_seconds=round(elapsed, 2))
return True
else:
elapsed_minutes = (current_ts - run_start_ts) / 60.0
if elapsed_minutes >= timeout_minutes:
try:
self._log_kv("超时", f"运行{round(elapsed_minutes, 1)}分钟仍未参与成功福袋,返回推荐页面重新进入直播间", run_minutes=round(elapsed_minutes, 1))
except Exception:
pass
self._return_to_recommend_and_reenter_live()
elapsed = time.time() - start_time
self._log_kv("流程", "run_once_basic完成(30分钟超时处理)", elapsed_seconds=round(elapsed, 2))
return True
except Exception as exc:
try:
self._log_kv("超时", "检查30分钟超时时出错", error=str(exc))
except Exception:
pass
return False
+176 -6
View File
@@ -2,14 +2,34 @@
路径配置模块:统一管理所有文件路径,便于整理文件夹结构而不影响代码
"""
import os
import sys
from typing import Optional
import json
def _detect_project_root() -> str:
"""返回运行根目录;源码运行是仓库根,PyInstaller 运行是 exe 所在目录。"""
if getattr(sys, "frozen", False):
return os.path.dirname(os.path.abspath(sys.executable))
# __file__ 位于 <project_root>/douyin/core/path_config.py,
# 所以项目根是当前文件向上两级目录。
return os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
# 项目根目录(所有路径的基准)
# __file__ 位于 <project_root>/douyin/core/path_config.py,
# 所以项目根是当前文件向上两级目录。
PROJECT_ROOT = os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
PROJECT_ROOT = _detect_project_root()
# 运行时路径与设备侧默认路径(支持环境变量覆盖,便于迁移)
DEFAULT_ANDROID_SCREENSHOT_PATH = "/sdcard/DCIM/screenshot.png"
DEFAULT_ANDROID_SCREENSHOT_ALT_PATH = "/sdcard/DCIM/screenshot1.png"
DEFAULT_ANDROID_WINDOW_DUMP_PATH = "/sdcard/window_dump.xml"
DEFAULT_DOUYIN_PACKAGES = (
"com.ss.android.ugc.aweme",
"com.ss.android.ugc.aweme.lite",
"com.zhiliaoapp.musically",
)
DEFAULT_ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"
DEFAULT_WEB_GUI_HOST = "127.0.0.1"
DEFAULT_WEB_GUI_PORT = 8000
def get_project_root() -> str:
@@ -17,6 +37,94 @@ def get_project_root() -> str:
return PROJECT_ROOT
def get_venv_python_path() -> str:
"""返回项目虚拟环境 Python 路径(Windows)。"""
return os.path.join(PROJECT_ROOT, ".venv", "Scripts", "python.exe")
def get_android_screenshot_path() -> str:
"""返回设备侧截图路径(可通过环境变量覆盖)。"""
return (
os.environ.get("ANDROID_SCREENSHOT_PATH", "").strip()
or DEFAULT_ANDROID_SCREENSHOT_PATH
)
def get_android_screenshot_alt_path() -> str:
"""返回设备侧备用截图路径(可通过环境变量覆盖)。"""
return (
os.environ.get("ANDROID_SCREENSHOT_ALT_PATH", "").strip()
or DEFAULT_ANDROID_SCREENSHOT_ALT_PATH
)
def get_android_window_dump_path() -> str:
"""返回设备侧 UI dump 路径(可通过环境变量覆盖)。"""
return (
os.environ.get("ANDROID_WINDOW_DUMP_PATH", "").strip()
or DEFAULT_ANDROID_WINDOW_DUMP_PATH
)
def get_douyin_packages() -> tuple[str, ...]:
"""返回抖音候选包名列表(支持环境变量覆盖,逗号分隔)。"""
raw = (os.environ.get("DOUYIN_PACKAGES", "") or "").strip()
if not raw:
return DEFAULT_DOUYIN_PACKAGES
items = tuple(x.strip() for x in raw.split(",") if x.strip())
return items or DEFAULT_DOUYIN_PACKAGES
def get_adb_keyboard_ime() -> str:
"""返回 ADBKeyboard IME(支持环境变量覆盖)。"""
return (os.environ.get("ADB_KEYBOARD_IME", "") or "").strip() or DEFAULT_ADB_KEYBOARD_IME
def _read_runtime_config() -> dict:
"""读取 config/config.json,失败时返回空字典。"""
try:
cfg_path = get_config_path()
if not os.path.exists(cfg_path):
return {}
with open(cfg_path, "r", encoding="utf-8") as f:
obj = json.load(f)
return obj if isinstance(obj, dict) else {}
except Exception:
return {}
def get_web_gui_host() -> str:
"""返回 Web GUI 监听 host(环境变量优先,其次 config.json,最后默认值)。"""
host = (os.environ.get("WEB_GUI_HOST") or "").strip()
if host:
return host
cfg = _read_runtime_config()
cfg_host = str(cfg.get("web_gui_host", "") or "").strip()
return cfg_host or DEFAULT_WEB_GUI_HOST
def get_web_gui_port() -> int:
"""返回 Web GUI 监听端口(环境变量优先,其次 config.json,最后默认值)。"""
env_raw = (os.environ.get("PORT") or os.environ.get("WEB_GUI_PORT") or "").strip()
if env_raw:
try:
port = int(env_raw)
if 1 <= port <= 65535:
return port
except Exception:
pass
cfg = _read_runtime_config()
cfg_raw = cfg.get("web_gui_port", DEFAULT_WEB_GUI_PORT)
try:
port = int(cfg_raw)
if 1 <= port <= 65535:
return port
except Exception:
pass
return DEFAULT_WEB_GUI_PORT
def get_config_path() -> str:
"""返回 config.json 的路径"""
return os.path.join(PROJECT_ROOT, "config", "config.json")
@@ -40,6 +148,16 @@ def get_log_file_path() -> str:
return os.path.join(PROJECT_ROOT, "logs", "unified.log")
def get_simple_log_path() -> str:
"""返回简洁日志文件的路径"""
return os.path.join(PROJECT_ROOT, "logs", "simple.log")
def get_detail_log_path() -> str:
"""返回详细日志文件的路径"""
return os.path.join(PROJECT_ROOT, "logs", "detail.log")
def get_actions_log_path() -> str:
"""返回行为日志文件 (actions.log) 的路径"""
return os.path.join(PROJECT_ROOT, "logs", "actions.log")
@@ -138,6 +256,49 @@ def get_run_cli_path() -> str:
return os.path.abspath(os.path.join(PROJECT_ROOT, "bin", "run_cli.py"))
def get_run_cli_command() -> list[str]:
"""返回启动 run_cli 的命令;源码模式用 Python 脚本,打包模式用同目录 exe。"""
if getattr(sys, "frozen", False):
exe_name = "run_cli.exe" if sys.platform.startswith("win") else "run_cli"
exe_path = os.path.join(PROJECT_ROOT, exe_name)
return [exe_path]
return [sys.executable, get_run_cli_path()]
def get_bundled_platform_tools_dir() -> str:
"""返回随包 Android platform-tools 目录。"""
return os.path.join(PROJECT_ROOT, "platform-tools")
def get_bundled_adb_path() -> str:
"""返回随包 adb 路径。"""
exe_name = "adb.exe" if sys.platform.startswith("win") else "adb"
return os.path.join(get_bundled_platform_tools_dir(), exe_name)
def find_bundled_adb() -> Optional[str]:
"""若分发包内自带 adb,返回其绝对路径。"""
candidates = [get_bundled_adb_path()]
meipass = getattr(sys, "_MEIPASS", None)
if meipass:
exe_name = "adb.exe" if sys.platform.startswith("win") else "adb"
candidates.append(os.path.join(str(meipass), "platform-tools", exe_name))
for path in candidates:
if os.path.exists(path):
return os.path.abspath(path)
return None
def get_bundled_android_tools_dir() -> str:
"""返回随包 Android 辅助工具目录。"""
return os.path.join(PROJECT_ROOT, "android-tools")
def get_bundled_adbkeyboard_apk_path() -> str:
"""返回随包 ADBKeyboard APK 路径。"""
return os.path.join(get_bundled_android_tools_dir(), "ADBKeyboard.apk")
def ensure_dir(path: str) -> None:
"""确保目录存在,不存在则创建"""
dir_path = os.path.dirname(path) if os.path.isfile(path) else path
@@ -177,14 +338,23 @@ def find_executable(cmd: str) -> Optional[str]:
try:
if sys.platform.startswith("win"):
# 使用 where 查找(Windows)
proc = subprocess.run(["where", cmd], capture_output=True, text=True)
# 注意:where 在未命中时会往 stderr 打印
# “INFO: Could not find files for the given pattern(s)”。
# 这里仅以 returncode/stdout 判断,不需要把该噪声透传到上层日志。
proc = subprocess.run(
["where", cmd],
capture_output=True,
text=True,
stderr=subprocess.DEVNULL,
)
if proc.returncode == 0 and proc.stdout:
first = proc.stdout.splitlines()[0].strip()
if first:
return first
else:
# 类 Unix:尝试 command -v 再 which
proc = subprocess.run(["/bin/sh", "-c", f"command -v {cmd} || which {cmd}"], capture_output=True, text=True)
import shlex
proc = subprocess.run(["/bin/sh", "-c", f"command -v {shlex.quote(cmd)} || which {shlex.quote(cmd)}"], capture_output=True, text=True)
if proc.returncode == 0 and proc.stdout:
first = proc.stdout.splitlines()[0].strip()
if first:
+113
View File
@@ -0,0 +1,113 @@
"""桌面自救共享逻辑
把 fudai_modules.run_once_basic_helpers 和 douyin.other.douyin_yanghao
中重复的"前台不在抖音 → 包名启动 → 失败兜底点击坐标"逻辑抽到这里。
"""
from __future__ import annotations
import time
from typing import Any, Callable, Optional
def is_douyin_foreground(top_pkg: str) -> bool:
"""判断给定的前台包名是否属于抖音相关包。"""
return bool(top_pkg) and (
"aweme" in top_pkg
or "douyin" in top_pkg
or "com.ss.android.ugc" in top_pkg
)
def fallback_click_recovery(
analyser: Any,
log: Optional[Callable[[str], None]] = None,
) -> None:
"""旧的点击坐标自救:桌面图标 → 直播按钮 → 进入直播间×2。
保留作为 launch_package 失败时的兜底。所有坐标读 analyser 上的属性,
取不到时使用默认值(适配 1080x2400 的位置)。
"""
op = analyser.operation
device_id = analyser.device_id
desktop_x = int(getattr(analyser, "desktop_icon_x", 153) or 153)
desktop_y = int(getattr(analyser, "desktop_icon_y", 260) or 260)
try:
op.click(device_id, desktop_x, desktop_y)
except Exception:
# 退化为默认硬编码位置
try:
op.click(device_id, 153, 260)
except Exception:
pass
op.delay(2)
fallback_x = int(getattr(analyser, "yanghao_fallback_live_x", 540) or 540)
fallback_y = int(getattr(analyser, "yanghao_fallback_live_y", 2000) or 2000)
try:
if log:
log(f"点击直播按钮 x={fallback_x} y={fallback_y}")
op.click(device_id, fallback_x, fallback_y)
op.delay(1.5)
except Exception:
pass
enter_x = int(getattr(analyser, "yanghao_fallback_enter_live_x", 540) or 540)
enter_y = int(getattr(analyser, "yanghao_fallback_enter_live_y", 1200) or 1200)
try:
if log:
log(f"点击进入直播间 x={enter_x} y={enter_y} 次数=2")
op.click(device_id, enter_x, enter_y)
op.delay(0.6)
op.click(device_id, enter_x, enter_y)
op.delay(2.0)
except Exception:
pass
def recover_to_douyin(
analyser: Any,
log: Optional[Callable[[str], None]] = None,
) -> bool:
"""统一的桌面自救入口。
流程:
1. 优先 op.launch_package(device_id, ""),按抖音常用包名顺序尝试
2. 包名启动失败或抛异常时,回退到点击坐标自救(fallback_click_recovery)
参数:
analyser: 提供 .operation / .device_id / 自救坐标属性的对象
log: 可选的日志回调(接受单字符串)
返回:
True 表示已尝试某种自救(不保证一定成功,但已执行动作);
False 仅在调用环境本身出现严重异常时返回。
"""
try:
op = analyser.operation
device_id = analyser.device_id
except Exception:
return False
launched_ok = False
used_pkg = ""
try:
launched_ok, used_pkg = op.launch_package(device_id, "")
except Exception as exc:
if log:
log(f"包名启动调用异常 {exc},回退点击坐标")
if launched_ok:
if log:
log(f"包名启动抖音成功 pkg={used_pkg}")
try:
op.delay(2.5)
except Exception:
time.sleep(2.5)
return True
# 兜底:保留旧的点击坐标自救
if log:
log("包名启动失败,回退点击桌面图标 + 备用坐标")
fallback_click_recovery(analyser, log=log)
return True
File diff suppressed because it is too large. Load diff
@@ -22,6 +22,33 @@ from .swipe_sendevent import _swipe_with_sendevent_improved
from .clipboard import set_clipboard_text
from .device_select import select_device
from .ocr_digits import analyse_pic_digits
from .text_input import (
paste_from_clipboard,
input_text,
paste_text,
get_current_ime,
list_imes,
ensure_adbkeyboard_ime,
restore_ime,
try_set_ime,
_adbkeyboard_broadcast,
_adbkeyboard_broadcast_int,
keyevent,
adbkeyboard_editor_action,
confirm_from_keyboard,
input_text_adbkeyboard,
paste_text_at,
)
from .ui_automator import (
uiautomator_dump,
tap_by_text,
tap_close_icon,
)
from .foreground import (
get_top_package,
launch_package,
is_douyin_foreground,
)
from .adb_helpers import _adb_args
@@ -39,4 +66,25 @@ __all__ = [
"_adb_args",
"select_device",
"analyse_pic_digits",
"paste_from_clipboard",
"input_text",
"paste_text",
"get_current_ime",
"list_imes",
"ensure_adbkeyboard_ime",
"restore_ime",
"try_set_ime",
"_adbkeyboard_broadcast",
"_adbkeyboard_broadcast_int",
"keyevent",
"adbkeyboard_editor_action",
"confirm_from_keyboard",
"input_text_adbkeyboard",
"paste_text_at",
"uiautomator_dump",
"tap_by_text",
"tap_close_icon",
"get_top_package",
"launch_package",
"is_douyin_foreground",
]
@@ -8,12 +8,18 @@ from __future__ import annotations
import os
from typing import List
from douyin.core import path_config
def _adb_path() -> str:
"""返回可用于 subprocess(list_args) 的 adb 路径(不带外层引号)。"""
adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb")
if adb.startswith('"') and adb.endswith('"'):
adb = adb[1:-1]
if adb == "adb":
bundled_adb = path_config.find_bundled_adb()
if bundled_adb:
return bundled_adb
return adb
@@ -14,7 +14,7 @@ import logging
import re
import time
from datetime import datetime, timedelta
from typing import Tuple
from typing import Optional, Tuple
# 与原 underlying_operations._uo_log 同名 logger,避免改变历史日志检索
_LOGGER = logging.getLogger("douyin.core.underlying_operations")
@@ -123,16 +123,16 @@ def check_countdown(last_time=""):
else:
total2 = None
if total1 is not None and total1 <= 900:
if total1 is not None and total1 <= 3600:
return total1
if total2 is not None and total2 <= 900:
if total2 is not None and total2 <= 3600:
return total2
# 若一个明显异常而另一个更合理(<=900),交换
# 若一个明显异常而另一个更合理(<=3600),交换
if total1 is not None and total2 is not None:
if total1 > 900 and total2 <= 900:
if total1 > 3600 and total2 <= 3600:
return total2
if total2 > 900 and total1 <= 900:
if total2 > 3600 and total1 <= 3600:
return total1
# 兜底:谁能解析就用谁;都不行则做进位
@@ -181,18 +181,18 @@ def check_countdown(last_time=""):
if total_seconds is None:
_uo_log("时间格式异常")
return False
_uo_log("剩余总秒数:", total_seconds)
# 超过 15 分钟基本是误识别:按 14分50秒处理,避免卡死等待
if total_seconds > 900:
total_seconds = 890
_uo_log(f"剩余总秒数:{total_seconds}")
# 超过 60 分钟视为 OCR 误识别,按 59 分 50 秒处理
if total_seconds > 3600:
total_seconds = 3590
now = datetime.now()
_uo_log("当前时间:", now.strftime("%Y-%m-%d %H:%M:%S"))
_uo_log(f"当前时间:{now.strftime('%Y-%m-%d %H:%M:%S')}")
future_time = now + timedelta(seconds=int(total_seconds))
future_timestamp = future_time.timestamp()
future_datetime = datetime.fromtimestamp(future_timestamp)
formatted_future_time = future_datetime.strftime("%Y-%m-%d %H:%M:%S")
_uo_log("预计开奖时间:", formatted_future_time)
_uo_log(f"预计开奖时间:{formatted_future_time}")
return int(total_seconds), future_timestamp
except Exception:
_uo_log("输入的字符串不是有效的时间格式")
@@ -57,10 +57,18 @@ def select_device():
print("检测到多台设备且当前不是交互式终端,请通过 --device-id 明确指定设备。")
return False
num = input()
num = int(num)
try:
num = int(num)
except ValueError:
print("请输入有效数字:")
return False
while not num in dictdevice.keys():
print("输入不正确,请重新输入:")
num = input()
num = int(num)
try:
num = int(num)
except ValueError:
print("请输入有效数字:")
return False
return dictdevice[num]
@@ -0,0 +1,84 @@
"""前台包检测与应用拉起逻辑(从 underlying_operations.py 抽离)。"""
from __future__ import annotations
import re
from typing import TYPE_CHECKING, Tuple
from douyin.core import path_config
if TYPE_CHECKING:
from douyin.core.underlying_operations import underlying_operations
DOUYIN_PACKAGES = path_config.get_douyin_packages()
def get_top_package(self: "underlying_operations", device_id: str) -> str:
"""尝试返回当前处于前台的包名。失败返回空字符串。"""
try:
ok, out = self._run_adb_shell_capture(
device_id, "dumpsys window windows", timeout_seconds=4.0
)
if ok and out:
for ln in (out or "").splitlines():
if (
"mCurrentFocus" in ln
or "mFocusedApp" in ln
or "mFocusedWindow" in ln
):
m = re.search(r"([A-Za-z0-9_\.]+)\/", ln)
if m:
return m.group(1)
ok2, out2 = self._run_adb_shell_capture(
device_id, "dumpsys activity activities", timeout_seconds=4.0
)
if ok2 and out2:
for ln in (out2 or "").splitlines():
if "mResumedActivity" in ln or "ResumedActivity" in ln:
m = re.search(r"([A-Za-z0-9_\.]+)\/", ln)
if m:
return m.group(1)
except Exception:
pass
return ""
def launch_package(
self: "underlying_operations",
device_id: str,
package_name: str = "",
timeout_seconds: float = 5.0,
) -> Tuple[bool, str]:
"""通过包名启动应用。"""
candidates = [package_name] if package_name else list(DOUYIN_PACKAGES)
for pkg in candidates:
pkg = (pkg or "").strip()
if not pkg:
continue
cmd = f"monkey -p {pkg} -c android.intent.category.LAUNCHER 1"
ok, out = self._run_adb_shell_capture(
device_id, cmd, timeout_seconds=timeout_seconds
)
if ok and "No activities found" not in (out or "") and "aborted" not in (
out or ""
).lower():
return True, pkg
for activity in (
".main.MainActivity",
".splash.SplashActivity",
".main.homepage.MainActivity",
):
am_cmd = f"am start -n {pkg}/{activity}"
if self._run_adb_shell(
device_id, am_cmd, timeout_seconds=timeout_seconds
):
return True, pkg
return False, ""
def is_douyin_foreground(self: "underlying_operations", device_id: str) -> bool:
"""便捷判断:当前前台是否是抖音相关包。"""
top_pkg = self.get_top_package(device_id) or ""
return bool(top_pkg) and (
"aweme" in top_pkg or "douyin" in top_pkg or "com.ss.android.ugc" in top_pkg
)
@@ -0,0 +1,296 @@
"""douyin/core/underlying_operations_pkg/image_ops - cut_pic 图片裁剪管道
把 underlying_operations.cut_pic 整段抽出来。流程:
- 默认分支(target=""):从项目根 pic/screenshot.png 读图,裁出 cut.png 或 ocr/<name>.png
- 命名分支(target="xxx"):从 pic/<target>/screenshot.png 读图,裁出 pic/<target>/<name>.png
- 重试 3 次(截图缺失/文件太小/PIL 损坏)
- 写入坐标缓存供 analyse_pic_word 调试图像用
- 可选保存 cut_pic 调试图(SAVE_CUT_PIC_DEBUG_IMAGES=1)
入口:cut_pic(self, left_up, right_down, target, name) -> bool
self 必须提供:_find_pic_path / _ocr_coords_lock / _ocr_coords_cache
"""
from __future__ import annotations
import logging
import os
import time as time_module
from typing import Any
from PIL import Image
def _ensure_parent_dir(path: str) -> None:
"""确保路径的父目录存在。"""
try:
parent = os.path.dirname(path)
if parent:
os.makedirs(parent, exist_ok=True)
except Exception:
pass
def _validate_coords(
left_up: tuple, right_down: tuple, image_size: tuple
) -> bool:
"""检查裁剪坐标在图片范围内且非空。"""
left, top = left_up
right, bottom = right_down
width, height = image_size
return not (
left < 0 or top < 0
or right > width or bottom > height
or left >= right or top >= bottom
)
def _save_cut_debug_images(self: Any, cropped_img, pic, name: str, source_label: str, left: int, top: int, right: int, bottom: int) -> None:
"""根据环境变量决定是否保存 cut_pic 调试图。"""
try:
try:
from douyin.fudai.core.fudai_debug_utils import (
is_fudai_detail_field_debug_picname,
)
if is_fudai_detail_field_debug_picname(name):
return
except Exception:
pass
save_debug = os.environ.get("SAVE_CUT_PIC_DEBUG_IMAGES", "0") == "1"
if not save_debug:
try:
save_debug = os.environ.get("SAVE_DEBUG_IMAGES", "0") == "1"
except Exception:
pass
if not save_debug:
return
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(
cropped_img, operation_type="cut_pic"
)
# 保存调试图像(完整截图+区域标注)
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="cut_pic",
picname=name if name else "cut",
step="before_ocr",
coords=(left, top, right, bottom),
extra_info={
"source": source_label,
"size": f"{right-left}x{bottom-top}",
},
)
if debug_path:
try:
logging.debug("[调试图像] cut_pic保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
def cut_pic(
self: Any,
left_up=(0, 63),
right_down=(1080, 1620),
target: str = "",
name: str = "",
) -> bool:
"""裁剪图片,获取需要的区域小图片方便识别。"""
from douyin.core.underlying_operations import _uo_log
max_retries = 3
retry_delay = 0.1
for attempt in range(max_retries):
try:
if target == "" or target is False:
from douyin.core import path_config
path = path_config.get_pic_dir()
pic1_path = path_config.get_screenshot_path()
cut_pic_path = None
if not os.path.exists(pic1_path):
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
if os.path.getsize(pic1_path) < 100:
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
# 尝试打开并验证图片
try:
pic = Image.open(pic1_path)
_ = pic.size
pic.load()
except (SyntaxError, IOError, OSError) as e:
if attempt < max_retries - 1:
_uo_log(
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
)
time_module.sleep(retry_delay * (attempt + 1))
continue
raise
if name == "":
cut_pic_path = path + "/cut.png"
else:
cut_pic_path = self._find_pic_path(name, for_reading=False)
if not _validate_coords(left_up, right_down, pic.size):
raise ValueError(
f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}"
)
left, top = left_up
right, bottom = right_down
cropped_img = pic.crop((left, top, right, bottom))
assert cut_pic_path is not None
try:
_ensure_parent_dir(cut_pic_path)
cropped_img.save(cut_pic_path)
except Exception:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
# 存储坐标信息供 analyse_pic_word 使用
if name:
try:
with self._ocr_coords_lock:
self._ocr_coords_cache[name] = (left, top, right, bottom)
except Exception:
pass
try:
_save_cut_debug_images(
self, cropped_img, pic, name,
"screenshot.png", left, top, right, bottom,
)
finally:
pic.close()
return True
else:
from douyin.core import path_config
path_target = os.path.join(path_config.get_pic_dir(), target)
pic1_path = os.path.join(path_target, "screenshot.png")
cut_pic_path = None
if not os.path.exists(pic1_path):
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise FileNotFoundError(f"截图文件不存在: {pic1_path}")
if os.path.getsize(pic1_path) < 100:
if attempt < max_retries - 1:
time_module.sleep(retry_delay * (attempt + 1))
continue
raise ValueError(f"截图文件太小,可能损坏: {pic1_path}")
try:
pic = Image.open(pic1_path)
_ = pic.size
pic.load()
except (SyntaxError, IOError, OSError) as e:
if attempt < max_retries - 1:
_uo_log(
f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}"
)
time_module.sleep(retry_delay * (attempt + 1))
continue
raise
if name == "":
cut_pic_path = path_target + "/cut.png"
else:
cut_pic_path = path_target + "/" + name + ".png"
try:
if not _validate_coords(left_up, right_down, pic.size):
error_msg = (
f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, "
f"image_size={pic.size}"
)
if attempt == max_retries - 1:
_uo_log(f"[错误] {error_msg}")
return False
continue
left, top = left_up
right, bottom = right_down
assert cut_pic_path is not None
cropped_img = pic.crop((left, top, right, bottom))
try:
_ensure_parent_dir(cut_pic_path)
cropped_img.save(cut_pic_path)
except Exception:
logging.exception("保存裁剪图片失败: %s", cut_pic_path)
return False
if name:
try:
with self._ocr_coords_lock:
self._ocr_coords_cache[name] = (left, top, right, bottom)
except Exception:
pass
# 命名分支总是保存 cut_pic 调试图(与原版行为一致 — 没有开关检查)
try:
try:
from douyin.fudai.core.fudai_debug_utils import (
is_fudai_detail_field_debug_picname,
)
if is_fudai_detail_field_debug_picname(name):
return True
except Exception:
pass
from douyin.handlers import douyin_screenshot_manager
pic_rgb = pic.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb,
operation_type="cut_pic",
picname=name if name else "cut",
step="before_ocr",
coords=(left, top, right, bottom),
extra_info={
"source": target + "/screenshot.png",
"size": f"{right-left}x{bottom-top}",
},
)
if debug_path:
try:
logging.debug("[调试图像] cut_pic保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
return True
finally:
pic.close()
except (SyntaxError, IOError, OSError, FileNotFoundError, ValueError) as e:
if attempt == max_retries - 1:
error_msg = f"[错误] 裁剪图片失败 (尝试 {max_retries} 次): {e}"
_uo_log(error_msg)
_uo_log(f" 源文件: {locals().get('pic1_path', 'N/A')}")
_uo_log(f" 目标文件: {locals().get('cut_pic_path', 'N/A')}")
return False
continue
return False
@@ -0,0 +1,406 @@
"""douyin/core/underlying_operations_pkg/ocr_pipeline - analyse_pic_word OCR 管道
把 underlying_operations.analyse_pic_word 整段抽出来。流程:
1. 路径解析 + 缓存查询(基于图片字节哈希)
2. 加载 + 验证图片完整性
3. change_color 预处理(0=保留彩色,1/2=二值化)
4. 调试图像保存(preprocessed 步骤,仅当 SAVE_OCR_DEBUG_IMAGES=1)
5. 调用 OCR(EasyOCR / PaddleOCR predict/ocr)
6. 提取文本 + 置信度
7. 写缓存
8. 调试图像保存(after_ocr 步骤)
9. 成功识别保存到 ocr/<category>/<picname>_success.png
入口:analyse_pic_word(self, picname, change_color, pic_path, return_confidence)
self 必须提供:_find_pic_path / extract_ocr_content / ocr / ocr_type /
_ocr_coords_lock / _ocr_coords_cache / save_ocr_debug_images
"""
from __future__ import annotations
import logging
import os
from typing import Any, Optional
from PIL import Image, UnidentifiedImageError
import numpy as np
def _skip_fudai_detail_field_debug(self: Any, picname: str) -> bool:
try:
from douyin.fudai.core.fudai_debug_utils import (
is_fudai_detail_field_debug_picname,
)
return is_fudai_detail_field_debug_picname(picname)
except Exception:
return False
def analyse_pic_word(
self: Any,
picname: str,
change_color: int = 0,
pic_path: Optional[str] = None,
return_confidence: bool = False,
):
"""对指定图片运行 OCR 并返回拼接后的文本结果。
Args:
self: underlying_operations 实例
picname: 图片名(如"福袋内容")
change_color: 0=保留彩色,1/2=二值化
pic_path: 可选;未提供时通过 self._find_pic_path 查找
return_confidence: True 时返回 (text, confidence_info);否则只返回 text
Returns:
return_confidence=False: text(str)
return_confidence=True: (text, confidence_info)
"""
from douyin.core.underlying_operations import _uo_log
if not pic_path:
try:
pic_path = self._find_pic_path(picname)
except Exception:
pic_path = None
if not pic_path or not os.path.exists(pic_path):
return ("", None) if return_confidence else ""
# ===== 缓存查询:基于图片字节哈希 =====
cache_key = None
try:
from operations.ocr_operations import (
_img_fingerprint, cache_get, cache_put,
)
with open(pic_path, "rb") as _f:
_bytes = _f.read()
cache_key = _img_fingerprint(_bytes, mode=int(change_color or 0))
cached = cache_get(cache_key)
if cached is not None:
return cached if return_confidence else cached[0]
except Exception:
cache_key = None
# 加载图片
_pic_raw = None
img = None
try:
_pic_raw = Image.open(pic_path)
_pic_raw.load()
img = _pic_raw.convert("RGB")
_pic_raw.close()
_pic_raw = None
except (IOError, OSError, UnidentifiedImageError):
if _pic_raw is not None:
_pic_raw.close()
return ("", None) if return_confidence else ""
if img is None:
return ("", None) if return_confidence else ""
# 预处理:实测 PaddleOCR v4-mobile 内部已自带 resize/normalize,
# 外层"放大+锐化+对比度增强"反而会引入伪影,让识别变差。
# 因此默认走原图。仅在 change_color=1/2 业务显式要求二值化时才做。
if change_color in (1, 2):
old = img
img = img.convert("L")
old.close()
thresh = 128 if change_color == 1 else 180
img = img.point(lambda x, t=thresh: 0 if int(x) < t else 255)
# PaddleOCR 期望 HWC 三通道输入;保持二值化效果同时转回 RGB,避免
# ValueError: not enough values to unpack (expected 3, got 2)
img = img.convert("RGB")
else:
img = img.convert("RGB")
w, h = img.size
img1 = img # 不再做放大/锐化/对比度
# 调试图像保存(preprocessed 步骤)
_save_debug_preprocessed(self, img1, picname, pic_path, change_color, w, h)
img_np = np.array(img1)
ocr_confidence_info = None
# 并行模式下优先使用线程私有 OCR 实例,避免共享实例并发导致底层崩溃。
try:
get_ocr = getattr(self, "_get_ocr_for_current_thread", None)
if callable(get_ocr):
ocr_obj, ocr_type = get_ocr()
else:
ocr_obj = getattr(self, "ocr", None)
ocr_type = getattr(self, "ocr_type", None)
except Exception:
ocr_obj = None
ocr_type = None
if ocr_obj is None:
try:
logging.warning("OCR 未初始化,跳过识别:picname=%s", picname)
except Exception:
pass
return ("", None) if return_confidence else ""
# 执行 OCR
try:
if ocr_type == "easyocr":
result = ocr_obj.readtext(img_np)
extract_result = self.extract_ocr_content(result, return_confidence=True)
if isinstance(extract_result, tuple):
text, ocr_confidence_info = extract_result
else:
text = extract_result
else:
# PaddleOCR 3.x:predict() 是新推荐 API;ocr() 仍兼容
_predict = getattr(ocr_obj, "predict", None) or ocr_obj.ocr
result = _predict(img_np)
if result == [None]:
if cache_key:
try:
cache_put(cache_key, ("", None))
except Exception:
pass
return ("", None) if return_confidence else ""
extract_result = self.extract_ocr_content(result, return_confidence=True)
if isinstance(extract_result, tuple):
text, ocr_confidence_info = extract_result
else:
text = extract_result
except Exception as e:
try:
logging.warning("OCR 调用失败,返回空结果:%s", e)
except Exception:
pass
return ("", None) if return_confidence else ""
# 写缓存
if cache_key:
try:
cache_put(cache_key, (text, ocr_confidence_info))
except Exception:
pass
# 调试日志:福袋内容 / 福袋倒计时 OCR 失败时打印 result 结构
if picname in ("福袋内容", "福袋倒计时") and not text:
try:
if isinstance(result, list) and result and isinstance(result[0], dict):
_uo_log(f"OCR调试({picname}): result[0] keys={list(result[0].keys())}")
else:
_uo_log(f"OCR调试({picname}): result type={type(result)}")
except Exception:
pass
# 调试图像保存(after_ocr 步骤)+ 置信度日志
_save_debug_after_ocr(
self, img1, picname, change_color, text,
ocr_confidence_info,
)
# 成功识别 → 保存到 ocr/<category>/<picname>_success.png
if text and text.strip() and picname:
_save_success_pic(img, img1, picname, text)
if return_confidence:
return text, ocr_confidence_info
else:
return text
def _save_debug_preprocessed(
self: Any, img1, picname: str, pic_path: str,
change_color: int, w: int, h: int,
) -> None:
"""保存预处理后的调试图像(OCR 输入),仅当 SAVE_OCR_DEBUG_IMAGES=1 时执行。"""
try:
save_debug = os.environ.get("SAVE_OCR_DEBUG_IMAGES", "0") == "1"
if save_debug and _skip_fudai_detail_field_debug(self, picname):
return
if not save_debug:
try:
save_debug = bool(getattr(self, "save_ocr_debug_images", False))
except Exception:
pass
if save_debug and _skip_fudai_detail_field_debug(self, picname):
return
if not save_debug:
return
from douyin.handlers import douyin_screenshot_manager
from douyin.core import path_config
ocr_coords = None
try:
with self._ocr_coords_lock:
ocr_coords = self._ocr_coords_cache.get(picname)
except Exception:
pass
full_screenshot = None
try:
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
_raw = Image.open(screenshot_path)
try:
_raw.load()
full_screenshot = _raw.convert("RGB")
finally:
_raw.close()
except Exception:
pass
debug_image = full_screenshot if full_screenshot is not None else img1
debug_path = douyin_screenshot_manager.save_debug_image(
debug_image,
operation_type="ocr",
picname=picname,
step="preprocessed",
coords=ocr_coords,
extra_info={
"mode": change_color,
"size": f"{w}x{h}",
"source": pic_path if pic_path else picname,
"has_full_screenshot": full_screenshot is not None,
"has_coords": ocr_coords is not None,
},
)
if debug_path:
try:
logging.debug("[调试图像] OCR预处理保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
def _save_debug_after_ocr(
self: Any, img1, picname: str, change_color: int,
text: Optional[str], ocr_confidence_info: Optional[dict],
) -> None:
"""保存 OCR 完成后的调试图像(含识别文本预览 + 置信度)。"""
try:
if _skip_fudai_detail_field_debug(self, picname):
return
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(img1, operation_type="ocr")
ocr_result_preview = (text or "").strip()[:50] if text else ""
extra_info_dict = {
"mode": change_color,
"text_len": len(text or ""),
"text_preview": ocr_result_preview,
"used_img2": False, # 二次 OCR 已禁用
}
if ocr_confidence_info:
extra_info_dict["avg_confidence"] = round(
ocr_confidence_info.get("avg_confidence", 0.0), 4
)
extra_info_dict["min_confidence"] = round(
ocr_confidence_info.get("min_confidence", 0.0), 4
)
extra_info_dict["max_confidence"] = round(
ocr_confidence_info.get("max_confidence", 0.0), 4
)
extra_info_dict["confidence_items"] = ocr_confidence_info.get(
"item_count", 0
)
ocr_coords = None
try:
ocr_coords = self._ocr_coords_cache.get(picname)
except Exception:
pass
full_screenshot = None
try:
from douyin.core import path_config
screenshot_path = path_config.get_screenshot_path()
if os.path.exists(screenshot_path):
_raw = Image.open(screenshot_path)
try:
_raw.load()
full_screenshot = _raw.convert("RGB")
finally:
_raw.close()
except Exception:
pass
debug_image = full_screenshot if full_screenshot is not None else img1
extra_info_dict["has_full_screenshot"] = full_screenshot is not None
extra_info_dict["has_coords"] = ocr_coords is not None
debug_path = douyin_screenshot_manager.save_debug_image(
debug_image,
operation_type="ocr",
picname=picname,
step="after_ocr",
coords=ocr_coords,
extra_info=extra_info_dict,
)
# 记录 OCR 置信度到日志
if ocr_confidence_info and ocr_confidence_info.get("item_count", 0) > 0:
try:
logging.debug(
"[OCR置信度] %s: 平均=%.4f, 最小=%.4f, 最大=%.4f, 项目数=%d",
picname,
ocr_confidence_info.get("avg_confidence", 0.0),
ocr_confidence_info.get("min_confidence", 0.0),
ocr_confidence_info.get("max_confidence", 0.0),
int(ocr_confidence_info.get("item_count", 0) or 0),
)
except Exception:
pass
if debug_path:
try:
logging.debug(
"[调试图像] OCR结果保存: %s, 文本: %s",
debug_path,
ocr_result_preview,
)
except Exception:
pass
except Exception:
pass
def _save_success_pic(img, img1, picname: str, text: str) -> None:
"""成功识别后保存到 ocr/<category>/<picname>_success.png。"""
try:
try:
from douyin.handlers import douyin_screenshot_manager
category = douyin_screenshot_manager.get_category_for_picname(picname)
except Exception:
category = "others"
from douyin.core import path_config
pic_base = path_config.get_pic_dir()
category_dir = os.path.join(pic_base, "ocr", category)
os.makedirs(category_dir, exist_ok=True)
success_path = os.path.join(category_dir, f"{picname}_success.png")
try:
img_to_save = img1
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_last_success(
img_to_save, operation_type="ocr"
)
except Exception:
pass
img_to_save.save(success_path)
except Exception:
try:
if img is not None:
img.save(success_path)
except Exception:
pass
except Exception:
pass
@@ -47,6 +47,7 @@ def save_reward_pic(device_id):
out_file = os.path.join(out_dir, f"{timepic}.png")
adb = _adb_path()
remote_shot = path_config.get_android_screenshot_path()
# 同样优先使用 exec-out,减少手机端 I/O
try:
@@ -72,20 +73,20 @@ def save_reward_pic(device_id):
"shell",
"screencap",
"-p",
"/sdcard/DCIM/screenshot.png",
remote_shot,
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
)
subprocess.run(
[adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", out_file],
[adb, "-s", device_id, "pull", remote_shot, out_file],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=True,
)
subprocess.run(
[adb, "-s", device_id, "shell", "rm", "/sdcard/DCIM/screenshot.png"],
[adb, "-s", device_id, "shell", "rm", remote_shot],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False,
@@ -0,0 +1,663 @@
"""underlying_operations._get_screenshot_direct 的实现。
从 underlying_operations.py 抽出,原方法保留为 thin shim 调用 capture_screenshot_direct。
依赖:
- self._adb_path() —— 取 adb 可执行文件路径
- self.get_screenshot() —— 在最深兜底分支递归调用一次(注意保持兼容)
- io_utils._safe_replace_file
- io_utils._mirror_screenshot_to_external
"""
from __future__ import annotations
import logging
import os
import subprocess
import threading
import time as time_module
from datetime import datetime
from typing import TYPE_CHECKING
from douyin.core import path_config
from douyin.core.io_utils import (
_mirror_screenshot_to_external,
_safe_replace_file,
)
if TYPE_CHECKING:
from douyin.core.underlying_operations import underlying_operations
def _uo_log(msg: str, level: str = "INFO") -> None:
"""与 underlying_operations._uo_log 一致:默认 INFO 级别。"""
try:
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
def _valid_png(path0: str) -> bool:
"""校验截图 PNG 是否完整;测试可 patch 此模块级函数。"""
skip_verify = os.environ.get("SKIP_SCREENSHOT_VERIFY", "0") == "1"
if skip_verify:
try:
if not os.path.exists(path0):
return False
return os.path.getsize(path0) >= 1024
except Exception:
return False
verify_start = time_module.time()
try:
if not os.path.exists(path0):
return False
sz = os.path.getsize(path0)
if sz < 1024:
return False
header_check_start = time_module.time()
try:
with open(path0, "rb") as _f:
header = _f.read(4)
if header != b"\x89PNG":
return False
try:
_f.seek(-256, 2)
except Exception:
_f.seek(0)
tail = _f.read(256)
if b"IEND" not in tail:
return False
except Exception:
return False
header_check_dur = (time_module.time() - header_check_start) * 1000.0
if header_check_dur > 10.0:
logging.debug(
"[截图] PNG头尾校验耗时(ms)=%.1f path=%s",
header_check_dur,
path0,
)
verify_total_dur = (time_module.time() - verify_start) * 1000.0
if verify_total_dur > 100.0:
logging.info(
"[截图] _valid_png总耗时(ms)=%.1f path=%s",
verify_total_dur,
path0,
)
return True
except Exception:
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:
"""直接截图(不使用服务模式)。从 underlying_operations._get_screenshot_direct 抽出。
流程:
1. 准备输出目录 + 文件名
2. 优先 exec-out 路径(最多 2 次重试 + watchdog)
3. 失败 → 回退 shell screencap + adb pull
4. 再失败 → 兜底 mv + 递归调用 get_screenshot
"""
overall_start = time_module.time()
cleanup_dur = 0.0
adb_subprocess_dur = 0.0
validate_tmp_dur = 0.0
replace_dur = 0.0
mirror_dur = 0.0
validate_out_dur = 0.0
if path == "pic":
try:
from douyin.core import path_config
out_dir = path_config.get_pic_dir()
except Exception:
from douyin.core import path_config
out_dir = path_config.get_pic_dir()
else:
out_dir = os.path.join(path_config.get_project_root(), "target_pic")
if not os.path.exists(out_dir):
os.makedirs(out_dir)
out_file = os.path.join(out_dir, "screenshot.png")
tmp_file = out_file + ".tmp"
timetag = datetime.now().strftime("%H:%M:%S")
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"))
except ValueError:
execout_timeout_sec = 10.0
try:
execout_warn_after_sec = float(
os.environ.get("ADB_EXECOUT_WARN_AFTER_SEC", "3")
)
except ValueError:
execout_warn_after_sec = 3.0
try:
execout_heartbeat_interval_sec = float(
os.environ.get("ADB_EXECOUT_HEARTBEAT_INTERVAL_SEC", "5")
)
except ValueError:
execout_heartbeat_interval_sec = 5.0
try:
execout_heartbeat_max = int(os.environ.get("ADB_EXECOUT_HEARTBEAT_MAX", "3"))
except ValueError:
execout_heartbeat_max = 3
for attempt in range(2):
try:
cleanup_start = time_module.time()
try:
if os.path.exists(tmp_file):
os.remove(tmp_file)
except Exception:
pass
cleanup_dur = (time_module.time() - cleanup_start) * 1000.0
if cleanup_dur > 10.0:
logging.debug("[截图] 清理临时文件耗时(ms)=%.1f", cleanup_dur)
adb_start = time_module.time()
try:
process = subprocess.Popen(
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=0,
)
done_event = None
watchdog_thread = None
try:
done_event = threading.Event()
def _watchdog() -> None:
try:
if execout_warn_after_sec > 0:
if done_event.wait(timeout=execout_warn_after_sec):
return
start_wait = time_module.time()
for i in range(max(0, execout_heartbeat_max)):
if done_event.is_set():
return
waited = (time_module.time() - start_wait) * 1000.0
logging.warning(
"[截图] exec-out 仍在进行中:已等待(ms)=%.0f device=%s attempt=%s",
waited,
device_id,
attempt + 1,
)
if done_event.wait(
timeout=max(0.5, execout_heartbeat_interval_sec)
):
return
except Exception:
return
watchdog_thread = threading.Thread(
target=_watchdog, name="adb-execout-watchdog", daemon=True
)
watchdog_thread.start()
except Exception:
done_event = None
stdout_data, stderr_data = process.communicate(timeout=execout_timeout_sec)
if done_event is not None:
done_event.set()
if process.returncode != 0:
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:
f.write(stdout_data)
adb_subprocess_dur = (time_module.time() - adb_start) * 1000.0
except subprocess.TimeoutExpired:
process.kill()
try:
process.communicate(timeout=1)
except Exception:
pass
try:
if done_event is not None:
done_event.set()
except Exception:
pass
raise
validate_tmp_start = time_module.time()
is_valid = _valid_png(tmp_file)
validate_tmp_dur = (time_module.time() - validate_tmp_start) * 1000.0
if validate_tmp_dur > 50.0:
logging.info(
"[截图] 临时文件验证耗时(ms)=%.1f result=%s",
validate_tmp_dur,
is_valid,
)
if is_valid:
replace_start = time_module.time()
replace_success = _safe_replace_file(tmp_file, out_file)
replace_dur = (time_module.time() - replace_start) * 1000.0
if replace_dur > 50.0:
logging.info(
"[截图] 文件替换耗时(ms)=%.1f result=%s",
replace_dur,
replace_success,
)
if replace_success:
mirror_start = time_module.time()
_mirror_screenshot_to_external(out_file)
mirror_dur = (time_module.time() - mirror_start) * 1000.0
if mirror_dur > 50.0:
logging.info(
"[截图] 镜像到外部路径耗时(ms)=%.1f", mirror_dur
)
validate_out_start = time_module.time()
try:
if os.path.exists(out_file):
file_size = os.path.getsize(out_file)
if file_size >= 1024:
try:
with open(out_file, "rb") as f:
header = f.read(4)
if header == b"\x89PNG":
validate_out_dur = (
time_module.time()
- validate_out_start
) * 1000.0
if validate_out_dur > 50.0:
logging.info(
"[截图] 目标文件快速验证耗时(ms)=%.1f",
validate_out_dur,
)
overall_dur = (
time_module.time() - overall_start
) * 1000.0
logging.info(
"[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (exec-out成功) | 汇总: cleanup=%.1f adb_execout=%.1f validate_tmp=%.1f replace=%.1f mirror=%.1f validate_out=%.1f",
overall_dur,
cleanup_dur,
adb_subprocess_dur,
validate_tmp_dur,
replace_dur,
mirror_dur,
validate_out_dur,
)
return True
except Exception:
pass
try:
st = os.stat(out_file)
_uo_log(
f"[截图诊断] 目标文件验证失败: size={st.st_size}, mtime={st.st_mtime}"
)
except Exception:
pass
except Exception:
pass
else:
try:
if os.path.exists(tmp_file):
st = os.stat(tmp_file)
_uo_log(
f"[截图诊断] 临时文件存在但替换失败: tmp={tmp_file}, size={st.st_size}"
)
except Exception:
pass
else:
try:
if os.path.exists(tmp_file):
st = os.stat(tmp_file)
_uo_log(
f"[截图诊断] 临时文件无效: path={tmp_file}, size={st.st_size}"
)
except Exception:
pass
except subprocess.TimeoutExpired:
_uo_log("[截图] exec-out 超时,尝试重试或回退方案")
try:
if os.path.exists(tmp_file):
os.remove(tmp_file)
except Exception:
pass
except Exception as 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)
except Exception:
pass
# 回退方案:老式 shell screencap + pull
fallback_start = time_module.time()
try:
shell_screencap_start = time_module.time()
remote_shot = path_config.get_android_screenshot_path()
remote_shot_alt = path_config.get_android_screenshot_alt_path()
shell_result = subprocess.run(
[
adb,
"-s",
device_id,
"shell",
"screencap",
"-p",
remote_shot,
],
stdout=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",
shell_screencap_dur,
device_id,
)
pull_start = time_module.time()
pull_result = subprocess.run(
[adb, "-s", device_id, "pull", remote_shot, tmp_file],
stdout=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
)
fallback_validate_start = time_module.time()
if _valid_png(tmp_file):
fallback_validate_dur = (
time_module.time() - fallback_validate_start
) * 1000.0
if fallback_validate_dur > 50.0:
logging.info(
"[截图] 回退方案-临时文件验证耗时(ms)=%.1f",
fallback_validate_dur,
)
fallback_replace_start = time_module.time()
if _safe_replace_file(tmp_file, out_file):
fallback_replace_dur = (
time_module.time() - fallback_replace_start
) * 1000.0
if fallback_replace_dur > 50.0:
logging.info(
"[截图] 回退方案-文件替换耗时(ms)=%.1f",
fallback_replace_dur,
)
fallback_mirror_start = time_module.time()
_mirror_screenshot_to_external(out_file)
fallback_mirror_dur = (
time_module.time() - fallback_mirror_start
) * 1000.0
if fallback_mirror_dur > 50.0:
logging.info(
"[截图] 回退方案-镜像耗时(ms)=%.1f", fallback_mirror_dur
)
try:
if _valid_png(out_file):
overall_dur = (time_module.time() - overall_start) * 1000.0
fallback_total_dur = (
time_module.time() - fallback_start
) * 1000.0
logging.info(
"[截图] ✓ 获取屏幕截图成功 | 总耗时(ms)=%.1f (回退方案成功, 回退部分耗时=%.1fms)",
overall_dur,
fallback_total_dur,
)
return True
except Exception:
pass
else:
# 替换失败 → 直接复制 / 兜底
try:
if os.path.exists(tmp_file):
try:
with open(tmp_file, "rb") as src, open(
out_file, "wb"
) as dst:
dst.write(src.read())
_mirror_screenshot_to_external(out_file)
try:
if _valid_png(out_file):
_uo_log(
f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)"
)
return True
except Exception:
pass
except (OSError, PermissionError) as e:
replace_success = _safe_replace_file(tmp_file, out_file)
if replace_success:
_mirror_screenshot_to_external(out_file)
try:
if _valid_png(out_file):
_uo_log(
f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过优化替换)"
)
return True
except Exception:
pass
else:
_uo_log(
f"[截图] 文件替换失败({e}),但截图已保存到临时文件 {tmp_file}"
)
return True
except Exception:
_uo_log(f"[截图] 文件替换失败,但截图已保存到临时文件 {tmp_file}")
return True
try:
if os.path.exists(tmp_file):
st = os.stat(tmp_file)
_uo_log(
f"[截图] 回退方案截图无效,继续尝试 shell stdout 回退: size={st.st_size}"
)
except Exception:
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
@@ -0,0 +1,149 @@
"""Screenshot pipeline helpers for underlying_operations."""
from __future__ import annotations
import json
import os
import threading
from datetime import datetime
import time as time_module
import logging
def _screenshot_trace_enabled() -> bool:
"""Return whether verbose per-screenshot stack tracing is enabled."""
try:
flag = str(os.environ.get("DOUYIN_SCREENSHOT_TRACE", "")).strip().lower()
return flag in {"1", "true", "yes", "on"}
except Exception:
return False
def _append_screenshot_trace(self, record: dict) -> None:
try:
if hasattr(self, "_screenshot_call_cache"):
try:
self._screenshot_call_cache.append(record)
except Exception:
pass
except Exception:
pass
try:
with open(self._screenshot_log_path, "a", encoding="utf-8") as _lf:
_lf.write(json.dumps(record, ensure_ascii=False) + "\n")
except Exception:
pass
def get_screenshot(self, device_id, path="pic", use_service: bool = False):
"""截图(支持后台服务模式)"""
start_ts = time_module.time()
trace_enabled = _screenshot_trace_enabled()
if trace_enabled:
try:
import inspect
frames = []
for fr in inspect.stack()[1:9]:
frame_info = {
"file": os.path.relpath(fr.filename, os.path.dirname(__file__)),
"line": fr.lineno,
"function": fr.function,
}
frames.append(frame_info)
pre_record = {
"ts": datetime.now().isoformat(),
"device_id": device_id,
"use_service": bool(use_service),
"path": path,
"phase": "start",
"thread": threading.get_ident(),
"stack": frames,
}
_append_screenshot_trace(self, pre_record)
except Exception:
pass
elif not getattr(self, "_screenshot_trace_disabled_logged", False):
try:
logging.info(
"[截图] screenshot_calls.jsonl 调用栈追踪默认关闭;如需诊断设置 DOUYIN_SCREENSHOT_TRACE=1"
)
self._screenshot_trace_disabled_logged = True
except Exception:
pass
service_success = False
if use_service:
try:
from operations.screenshot_service import ScreenshotService
service = ScreenshotService.get_instance()
service_running = getattr(service, "_running", False)
if not service_running:
logging.debug("[截图] 后台服务未运行,尝试启动 device=%s", device_id)
try:
service.start(device_id, interval=1.5)
time_module.sleep(0.2)
except Exception as start_err:
logging.warning("[截图] 启动后台服务失败: %s,将使用直接截图", start_err)
try:
if service.get_screenshot(device_id, force=False):
dur = (time_module.time() - start_ts) * 1000.0
logging.info("[截图] 使用后台服务耗时(ms)=%.1f device=%s", dur, device_id)
if trace_enabled:
end_record = {
"ts": datetime.now().isoformat(),
"device_id": device_id,
"use_service": True,
"path": path,
"phase": "end",
"result": True,
"duration_ms": dur,
"thread": threading.get_ident(),
}
_append_screenshot_trace(self, end_record)
service_success = True
else:
timetag = datetime.now().strftime("%H:%M:%S")
logging.info("[%s] [截图操作] 后台服务未提供有效截图,回退到直接截图", timetag)
except Exception as e:
timetag = datetime.now().strftime("%H:%M:%S")
logging.warning("[%s] [截图操作] 调用后台服务异常,回退到直接截图: %s", timetag, e)
service_success = False
except ImportError as e:
timetag = datetime.now().strftime("%H:%M:%S")
logging.warning("[%s] [截图操作] 无法导入截图服务模块,回退到直接截图: %s", timetag, e)
service_success = False
except Exception as e:
timetag = datetime.now().strftime("%H:%M:%S")
logging.warning("[%s] [截图操作] 服务模式不可用,回退到直接截图: %s", timetag, e)
service_success = False
try:
if service_success:
final_result = True
else:
final_result = self._get_screenshot_direct(device_id, path)
except Exception:
final_result = False
dur = (time_module.time() - start_ts) * 1000.0
logging.info("[截图] 总耗时(ms)=%.1f use_service=%s result=%s", dur, bool(use_service), final_result)
if trace_enabled:
end_record = {
"ts": datetime.now().isoformat(),
"device_id": device_id,
"use_service": bool(use_service),
"path": path,
"phase": "end",
"result": bool(final_result),
"duration_ms": dur,
"thread": threading.get_ident(),
}
_append_screenshot_trace(self, end_record)
return bool(final_result)
@@ -0,0 +1,334 @@
"""文本输入与输入法相关实现(从 underlying_operations.py 抽离)。"""
from __future__ import annotations
import base64
import os
import shlex
import subprocess
import time as time_module
from typing import TYPE_CHECKING, Tuple
from douyin.core import path_config
if TYPE_CHECKING:
from douyin.core.underlying_operations import underlying_operations
def paste_from_clipboard(self: "underlying_operations", device_id: str) -> bool:
"""尝试触发“粘贴”操作(需要输入框已获得焦点)。"""
# KEYCODE_PASTE=279(部分机型/系统可能不支持,但无副作用)
return self._run_adb_shell(device_id, "input keyevent 279", timeout_seconds=2.0)
def input_text(self: "underlying_operations", device_id: str, text: str) -> bool:
"""使用 adb input text 输入(对中文可能不稳定,仅兜底)。"""
t = str(text or "")
if not t:
return False
# 空格用 %s,避免被 shell 分词
t = t.replace(" ", "%s")
# 完整转义所有 shell 特殊字符
for ch in [
"&",
"<",
">",
"|",
";",
"$",
"`",
"'",
'"',
"\\",
"(",
")",
"{",
"}",
"[",
"]",
"!",
"#",
"*",
"?",
]:
t = t.replace(ch, "\\" + ch)
try:
return (
subprocess.run(
self._adb_args(device_id, "shell", "input", "text", t),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=5.0,
check=False,
).returncode
== 0
)
except Exception:
return False
def paste_text(self: "underlying_operations", device_id: str, text: str) -> bool:
"""优先走剪贴板粘贴,其次兜底 input text。"""
if self.set_clipboard_text(device_id, text):
self.paste_from_clipboard(device_id)
return True
return self.input_text(device_id, text)
def get_current_ime(self: "underlying_operations", device_id: str) -> str:
ok, out = self._run_adb_shell_capture(
device_id, "settings get secure default_input_method", timeout_seconds=2.0
)
if not ok:
return ""
return (out or "").strip()
def list_imes(self: "underlying_operations", device_id: str) -> list[str]:
# 部分 ROM 会限制 `ime` shell 命令(报 WRITE_SECURE_SETTINGS),这里优先用 settings 查询。
ok, out = self._run_adb_shell_capture(
device_id, "settings get secure enabled_input_methods", timeout_seconds=2.5
)
if ok and out:
raw = (out or "").strip()
# 形如:a/.A:b/.B:c/.C
parts = [p.strip() for p in raw.split(":") if p.strip()]
if parts:
return parts
ok2, out2 = self._run_adb_shell_capture(device_id, "ime list -s", timeout_seconds=2.5)
if not ok2:
# 最后兜底:至少把当前默认输入法返回,避免上层无法判断
cur = self.get_current_ime(device_id)
return [cur] if cur else []
lines = [ln.strip() for ln in (out2 or "").splitlines() if ln.strip()]
return lines
def ensure_adbkeyboard_ime(
self: "underlying_operations",
device_id: str,
preferred_ime: str = path_config.get_adb_keyboard_ime(),
) -> Tuple[bool, str, str]:
"""确保 ADBKeyboard 输入法处于激活状态。"""
prev = self.get_current_ime(device_id)
# 如果当前已经是 ADBKeyboard,就不用再尝试切换(很多 ROM 禁止 ime set)
if "adbkeyboard" in str(prev).lower() or "adbime" in str(prev).lower():
return True, prev, prev
imes = self.list_imes(device_id)
if not self._pick_adbkeyboard_ime(imes):
apk_path = path_config.get_bundled_adbkeyboard_apk_path()
if os.path.exists(apk_path):
try:
subprocess.run(
[self._adb_path(), "-s", str(device_id), "install", "-r", apk_path],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=20.0,
check=False,
)
imes = self.list_imes(device_id)
except Exception:
pass
adb_ime = ""
pref = str(preferred_ime or "").strip()
if pref and pref in imes:
adb_ime = pref
else:
adb_ime = self._pick_adbkeyboard_ime(imes)
if not adb_ime:
return False, prev, ""
if prev != adb_ime:
if not self.try_set_ime(device_id, adb_ime):
return False, prev, adb_ime
return True, prev, adb_ime
def restore_ime(self: "underlying_operations", device_id: str, prev_ime: str) -> bool:
ime = str(prev_ime or "").strip()
if not ime:
return False
return self.try_set_ime(device_id, ime)
def try_set_ime(self: "underlying_operations", device_id: str, ime_id: str) -> bool:
ime = str(ime_id or "").strip()
if not ime:
return False
# 1) 优先走 ime(某些 ROM 会失败)
self._run_adb_shell(device_id, f"ime enable {shlex.quote(ime)}", timeout_seconds=2.5)
if self._run_adb_shell(device_id, f"ime set {shlex.quote(ime)}", timeout_seconds=2.5):
return True
# 2) 退化:尝试 settings put(通常也会被 ROM 限制,但试一下无害)
if self._run_adb_shell(
device_id,
f"settings put secure default_input_method {shlex.quote(ime)}",
timeout_seconds=2.5,
):
cur = self.get_current_ime(device_id)
return cur == ime
return False
def _adbkeyboard_broadcast(
self: "underlying_operations", device_id: str, action: str, msg: str
) -> bool:
act = str(action or "").strip()
if not act:
return False
safe_msg = shlex.quote(str(msg or ""))
try:
return (
subprocess.run(
self._adb_args(
device_id, "shell", "am", "broadcast", "-a", act, "--es", "msg", safe_msg
),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=3.0,
check=False,
).returncode
== 0
)
except Exception:
return False
def _adbkeyboard_broadcast_int(
self: "underlying_operations", device_id: str, action: str, key: str, value: int
) -> bool:
act = str(action or "").strip()
k = str(key or "").strip()
if not act or not k:
return False
try:
v = int(value)
except Exception:
return False
safe_k = shlex.quote(k)
try:
return (
subprocess.run(
self._adb_args(device_id, "shell", "am", "broadcast", "-a", act, "--ei", safe_k, v),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=3.0,
check=False,
).returncode
== 0
)
except Exception:
return False
def keyevent(self: "underlying_operations", device_id: str, keycode: int) -> bool:
try:
code = int(keycode)
except Exception:
return False
return self._run_adb_shell(device_id, f"input keyevent {code}", timeout_seconds=2.0)
def adbkeyboard_editor_action(
self: "underlying_operations", device_id: str, action_code: int = 4
) -> bool:
"""使用 ADBKeyBoard 触发 editor action。"""
return self._adbkeyboard_broadcast_int(device_id, "ADB_EDITOR_CODE", "code", int(action_code))
def confirm_from_keyboard(self: "underlying_operations", device_id: str) -> bool:
"""在输入框中用“键盘确认/发送”提交。"""
cur = ""
try:
cur = self.get_current_ime(device_id)
except Exception:
cur = ""
if "adbkeyboard" in str(cur).lower() or "adbime" in str(cur).lower():
if self.adbkeyboard_editor_action(device_id, 4):
return True
return self.keyevent(device_id, 66)
def input_text_adbkeyboard(
self: "underlying_operations",
device_id: str,
text: str,
ime_id: str = path_config.get_adb_keyboard_ime(),
restore_prev: bool = True,
) -> bool:
"""使用 ADBKeyboard 输入文本(更适合中文)。"""
t = str(text or "")
if not t:
return False
ok, prev, adb_ime = self.ensure_adbkeyboard_ime(device_id, preferred_ime=ime_id)
if not ok:
return False
success = False
try:
b64 = base64.b64encode(t.encode("utf-8")).decode("ascii")
if self._adbkeyboard_broadcast(device_id, "ADB_INPUT_B64", b64):
success = True
elif self._adbkeyboard_broadcast(device_id, "ADB_INPUT_TEXT", t):
success = True
time_module.sleep(0.35)
return success
finally:
if restore_prev and prev and prev != adb_ime:
time_module.sleep(0.25)
self.restore_ime(device_id, prev)
def paste_text_at(
self: "underlying_operations",
device_id: str,
x: int,
y: int,
text: str,
ensure_focus: bool = True,
) -> bool:
"""点击输入框后粘贴/输入文本。"""
t = str(text or "").strip()
if not t:
return False
try:
if ensure_focus:
self.click(device_id, int(x), int(y))
time_module.sleep(0.2)
self.click(device_id, int(x), int(y))
time_module.sleep(0.15)
except Exception:
pass
try:
if bool(self.input_text_adbkeyboard(device_id, t, restore_prev=False)):
return True
except Exception:
pass
ok_clip = False
try:
ok_clip = bool(self.set_clipboard_text(device_id, t))
except Exception:
ok_clip = False
if ok_clip:
time_module.sleep(0.15)
try:
if bool(self.paste_from_clipboard(device_id)):
return True
except Exception:
pass
return self.input_text(device_id, t)
@@ -0,0 +1,167 @@
"""UIAutomator 相关交互实现(从 underlying_operations.py 抽离)。"""
from __future__ import annotations
import os
import subprocess
import time as time_module
import xml.etree.ElementTree as ET
from typing import TYPE_CHECKING
from douyin.core import path_config
if TYPE_CHECKING:
from douyin.core.underlying_operations import underlying_operations
def uiautomator_dump(
self: "underlying_operations", device_id: str, local_path: str
) -> bool:
"""拉取当前界面 UI 树到本地 xml(失败返回 False)。"""
try:
remote = path_config.get_android_window_dump_path()
subprocess.run(
self._adb_args(device_id, "shell", "uiautomator", "dump", remote),
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=2,
check=False,
)
subprocess.run(
[self._adb_path(), "-s", str(device_id), "pull", remote, str(local_path)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
timeout=2,
check=False,
)
return os.path.exists(local_path)
except subprocess.TimeoutExpired:
return False
except Exception:
return False
def tap_by_text(
self: "underlying_operations",
device_id: str,
text: str,
contains: bool = True,
timeout_seconds: float = 2.0,
) -> bool:
"""通过 uiautomator dump 按 text/content-desc 点击(命中即点并返回 True)。"""
if not text:
return False
local_path = path_config.get_window_dump_path()
start = time_module.time()
while True:
if self._uiautomator_dump(device_id, local_path):
try:
tree = ET.parse(local_path)
root = tree.getroot()
except Exception:
root = None
if root is not None:
target = str(text)
for node in root.iter():
t = node.attrib.get("text", "")
d = node.attrib.get("content-desc", "")
hit = False
if contains:
if (target in t) or (target in d):
hit = True
else:
if (target == t) or (target == d):
hit = True
if not hit:
continue
b = node.attrib.get("bounds", "")
parsed = self._parse_bounds(b)
if not parsed:
continue
x1, y1, x2, y2 = parsed
cx = int((x1 + x2) / 2)
cy = int((y1 + y2) / 2)
self.click(device_id, cx, cy)
return True
if time_module.time() - start >= timeout_seconds:
return False
time_module.sleep(0.2)
def tap_close_icon(
self: "underlying_operations",
device_id: str,
screen_width: int = 1080,
timeout_seconds: float = 2.0,
) -> bool:
"""尝试点击直播间顶部的关闭(X)按钮。"""
local_path = path_config.get_window_dump_path()
start = time_module.time()
def _score(node_attrib: dict, bounds_tuple) -> int:
x1, y1, x2, y2 = bounds_tuple
w = x2 - x1
h = y2 - y1
if y2 > 420:
return -9999
if w < 50 or h < 50 or w > 260 or h > 260:
return -9999
t = (node_attrib.get("text", "") or "").strip()
d = (node_attrib.get("content-desc", "") or "").strip()
s = t + " " + d
score = 0
for kw in ("关闭", "退出", "返回", "close", "Close"):
if kw in s:
score += 200
for bad in ("分享", "更多", "菜单", "礼物", "榜", "关注", "评论"):
if bad in s:
score -= 120
score += max(0, 120 - y1)
score -= abs(w - h)
cx = (x1 + x2) / 2
if screen_width > 0:
score += int((cx / screen_width) * 40)
return score
while True:
if self._uiautomator_dump(device_id, local_path):
try:
root = ET.parse(local_path).getroot()
except Exception:
root = None
best = None
best_score = -999999
if root is not None:
for node in root.iter():
attrib = getattr(node, "attrib", {}) or {}
if str(attrib.get("clickable", "")).lower() != "true":
continue
if str(attrib.get("enabled", "true")).lower() == "false":
continue
b = attrib.get("bounds", "")
parsed = self._parse_bounds(b)
if not parsed:
continue
sc = _score(attrib, parsed)
if sc > best_score:
best_score = sc
best = parsed
if best and best_score > -1000:
x1, y1, x2, y2 = best
cx = int((x1 + x2) / 2)
cy = int((y1 + y2) / 2)
self.click(device_id, cx, cy)
return True
if time_module.time() - start >= timeout_seconds:
return False
time_module.sleep(0.2)
+2 -2
View File
@@ -10,8 +10,8 @@
from typing import Optional
APP_NAME = "douyin_guaji"
APP_VERSION = "V3.3.3"
APP_BUILD_DATE = "2025-12-28"
APP_VERSION = "V3.3.11"
APP_BUILD_DATE = "2026-06-29"
# 兼容旧代码与测试:提供 VERSION / RELEASE_DATE 别名
# tests 期望: from version import VERSION, RELEASE_DATE, print_version_banner
+385 -5
View File
@@ -8,20 +8,40 @@ from __future__ import annotations
# pylint: disable=no-member
import os
import re
import time
from typing import Any
from PIL import Image
from ._common import _ensure_detection_cache
def check_detail_height(analyser: Any) -> int:
def check_detail_height(analyser: Any, pic_rgb: Any = None) -> int:
"""Detect how many tasks are required in the fudai detail popup.
Returns:
0 / 1 / 2 / 3 (number of tasks).
"""
try:
from douyin.fudai.core.coords import normalize_fudai_detail_ui_mode
ui_mode = normalize_fudai_detail_ui_mode(
getattr(analyser, "fudai_detail_ui_mode", "auto")
)
except Exception:
ui_mode = "auto"
if ui_mode == "legacy":
return _check_detail_task_count_legacy_pixels(analyser)
detected_v2_template = _check_detail_task_count_v2(analyser, pic_rgb=pic_rgb)
if detected_v2_template:
return detected_v2_template
return 0
def _check_detail_task_count_legacy_pixels(analyser: Any) -> int:
"""Legacy detail task-count detection. Kept separate from v2 UI height logic."""
# 使用统一的截图路径配置
try:
from douyin.core import path_config
@@ -44,6 +64,8 @@ def check_detail_height(analyser: Any) -> int:
pic = None
for attempt in range(3):
try:
from PIL import Image
pic = Image.open(pic1_path)
pic.load() # force load to catch truncated files early
break
@@ -206,6 +228,7 @@ def check_detail_height(analyser: Any) -> int:
task_count=(
detected_task_count if detected_task_count is not None else 0
),
log_type="DEBUG",
)
except Exception:
pass
@@ -244,6 +267,358 @@ def check_detail_height(analyser: Any) -> int:
return 0
def _check_detail_task_count_v2_pixels(analyser: Any) -> int:
"""Fast v2 task-count decision from scanning the dark task-card top edge."""
try:
from douyin.fudai.core.coords import normalize_fudai_detail_ui_mode
ui_mode = normalize_fudai_detail_ui_mode(
getattr(analyser, "fudai_detail_ui_mode", "auto")
)
if ui_mode == "legacy":
return 0
except Exception:
ui_mode = "auto"
try:
from douyin.core import path_config
from PIL import Image
pic_path = path_config.get_screenshot_path()
pic = Image.open(pic_path).convert("RGB")
width, height = pic.size
except Exception:
return 0
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
except Exception:
rx = 1080
try:
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
ry = 2400
# 快速区分 two-task:你提供的上方大横带在 two-task 样本里深色命中明显更多。
upper_x_start = 2 * rx // 1080
upper_x_end = 1075 * rx // 1080
upper_y_start = 1018 * ry // 2400
upper_y_end = 1080 * ry // 2400
# one-task 兜底:保留较低位置的任务卡顶部横带检测。
lower_x_start = 420 * rx // 1080
lower_x_end = 860 * rx // 1080
lower_y_band = 1866 * ry // 2400
legacy_two_task_y1 = 1686 * ry // 2400
legacy_two_task_y2 = 1788 * ry // 2400
if not (
0 <= upper_x_start < width
and 0 < upper_x_end <= width
and upper_x_start < upper_x_end
and 0 <= upper_y_start < height
and 0 < upper_y_end <= height
and upper_y_start < upper_y_end
and 0 <= lower_x_start < width
and 0 < lower_x_end <= width
and lower_x_start < lower_x_end
and 0 <= lower_y_band < height
and 0 <= legacy_two_task_y1 < height
and 0 <= legacy_two_task_y2 < height
):
return 0
def _is_white_text(pixel: tuple[int, int, int]) -> bool:
r, g, b = pixel
return r >= 215 and g >= 215 and b >= 215
def _is_dark_card(pixel: tuple[int, int, int]) -> bool:
r, g, b = pixel
return 5 <= r <= 45 and 10 <= g <= 55 and 35 <= b <= 95
upper_sample_xs = [
int(v)
for v in (
upper_x_start,
upper_x_start + (upper_x_end - upper_x_start) * 0.2,
upper_x_start + (upper_x_end - upper_x_start) * 0.4,
upper_x_start + (upper_x_end - upper_x_start) * 0.6,
upper_x_start + (upper_x_end - upper_x_start) * 0.8,
upper_x_end - 1,
)
]
upper_sample_xs = [x for x in upper_sample_xs if 0 <= x < width]
lower_sample_xs = [
int(v)
for v in (
lower_x_start,
lower_x_start + (lower_x_end - lower_x_start) * 0.25,
lower_x_start + (lower_x_end - lower_x_start) * 0.5,
lower_x_start + (lower_x_end - lower_x_start) * 0.75,
lower_x_end - 1,
)
]
lower_sample_xs = [x for x in lower_sample_xs if 0 <= x < width]
def _dark_hits_at_y(y_coord: int, xs: list[int]) -> int:
hits = 0
for sx in xs:
try:
pixel = pic.getpixel((sx, y_coord))
except Exception:
continue
if _is_dark_card((int(pixel[0]), int(pixel[1]), int(pixel[2]))):
hits += 1
return hits
upper_band_dark_sum = 0
lower_band_dark_hits = 0
legacy_two_task_hits_1 = 0
legacy_two_task_hits_2 = 0
try:
for y_coord in range(upper_y_start, upper_y_end + 1, max(1, 4 * ry // 2400)):
upper_band_dark_sum += _dark_hits_at_y(y_coord, upper_sample_xs)
lower_band_dark_hits = _dark_hits_at_y(lower_y_band, lower_sample_xs)
legacy_two_task_hits_1 = _dark_hits_at_y(legacy_two_task_y1, lower_sample_xs)
legacy_two_task_hits_2 = _dark_hits_at_y(legacy_two_task_y2, lower_sample_xs)
except Exception:
return 0
detected = 0
reason = ""
if upper_band_dark_sum >= 36:
detected = 2
reason = "upper_band_dark_sum_two_task"
elif legacy_two_task_hits_1 >= 3 and legacy_two_task_hits_2 >= 3:
detected = 2
reason = "legacy_two_task_band_hits"
elif lower_band_dark_hits >= 3:
detected = 1
reason = "lower_band_dark_hits_one_task"
if detected:
try:
setattr(analyser, "_fudai_detail_task_count_source", "v2_pixels")
analyser._log_kv(
"检测",
f"识别到福袋任务数量:{detected}个(v2像素高度)",
task_count=detected,
source="v2_pixels",
)
analyser._log_kv(
"检测",
"福袋任务数量v2像素高度详情",
task_count=detected,
source="v2_pixels",
reason=reason,
upper_x_start=upper_x_start,
upper_x_end=upper_x_end,
upper_y_start=upper_y_start,
upper_y_end=upper_y_end,
upper_sample_xs=",".join(str(v) for v in upper_sample_xs),
upper_band_dark_sum=upper_band_dark_sum,
lower_x_start=lower_x_start,
lower_x_end=lower_x_end,
lower_y_band=lower_y_band,
lower_sample_xs=",".join(str(v) for v in lower_sample_xs),
lower_band_dark_hits=lower_band_dark_hits,
legacy_two_task_y1=legacy_two_task_y1,
legacy_two_task_y2=legacy_two_task_y2,
legacy_two_task_hits_1=legacy_two_task_hits_1,
legacy_two_task_hits_2=legacy_two_task_hits_2,
ui_mode=ui_mode,
log_type="DEBUG",
)
except Exception:
pass
return detected
def get_detail_task_status_search_box() -> tuple[int, int, int, int]:
"""Unified v2 task-status area; two-task height contains both status words."""
try:
from douyin.fudai.core.coords import get_pixel_region
return get_pixel_region("fudai_task_status", (820, 1815, 1050, 2035))
except Exception:
return (820, 1815, 1050, 2035)
def _check_detail_task_count_v2(analyser: Any, pic_rgb: Any = None) -> int:
"""Fast v2 task-count recognition by matching the shape of "达成"."""
try:
import cv2 # type: ignore[import-untyped]
import numpy as np # type: ignore[import-untyped]
from PIL import Image
from douyin.core import path_config
if pic_rgb is not None:
pic = pic_rgb.convert("RGB") if hasattr(pic_rgb, "convert") else Image.fromarray(pic_rgb).convert("RGB")
else:
pic_path = path_config.get_screenshot_path()
if not os.path.exists(pic_path):
return 0
pic = Image.open(pic_path).convert("RGB")
assets_dir = path_config.get_assets_dir()
template_path = os.path.join(assets_dir, "fudai_task_status_dacheng_shape.png")
if not os.path.exists(template_path):
return 0
width, height = pic.size
search_box = get_detail_task_status_search_box()
x1, y1, x2, y2 = _scale_box_to_image(search_box, width, height)
if x1 >= x2 or y1 >= y2:
return 0
template_rgb = Image.open(template_path).convert("RGB")
template_edges = _task_status_shape_edges(template_rgb, cv2, np)
roi = pic.crop((x1, y1, x2, y2))
roi_edges = _task_status_shape_edges(roi, cv2, np)
th, tw = template_edges.shape[:2]
rh, rw = roi_edges.shape[:2]
if th <= 0 or tw <= 0 or rh < th or rw < tw:
return 0
res = cv2.matchTemplate(roi_edges, template_edges, cv2.TM_CCOEFF_NORMED)
threshold = float(
getattr(analyser, "fudai_task_status_template_threshold", 0.26) or 0.26
)
threshold = max(0.0, min(1.0, threshold))
matches = _collect_task_status_matches(res, threshold, tw, th)
best_score = float(matches[0][0]) if matches else -1.0
task_count = min(2, len(matches))
try:
analyser._log_kv(
"任务数诊断",
"[TASK_COUNT_DIAG] dacheng_shape_scored",
task_count=task_count,
source="v2_dacheng_shape",
search_box=(x1, y1, x2, y2),
template_path=template_path,
template_score=round(best_score, 4) if best_score >= 0 else best_score,
match_count=len(matches),
match_points=";".join(
f"{round(score, 3)}@{x1 + mx},{y1 + my}"
for score, mx, my in matches[:4]
),
threshold=threshold,
)
except Exception:
pass
if task_count in (1, 2):
try:
setattr(analyser, "_fudai_detail_task_count_source", "v2_dacheng_shape")
analyser._log_kv(
"检测",
f"识别到福袋任务数量:{task_count}个(v2 达成形状模板)",
task_count=task_count,
source="v2_dacheng_shape",
template_score=round(best_score, 4),
)
analyser._log_kv(
"任务数诊断",
"[TASK_COUNT_DIAG] matched",
task_count=task_count,
source="v2_dacheng_shape",
template_score=round(best_score, 4),
match_count=len(matches),
)
except Exception:
pass
return task_count
try:
analyser._log_kv(
"任务数诊断",
"[TASK_COUNT_DIAG] no_match",
source="v2_dacheng_shape",
match_count=len(matches),
best_score=round(best_score, 4) if best_score >= 0 else best_score,
)
except Exception:
pass
except Exception:
return 0
return 0
def _scale_box_to_image(
box: tuple[int, int, int, int],
width: int,
height: int,
) -> tuple[int, int, int, int]:
sx = width / 1080.0
sy = height / 2400.0
x1, y1, x2, y2 = box
return (
max(0, min(int(x1 * sx), width)),
max(0, min(int(y1 * sy), height)),
max(0, min(int(x2 * sx), width)),
max(0, min(int(y2 * sy), height)),
)
def _task_status_shape_edges(image: Any, cv2: Any, np: Any) -> Any:
arr = np.asarray(image.convert("RGB"))
gray = cv2.cvtColor(arr, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(gray, (3, 3), 0)
return cv2.Canny(blur, 40, 120)
def _collect_task_status_matches(
result: Any,
threshold: float,
template_width: int,
template_height: int,
) -> list[tuple[float, int, int]]:
import numpy as np # type: ignore[import-untyped]
loc = np.where(result >= threshold)
candidates: list[tuple[float, int, int]] = []
for y, x in zip(*loc):
candidates.append((float(result[y, x]), int(x), int(y)))
candidates.sort(reverse=True)
kept: list[tuple[float, int, int]] = []
min_y_gap = max(38, int(template_height * 0.65))
for score, x, y in candidates:
cx = x + template_width / 2.0
cy = y + template_height / 2.0
duplicate = False
for _score, kept_x, kept_y in kept:
kept_cx = kept_x + template_width / 2.0
kept_cy = kept_y + template_height / 2.0
if abs(cy - kept_cy) < min_y_gap and abs(cx - kept_cx) < template_width * 0.75:
duplicate = True
break
if not duplicate:
kept.append((score, x, y))
if len(kept) >= 4:
break
return kept
def get_detail_task_count_digit_box(task_count_box: tuple[int, int, int, int]) -> tuple[int, int, int, int]:
"""Extract the trailing task-count digit box inside the (0/1)/(1/2) badge."""
x1, y1, x2, y2 = [int(v) for v in task_count_box]
# one-task and two-task badges have different anchors in current verified samples.
if y1 >= 1830:
digit_x1 = x1 + 86
digit_x2 = x1 + 98
digit_y1 = y1 + 16
digit_y2 = y1 + 46
else:
digit_x1 = x1 + 114
digit_x2 = x1 + 135
digit_y1 = y1 + 44
digit_y2 = y1 + 75
if digit_x2 <= digit_x1:
digit_x2 = min(x2, digit_x1 + 1)
if digit_y2 <= digit_y1:
digit_y2 = min(y2, digit_y1 + 1)
return digit_x1, digit_y1, digit_x2, digit_y2
def check_in_fudai_detail(analyser: Any) -> bool:
@@ -279,9 +654,14 @@ def check_in_fudai_detail(analyser: Any) -> bool:
analyser._detection_cache[cache_key] = (now, False)
return False
from PIL import Image
pic = Image.open(pic_path)
pic.load()
pic_rgb = pic.convert("RGB")
try:
pic.load()
pic_rgb = pic.convert("RGB")
finally:
pic.close()
# 获取分辨率比例和Y偏移
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
+79 -45
View File
@@ -11,14 +11,20 @@ import os
import time
from typing import Any
from PIL import Image
from douyin.core import path_config
from ._common import _ensure_detection_cache
from .template_match_helpers import (
numpy_pixel_scan,
per_pixel_scan_fallback,
template_match_fallback,
from .finder_numpy_scan import scan_with_numpy
from .finder_pixel_scan import scan_pixel_by_pixel
from .finder_scan_config import (
FUDAI_ICON_DEFAULT_OPTIMAL_X,
FUDAI_ICON_SCAN_X_END,
FUDAI_ICON_SCAN_X_START,
FUDAI_ICON_SCAN_Y_BASES,
scale_x,
scale_y,
)
from .finder_template_match import match_template
def check_have_fudai_with_ready_screenshot(
@@ -68,26 +74,21 @@ def check_have_fudai_with_ready_screenshot(
func_start = time.time()
# 使用统一的截图路径配置
try:
from douyin.core import path_config
pic1_path = path_config.get_screenshot_path()
except Exception:
# 回退到旧路径(向后兼容)
from douyin.core import path_config
pic1_path = path_config.get_screenshot_path()
attempt_count = 0 # 仅用于日志记录,不影响循环控制
# ===== 像素检测版(优先使用),不依赖 OpenCV =====
# 改为按时间控制循环,而不是按次数限制
try:
retry_delay_s = float(
getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6) or 0.6
)
retry_delay_raw = getattr(analyser, "fudai_icon_retry_delay_seconds", 0.6)
retry_delay_s = float(0.6 if retry_delay_raw is None else retry_delay_raw)
except Exception:
retry_delay_s = 0.6
try:
max_wait_s = float(getattr(analyser, "fudai_icon_max_wait_seconds", 5.0) or 5.0)
max_wait_raw = getattr(analyser, "fudai_icon_max_wait_seconds", 5.0)
max_wait_s = float(5.0 if max_wait_raw is None else max_wait_raw)
except Exception:
max_wait_s = 5.0
if retry_delay_s < 0.1:
@@ -108,7 +109,12 @@ def check_have_fudai_with_ready_screenshot(
max_wait_s * 1.5, 15
) # 最长15秒,但不超过 max_wait_s * 1.5
while (time.time() - func_start) < max_wait_s and time.time() < absolute_timeout:
first_iteration = True
while (
first_iteration
or ((time.time() - func_start) < max_wait_s and time.time() < absolute_timeout)
):
first_iteration = False
# 额外的循环次数保护:防止无限循环
if loop >= max_loops:
try:
@@ -162,12 +168,16 @@ def check_have_fudai_with_ready_screenshot(
# 读取截图
pic = None
try:
from PIL import Image
pic = Image.open(pic1_path)
pic.load()
except Exception:
# 如果读取失败,尝试重新截图
try:
analyser.operation.get_screenshot(analyser.device_id, use_service=False)
from PIL import Image
pic = Image.open(pic1_path)
pic.load()
except Exception:
@@ -202,6 +212,7 @@ def check_have_fudai_with_ready_screenshot(
continue
pic_new = pic.convert("RGBA")
pic.close()
width, height = pic_new.size
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
@@ -219,26 +230,36 @@ def check_have_fudai_with_ready_screenshot(
detected = False
detected_x = None
# 初始化扫描范围变量(用于日志记录)
scan_x_start = 41 * rx // 1080
scan_x_end = min(410 * rx // 1080, width)
scan_y = 403 * ry // 2400 + y_pianyi_val
scan_x_start = scale_x(FUDAI_ICON_SCAN_X_START, rx)
scan_x_end = min(scale_x(FUDAI_ICON_SCAN_X_END, rx), width)
scan_y_candidates = [
scale_y(base_y, ry, y_pianyi_val)
for base_y in FUDAI_ICON_SCAN_Y_BASES
]
scan_y_values = [y for y in scan_y_candidates if 0 <= y < height]
scan_y = scan_y_values[0] if scan_y_values else 403 * ry // 2400 + y_pianyi_val
# 获取最优搜索起始位置(使用历史记录或默认值)
try:
# 尝试获取上次找到的福袋位置(1080基准)
last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0)
if last_fudai_x > 0 and scan_x_start <= last_fudai_x <= scan_x_end:
optimal_x_scaled = last_fudai_x * rx // 1080
last_fudai_x_scaled = last_fudai_x * rx // 1080
if last_fudai_x > 0 and scan_x_start <= last_fudai_x_scaled <= scan_x_end:
optimal_x_scaled = last_fudai_x_scaled
else:
# 使用默认最优位置:最热门区域中心(98-240的中心,约169)
optimal_x_scaled = 169 * rx // 1080
optimal_x_scaled = scale_x(FUDAI_ICON_DEFAULT_OPTIMAL_X, rx)
except Exception:
# 使用默认最优位置
optimal_x_scaled = 169 * rx // 1080
optimal_x_scaled = scale_x(FUDAI_ICON_DEFAULT_OPTIMAL_X, rx)
# 确保最优位置在搜索范围内
optimal_x_scaled = max(scan_x_start, min(optimal_x_scaled, scan_x_end - 1))
pixel_icon_enabled = bool(
getattr(analyser, "pixel_detect_fudai_icon_enabled", True)
)
# 保存完整截图用于调试(检测前)
try:
from douyin.handlers import douyin_screenshot_manager
@@ -252,12 +273,23 @@ def check_have_fudai_with_ready_screenshot(
picname="fudai_icon",
step="before_detect",
coords=(
(scan_x_start, scan_y - 3, scan_x_end, scan_y + 4)
if scan_y >= 3
(
scan_x_start,
max(0, min(scan_y_values) - 3),
scan_x_end,
min(height, max(scan_y_values) + 4),
)
if scan_y_values
else None
),
extra_info={
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
"scan_range": (
f"x:{scan_x_start}-{scan_x_end}, "
f"y:{min(scan_y_values)}-{max(scan_y_values)}"
if scan_y_values
else f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}"
),
"candidate_y": ",".join(str(y) for y in scan_y_values),
"resolution": f"{rx}x{ry}",
"y_offset": y_pianyi_val,
"loop": loop,
@@ -273,33 +305,34 @@ def check_have_fudai_with_ready_screenshot(
except Exception:
pass
# 先尝试 numpy 加速扫描水平带(性能优化:批量处理)
np_detected, np_x = numpy_pixel_scan(
analyser, pic_new, rx, ry, width, height, y_pianyi_val, optimal_x_scaled,
)
if np_detected:
detected = True
detected_x = np_x
# numpy 未命中/不可用时回退到原始逐像素检查
if not detected:
pp_detected, pp_x = per_pixel_scan_fallback(
analyser, pic_new, rx, ry, y_pianyi_val,
if pixel_icon_enabled:
# numpy 加速扫描(性能优化,失败回退到逐像素扫描)
detected, _detected_x = scan_with_numpy(
analyser, pic_new, rx, ry, y_pianyi_val, optimal_x_scaled
)
if pp_detected:
detected = True
detected_x = pp_x
if detected and _detected_x is not None:
detected_x = _detected_x
# numpy 未命中/不可用时回退到逐像素扫描
if not detected:
detected, _detected_x = scan_pixel_by_pixel(
analyser, pic_new, rx, ry, y_pianyi_val
)
if detected and _detected_x is not None:
detected_x = _detected_x
# 像素检测未命中时,使用模板匹配作为兜底
if not detected or detected_x is None:
tm_detected, tm_x = template_match_fallback(
analyser, pic_new, rx, ry, width, height, y_pianyi_val, loop,
)
if tm_detected:
_det, _x = match_template(analyser, pic_new, rx, ry, y_pianyi_val, loop)
if _det and _x is not None:
detected = True
detected_x = tm_x
detected_x = _x
if detected and detected_x is not None:
try:
analyser.last_fudai_x = int(detected_x)
except Exception:
pass
# 重置连续失败计数
consecutive_failures = 0
@@ -426,3 +459,4 @@ def check_have_fudai_with_ready_screenshot(
except Exception:
pass
return False
@@ -0,0 +1,184 @@
"""douyin/detection/detection_pkg/finder_numpy_scan - numpy 加速福袋图标像素扫描
把 check_have_fudai_with_ready_screenshot 中"numpy 加速扫描水平带"段抽出来。
逻辑:在 ROI 内根据预设颜色范围生成像素掩码,按列聚合,从最优起始列向两侧
交替搜索第一个匹配列,命中即返回检测到的 x 坐标(1080 基准)。
入口:scan_with_numpy(analyser, pic_new, rx, ry, y_pianyi_val, optimal_x_scaled)
返回:(detected: bool, detected_x: Optional[int])
"""
from __future__ import annotations
import time
from typing import Any, Optional, Tuple
from .finder_scan_config import (
FUDAI_ICON_SCAN_X_END,
FUDAI_ICON_SCAN_X_START,
FUDAI_ICON_SCAN_Y_BASES,
scale_x,
scale_y,
)
def scan_with_numpy(
analyser: Any,
pic_new,
rx: int,
ry: int,
y_pianyi_val: int,
optimal_x_scaled: int,
) -> Tuple[bool, Optional[int]]:
"""numpy 加速扫描福袋图标的水平像素带。
Args:
analyser: 可读 last_fudai_x / 写 last_fudai_x / last_find_fudai_time
pic_new: PIL.Image,已加载的当前截图
rx, ry: 目标分辨率宽/高(默认 1080x2400 基准)
y_pianyi_val: Y 偏移
optimal_x_scaled: 最优起始列(设备分辨率坐标)
Returns:
(detected, detected_x) — 命中时 detected_x 是 1080 基准坐标;
失败/异常返回 (False, None),由 caller 切换到逐像素扫描。
"""
try:
import numpy as _np
except (ImportError, ValueError, IndexError, AttributeError):
return False, None
width, height = pic_new.size
try:
# 计算检测区域,考虑分辨率缩放和偏移。
# 新版福袋 icon 可能更靠左,也可能出现在 403/503 两条高度带。
y_candidates = [
scale_y(base_y, ry, y_pianyi_val)
for base_y in FUDAI_ICON_SCAN_Y_BASES
]
x1 = max(0, scale_x(FUDAI_ICON_SCAN_X_START, rx))
x2 = min(width, scale_x(FUDAI_ICON_SCAN_X_END, rx))
y_values = [y for y in y_candidates if 0 <= y < height]
if not y_values:
return False, None
y_top = max(0, min(y_values) - 3)
y_bottom = min(height, max(y_values) + 4)
if not (x1 < x2 and y_top < y_bottom):
return False, None
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
# 双截图记录:保存实时操作截图(像素检测区域)
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(
roi, operation_type="pixel_detect"
)
except Exception:
pass
arr = _np.array(roi)
if arr.size == 0:
return False, None
r = arr[:, :, 0] # type: ignore[index]
g = arr[:, :, 1] # type: ignore[index]
b = arr[:, :, 2] # type: ignore[index]
# 精度优化:扩大颜色范围,提高容错性(考虑不同屏幕色温和亮度)
# 原来的范围:R[193-203], G[176-193], B[237-247]
# 优化后:适度放宽范围,但保持中心值权重
mask_center = (
(r >= 190) & (r <= 206)
& (g >= 173) & (g <= 196)
& (b >= 234) & (b <= 250)
) # type: ignore[operator]
mask = mask_center
# 检查每一列是否有足够多的匹配像素(提高准确性,避免单个噪点误判)
cols = _np.sum(mask, axis=0)
# 至少需要 2 个像素匹配(避免单个噪点误判)
valid_cols = cols >= 2
if not valid_cols.any():
return False, None
# 从最优位置开始向左右两侧交替搜索
roi_width = x2 - x1
optimal_col = optimal_x_scaled - x1
optimal_col = max(0, min(optimal_col, roi_width - 1))
found_col: Optional[int] = None
search_range = max(optimal_col, roi_width - optimal_col)
if valid_cols[optimal_col]:
found_col = optimal_col
else:
for offset in range(1, search_range + 1):
right_col = optimal_col + offset
if right_col < roi_width and valid_cols[right_col]:
found_col = right_col
break
left_col = optimal_col - offset
if left_col >= 0 and valid_cols[left_col]:
found_col = left_col
break
if found_col is None:
# 兜底:从左到右第一个匹配
found_col = int(_np.argmax(valid_cols))
col_idx = found_col
# 1080 基准坐标
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
# 保存找到的位置作为下次的最优起点
try:
analyser.last_fudai_x = detected_x
except Exception:
pass
# 双截图记录:成功识别存档
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_last_success(
roi, operation_type="pixel_detect"
)
pic_rgb_full = pic_new.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=(x1, y_top, x2, y_bottom),
extra_info={
"detected_x": detected_x,
"detected_x_scaled": x1 + col_idx,
"scan_range": f"x:{x1}-{x2}, y:{y_top}-{y_bottom}",
"candidate_y": ",".join(str(y) for y in y_values),
"resolution": f"{rx}x{ry}",
"result": "success",
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"福袋图标检测成功保存完整截图",
path=debug_path,
detected_x=detected_x,
)
except Exception:
pass
except Exception:
pass
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
return True, detected_x
except (ImportError, ValueError, IndexError, AttributeError):
return False, None
@@ -0,0 +1,222 @@
"""douyin/detection/detection_pkg/finder_pixel_scan - 逐像素福袋图标扫描兜底
当 numpy 加速扫描没找到时,回退到逐像素遍历。逻辑与 numpy 版相似但
使用 PIL.Image.load() 提供的像素访问,性能较慢但兼容性最好。
入口:scan_pixel_by_pixel(analyser, pic_new, rx, ry, y_pianyi_val)
返回:(detected: bool, detected_x: Optional[int])
颜色范围与 finder_numpy_scan 一致:r ∈ [190, 206], g ∈ [173, 196], b ∈ [234, 250]。
"""
from __future__ import annotations
import time
from typing import Any, Optional, Tuple
from .finder_scan_config import (
FUDAI_ICON_DEFAULT_OPTIMAL_X,
FUDAI_ICON_SCAN_X_END,
FUDAI_ICON_SCAN_X_START,
FUDAI_ICON_SCAN_Y_BASES,
scale_x,
scale_y,
)
# 福袋图标主色范围(与 finder_numpy_scan 共享)
_R_MIN, _R_MAX = 190, 206
_G_MIN, _G_MAX = 173, 196
_B_MIN, _B_MAX = 234, 250
def _is_target_pixel(px) -> bool:
"""检查像素是否落在目标颜色范围内。"""
if not (isinstance(px, tuple) and len(px) >= 3):
return False
r, g, b = px[0], px[1], px[2]
return _R_MIN <= r <= _R_MAX and _G_MIN <= g <= _G_MAX and _B_MIN <= b <= _B_MAX
def _safe_check_pixel(pix, x: int, y: int) -> bool:
"""读 pix[x, y] 后检查是否目标颜色,越界/类型错误时返回 False。"""
try:
return _is_target_pixel(pix[x, y])
except (IndexError, TypeError):
return False
def _pick_optimal_x(analyser, scan_x_start: int, scan_x_end: int, rx: int) -> int:
"""选择本次扫描的最优起始列:优先用历史 last_fudai_x,否则默认热区中心。"""
try:
last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0)
if (
last_fudai_x > 0
and scan_x_start <= last_fudai_x * rx // 1080 <= scan_x_end
):
return last_fudai_x * rx // 1080
except Exception:
pass
# 默认最优位置:最热门区域中心(98-240 的中心,约 169)
return scale_x(FUDAI_ICON_DEFAULT_OPTIMAL_X, rx)
def _search_along_y(
pix,
scan_x_start: int,
scan_x_end: int,
optimal_x_scaled: int,
check_y: int,
) -> Optional[int]:
"""在指定 y 行上找第一个目标色像素的 x 坐标。
搜索顺序:optimal_x → 向两侧交替搜索 → 最后从左到右兜底。
"""
# 1. 先检查最优位置本身
if _safe_check_pixel(pix, optimal_x_scaled, check_y):
return optimal_x_scaled
# 2. 向左右两侧交替搜索
search_range = max(
optimal_x_scaled - scan_x_start,
scan_x_end - optimal_x_scaled,
)
for offset in range(1, search_range + 1):
right_x = optimal_x_scaled + offset
if right_x < scan_x_end and _safe_check_pixel(pix, right_x, check_y):
return right_x
left_x = optimal_x_scaled - offset
if left_x >= scan_x_start and _safe_check_pixel(pix, left_x, check_y):
return left_x
# 3. 最后从左到右扫一遍兜底
for x_scaled in range(scan_x_start, scan_x_end):
if _safe_check_pixel(pix, x_scaled, check_y):
return x_scaled
return None
def scan_pixel_by_pixel(
analyser: Any,
pic_new,
rx: int,
ry: int,
y_pianyi_val: int,
) -> Tuple[bool, Optional[int]]:
"""逐像素遍历兜底(numpy 不可用 / 未命中时使用)。
Args:
analyser: 可读 last_fudai_x / 写 last_fudai_x / last_find_fudai_time
pic_new: PIL.Image,已加载的当前截图
rx, ry: 目标分辨率宽/高(默认 1080x2400 基准)
y_pianyi_val: Y 偏移
Returns:
(detected, detected_x) — 命中时 detected_x 是 1080 基准坐标。
"""
detected = False
detected_x: Optional[int] = None
try:
pix = pic_new.load()
pic_width, pic_height = pic_new.size
# 计算实际扫描范围,防止越界
scan_x_start = scale_x(FUDAI_ICON_SCAN_X_START, rx)
scan_x_end = min(scale_x(FUDAI_ICON_SCAN_X_END, rx), pic_width)
scan_y_candidates = [
scale_y(base_y, ry, y_pianyi_val)
for base_y in FUDAI_ICON_SCAN_Y_BASES
]
optimal_x_scaled = _pick_optimal_x(analyser, scan_x_start, scan_x_end, rx)
# 确保最优位置在搜索范围内
optimal_x_scaled = max(scan_x_start, min(optimal_x_scaled, scan_x_end - 1))
scan_y_values = [y for y in scan_y_candidates if 0 <= y < pic_height]
if not scan_y_values:
return False, None
# 精度优化:同时检查上下几行像素
for scan_y in scan_y_values:
for offset_y in (0, -1, 1, -2, 2):
check_y = scan_y + offset_y
if not (0 <= check_y < pic_height):
continue
found_x = _search_along_y(
pix, scan_x_start, scan_x_end, optimal_x_scaled, check_y
)
if found_x is None:
continue
# 命中:转换回 1080 基准
detected_x = int(found_x * 1080.0 / max(1, rx))
detected = True
try:
analyser.last_fudai_x = detected_x
except Exception:
pass
# 双截图记录:成功识别存档
try:
from douyin.handlers import douyin_screenshot_manager
detect_roi = pic_new.crop(
(
scan_x_start,
max(0, scan_y - 3),
scan_x_end,
min(pic_height, scan_y + 4),
)
).convert("RGB")
douyin_screenshot_manager.save_last_success(
detect_roi,
operation_type="pixel_detect",
)
pic_rgb_full = pic_new.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=(
scan_x_start,
max(0, scan_y - 3),
scan_x_end,
min(pic_height, scan_y + 4),
),
extra_info={
"detected_x": detected_x,
"detected_x_scaled": found_x,
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
"candidate_y": ",".join(str(y) for y in scan_y_values),
"resolution": f"{rx}x{ry}",
"result": "success",
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"福袋图标检测成功保存完整截图",
path=debug_path,
detected_x=detected_x,
)
except Exception:
pass
except Exception:
pass
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
break
if detected:
break
except Exception:
# 像素检测失败,记录但不影响主流程
pass
return detected, detected_x
@@ -0,0 +1,17 @@
"""Shared scan ranges for finding the small fudai icon."""
from __future__ import annotations
# v2 live-room icon can sit slightly further left than the old hot zone.
FUDAI_ICON_SCAN_X_START = 20
FUDAI_ICON_SCAN_X_END = 430
FUDAI_ICON_SCAN_Y_BASES = (403, 503, 354)
FUDAI_ICON_DEFAULT_OPTIMAL_X = 169
def scale_x(value: int, rx: int) -> int:
return int(value * rx // 1080)
def scale_y(value: int, ry: int, y_offset: int = 0) -> int:
return int(value * ry // 2400 + y_offset)
@@ -0,0 +1,283 @@
"""douyin/detection/detection_pkg/finder_template_match - OpenCV 模板匹配兜底
像素检测(numpy + 逐像素)都失败时的最后兜底:用 OpenCV 模板匹配
(TM_CCOEFF_NORMED)在搜索区域里找 fudai.png 模板。
入口:match_template(analyser, pic_new, rx, ry, y_pianyi_val, loop) -> (detected, x)
"""
from __future__ import annotations
import os
import time
from typing import Any, Optional, Tuple
def _resolve_template_path() -> str:
"""获取 fudai.png 模板的绝对路径。优先 path_config,回退到本文件相邻 assets/。"""
try:
from douyin.core import path_config
return path_config.get_assets_dir() + "/fudai.png"
except Exception:
# 兜底:导入失败时显式拼到项目根的 assets/,
# 不要用 dirname(__file__) 拼 "assets"(那样会推到 detection_pkg/assets)
return os.path.normpath(
os.path.join(
os.path.dirname(__file__),
"..", "..", "..",
"assets", "fudai.png",
)
)
def _save_search_roi(analyser, search_roi, last_match_path: str, loop: int, x1: int, x2: int, y_top: int, y_bottom: int, rw: int, rh: int) -> None:
"""保存搜索区域到 last_match.png(仅作日志/调试用)。"""
try:
import cv2
save_success = cv2.imwrite(last_match_path, search_roi)
if save_success:
try:
analyser._log_kv(
"[找福袋图标] 已保存搜索区域截图",
loop=loop,
文件路径=last_match_path,
搜索区域尺寸=f"{rw}x{rh}",
搜索区域坐标=f"({x1},{y_top})-({x2},{y_bottom})",
)
except Exception:
pass
else:
try:
analyser._log_kv(
"[找福袋图标] 保存搜索区域截图失败",
loop=loop,
文件路径=last_match_path,
)
except Exception:
pass
except Exception as save_err:
try:
analyser._log_kv(
"[找福袋图标] 保存搜索区域截图异常",
loop=loop,
错误类型=type(save_err).__name__,
错误信息=str(save_err),
)
except Exception:
pass
def match_template(
analyser: Any,
pic_new,
rx: int,
ry: int,
y_pianyi_val: int,
loop: int,
) -> Tuple[bool, Optional[int]]:
"""像素检测全部失败后的模板匹配兜底。
Args:
analyser: 提供 fudai_template_match_threshold / _log_kv / last_find_fudai_time
pic_new: PIL.Image,已加载的当前截图
rx, ry: 目标分辨率宽/高(默认 1080x2400 基准)
y_pianyi_val: Y 偏移
loop: 当前循环次数(仅用于日志)
Returns:
(detected, detected_x) — 命中时 detected_x 是 1080 基准坐标。
"""
detected = False
detected_x: Optional[int] = None
try:
import cv2
import numpy as np
template_path = _resolve_template_path()
if not os.path.exists(template_path):
return False, None
# 获取匹配阈值
try:
template_threshold = float(
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
)
except Exception:
template_threshold = 0.7
# 读取模板
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
if template is None:
return False, None
# 将 PIL 图片转换为 OpenCV 格式
pic_rgb = pic_new.convert("RGB")
screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR)
height, width = screenshot_bgr.shape[:2]
# 定义搜索区域:X=156-269(1080 基准),Y=351-451(2400 基准)
x1 = max(0, 156 * rx // 1080)
x2 = min(width, 269 * rx // 1080)
y_top = max(0, 351 * ry // 2400 + y_pianyi_val)
y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val)
if not (x1 < x2 and y_top < y_bottom):
try:
analyser._log_kv(
"[找福袋图标] 模板匹配失败-坐标无效",
loop=loop,
x1=x1,
x2=x2,
y_top=y_top,
y_bottom=y_bottom,
截图尺寸=f"{width}x{height}",
分辨率=f"{rx}x{ry}",
)
except Exception:
pass
return False, None
search_roi = screenshot_bgr[y_top:y_bottom, x1:x2] # type: ignore[index]
if search_roi.size == 0:
try:
analyser._log_kv(
"[找福袋图标] 模板匹配失败-搜索区域为空",
loop=loop,
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
截图尺寸=f"{width}x{height}",
)
except Exception:
pass
return False, None
th, tw = template.shape[:2]
rh, rw = search_roi.shape[:2]
# 保存搜索区域截图到 last_match.png
try:
from douyin.core import path_config as _pc
match_dir = os.path.join(_pc.get_pic_dir(), "template_match")
except Exception:
match_dir = os.path.normpath(
os.path.join(
os.path.dirname(__file__),
"..", "..", "..",
"pic", "template_match",
)
)
try:
os.makedirs(match_dir, exist_ok=True)
last_match_path = os.path.join(match_dir, "last_match.png")
_save_search_roi(
analyser, search_roi, last_match_path, loop,
x1, x2, y_top, y_bottom, rw, rh,
)
except Exception:
pass
# 模板太大就缩小
if th > rh or tw > rw:
scale = min(rh / max(th, 1), rw / max(tw, 1))
if scale > 0:
template = cv2.resize(
template,
(max(1, int(tw * scale)), max(1, int(th * scale))),
)
th, tw = template.shape[:2]
# 执行模板匹配
if not (th <= rh and tw <= rw):
try:
analyser._log_kv(
"[找福袋图标] 模板匹配失败-尺寸不匹配",
loop=loop,
模板尺寸=f"{tw}x{th}",
搜索区域尺寸=f"{rw}x{rh}",
条件=f"th({th})<=rh({rh}) and tw({tw})<=rw({rw})",
)
except Exception:
pass
return False, None
res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED)
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res)
# 双截图记录:保存实时操作截图(搜索区域)
try:
from douyin.handlers import douyin_screenshot_manager
from PIL import Image as PILImage
search_roi_pil = PILImage.fromarray(
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
)
douyin_screenshot_manager.save_latest_attempt(
search_roi_pil, operation_type="template_match"
)
except Exception:
pass
try:
analyser._log_kv(
"[找福袋图标] 模板匹配兜底",
loop=loop,
匹配分数=round(max_val, 4),
阈值=template_threshold,
是否通过=bool(max_val >= template_threshold),
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
搜索区域尺寸=f"{rw}x{rh}",
模板尺寸=f"{tw}x{th}",
截图尺寸=f"{width}x{height}",
分辨率=f"{rx}x{ry}",
)
except Exception:
pass
if max_val < template_threshold:
return False, None
# 命中:保存成功识别存档
try:
from douyin.handlers import douyin_screenshot_manager
from PIL import Image as PILImage
search_roi_pil = PILImage.fromarray(
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
)
douyin_screenshot_manager.save_last_success(
search_roi_pil, operation_type="template_match"
)
except Exception:
pass
# 1080 基准坐标
detected_x_in_roi = max_loc[0]
detected_x = int(
(x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx)
)
detected = True
try:
analyser.last_fudai_x = detected_x
except Exception:
pass
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
return detected, detected_x
except (ImportError, Exception) as e:
# OpenCV 不可用或模板匹配失败,让 caller 继续走未命中分支
try:
analyser._log_kv(
"[找福袋图标] 模板匹配异常",
loop=loop,
错误类型=type(e).__name__,
错误信息=str(e),
)
except Exception:
pass
return False, None
@@ -1,547 +0,0 @@
"""finder.py 的辅助函数:模板匹配兜底。
把 check_have_fudai_with_ready_screenshot 中"OpenCV 模板匹配兜底"逻辑(226 行)
抽出来,便于独立测试与维护。
同时包含 numpy 加速像素扫描 + 逐像素扫描兜底的辅助函数。
"""
from __future__ import annotations
import os
import time
from typing import Any, Optional
def numpy_pixel_scan(
analyser: Any,
pic_new: Any, # PIL.Image (RGBA)
rx: int,
ry: int,
width: int,
height: int,
y_pianyi_val: int,
optimal_x_scaled: int,
) -> tuple[bool, Optional[int]]:
"""先尝试 numpy 加速扫描水平带(性能优化:批量处理)。
返回 (detected, detected_x_in_1080_basis)。失败/异常返回 (False, None)。
"""
try:
import numpy as _np
y0 = 354 * ry // 2400 + y_pianyi_val
x1 = max(0, 157 * rx // 1080)
x2 = min(width, 410 * rx // 1080)
y_top = max(0, y0 - 3)
y_bottom = min(height, y0 + 4)
if not (x1 < x2 and y_top < y_bottom):
return False, None
roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB")
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_latest_attempt(
roi, operation_type="pixel_detect"
)
except Exception:
pass
arr = _np.array(roi)
if arr.size == 0:
return False, None
r = arr[:, :, 0]
g = arr[:, :, 1]
b = arr[:, :, 2]
mask_center = (
(r >= 190) & (r <= 206)
& (g >= 173) & (g <= 196)
& (b >= 234) & (b <= 250)
)
cols = _np.sum(mask_center, axis=0)
valid_cols = cols >= 2
if not valid_cols.any():
return False, None
roi_width = x2 - x1
optimal_col = max(0, min(optimal_x_scaled - x1, roi_width - 1))
# 从最优位置开始,向左右两侧交替搜索
found_col = None
search_range = max(optimal_col, roi_width - optimal_col)
if valid_cols[optimal_col]:
found_col = optimal_col
else:
for offset in range(1, search_range + 1):
right_col = optimal_col + offset
if right_col < roi_width and valid_cols[right_col]:
found_col = right_col
break
left_col = optimal_col - offset
if left_col >= 0 and valid_cols[left_col]:
found_col = left_col
break
if found_col is None:
found_col = int(_np.argmax(valid_cols))
col_idx = found_col
detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx))
try:
analyser.last_fudai_x = detected_x
except Exception:
pass
try:
from douyin.handlers import douyin_screenshot_manager
douyin_screenshot_manager.save_last_success(
roi, operation_type="pixel_detect"
)
pic_rgb_full = pic_new.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=(x1, y_top, x2, y_bottom),
extra_info={
"detected_x": detected_x,
"detected_x_scaled": x1 + col_idx,
"scan_range": f"x:{x1}-{x2}, y:{y_top}-{y_bottom}",
"resolution": f"{rx}x{ry}",
"result": "success",
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"福袋图标检测成功保存完整截图",
path=debug_path,
detected_x=detected_x,
)
except Exception:
pass
except Exception:
pass
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
return True, detected_x
except (ImportError, ValueError, IndexError, AttributeError):
return False, None
def _is_target_pixel(px: Any) -> bool:
"""检查像素是否在目标颜色范围内。"""
if not (isinstance(px, tuple) and len(px) >= 3):
return False
return (
190 <= px[0] <= 206
and 173 <= px[1] <= 196
and 234 <= px[2] <= 250
)
def per_pixel_scan_fallback(
analyser: Any,
pic_new: Any,
rx: int,
ry: int,
y_pianyi_val: int,
) -> tuple[bool, Optional[int]]:
"""numpy 不可用或未命中时的逐像素扫描兜底。"""
try:
pix = pic_new.load()
pic_width, pic_height = pic_new.size
scan_x_start = 41 * rx // 1080
scan_x_end = min(410 * rx // 1080, pic_width)
scan_y = 403 * ry // 2400 + y_pianyi_val
try:
last_fudai_x = int(getattr(analyser, "last_fudai_x", 0) or 0)
if (
last_fudai_x > 0
and scan_x_start <= last_fudai_x * rx // 1080 <= scan_x_end
):
optimal_x_scaled = last_fudai_x * rx // 1080
else:
optimal_x_scaled = 169 * rx // 1080
except Exception:
optimal_x_scaled = 169 * rx // 1080
optimal_x_scaled = max(scan_x_start, min(optimal_x_scaled, scan_x_end - 1))
if not (0 <= scan_y < pic_height):
return False, None
for offset_y in [0, -1, 1, -2, 2]:
check_y = scan_y + offset_y
if not (0 <= check_y < pic_height):
continue
found_x = _scan_one_row(
pix, check_y, scan_x_start, scan_x_end, optimal_x_scaled
)
if found_x is not None:
detected_x = int(found_x * 1080.0 / max(1, rx))
try:
analyser.last_fudai_x = detected_x
except Exception:
pass
_save_per_pixel_success(
analyser, pic_new, scan_x_start, scan_y, scan_x_end,
pic_height, detected_x, found_x, rx, ry,
)
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
return True, detected_x
return False, None
except Exception:
return False, None
def _scan_one_row(
pix: Any,
check_y: int,
scan_x_start: int,
scan_x_end: int,
optimal_x_scaled: int,
) -> Optional[int]:
"""在单行扫描目标像素:先查最优位置,然后左右交替,最后从左到右兜底。"""
# 先检查最优位置
try:
if _is_target_pixel(pix[optimal_x_scaled, check_y]):
return optimal_x_scaled
except (IndexError, TypeError):
pass
# 向左右两侧交替搜索
search_range = max(
optimal_x_scaled - scan_x_start,
scan_x_end - optimal_x_scaled,
)
for offset in range(1, search_range + 1):
right_x = optimal_x_scaled + offset
if right_x < scan_x_end:
try:
if _is_target_pixel(pix[right_x, check_y]):
return right_x
except (IndexError, TypeError):
pass
left_x = optimal_x_scaled - offset
if left_x >= scan_x_start:
try:
if _is_target_pixel(pix[left_x, check_y]):
return left_x
except (IndexError, TypeError):
pass
# 兜底:从左到右
for x_scaled in range(scan_x_start, scan_x_end):
try:
if _is_target_pixel(pix[x_scaled, check_y]):
return x_scaled
except (IndexError, TypeError):
continue
return None
def _save_per_pixel_success(
analyser: Any, pic_new: Any, scan_x_start: int, scan_y: int,
scan_x_end: int, pic_height: int, detected_x: int, found_x: int,
rx: int, ry: int,
) -> None:
try:
from douyin.handlers import douyin_screenshot_manager
detect_roi = pic_new.crop(
(scan_x_start, max(0, scan_y - 3), scan_x_end, min(pic_height, scan_y + 4))
).convert("RGB")
douyin_screenshot_manager.save_last_success(
detect_roi, operation_type="pixel_detect",
)
pic_rgb_full = pic_new.convert("RGB")
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb_full,
operation_type="pixel_detect",
picname="fudai_icon",
step="detected",
coords=(
scan_x_start, max(0, scan_y - 3),
scan_x_end, min(pic_height, scan_y + 4),
),
extra_info={
"detected_x": detected_x,
"detected_x_scaled": found_x,
"scan_range": f"x:{scan_x_start}-{scan_x_end}, y:{scan_y}",
"resolution": f"{rx}x{ry}",
"result": "success",
},
)
if debug_path:
try:
analyser._log_kv(
"[调试图像]",
"福袋图标检测成功保存完整截图",
path=debug_path,
detected_x=detected_x,
)
except Exception:
pass
except Exception:
pass
def template_match_fallback(
analyser: Any,
pic_new: Any, # PIL.Image (RGBA)
rx: int,
ry: int,
width: int,
height: int,
y_pianyi_val: int,
loop: int,
) -> tuple[bool, Optional[int]]:
"""像素检测未命中时使用 OpenCV 模板匹配作为兜底。
返回 (detected, detected_x_in_1080_basis)。失败/异常返回 (False, None)。
"""
try:
import cv2
import numpy as np
# 获取模板路径
try:
from douyin.core import path_config
template_path = path_config.get_assets_dir() + "/fudai.png"
except Exception:
base_dir = os.path.dirname(os.path.abspath(__file__))
template_path = os.path.join(base_dir, "assets", "fudai.png")
if not os.path.exists(template_path):
return False, None
try:
template_threshold = float(
getattr(analyser, "fudai_template_match_threshold", 0.7) or 0.7
)
except Exception:
template_threshold = 0.7
template = cv2.imread(template_path, cv2.IMREAD_COLOR)
if template is None:
return False, None
pic_rgb = pic_new.convert("RGB")
screenshot_bgr = cv2.cvtColor(np.array(pic_rgb), cv2.COLOR_RGB2BGR)
# 搜索区域:X=156-269(1080基准),Y=351-451(2400基准)
x1 = max(0, 156 * rx // 1080)
x2 = min(width, 269 * rx // 1080)
y_top = max(0, 351 * ry // 2400 + y_pianyi_val)
y_bottom = min(height, 451 * ry // 2400 + y_pianyi_val)
if not (x1 < x2 and y_top < y_bottom):
try:
analyser._log_kv(
"[找福袋图标] 模板匹配失败-坐标无效",
loop=loop,
x1=x1,
x2=x2,
y_top=y_top,
y_bottom=y_bottom,
截图尺寸=f"{width}x{height}",
分辨率=f"{rx}x{ry}",
)
except Exception:
pass
return False, None
search_roi = screenshot_bgr[y_top:y_bottom, x1:x2]
if search_roi.size <= 0:
try:
analyser._log_kv(
"[找福袋图标] 模板匹配失败-搜索区域为空",
loop=loop,
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
截图尺寸=f"{width}x{height}",
)
except Exception:
pass
return False, None
th, tw = template.shape[:2]
rh, rw = search_roi.shape[:2]
# 保存搜索区域截图到 last_match.png(仅用于调试)
_save_last_match_debug(analyser, search_roi, loop, x1, x2, y_top, y_bottom, rw, rh)
# 如果模板太大,缩小模板
if th > rh or tw > rw:
scale = min(rh / max(th, 1), rw / max(tw, 1))
if scale > 0:
template = cv2.resize(
template,
(max(1, int(tw * scale)), max(1, int(th * scale))),
)
th, tw = template.shape[:2]
if not (th <= rh and tw <= rw):
try:
analyser._log_kv(
"[找福袋图标] 模板匹配失败-尺寸不匹配",
loop=loop,
模板尺寸=f"{tw}x{th}",
搜索区域尺寸=f"{rw}x{rh}",
条件=f"th({th})<=rh({rh}) and tw({tw})<=rw({rw})",
)
except Exception:
pass
return False, None
# 执行模板匹配
res = cv2.matchTemplate(search_roi, template, cv2.TM_CCOEFF_NORMED)
_min_val, max_val, _min_loc, max_loc = cv2.minMaxLoc(res)
_save_template_match_attempt_log(analyser, search_roi)
try:
analyser._log_kv(
"[找福袋图标] 模板匹配兜底",
loop=loop,
匹配分数=round(max_val, 4),
阈值=template_threshold,
是否通过=bool(max_val >= template_threshold),
搜索区域=f"({x1},{y_top})-({x2},{y_bottom})",
搜索区域尺寸=f"{rw}x{rh}",
模板尺寸=f"{tw}x{th}",
截图尺寸=f"{width}x{height}",
分辨率=f"{rx}x{ry}",
)
except Exception:
pass
if max_val < template_threshold:
return False, None
_save_template_match_success(analyser, search_roi)
# 命中:计算 1080 基准 x 坐标
detected_x_in_roi = max_loc[0]
detected_x = int((x1 + detected_x_in_roi + tw // 2) * 1080.0 / max(1, rx))
try:
analyser.last_find_fudai_time = time.time()
except Exception:
pass
return True, detected_x
except Exception as e:
try:
analyser._log_kv(
"[找福袋图标] 模板匹配异常",
loop=loop,
错误类型=type(e).__name__,
错误信息=str(e),
)
except Exception:
pass
return False, None
def _save_last_match_debug(
analyser: Any, search_roi: Any, loop: int, x1: int, x2: int,
y_top: int, y_bottom: int, rw: int, rh: int,
) -> None:
try:
import cv2
base_dir = os.path.dirname(os.path.abspath(__file__))
pic_base = os.path.join(base_dir, "pic")
match_dir = os.path.join(pic_base, "template_match")
os.makedirs(match_dir, exist_ok=True)
last_match_path = os.path.join(match_dir, "last_match.png")
save_success = cv2.imwrite(last_match_path, search_roi)
if save_success:
try:
analyser._log_kv(
"[找福袋图标] 已保存搜索区域截图",
loop=loop,
文件路径=last_match_path,
搜索区域尺寸=f"{rw}x{rh}",
搜索区域坐标=f"({x1},{y_top})-({x2},{y_bottom})",
)
except Exception:
pass
else:
try:
analyser._log_kv(
"[找福袋图标] 保存搜索区域截图失败",
loop=loop,
文件路径=last_match_path,
)
except Exception:
pass
except Exception as save_err:
try:
analyser._log_kv(
"[找福袋图标] 保存搜索区域截图异常",
loop=loop,
错误类型=type(save_err).__name__,
错误信息=str(save_err),
)
except Exception:
pass
def _save_template_match_attempt_log(analyser: Any, search_roi: Any) -> None:
"""保存"实时尝试"截图(双截图记录用)。"""
try:
import cv2
from PIL import Image as PILImage
from douyin.handlers import douyin_screenshot_manager
search_roi_pil = PILImage.fromarray(
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
)
douyin_screenshot_manager.save_latest_attempt(
search_roi_pil,
operation_type="template_match",
)
except Exception:
pass
def _save_template_match_success(analyser: Any, search_roi: Any) -> None:
"""命中时保存成功识别存档截图。"""
try:
import cv2
from PIL import Image as PILImage
from douyin.handlers import douyin_screenshot_manager
search_roi_pil = PILImage.fromarray(
cv2.cvtColor(search_roi, cv2.COLOR_BGR2RGB)
)
douyin_screenshot_manager.save_last_success(
search_roi_pil,
operation_type="template_match",
)
except Exception:
pass
+8 -5
View File
@@ -13,16 +13,19 @@
import os
from typing import Any, Optional
from PIL import Image
def _safe_open_screenshot_rgb(pic_path: str) -> Optional[Image.Image]:
def _safe_open_screenshot_rgb(pic_path: str):
try:
if not pic_path or (not os.path.exists(pic_path)):
return None
from PIL import Image
pic = Image.open(pic_path)
pic.load() # Force load to catch truncated files early
return pic.convert("RGB")
try:
pic.load()
return pic.convert("RGB")
finally:
pic.close()
except (OSError, IOError, SyntaxError):
# Handle truncated image files
return None
+132 -114
View File
@@ -1,3 +1,5 @@
from __future__ import annotations
# pyright: reportGeneralTypeIssues=false
# pyright: reportAttributeAccessIssue=false
# pyright: reportMissingModuleSource=false
@@ -14,16 +16,23 @@ import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Optional
from PIL import Image
from ._common import _safe_open_screenshot_rgb
def _read_rgb_pixel(pic_rgb: Image.Image, x: int, y: int) -> tuple[int, int, int]:
pixel = pic_rgb.getpixel((x, y))
if isinstance(pixel, tuple):
return int(pixel[0]), int(pixel[1]), int(pixel[2])
value = int(pixel)
return value, value, value
def detect_attend_button_red_area(
pic_rgb: Image.Image,
return_info: bool = False,
red_ratio_threshold: float | None = None,
analyser: Any = None,
save_debug: bool = False,
) -> bool | tuple[bool, dict]:
"""检测参与按钮:大片红色区域。
@@ -32,16 +41,18 @@ def detect_attend_button_red_area(
扩展检测区域到更宽的范围以覆盖"一键参与评论"等按钮
"""
try:
from douyin.fudai.core.coords import get_pixel_region
width, height = pic_rgb.size
# 缩放坐标到实际尺寸
scale_x = width / 1080.0
scale_y = height / 2400.0
# 检测区域(基准1080x2400,扩展宽度以覆盖更宽的按钮)
x1 = int(200 * scale_x) # 扩展左侧
y1 = int(2000 * scale_y) # 稍微上移
x2 = int(880 * scale_x) # 扩展右侧
y2 = int(2120 * scale_y) # 稍微下移
bx1, by1, bx2, by2 = get_pixel_region("attend_button", (200, 2000, 880, 2120))
x1 = int(bx1 * scale_x)
y1 = int(by1 * scale_y)
x2 = int(bx2 * scale_x)
y2 = int(by2 * scale_y)
# 确保坐标在范围内
x1 = max(0, min(x1, width))
@@ -53,26 +64,27 @@ def detect_attend_button_red_area(
return False
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="attend_button",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
)
if debug_path:
try:
import logging
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="attend_button",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
)
if debug_path:
try:
import logging
logging.info("[调试图像] 参与按钮检测前保存: %s", debug_path)
except Exception: # type: ignore[general-exception]
pass
except Exception: # type: ignore[general-exception]
pass
logging.debug("[调试图像] 参与按钮检测前保存: %s", debug_path)
except Exception: # type: ignore[general-exception]
pass
except Exception: # type: ignore[general-exception]
pass
# 采样检测点:检测大片红色区域
red_count = 0
@@ -82,7 +94,7 @@ def detect_attend_button_red_area(
for y in range(y1, y2, step_y):
for x in range(x1, x2, step_x):
try:
r, g, b = pic_rgb.getpixel((x, y))
r, g, b = _read_rgb_pixel(pic_rgb, x, y)
# 检测红色:R值高,G和B相对较低
if r > 200 and (r - g) > 50 and (r - b) > 50:
red_count += 1
@@ -127,38 +139,39 @@ def detect_attend_button_red_area(
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
# 无论成功失败都保存debug截图
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="attend_button",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"threshold": threshold,
"result": "success" if result else "failed",
},
)
if debug_path:
try:
import logging
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="attend_button",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"threshold": threshold,
"result": "success" if result else "failed",
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 参与按钮检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s",
debug_path,
red_ratio,
threshold,
"success" if result else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
logging.debug(
"[调试图像] 参与按钮检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s",
debug_path,
red_ratio,
threshold,
"success" if result else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
return result
except Exception:
@@ -178,6 +191,7 @@ def detect_fansclub_join_red_area(
return_info: bool = False,
red_ratio_threshold: float | None = None,
analyser: Any = None,
save_debug: bool = False,
) -> bool | tuple[bool, dict]:
"""检测粉丝团加入:大片红色区域。
@@ -185,16 +199,18 @@ def detect_fansclub_join_red_area(
检测区域:(200,1940)-(880,2140) 基准1080x2400
"""
try:
from douyin.fudai.core.coords import get_pixel_region
width, height = pic_rgb.size
# 缩放坐标到实际尺寸
scale_x = width / 1080.0
scale_y = height / 2400.0
# 检测区域(基准1080x2400)
x1 = int(200 * scale_x)
y1 = int(1940 * scale_y)
x2 = int(880 * scale_x)
y2 = int(2140 * scale_y)
bx1, by1, bx2, by2 = get_pixel_region("fansclub_join", (200, 1940, 880, 2140))
x1 = int(bx1 * scale_x)
y1 = int(by1 * scale_y)
x2 = int(bx2 * scale_x)
y2 = int(by2 * scale_y)
# 确保坐标在范围内
x1 = max(0, min(x1, width))
@@ -212,29 +228,30 @@ def detect_fansclub_join_red_area(
return False
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="fansclub_join",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
)
if debug_path:
try:
import logging
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="fansclub_join",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={"region_size": f"{x2-x1}x{y2-y1}"},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 粉丝团加入检测前保存: %s",
debug_path,
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
logging.debug(
"[调试图像] 粉丝团加入检测前保存: %s",
debug_path,
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
# 采样检测点:检测大片红色区域
red_count = 0
@@ -244,7 +261,7 @@ def detect_fansclub_join_red_area(
for y in range(y1, y2, step_y):
for x in range(x1, x2, step_x):
try:
r, g, b = pic_rgb.getpixel((x, y))
r, g, b = _read_rgb_pixel(pic_rgb, x, y)
# 检测红色:R值高,G和B相对较低
if r > 200 and (r - g) > 50 and (r - b) > 50:
red_count += 1
@@ -280,39 +297,40 @@ def detect_fansclub_join_red_area(
result = red_ratio >= threshold
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
# 无论成功失败都保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="fansclub_join",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"threshold": threshold,
"result": "success" if result else "failed",
},
)
if debug_path:
try:
import logging
# 无论成功失败都保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="fansclub_join",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"threshold": threshold,
"result": "success" if result else "failed",
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 粉丝团加入检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s",
debug_path,
red_ratio,
threshold,
"success" if result else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
logging.debug(
"[调试图像] 粉丝团加入检测保存: %s, red_ratio=%.4f, threshold=%.4f, result=%s",
debug_path,
red_ratio,
threshold,
"success" if result else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
if return_info:
reason_value: Optional[str] = (
+441 -114
View File
@@ -1,3 +1,5 @@
from __future__ import annotations
# pyright: reportGeneralTypeIssues=false
# pyright: reportAttributeAccessIssue=false
# pyright: reportMissingModuleSource=false
@@ -15,10 +17,237 @@ import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Optional
from PIL import Image
from ._common import _safe_open_screenshot_rgb
_COUPON_TEMPLATE_CACHE: dict[str, Any] = {}
def _read_coupon_template(template_path: str):
cached = _COUPON_TEMPLATE_CACHE.get(template_path)
if cached is not None:
return cached
try:
import cv2 # type: ignore[import-untyped]
template = cv2.imread( # type: ignore[attr-defined]
template_path,
cv2.IMREAD_COLOR, # type: ignore[attr-defined]
)
if template is not None:
_COUPON_TEMPLATE_CACHE[template_path] = template
return template
except Exception:
return None
def _scaled_box(pic_rgb: Image.Image, box: tuple[int, int, int, int]) -> tuple[int, int, int, int]:
width, height = pic_rgb.size
scale_x = width / 1080.0
scale_y = height / 2400.0
x1, y1, x2, y2 = box
return (
max(0, min(int(x1 * scale_x), width)),
max(0, min(int(y1 * scale_y), height)),
max(0, min(int(x2 * scale_x), width)),
max(0, min(int(y2 * scale_y), height)),
)
def _detect_coupon_success_orange_panel(
pic_rgb: Image.Image,
return_info: bool = False,
analyser: Any = None,
) -> bool | tuple[bool, dict]:
"""检测居中橙色"领券成功 / 立即用券"优惠券弹窗。"""
try:
import numpy as np # type: ignore[import-untyped]
def _ratios(box: tuple[int, int, int, int]) -> dict[str, float]:
x1, y1, x2, y2 = _scaled_box(pic_rgb, box)
if x1 >= x2 or y1 >= y2:
return {"orange_ratio": 0.0, "warm_button_ratio": 0.0, "white_ratio": 0.0}
arr = np.asarray(pic_rgb.crop((x1, y1, x2, y2)).convert("RGB"))
if arr.size == 0:
return {"orange_ratio": 0.0, "warm_button_ratio": 0.0, "white_ratio": 0.0}
r = arr[:, :, 0]
g = arr[:, :, 1]
b = arr[:, :, 2]
ri = r.astype(int)
gi = g.astype(int)
bi = b.astype(int)
orange = (
(r >= 220)
& (g >= 80)
& (g <= 190)
& (b <= 130)
& ((ri - gi) >= 40)
& ((gi - bi) >= -5)
)
warm_button = (
(r >= 220)
& (g <= 180)
& (b <= 150)
& ((ri - gi) >= 40)
)
white = (r >= 235) & (g >= 235) & (b >= 235)
total = orange.size
if total <= 0:
return {"orange_ratio": 0.0, "warm_button_ratio": 0.0, "white_ratio": 0.0}
return {
"orange_ratio": float(np.sum(orange) / total),
"warm_button_ratio": float(np.sum(warm_button) / total),
"white_ratio": float(np.sum(white) / total),
}
panel = _ratios((150, 520, 930, 1580))
button = _ratios((250, 1320, 830, 1485))
try:
panel_threshold = float(
getattr(analyser, "coupon_success_panel_orange_ratio_threshold", 0.18)
or 0.18
)
except Exception:
panel_threshold = 0.18
try:
button_threshold = float(
getattr(analyser, "coupon_success_button_warm_ratio_threshold", 0.20)
or 0.20
)
except Exception:
button_threshold = 0.20
result = (
panel["orange_ratio"] >= panel_threshold
and button["warm_button_ratio"] >= button_threshold
)
info = {
"method": "coupon_success_orange_panel",
"orange_ratio": panel["orange_ratio"],
"button_warm_ratio": button["warm_button_ratio"],
"white_ratio": panel["white_ratio"],
"effective_panel_threshold": panel_threshold,
"effective_button_threshold": button_threshold,
"reason": None if result else "orange_panel_or_button_below_threshold",
}
if return_info:
return result, info
return result
except Exception as e: # type: ignore[general-exception]
if return_info:
return False, {
"method": "coupon_success_orange_panel",
"orange_ratio": 0.0,
"button_warm_ratio": 0.0,
"reason": f"exception: {str(e)}",
}
return False
def _detect_coupon_bottom_panel_by_pixels(
pic_rgb: Image.Image,
return_info: bool = False,
analyser: Any = None,
) -> bool | tuple[bool, dict]:
"""检测底部白底优惠券面板,覆盖模板低分但仍明显是券弹窗的样式。"""
try:
import numpy as np # type: ignore[import-untyped]
x1, y1, x2, y2 = _scaled_box(pic_rgb, (9, 1173, 1079, 2255))
if x1 >= x2 or y1 >= y2:
info = {
"method": "coupon_bottom_panel_pixels",
"white_ratio": 0.0,
"warm_ratio": 0.0,
"reason": "invalid_region",
}
return (False, info) if return_info else False
arr = np.asarray(pic_rgb.crop((x1, y1, x2, y2)).convert("RGB"))
if arr.size == 0:
info = {
"method": "coupon_bottom_panel_pixels",
"white_ratio": 0.0,
"warm_ratio": 0.0,
"reason": "empty_region",
}
return (False, info) if return_info else False
r = arr[:, :, 0]
g = arr[:, :, 1]
b = arr[:, :, 2]
ri = r.astype(int)
gi = g.astype(int)
bi = b.astype(int)
white = (r >= 235) & (g >= 235) & (b >= 235)
warm = (
(r >= 220)
& (g <= 190)
& (b <= 170)
& ((ri - gi) >= 35)
& ((ri - bi) >= 35)
)
total = white.size
white_ratio = float(np.sum(white) / total) if total > 0 else 0.0
warm_ratio = float(np.sum(warm) / total) if total > 0 else 0.0
try:
white_threshold = float(
getattr(analyser, "coupon_bottom_panel_white_ratio_threshold", 0.40)
or 0.40
)
except Exception:
white_threshold = 0.40
try:
warm_threshold = float(
getattr(analyser, "coupon_bottom_panel_warm_ratio_threshold", 0.08)
or 0.08
)
except Exception:
warm_threshold = 0.08
result = white_ratio >= white_threshold and warm_ratio >= warm_threshold
info = {
"method": "coupon_bottom_panel_pixels",
"white_ratio": white_ratio,
"warm_ratio": warm_ratio,
"effective_white_threshold": white_threshold,
"effective_warm_threshold": warm_threshold,
"reason": None if result else "white_or_warm_ratio_below_threshold",
}
if return_info:
return result, info
return result
except Exception as e: # type: ignore[general-exception]
if return_info:
return False, {
"method": "coupon_bottom_panel_pixels",
"white_ratio": 0.0,
"warm_ratio": 0.0,
"reason": f"exception: {str(e)}",
}
return False
def _coupon_success_or_return(
pic_rgb: Image.Image,
return_info: bool,
analyser: Any,
fallback_info: dict,
) -> bool | tuple[bool, dict]:
detected, info = _detect_coupon_success_orange_panel(
pic_rgb,
return_info=True,
analyser=analyser,
)
if detected:
return (True, info) if return_info else True
bottom_detected, bottom_info = _detect_coupon_bottom_panel_by_pixels(
pic_rgb,
return_info=True,
analyser=analyser,
)
if bottom_detected:
return (True, bottom_info) if return_info else True
return (False, fallback_info) if return_info else False
def detect_coupon_popup_background(
pic_rgb: Image.Image,
@@ -26,7 +255,10 @@ def detect_coupon_popup_background(
template_threshold: float | None = None,
analyser: Any = None,
) -> bool | tuple[bool, dict]:
"""检测底部优惠券大弹窗(仅模板匹配)。
"""检测优惠券弹窗。
优先检测底部优惠券模板;模板未命中时,兜底检测居中橙色
"领券成功 / 立即用券" 优惠券弹窗。
模板匹配区域(基于1080x2400基准):
- 左上: (9, 1173)
@@ -44,15 +276,49 @@ def detect_coupon_popup_background(
tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时)
"""
try:
from douyin.fudai.core.coords import get_pixel_region
try:
import cv2 # type: ignore[import-untyped]
import numpy as np # type: ignore[import-untyped]
except Exception as e: # type: ignore[general-exception]
if return_info:
return False, {
return _coupon_success_or_return(
pic_rgb,
return_info,
analyser,
{
"method": "template_match",
"template_score": None,
"reason": "opencv_unavailable",
},
)
success_detected, success_info = _detect_coupon_success_orange_panel(
pic_rgb,
return_info=True,
analyser=analyser,
)
if success_detected:
return (True, success_info) if return_info else True
bottom_detected, bottom_info = _detect_coupon_bottom_panel_by_pixels(
pic_rgb,
return_info=True,
analyser=analyser,
)
if bottom_detected:
return (True, bottom_info) if return_info else True
if (
success_info.get("orange_ratio", 0.0) < 0.04
and bottom_info.get("white_ratio", 0.0) < 0.20
):
if return_info:
return False, {
"method": "coupon_fast_pixel_prefilter",
"orange_ratio": success_info.get("orange_ratio", 0.0),
"bottom_white_ratio": bottom_info.get("white_ratio", 0.0),
"bottom_warm_ratio": bottom_info.get("warm_ratio", 0.0),
"reason": "pixel_ratios_too_low_for_coupon",
}
return False
@@ -60,10 +326,11 @@ def detect_coupon_popup_background(
scale_x = width / 1080.0
scale_y = height / 2400.0
x1 = int(9 * scale_x)
y1 = int(1173 * scale_y)
x2 = int(1079 * scale_x)
y2 = int(2255 * scale_y)
bx1, by1, bx2, by2 = get_pixel_region("coupon_popup", (9, 1173, 1079, 2255))
x1 = int(bx1 * scale_x)
y1 = int(by1 * scale_y)
x2 = int(bx2 * scale_x)
y2 = int(by2 * scale_y)
x1 = max(0, min(x1, width))
y1 = max(0, min(y1, height))
@@ -71,26 +338,32 @@ def detect_coupon_popup_background(
y2 = max(0, min(y2, height))
if x1 >= x2 or y1 >= y2:
if return_info:
return False, {
return _coupon_success_or_return(
pic_rgb,
return_info,
analyser,
{
"method": "template_match",
"template_score": None,
"reason": "invalid_region",
}
return False
},
)
bgr = cv2.cvtColor( # type: ignore[attr-defined]
np.asarray(pic_rgb), cv2.COLOR_RGB2BGR # type: ignore[attr-defined]
)
roi = bgr[y1:y2, x1:x2] # type: ignore[index]
if roi.size == 0:
if return_info:
return False, {
return _coupon_success_or_return(
pic_rgb,
return_info,
analyser,
{
"method": "template_match",
"template_score": None,
"reason": "empty_roi",
}
return False
},
)
# 使用统一的模板路径配置
try:
@@ -102,33 +375,40 @@ def detect_coupon_popup_background(
base_dir = os.path.dirname(__file__)
template_path = os.path.join(base_dir, "assets", "coupon.png")
if not os.path.exists(template_path):
if return_info:
return False, {
return _coupon_success_or_return(
pic_rgb,
return_info,
analyser,
{
"method": "template_match",
"template_score": None,
"reason": "template_not_found",
}
return False
},
)
template = cv2.imread( # type: ignore[attr-defined,assignment]
template_path, cv2.IMREAD_COLOR # type: ignore[attr-defined]
)
template = _read_coupon_template(template_path)
if template is None:
if return_info:
return False, {
return _coupon_success_or_return(
pic_rgb,
return_info,
analyser,
{
"method": "template_match",
"template_score": None,
"reason": "template_load_failed",
}
return False
},
)
if roi.shape[0] < template.shape[0] or roi.shape[1] < template.shape[1]:
if return_info:
return False, {
return _coupon_success_or_return(
pic_rgb,
return_info,
analyser,
{
"method": "template_match",
"template_score": None,
"reason": "template_too_large",
}
return False
},
)
res = cv2.matchTemplate( # type: ignore[attr-defined]
roi, template, cv2.TM_CCOEFF_NORMED # type: ignore[attr-defined]
@@ -148,6 +428,19 @@ def detect_coupon_popup_background(
threshold = 0.75
result = max_val >= threshold
if not result:
return _coupon_success_or_return(
pic_rgb,
return_info,
analyser,
{
"method": "template_match",
"template_score": float(max_val),
"effective_threshold": threshold,
"reason": "score_below_threshold",
},
)
if return_info:
reason_value: Optional[str] = None if result else "score_below_threshold"
return result, {
@@ -197,6 +490,7 @@ def detect_redpacket_popup_background(
tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时)
"""
try:
from douyin.fudai.core.coords import get_pixel_region
import numpy as np # type: ignore[import-untyped]
width, height = pic_rgb.size
@@ -205,10 +499,11 @@ def detect_redpacket_popup_background(
# 购物红包通常出现在屏幕中央
# 基准坐标(1080x2400)
x1 = int(200 * scale_x)
y1 = int(300 * scale_y)
x2 = int(880 * scale_x)
y2 = int(1400 * scale_y)
bx1, by1, bx2, by2 = get_pixel_region("shopping_redpacket", (200, 300, 880, 1400))
x1 = int(bx1 * scale_x)
y1 = int(by1 * scale_y)
x2 = int(bx2 * scale_x)
y2 = int(by2 * scale_y)
# 边界检查
x1 = max(0, min(x1, width))
@@ -292,23 +587,35 @@ def detect_redpacket_popup_background(
def detect_lucky_draw_result_popup(
pic_rgb: Image.Image, red_ratio_threshold: float = 0.8, return_info: bool = False
pic_rgb: Image.Image,
red_ratio_threshold: float = 0.8,
return_info: bool = False,
analyser: Any = None,
save_debug: bool = False,
) -> bool | tuple[bool, dict]:
"""检测抽奖结果弹窗:检测指定区域的红色占比("我知道了"按钮区域)。
"""检测抽奖结果弹窗:"我知道了"按钮区域,按 UI 版本检测对应按钮颜色。
使用基准 1080x2400 坐标的检测区域:
- 左上: (181, 1261)
- 右下: (890, 1389)
- legacy/v1:旧版红按钮,检查红色占比
- auto/v2_0:新版白按钮,检查白色按钮内部占比
"""
try:
from douyin.fudai.core.coords import get_lottery_result_confirm_profile
profile = get_lottery_result_confirm_profile(
getattr(analyser, "fudai_detail_ui_mode", "auto") if analyser is not None else "auto"
)
width, height = pic_rgb.size
scale_x = width / 1080.0
scale_y = height / 2400.0
x1 = int(181 * scale_x)
y1 = int(1261 * scale_y)
x2 = int(890 * scale_x)
y2 = int(1389 * scale_y)
bx1, by1, bx2, by2 = tuple(profile.get("pixel") or (181, 1261, 890, 1389))
x1 = int(bx1 * scale_x)
y1 = int(by1 * scale_y)
x2 = int(bx2 * scale_x)
y2 = int(by2 * scale_y)
pixel_style = str(profile.get("pixel_style") or "red")
# 边界与顺序
x1, x2 = max(0, min(x1, width)), max(0, min(x2, width))
@@ -323,41 +630,45 @@ def detect_lucky_draw_result_popup(
# 双截图记录:保存实时操作截图(像素检测区域)
detect_roi = None
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_latest_attempt(
detect_roi, operation_type="pixel_detect"
)
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_latest_attempt(
detect_roi, operation_type="pixel_detect"
)
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="lucky_draw_result",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"threshold": red_ratio_threshold,
"region_size": f"{x2-x1}x{y2-y1}",
},
)
if debug_path:
try:
import logging
# 保存调试图像(检测前)- 使用全屏截图,用框框选出识别区域
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="lucky_draw_result",
step="before_detect",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"threshold": red_ratio_threshold,
"region_size": f"{x2-x1}x{y2-y1}",
"ui_version": profile.get("version"),
"pixel_style": pixel_style,
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 像素检测前保存: %s, threshold=%s",
debug_path,
red_ratio_threshold,
)
except Exception: # type: ignore[general-exception]
pass
except Exception:
pass
logging.debug(
"[调试图像] 像素检测前保存: %s, threshold=%s",
debug_path,
red_ratio_threshold,
)
except Exception: # type: ignore[general-exception]
pass
except Exception:
pass
red_count = 0
white_count = 0
total_samples = 0
step_x = max(1, (x2 - x1) // 10)
step_y = max(1, (y2 - y1) // 10)
@@ -371,6 +682,9 @@ def detect_lucky_draw_result_popup(
# 红色按钮检测:R >= 245 且 R 明显大于 G 和 B
if r >= 245 and r <= 255 and (r - g) >= 50 and (r - b) >= 50:
red_count += 1
# 新版“我知道了”按钮为白底红字,按钮内部白色占比很高。
if r >= 230 and g >= 230 and b >= 230:
white_count += 1
except Exception as e: # type: ignore[general-exception]
continue
@@ -378,50 +692,59 @@ def detect_lucky_draw_result_popup(
return False
red_ratio = red_count / total_samples
result = red_ratio >= red_ratio_threshold
white_ratio = white_count / total_samples
if pixel_style == "white":
result = white_ratio >= red_ratio_threshold
else:
result = red_ratio >= red_ratio_threshold
# 保存调试图像(检测结果)- 使用全屏截图,用框框选出识别区域
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
if result:
# 检测成功
if detect_roi is None:
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_last_success(
detect_roi, operation_type="pixel_detect"
)
# 无论成功失败都保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="lucky_draw_result",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"red_count": red_count,
"total_samples": total_samples,
"threshold": red_ratio_threshold,
"result": "success" if result else "failed",
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 抽奖结果检测保存: %s, red_ratio=%.4f, threshold=%s, score=%.4f",
debug_path,
red_ratio,
red_ratio_threshold,
red_ratio,
if result:
# 检测成功
if detect_roi is None:
detect_roi = pic_rgb.crop((x1, y1, x2, y2))
douyin_screenshot_manager.save_last_success(
detect_roi, operation_type="pixel_detect"
)
except Exception: # type: ignore[general-exception]
pass
except Exception:
pass
# 无论成功失败都保存debug截图
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="lucky_draw_result",
step="detected" if result else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域
extra_info={
"red_ratio": round(red_ratio, 4),
"white_ratio": round(white_ratio, 4),
"red_count": red_count,
"white_count": white_count,
"total_samples": total_samples,
"threshold": red_ratio_threshold,
"result": "success" if result else "failed",
"ui_version": profile.get("version"),
"pixel_style": pixel_style,
},
)
if debug_path:
try:
import logging
logging.debug(
"[调试图像] 抽奖结果检测保存: %s, red_ratio=%.4f, threshold=%s, score=%.4f",
debug_path,
red_ratio,
red_ratio_threshold,
red_ratio,
)
except Exception: # type: ignore[general-exception]
pass
except Exception:
pass
# 如果请求详细信息,返回包含red_ratio的字典
if return_info:
@@ -431,9 +754,13 @@ def detect_lucky_draw_result_popup(
return result, {
"method": "pixel_detect",
"red_ratio": red_ratio,
"white_ratio": white_ratio,
"red_count": red_count,
"white_count": white_count,
"total_samples": total_samples,
"effective_threshold": red_ratio_threshold,
"ui_version": profile.get("version"),
"pixel_style": pixel_style,
"reason": reason_value,
}
+361 -105
View File
@@ -1,3 +1,5 @@
from __future__ import annotations
# pyright: reportGeneralTypeIssues=false
# pyright: reportAttributeAccessIssue=false
# pyright: reportMissingModuleSource=false
@@ -11,16 +13,244 @@
- read_pixel_stage_state_from_screenshot 综合多种检测,返回阶段状态
"""
import os
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Optional
from PIL import Image
from ._common import _safe_open_screenshot_rgb
from .buttons import (
detect_attend_button_red_area,
detect_fansclub_join_red_area,
)
from .popups import (
detect_coupon_popup_background,
detect_lucky_draw_result_popup,
detect_redpacket_popup_background,
)
def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
def _scale_box(
box: tuple[int, int, int, int],
width: int,
height: int,
) -> tuple[int, int, int, int]:
scale_x = width / 1080.0
scale_y = height / 2400.0
x1, y1, x2, y2 = box
sx1 = max(0, min(int(x1 * scale_x), width))
sy1 = max(0, min(int(y1 * scale_y), height))
sx2 = max(0, min(int(x2 * scale_x), width))
sy2 = max(0, min(int(y2 * scale_y), height))
return min(sx1, sx2), min(sy1, sy2), max(sx1, sx2), max(sy1, sy2)
def _live_room_icon_bbox(width: int, height: int) -> tuple[int, int, int, int]:
from douyin.fudai.core.coords import get_live_room_icon_bbox
return _scale_box(get_live_room_icon_bbox(), width, height)
def _ratio_threshold(analyser: Any, name: str, default: float) -> float:
try:
value = float(getattr(analyser, name, default) or default)
except Exception:
value = default
return max(0.0, min(1.0, value))
def _detect_fudai_detail_body_colors(
pic_rgb: Image.Image,
analyser: Any = None,
) -> tuple[bool, dict]:
"""Use the v2 popup body color volume to identify the fudai detail page."""
try:
import numpy as np # type: ignore[import-untyped]
from douyin.fudai.core.coords import get_fudai_detail_body_region
arr = np.asarray(pic_rgb.convert("RGB")).astype("int16")
height, width = arr.shape[:2]
x1, y1, x2, y2 = _scale_box(get_fudai_detail_body_region(), width, height)
if x1 >= x2 or y1 >= y2:
return False, {"method": "detail_body_color", "reason": "invalid_body_box"}
roi = arr[y1:y2, x1:x2]
r, g, b = roi[:, :, 0], roi[:, :, 1], roi[:, :, 2]
bluepurple_ratio = float(
(
(r < 105)
& (g < 95)
& (b > 45)
& (b > r * 0.75)
).mean()
)
dark_ratio = float(((r < 65) & (g < 65) & (b < 120)).mean())
purple_ratio = float(
(
(b > r * 0.75)
& (b > g * 0.9)
& (r < 130)
& (g < 110)
& (b > 35)
).mean()
)
bluepurple_threshold = _ratio_threshold(
analyser, "fudai_detail_body_bluepurple_threshold", 0.45
)
dark_threshold = _ratio_threshold(
analyser, "fudai_detail_body_dark_threshold", 0.35
)
detected = bluepurple_ratio >= bluepurple_threshold and dark_ratio >= dark_threshold
return detected, {
"method": "detail_body_color",
"body_box": (x1, y1, x2, y2),
"bluepurple_ratio": round(bluepurple_ratio, 4),
"dark_ratio": round(dark_ratio, 4),
"purple_ratio": round(purple_ratio, 4),
"bluepurple_threshold": bluepurple_threshold,
"dark_threshold": dark_threshold,
"effective_threshold": bluepurple_threshold,
"reason": None if detected else "detail_body_color_not_matched",
}
except Exception as exc:
return False, {"method": "detail_body_color", "reason": f"color_exception: {exc}"}
def _save_pixel_stage_overview(
pic_rgb: Image.Image,
state: dict[str, bool],
details: dict[str, dict],
analyser: Any = None,
) -> None:
try:
from PIL import ImageDraw, ImageFont
from douyin.fudai.core.coords import (
get_fudai_detail_body_region,
get_fudai_detail_profile,
get_lottery_result_confirm_profile,
get_pixel_region,
)
from douyin.handlers import douyin_screenshot_manager
from douyin.handlers.screenshot_manager.save_image_helpers import is_debug_captures_enabled
if not is_debug_captures_enabled():
return
width, height = pic_rgb.size
overview = pic_rgb.copy()
draw = ImageDraw.Draw(overview)
try:
font = ImageFont.truetype("arial.ttf", 24)
small_font = ImageFont.truetype("arial.ttf", 18)
except Exception:
font = ImageFont.load_default()
small_font = font
mode = getattr(analyser, "fudai_detail_ui_mode", "auto") if analyser is not None else "auto"
task_count = details.get("has_fudai_detail", {}).get("task_count")
detail_profile = get_fudai_detail_profile(mode, task_count=task_count)
lottery_profile = get_lottery_result_confirm_profile(mode)
regions: dict[str, tuple[str, tuple[int, int, int, int]]] = {
"lottery": ("has_lucky_draw_result", tuple(lottery_profile.get("pixel") or (181, 1261, 890, 1389))),
"attend": ("has_attend_button_red", get_pixel_region("attend_button", (200, 2000, 880, 2120))),
"fansclub": ("has_fansclub_join_red", get_pixel_region("fansclub_join", (200, 1940, 880, 2140))),
}
if state.get("has_fudai_detail"):
regions["detail_body"] = ("has_fudai_detail", get_fudai_detail_body_region())
from douyin.detection.detection_pkg.detail import get_detail_task_status_search_box
regions["task_status"] = (
"has_fudai_detail",
get_detail_task_status_search_box(),
)
else:
if "has_fudai_detail" in details:
from douyin.detection.detection_pkg.detail import get_detail_task_status_search_box
regions["task_status"] = (
"has_fudai_detail",
get_detail_task_status_search_box(),
)
if details.get("has_coupon_bg", {}).get("method") != "disabled":
regions["coupon"] = ("has_coupon_bg", get_pixel_region("coupon_popup", (9, 1173, 1079, 2255)))
if details.get("has_redpacket_bg", {}).get("method") != "disabled":
regions["redpacket"] = ("has_redpacket_bg", get_pixel_region("shopping_redpacket", (200, 300, 880, 1400)))
def _color_for(key: str) -> tuple[int, int, int]:
info = details.get(key, {})
if info.get("method") == "disabled":
return (160, 160, 160)
return (0, 220, 80) if state.get(key) else (255, 70, 70)
lines = ["pixel stage overview"]
for key in (
"has_coupon_bg",
"has_redpacket_bg",
"has_lucky_draw_result",
"has_attend_button_red",
"has_fansclub_join_red",
"has_fudai_detail",
"has_live_room_pixel",
):
info = details.get(key, {})
status = "off" if info.get("method") == "disabled" else ("ok" if state.get(key) else "no")
score = info.get("confidence")
if score is None:
score = info.get("red_ratio")
if score is None:
score = info.get("white_ratio")
if score is None:
score = info.get("bluepurple_ratio")
if score is None:
score = info.get("template_score")
score_text = "" if score is None else f" score={float(score):.3f}"
elapsed = info.get("elapsed_ms")
elapsed_text = "" if elapsed is None else f" {elapsed}ms"
lines.append(f"{key.replace('has_', '')}: {status}{score_text}{elapsed_text}")
panel_w = 620
panel_h = 36 + len(lines) * 28
panel_x = 24
panel_y = 24
draw.rectangle((panel_x - 10, panel_y - 10, panel_x + panel_w, panel_y + panel_h), fill=(0, 0, 0))
for idx, line in enumerate(lines):
draw.text((panel_x, panel_y + idx * 28), line, fill=(255, 255, 255), font=font if idx == 0 else small_font)
for label, (key, base_box) in regions.items():
x1, y1, x2, y2 = _scale_box(base_box, width, height)
if x1 >= x2 or y1 >= y2:
continue
color = _color_for(key)
line_width = 4 if state.get(key) else 2
draw.rectangle((x1, y1, x2, y2), outline=color, width=line_width)
draw.text((x1 + 6, max(0, y1 - 26)), label, fill=color, font=small_font)
x1, y1, x2, y2 = _live_room_icon_bbox(width, height)
color = _color_for("has_live_room_pixel")
line_width = 4 if state.get("has_live_room_pixel") else 2
draw.rectangle((x1, y1, x2, y2), outline=color, width=line_width)
draw.text((max(0, x1 - 120), max(0, y1 - 26)), "liveicon", fill=color, font=small_font)
ok_count = sum(1 for value in state.values() if value)
debug_path = douyin_screenshot_manager.save_debug_image(
overview,
operation_type="pixel_detect",
picname="pixel_stage",
step="overview",
extra_info={"ok": ok_count},
annotate=False,
background=False,
)
if debug_path:
try:
import logging
logging.debug("[调试图像] 像素阶段总览保存: %s", debug_path)
except Exception:
pass
except Exception:
pass
def detect_live_room_icons_by_pixel(pic_rgb: Image.Image, save_debug: bool = True) -> tuple[bool, float]:
"""通过像素检测多边形区域内的白色像素,判断是否在直播间。
检测指定多边形区域内的白色像素比例,基于1080x2400分辨率:
@@ -33,7 +263,7 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
(detected, confidence) 其中 confidence 为白色像素比例(0.0~1.0)
"""
try:
from PIL import ImageDraw
from PIL import Image, ImageDraw
import numpy as np
width, height = pic_rgb.size
@@ -115,42 +345,43 @@ def detect_live_room_icons_by_pixel(pic_rgb: Image.Image) -> tuple[bool, float]:
x1, y1, x2, y2 = 0, 0, 0, 0
# 保存调试图像(检测结果)
try:
from douyin.handlers import douyin_screenshot_manager
if save_debug:
try:
from douyin.handlers import douyin_screenshot_manager
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="live_room_icons",
step="detected" if detected else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域边界框
extra_info={
"white_ratio": round(white_ratio, 4),
"white_count": white_count,
"total_pixels": total_pixels,
"confidence": round(confidence, 4),
"threshold": 0.8,
"result": "success" if detected else "failed",
"polygon_points": len(polygon_points),
},
)
if debug_path:
try:
import logging
debug_path = douyin_screenshot_manager.save_debug_image(
pic_rgb, # 使用全屏截图
operation_type="pixel_detect",
picname="live_room_icons",
step="detected" if detected else "not_detected",
coords=(x1, y1, x2, y2), # 标注识别区域边界框
extra_info={
"white_ratio": round(white_ratio, 4),
"white_count": white_count,
"total_pixels": total_pixels,
"confidence": round(confidence, 4),
"threshold": 0.8,
"result": "success" if detected else "failed",
"polygon_points": len(polygon_points),
},
)
if debug_path:
try:
import logging
logging.info(
"[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, white_count=%d, total_pixels=%d, confidence=%.4f, result=%s",
debug_path,
white_ratio,
white_count,
total_pixels,
confidence,
"success" if detected else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
logging.debug(
"[调试图像] 直播间图标检测保存: %s, white_ratio=%.4f, white_count=%d, total_pixels=%d, confidence=%.4f, result=%s",
debug_path,
white_ratio,
white_count,
total_pixels,
confidence,
"success" if detected else "failed",
)
except Exception as e: # type: ignore[general-exception]
pass
except Exception as e: # type: ignore[general-exception]
pass
return bool(detected), float(confidence)
except Exception as e: # type: ignore[general-exception]
@@ -170,10 +401,10 @@ def detect_fudai_detail_page(
) -> bool | tuple[bool, dict]:
"""检测是否处于福袋详情页。
检测策略:任务数量检测
1. 通过检测任务数量来判断是否在福袋详情页
2. 如果任务数量 <= 0,则认为不在福袋详情页
3. 如果任务数量 >= 1,则认为在福袋详情页,并返回任务数量
检测策略:detail_body 颜色体量识别
1. 通过福袋详情弹窗主体的深蓝紫颜色数量判断是否在详情页;
2. 任务数量只作为附加信息读取,不再决定是否为详情页;
3. 避免任务数量漏识别时误判“不在详情页”。
参数:
pic_rgb: RGB格式的整屏截图(保留用于兼容性,实际不使用)
@@ -188,42 +419,35 @@ def detect_fudai_detail_page(
bool: 是否检测到福袋详情页(return_info=False时)
tuple[bool, dict]: (检测结果, 详细信息)(return_info=True时)
详细信息包含:
- method: 检测方法("task_count")
- method: 检测方法("detail_body_color")
- task_count: 任务数量(0/1/2/3)
"""
# ---------- 任务数量检测 ----------
if analyser is None:
# analyser 参数必需
detected, color_info = _detect_fudai_detail_body_colors(_pic_rgb, analyser)
if return_info:
return False, {
"method": "task_count",
return detected, {
**color_info,
"task_count": 0,
"reason": "analyser_required",
}
return False
return detected
try:
from .douyin_detection import check_detail_height
from douyin.detection.douyin_detection import check_detail_height
# 执行任务数量检测
task_count = int(check_detail_height(analyser) or 0)
# 判断是否在福袋详情页
# 如果任务数量 <= 0,则认为不在福袋详情页
# 如果任务数量 >= 1,则认为在福袋详情页
is_in_detail = task_count >= 1
color_detected, color_info = _detect_fudai_detail_body_colors(_pic_rgb, analyser)
task_count = int(check_detail_height(analyser, pic_rgb=_pic_rgb) or 0)
if return_info:
return is_in_detail, {
"method": "task_count",
return color_detected, {
**color_info,
"task_count": task_count,
}
return is_in_detail
return color_detected
except Exception as e: # type: ignore[general-exception]
# 检测异常
if return_info:
return False, {
"method": "task_count",
"method": "detail_body_color",
"task_count": 0,
"reason": f"detection_exception: {str(e)}",
}
@@ -318,11 +542,17 @@ def read_pixel_stage_state_from_screenshot(
except Exception as e: # type: ignore[general-exception]
pass
def _enabled(name: str, default: bool = True) -> bool:
try:
return bool(getattr(analyser, name, default)) if analyser is not None else default
except Exception:
return default
# 定义直播间图标像素检测包装函数
def _detect_live_room_pixel_wrapper(pic: Image.Image) -> tuple[bool, dict]:
"""直播间图标像素检测包装函数,返回 (bool, dict) 格式"""
try:
detected, confidence = detect_live_room_icons_by_pixel(pic)
detected, confidence = detect_live_room_icons_by_pixel(pic, save_debug=False)
threshold = live_room_pixel_threshold or 0.8
is_detected = detected and confidence >= threshold
return is_detected, {
@@ -335,35 +565,47 @@ def read_pixel_stage_state_from_screenshot(
# 模板匹配已删除,只使用像素检测
detection_tasks = {
"has_coupon_bg": lambda pic: detect_coupon_popup_background(
detection_tasks = {}
if _enabled("pixel_detect_coupon_popup_enabled", True):
detection_tasks["has_coupon_bg"] = lambda pic: detect_coupon_popup_background(
pic,
return_info=True,
template_threshold=coupon_threshold,
analyser=analyser,
),
"has_redpacket_bg": lambda pic: detect_redpacket_popup_background(
)
if _enabled("pixel_detect_shopping_redpacket_enabled", False):
detection_tasks["has_redpacket_bg"] = lambda pic: detect_redpacket_popup_background(
pic,
return_info=True,
red_ratio_threshold=redpacket_threshold,
analyser=analyser,
),
"has_lucky_draw_result": lambda pic: detect_lucky_draw_result_popup(
pic, lucky_draw_red_ratio_threshold, return_info=True
),
"has_attend_button_red": lambda pic: detect_attend_button_red_area(
)
if _enabled("pixel_detect_lottery_result_enabled", True):
detection_tasks["has_lucky_draw_result"] = lambda pic: detect_lucky_draw_result_popup(
pic,
lucky_draw_red_ratio_threshold,
return_info=True,
analyser=analyser,
save_debug=False,
)
if _enabled("pixel_detect_attend_button_enabled", True):
detection_tasks["has_attend_button_red"] = lambda pic: detect_attend_button_red_area(
pic,
return_info=True,
red_ratio_threshold=attend_button_threshold,
analyser=analyser,
),
"has_fansclub_join_red": lambda pic: detect_fansclub_join_red_area(
save_debug=False,
)
if _enabled("pixel_detect_fansclub_join_enabled", True):
detection_tasks["has_fansclub_join_red"] = lambda pic: detect_fansclub_join_red_area(
pic,
return_info=True,
red_ratio_threshold=fansclub_threshold,
analyser=analyser,
),
"has_fudai_detail": lambda pic: detect_fudai_detail_page(
save_debug=False,
)
if _enabled("pixel_detect_fudai_detail_enabled", True):
detection_tasks["has_fudai_detail"] = lambda pic: detect_fudai_detail_page(
pic,
resolution_ratio_x,
resolution_ratio_y,
@@ -371,9 +613,17 @@ def read_pixel_stage_state_from_screenshot(
fudai_template_threshold,
return_info=True,
analyser=analyser,
),
"has_live_room_pixel": _detect_live_room_pixel_wrapper, # 直播间图标像素检测(多边形区域白色像素检测)
}
)
if _enabled("pixel_detect_live_room_enabled", True):
detection_tasks["has_live_room_pixel"] = _detect_live_room_pixel_wrapper
for key in state:
if key not in detection_tasks:
details[key] = {"detected": False, "method": "disabled", "reason": "switch_off"}
if not detection_tasks:
if return_details:
return state, details
return state
# 使用线程池并行执行检测(增加线程数以支持直播间图标检测)
with ThreadPoolExecutor(max_workers=8) as executor:
@@ -398,38 +648,44 @@ def read_pixel_stage_state_from_screenshot(
# 检测函数返回 (bool, dict) 格式
is_detected, info = result
state[key] = bool(is_detected)
if return_details:
details[key] = {
"detected": bool(is_detected),
"method": info.get("method", "unknown"),
"template_score": info.get("template_score"),
"confidence": info.get(
"confidence"
), # 添加confidence支持(用于像素检测)
"task_count": info.get("task_count"), # 添加task_count支持
"red_ratio": info.get("red_ratio"), # 添加red_ratio支持
"effective_threshold": info.get("effective_threshold"),
"reason": info.get("reason"),
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
details[key] = {
"detected": bool(is_detected),
"method": info.get("method", "unknown"),
"template_score": info.get("template_score"),
"confidence": info.get(
"confidence"
), # 添加confidence支持(用于像素检测)
"task_count": info.get("task_count"), # 添加task_count支持
"body_box": info.get("body_box"),
"bluepurple_ratio": info.get("bluepurple_ratio"),
"dark_ratio": info.get("dark_ratio"),
"purple_ratio": info.get("purple_ratio"),
"panel_bluepurple_ratio": info.get("panel_bluepurple_ratio"),
"panel_box": info.get("panel_box"),
"red_ratio": info.get("red_ratio"), # 添加red_ratio支持
"white_ratio": info.get("white_ratio"),
"effective_threshold": info.get("effective_threshold"),
"reason": info.get("reason"),
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
else:
# 其他检测返回 bool(不应该发生,因为所有检测都支持return_info)
state[key] = bool(result)
if return_details:
details[key] = {
"detected": bool(result),
"method": "unknown",
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
details[key] = {
"detected": bool(result),
"method": "unknown",
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
except Exception as e: # type: ignore[general-exception]
# 如果某个检测失败,保持默认值 False
state[key] = False
if return_details:
details[key] = {
"detected": False,
"error": str(e),
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
details[key] = {
"detected": False,
"error": str(e),
"elapsed_ms": round(elapsed_ms, 1), # 添加耗时
}
_save_pixel_stage_overview(pic_rgb, state, details, analyser=analyser)
if return_details:
return state, details
+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
+285 -35
View File
@@ -1,69 +1,319 @@
# 统一的坐标常量(基准分辨率 1080x2400)
# 仅包含常用的福袋详情相关裁剪框,后续可按需扩展。
"""福袋与像素检测常用坐标。
# 福袋价值裁剪区域 (left, top, right, bottom)
"""
统一的坐标常量(基准分辨率 1080x2400)
集中维护常用裁剪框,避免代码中硬编码数字。
基准分辨率统一为 1080x2400。
默认值保留在本文件;运行时若 `config.json` 提供覆盖,则优先使用配置。
"""
from __future__ import annotations
from functools import lru_cache
from typing import Any
def _tuple4(values: Any) -> tuple[int, int, int, int] | None:
try:
seq = list(values or [])
except Exception:
return None
if len(seq) != 4:
return None
try:
return tuple(int(v) for v in seq)
except Exception:
return None
def _tuple2(values: Any) -> tuple[int, int] | None:
parsed = _tuple4(values)
if parsed is None:
try:
seq = list(values or [])
except Exception:
return None
if len(seq) != 2:
return None
try:
return int(seq[0]), int(seq[1])
except Exception:
return None
return parsed[0], parsed[1]
def _deep_get(obj: Any, *parts: str) -> Any:
cur = obj
for part in parts:
if not isinstance(cur, dict) or part not in cur:
return None
cur = cur[part]
return cur
@lru_cache(maxsize=1)
def _read_runtime_region_config() -> dict:
try:
from gui.gui_core_pkg.config import read_config
cfg = read_config()
return cfg if isinstance(cfg, dict) else {}
except Exception:
return {}
def reset_region_config_cache() -> None:
_read_runtime_region_config.cache_clear()
# 福袋相关常用坐标
# 福袋价值裁剪区域 (left, top, right, bottom)
VALUE_BOX_TARGET = (643, 1466, 769, 1656)
# 福袋详情内容区域(任务/描述)
CONTENT_BOX = (389, 1273, 1000, 1534)
# 倒计时不同场景的裁剪区域(按出现情况命名)
# 倒计时不同场景的裁剪区域
COUNTDOWN_1110_1230 = (390, 1110, 690, 1230)
COUNTDOWN_1140_1290 = (390, 1140, 690, 1290)
COUNTDOWN_1010_1130 = (390, 1010, 690, 1130)
COUNTDOWN_1460_1580 = (390, 1460, 690, 1580)
# 任务列表区域(用于检测观看任务)
TASK_LIST = (50, 1621, 1032, 1960)
# 参与按钮区域(向下扩大,增强对部分机型底部按钮的覆盖)
PARTICIPATE_BUTTON = (306, 2030, 780, 2180)
# 扩大识别区域(加入粉丝团 / OCR 扩大区域)
JOIN_FANSCLUB_REGION = (150, 1900, 950, 2200)
# 抽奖结果 / 弹窗确认
DRAW_RESULT = (380, 660, 720, 755)
NO_PRIZE_CONFIRM = (340, 1195, 740, 1355)
# 抽奖结果相关区域
LOTTERY_RESULT_AREA = (300, 600, 800, 800)
LOTTERY_RESULT_CONFIRM_BUTTON = (181, 1261, 890, 1389)
LOTTERY_RESULT_CONFIRM_BUTTON_V1 = (181, 1261, 890, 1389)
LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1 = LOTTERY_RESULT_CONFIRM_BUTTON_V1
LOTTERY_RESULT_CONFIRM_CLICK_V1 = (532, 1289)
LOTTERY_RESULT_CONFIRM_BUTTON_V2 = (250, 1275, 825, 1435)
LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V2 = (290, 1300, 790, 1415)
LOTTERY_RESULT_CONFIRM_CLICK_V2 = (540, 1360)
LOTTERY_RESULT_CONFIRM_BUTTON = LOTTERY_RESULT_CONFIRM_BUTTON_V1
LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL = LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1
LOTTERY_RESULT_CONFIRM_CLICK = LOTTERY_RESULT_CONFIRM_CLICK_V1
# 购物红包/弹窗诊断区域
SHOPPING_REDPACKET_AREA = (200, 300, 880, 1200)
STAGE_RED_PACKET_OCR = (200, 300, 880, 1200)
COUPON_PARTICIPATE_BUTTON_ALT = (200, 1940, 880, 2140)
# 常用标签栏(推荐/关注/直播)
RECOMMEND_TAB = (400, 140, 900, 200)
RECOMMEND_TAB = (0, 140, 1080, 220)
FOLLOW_TAB = (658, 147, 765, 194)
LIVE_LIST_TAB = (400, 140, 900, 200)
LIVE_LIST_TAB = (0, 140, 1080, 220)
LIVE_ROOM_TITLE = (130, 120, 560, 225)
LIVE_ROOM_ICON_BBOX = (999, 172, 1028, 202)
FUDAI_DETAIL_BODY_DEFAULT = (0, 1160, 1080, 2250)
FUDAI_TASK_STATUS_DEFAULT = (820, 1815, 1050, 2035)
ATTEND_BUTTON_PIXEL_BOX = (200, 2000, 880, 2120)
FANSCLUB_JOIN_PIXEL_BOX = (200, 1940, 880, 2140)
COUPON_POPUP_BOX = (9, 1173, 1079, 2255)
SHOPPING_REDPACKET_PIXEL_BOX = (200, 300, 880, 1400)
DETAIL_UI_LEGACY = {
"version": "legacy",
"content": CONTENT_BOX,
"value": VALUE_BOX_TARGET,
"countdown_full": COUNTDOWN_1110_1230,
"task_list": TASK_LIST,
"task_count": (0, 0, 0, 0),
"participants": CONTENT_BOX,
"button": PARTICIPATE_BUTTON,
"live_title": LIVE_ROOM_TITLE,
}
DETAIL_UI_V2_0 = {
"version": "v2_0",
"content": (365, 1368, 1040, 1465),
"value": (300, 1518, 820, 1695),
"countdown_full": (760, 1265, 1040, 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": LIVE_ROOM_TITLE,
}
DETAIL_UI_V2_0_ONE_TASK = {
"version": "v2_0",
"variant": "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": (60, 1845, 885, 2005),
"task_count": (890, 1855, 1040, 1960),
"participants": (516, 1396, 743, 1443),
"button": (70, 2050, 1010, 2195),
"live_title": LIVE_ROOM_TITLE,
}
FUDAI_DETAIL_REGION_DEFAULTS = {
"legacy": DETAIL_UI_LEGACY,
"v2_0_two_task": DETAIL_UI_V2_0,
"v2_0_one_task": DETAIL_UI_V2_0_ONE_TASK,
}
STALE_DETAIL_REGION_DEFAULTS = {
"v2_0_two_task": {
"content": (360, 1410, 1035, 1495),
"value": (300, 1585, 650, 1685),
"countdown_full": (760, 1328, 1038, 1398),
},
"v2_0_one_task": {
"countdown_full": (700, 1320, 930, 1415),
},
}
STALE_DETAIL_REGION_OVERRIDES = {
"v2_0_one_task": {
"countdown_full": (
(730, 1338, 1038, 1418),
(769, 1384, 1029, 1442),
(700, 1320, 930, 1415),
),
},
}
PIXEL_REGION_DEFAULTS = {
"lottery_result": {
"button": LOTTERY_RESULT_CONFIRM_BUTTON_V2,
"pixel": LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V2,
"click": LOTTERY_RESULT_CONFIRM_CLICK_V2,
"legacy_button": LOTTERY_RESULT_CONFIRM_BUTTON_V1,
"legacy_pixel": LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1,
"legacy_click": LOTTERY_RESULT_CONFIRM_CLICK_V1,
},
"attend_button": ATTEND_BUTTON_PIXEL_BOX,
"fansclub_join": FANSCLUB_JOIN_PIXEL_BOX,
"coupon_popup": COUPON_POPUP_BOX,
"shopping_redpacket": SHOPPING_REDPACKET_PIXEL_BOX,
"fudai_detail_body": FUDAI_DETAIL_BODY_DEFAULT,
"fudai_task_status": FUDAI_TASK_STATUS_DEFAULT,
"live_room_icon_bbox": LIVE_ROOM_ICON_BBOX,
}
def normalize_fudai_detail_ui_mode(mode: str | None) -> str:
mode_s = str(mode or "auto").strip().lower().replace("-", "_").replace(".", "_")
if mode_s in ("v2", "2_0", "v2_0"):
return "v2_0"
if mode_s in ("legacy", "old", "v1"):
return "legacy"
return "auto"
def _detail_profile_key(mode: str | None, task_count: int | None) -> str:
normalized = normalize_fudai_detail_ui_mode(mode)
if normalized == "legacy":
return "legacy"
try:
if int(task_count or 0) == 1:
return "v2_0_one_task"
except Exception:
pass
return "v2_0_two_task"
def _apply_region_overrides(defaults: dict[str, Any], overrides: Any) -> dict[str, Any]:
merged = dict(defaults)
if not isinstance(overrides, dict):
return merged
for key, default_value in defaults.items():
candidate = overrides.get(key)
if isinstance(default_value, tuple):
parsed = _tuple4(candidate)
if parsed is not None:
merged[key] = parsed
elif key in overrides and candidate is not None:
merged[key] = candidate
return merged
def _drop_stale_region_overrides(profile_key: str, overrides: dict[str, Any]) -> dict[str, Any]:
stale = STALE_DETAIL_REGION_DEFAULTS.get(profile_key, {})
stale_overrides = STALE_DETAIL_REGION_OVERRIDES.get(profile_key, {})
if not stale and not stale_overrides:
return dict(overrides)
cleaned = dict(overrides)
for key, old_value in stale.items():
parsed = _tuple4(cleaned.get(key))
if parsed is not None and parsed == tuple(old_value):
cleaned.pop(key, None)
for key, old_values in stale_overrides.items():
parsed = _tuple4(cleaned.get(key))
if parsed is None:
continue
if any(parsed == tuple(old_value) for old_value in old_values):
cleaned.pop(key, None)
return cleaned
def get_fudai_detail_profile(mode: str | None = "auto", task_count: int | None = None) -> dict:
profile_key = _detail_profile_key(mode, task_count)
defaults = FUDAI_DETAIL_REGION_DEFAULTS[profile_key]
cfg = _read_runtime_region_config()
overrides = _deep_get(cfg, "fudai_detail_regions", profile_key)
if not isinstance(overrides, dict) or not overrides:
return defaults
overrides = _drop_stale_region_overrides(profile_key, overrides)
return _apply_region_overrides(defaults, overrides)
def get_pixel_region(name: str, default: tuple[int, int, int, int] | None = None) -> tuple[int, int, int, int]:
defaults = PIXEL_REGION_DEFAULTS.get(name, default)
if defaults is None or isinstance(defaults, dict):
raise KeyError(name)
cfg = _read_runtime_region_config()
parsed = _tuple4(_deep_get(cfg, "pixel_regions", name))
return parsed if parsed is not None else tuple(defaults)
def get_live_room_icon_bbox() -> tuple[int, int, int, int]:
return get_pixel_region("live_room_icon_bbox", LIVE_ROOM_ICON_BBOX)
def get_fudai_detail_body_region() -> tuple[int, int, int, int]:
return get_pixel_region("fudai_detail_body", FUDAI_DETAIL_BODY_DEFAULT)
def get_lottery_result_confirm_profile(mode: str | None = "auto") -> dict:
normalized = normalize_fudai_detail_ui_mode(mode)
cfg = _read_runtime_region_config()
overrides = _deep_get(cfg, "pixel_regions", "lottery_result")
if normalized == "legacy":
result = {
"version": "legacy",
"button": LOTTERY_RESULT_CONFIRM_BUTTON_V1,
"pixel": LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V1,
"click": LOTTERY_RESULT_CONFIRM_CLICK_V1,
"pixel_style": "red",
}
if isinstance(overrides, dict):
result["button"] = _tuple4(overrides.get("legacy_button")) or result["button"]
result["pixel"] = _tuple4(overrides.get("legacy_pixel")) or result["pixel"]
result["click"] = _tuple2(overrides.get("legacy_click")) or result["click"]
return result
result = {
"version": "v2_0",
"button": LOTTERY_RESULT_CONFIRM_BUTTON_V2,
"pixel": LOTTERY_RESULT_CONFIRM_BUTTON_PIXEL_V2,
"click": LOTTERY_RESULT_CONFIRM_CLICK_V2,
"pixel_style": "white",
}
if isinstance(overrides, dict):
result["button"] = _tuple4(overrides.get("button")) or result["button"]
result["pixel"] = _tuple4(overrides.get("pixel")) or result["pixel"]
result["click"] = _tuple2(overrides.get("click")) or result["click"]
return result
# 直播间标题中部(用于部分详情模块)
LIVE_ROOM_TITLE = (144, 144, 329, 185)
# 备用/替代参与按钮区域(弹窗/诊断模块使用)
PARTICIPATE_BUTTON_ALT = PARTICIPATE_BUTTON
# 直播/人机验证相关区域(占位值,可按实际截图微调)
LIVE_VERIFY1 = (200, 600, 880, 900)
LIVE_VERIFY2 = (200, 900, 880, 1200)
# 机器人验证图片裁剪区域(用于保存/处理验证图片)
ROBOT_VERIFY = (100, 1200, 980, 1780)
# 诊断购物红包(弹窗快速检测区域 - 文字区域)
DIAG_SHOPPING_REDPACKET = (200, 300, 880, 1000)
# 倒计时、任务、按钮等常用区域(保留占位,可根据需要填写)
# COUNTDOWN_BOX = (390, 1140, 570, 1290)
# BUTTON_BOX = (306, 2030, 780, 2180)
# CONTENT_BOX = (200, 600, 880, 900)
DETAIL_OUTSIDE_CLICK = (500, 470)
PARTICIPATE_BTN_CLICK = (543, 2070)
FANSCLUB_JOIN_CLICK = (550, 2050)
FANSCLUB_JOIN_FALLBACK_CLICK = (540, 2006)
+266 -78
View File
@@ -7,9 +7,16 @@ from __future__ import annotations
import os
import time
from datetime import datetime
from typing import Any
from douyin.core import path_config
from douyin.fudai.douyin_fudai_core_pkg.button_state import (
decide_button_status,
is_button_text_non_actionable,
)
from .coords import DETAIL_OUTSIDE_CLICK, PARTICIPATE_BTN_CLICK
def attend_choujiang(analyser) -> bool:
@@ -30,10 +37,19 @@ def attend_choujiang(analyser) -> bool:
except Exception:
cached_room_pos = 0
# 如果并行OCR属性缺失或不完整,尝试从其它缓存字段复用识别结果(例如 button_text_raw 或映射表)
# 如果并行OCR属性缺失或不完整,尝试从其它缓存字段复用识别结果。
# 注意:button_text_raw 是全局缓存,可能来自上一个直播间;
# 只有确认同房间时,才允许直接信任它。
if not button_text or not button_status:
try:
candidate = getattr(analyser, "button_text_raw", None)
same_room_cache = (
not current_room_pos
or not cached_room_pos
or current_room_pos == cached_room_pos
)
candidate = None
if same_room_cache:
candidate = getattr(analyser, "button_text_raw", None)
if not candidate:
try:
room_pos = int(getattr(analyser, "room_pos", 0) or 0)
@@ -49,25 +65,48 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
if not candidate:
try:
current_title = str(
getattr(analyser, "current_room_title", "") or ""
).strip()
current_title_raw = str(
getattr(analyser, "current_room_title_raw", "") or ""
).strip()
room_map = getattr(analyser, "_room_pos_to_title_map", {}) or {}
if isinstance(room_map, dict) and (
current_title or current_title_raw
):
for info in room_map.values():
if not isinstance(info, dict):
continue
mapped_title = str(info.get("title") or "").strip()
mapped_title_raw = str(
info.get("title_raw") or ""
).strip()
if not (
(current_title and mapped_title == current_title)
or (
current_title_raw
and mapped_title_raw == current_title_raw
)
):
continue
fudai_detail = info.get("fudai_detail") or {}
candidate = (
fudai_detail.get("button_text")
or fudai_detail.get("button_text_raw")
or None
)
if candidate:
break
except Exception:
pass
if candidate:
bt = str(candidate or "").strip()
if bt:
# 推断按钮状态(与并行OCR的判断逻辑保持一致)
if "参与成功" in bt or "等待开奖" in bt:
bs = "已参与"
elif "加入粉丝团" in bt or "粉丝团" in bt:
bs = "需要加入粉丝团"
elif "评论" in bt or "发表评论" in bt or "一键发表评论" in bt:
bs = "需要评论"
elif "还需看播" in bt or "开始观看" in bt:
bs = "需要观看"
elif "未达成" in bt:
bs = "未达成要求"
elif "参与抽奖" in bt or "参与" in bt:
bs = "可以参与"
else:
bs = "未知状态"
bs = decide_button_status(bt)
try:
analyser._fudai_button_status = bs
@@ -97,7 +136,17 @@ def attend_choujiang(analyser) -> bool:
try:
button_ocr_time = getattr(analyser, "_fudai_button_ocr_time", 0)
current_time = time.time()
if button_text and button_status and current_time - button_ocr_time < 5.0:
same_room = (
not current_room_pos
or not cached_room_pos
or current_room_pos == cached_room_pos
)
if (
button_text
and button_status
and current_time - button_ocr_time < 5.0
and same_room
):
attend_button_text = button_text
analyser._log_kv(
"参与",
@@ -108,11 +157,6 @@ def attend_choujiang(analyser) -> bool:
button_status=button_status,
)
elif button_text and button_status:
same_room = (
not current_room_pos
or not cached_room_pos
or current_room_pos == cached_room_pos
)
if same_room:
attend_button_text = button_text
try:
@@ -134,10 +178,31 @@ def attend_choujiang(analyser) -> bool:
except Exception:
pass
try:
analyser._log_kv(
"参与",
"参与按钮决策输入",
room_pos=current_room_pos,
cached_room_pos=cached_room_pos,
button_text=(attend_button_text[:120] if attend_button_text else ""),
button_status=str(button_status or ""),
click_attempt_index=click_times + 1,
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
# 如果并行OCR结果不可用,直接放弃参与(决策已由福袋详情中的并行OCR进行)
if not attend_button_text:
analyser.last_attend_fail_reason = "no_parallel_ocr_result"
analyser._log_kv("参与", "并行OCR结果不可用,放弃参与", result="不参与")
analyser._log_kv(
"参与",
"并行OCR结果不可用,放弃参与",
result="不参与",
reason="no_parallel_ocr_result",
decision="close_detail_without_attend",
room_pos=current_room_pos,
)
try:
analyser._log_kv(
"统计",
@@ -149,11 +214,37 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
analyser.click(500, 470)
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
# 基于并行OCR结果进行决策
if attend_button_text and is_button_text_non_actionable(attend_button_text):
analyser.last_attend_fail_reason = "button_not_actionable"
analyser._log_kv(
"参与",
"按钮文案不可参与,直接放弃",
result="不参与",
reason="button_not_actionable",
button_text=attend_button_text[:120],
button_status=str(button_status or ""),
decision="close_detail_without_attend",
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="fail",
reason="button_not_actionable",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
if attend_button_text and "不满足参与条件" in attend_button_text:
analyser.last_attend_fail_reason = "condition_not_met"
analyser._log_kv("参与", "不满足参与条件,直接放弃", result="不满足条件")
@@ -168,11 +259,17 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
analyser.click(500, 470)
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif (
attend_button_text and "参与成功" in attend_button_text
attend_button_text
and (
"参与成功" in attend_button_text
or "等待开奖" in attend_button_text
or "失去抽奖" in attend_button_text
or "否则会失去" in attend_button_text
)
): # 如果识别到已经参与抽奖
analyser._log_kv("参与", "已参与,等待开奖", result="已参与")
@@ -205,7 +302,13 @@ def attend_choujiang(analyser) -> bool:
future_ts = 0.0
try:
# 从 detail 中获取 future_ts(如果可用)
future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
future_ts_raw = (
getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0
)
try:
future_ts = float(future_ts_raw)
except Exception:
future_ts = 0.0
# 如果没有从 detail 中获取到 future_ts,尝试直接解析当前详情页的倒计时文本
if not future_ts:
try:
@@ -219,7 +322,10 @@ def attend_choujiang(analyser) -> bool:
res = analyser.operation.check_countdown(time_text)
if isinstance(res, tuple) and len(res) == 2:
_, parsed_future = res
future_ts = float(parsed_future or 0.0)
try:
future_ts = float(parsed_future or 0.0)
except Exception:
future_ts = 0.0
except Exception:
pass
except Exception:
@@ -232,10 +338,16 @@ def attend_choujiang(analyser) -> bool:
participated_fudai_ts = set()
participated_fudai_ts.add(future_ts)
analyser._participated_fudai_future_ts = participated_fudai_ts
try:
future_time_str = datetime.fromtimestamp(float(future_ts)).strftime(
"%Y-%m-%d %H:%M:%S"
)
except Exception:
future_time_str = ""
analyser._log_kv(
"参与",
"记录已参与福袋",
future_ts=future_ts,
开奖时间=future_time_str if future_time_str else "未知",
total_participated=len(participated_fudai_ts),
)
except Exception:
@@ -251,11 +363,21 @@ def attend_choujiang(analyser) -> bool:
analyser._waiting_for_lottery_result = True
analyser._lottery_result_expected_ts = future_ts
analyser._lottery_wait_start_ts = current_time
try:
analyser._lottery_wait_prize_value_yuan = float(
prize_value_yuan or 0.0
)
except Exception:
analyser._lottery_wait_prize_value_yuan = 0.0
analyser._log_kv(
"参与",
"参与成功,设置等待开奖标志",
remain_seconds=int(remain_seconds),
future_ts=int(future_ts),
prize_value_yuan=float(
getattr(analyser, "_lottery_wait_prize_value_yuan", 0.0)
or 0.0
),
lottery_result_expected_ts=int(
analyser._lottery_result_expected_ts
),
@@ -281,7 +403,7 @@ def attend_choujiang(analyser) -> bool:
except Exception:
pass
analyser.click(500, 470) # 点击刚才打开福袋的旁边位置
analyser.click(*DETAIL_OUTSIDE_CLICK) # 点击刚才打开福袋的旁边位置
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return True
elif attend_button_text and (
@@ -317,7 +439,7 @@ def attend_choujiang(analyser) -> bool:
analyser.operation.delay(0.5)
except Exception:
try:
analyser.click(500, 470)
analyser.click(*DETAIL_OUTSIDE_CLICK)
except Exception:
pass
return False
@@ -337,7 +459,7 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
analyser.click(500, 470)
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif attend_button_text and "无法参与" in attend_button_text:
@@ -353,7 +475,7 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
analyser.click(500, 470)
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif attend_button_text and "时长不足" in attend_button_text:
@@ -369,21 +491,24 @@ def attend_choujiang(analyser) -> bool:
)
except Exception:
pass
analyser.click(500, 470)
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv("参与", "关闭福袋详情", action="关闭详情")
return False
elif attend_button_text and "评论" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
analyser.click(543, 2070)
analyser.click(*PARTICIPATE_BTN_CLICK)
analyser._log_kv(
"参与",
"点击参与抽奖(基于截图优化坐标)",
action="点击参与",
mode="评论",
button_text=(attend_button_text[:120] if attend_button_text else ""),
button_status=str(button_status or ""),
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
decision="attend_click_sent",
)
try:
analyser._log_kv(
@@ -400,15 +525,18 @@ def attend_choujiang(analyser) -> bool:
elif attend_button_text and "参与抽奖" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
analyser.click(543, 2070)
analyser.click(*PARTICIPATE_BTN_CLICK)
analyser._log_kv(
"参与",
"点击参与抽奖(基于截图优化坐标)",
action="点击参与",
mode="普通",
button_text=(attend_button_text[:120] if attend_button_text else ""),
button_status=str(button_status or ""),
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
decision="attend_click_sent",
)
try:
analyser._log_kv(
@@ -435,26 +563,36 @@ def attend_choujiang(analyser) -> bool:
from douyin.core.path_config import get_debug_log_path
current_ts_debug = int(time.time() * 1000)
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
f.write(
json.dumps(
{
"id": f"log_{current_ts_debug}_set_countdown_start",
"timestamp": current_ts_debug,
"location": "fudai_attend.py:186",
"message": "开始设置等待开奖标志",
"data": {
"future_ts": getattr(
analyser, "_current_fudai_future_ts", 0.0
)
try:
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
f.write(
json.dumps(
{
"id": f"log_{current_ts_debug}_set_countdown_start",
"timestamp": current_ts_debug,
"location": "fudai_attend.py:186",
"message": "开始设置等待开奖标志",
"data": {
"future_ts": float(
getattr(
analyser,
"_current_fudai_future_ts",
0.0,
)
or 0.0
)
},
"sessionId": "debug-session",
"runId": "countdown_debug_run1",
"hypothesisId": "countdown_hyp2",
},
"sessionId": "debug-session",
"runId": "countdown_debug_run1",
"hypothesisId": "countdown_hyp2",
}
ensure_ascii=False,
default=str,
)
+ "\n"
)
+ "\n"
)
except Exception:
pass
# #endregion
try:
@@ -470,28 +608,38 @@ def attend_choujiang(analyser) -> bool:
analyser._lottery_wait_start_ts = current_time
# #region agent log - countdown set
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
f.write(
json.dumps(
{
"id": f"log_{current_ts_debug}_countdown_set",
"timestamp": current_ts_debug,
"location": "fudai_attend.py:195",
"message": "成功设置等待开奖标志",
"data": {
"waiting_for_lottery_result": analyser._waiting_for_lottery_result,
"lottery_result_expected_ts": analyser._lottery_result_expected_ts,
"future_ts": future_ts,
"current_time": current_time,
"remain_seconds": remain_seconds,
try:
with open(get_debug_log_path(), "a", encoding="utf-8") as f:
f.write(
json.dumps(
{
"id": f"log_{current_ts_debug}_countdown_set",
"timestamp": current_ts_debug,
"location": "fudai_attend.py:195",
"message": "成功设置等待开奖标志",
"data": {
"waiting_for_lottery_result": bool(
analyser._waiting_for_lottery_result
),
"lottery_result_expected_ts": float(
analyser._lottery_result_expected_ts
or 0.0
),
"future_ts": float(future_ts or 0.0),
"current_time": float(current_time or 0.0),
"remain_seconds": int(remain_seconds),
},
"sessionId": "debug-session",
"runId": "countdown_debug_run1",
"hypothesisId": "countdown_hyp2",
},
"sessionId": "debug-session",
"runId": "countdown_debug_run1",
"hypothesisId": "countdown_hyp2",
}
ensure_ascii=False,
default=str,
)
+ "\n"
)
+ "\n"
)
except Exception:
pass
# #endregion
analyser._log_kv(
"参与",
@@ -520,35 +668,71 @@ def attend_choujiang(analyser) -> bool:
elif attend_button_text and (
"加入粉丝团" in attend_button_text or "粉丝团" in attend_button_text
):
from douyin.fudai.core.fudai_attend_fansclub import handle_fansclub_branch
from douyin.fudai.core.fudai_attend_pkg.fansclub_handler import (
handle_fansclub_branch,
)
return handle_fansclub_branch(analyser, attend_button_text)
elif attend_button_text and "开始观看" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
analyser.click(543, 2070)
analyser.click(*PARTICIPATE_BTN_CLICK)
analyser._log_kv(
"参与",
"点击开始观看(基于截图优化坐标)",
action="点击观看",
button_text=(attend_button_text[:120] if attend_button_text else ""),
button_status=str(button_status or ""),
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
decision="watch_click_sent",
)
return True
elif attend_button_text and "参与" in attend_button_text:
# 基于截图优化坐标:OCR区域(306,2030)-(780,2110),尺寸474x80
# 区域中心X = (306+780)/2 = 543,Y = (2030+2110)/2 = 2070
analyser.click(543, 2070)
analyser.click(*PARTICIPATE_BTN_CLICK)
analyser._log_kv(
"参与",
"点击参与(基于截图优化坐标)",
action="点击参与",
button_text=(attend_button_text[:120] if attend_button_text else ""),
button_status=str(button_status or ""),
base_x=543,
base_y=2070,
region="(306,2030)-(780,2110)",
decision="attend_click_sent",
)
return True
# 并行 OCR 命中文本但状态未知:执行一次固定坐标参与点击兜底。
# 这不是 OCR 降级,不会触发额外串行识别;仅避免误识别文案导致整轮放弃。
if attend_button_text:
analyser.click(*PARTICIPATE_BTN_CLICK)
analyser._log_kv(
"参与",
"并行OCR文本未知,执行固定坐标兜底点击",
action="点击参与",
mode="兜底",
button_text=(attend_button_text[:100] if attend_button_text else ""),
button_status=str(button_status or ""),
base_x=543,
base_y=2070,
decision="unknown_text_fallback_click_sent",
)
try:
analyser._log_kv(
"统计",
"metric",
metric="fudai_attend",
metric_type="attempt",
reason="unknown_button_text_fallback_click",
run_id=getattr(analyser, "_run_id", ""),
)
except Exception:
pass
return True
# 未命中任何已知按钮文案时,避免死循环:限次重试并稍作等待
click_times += 1
if click_times < 2:
@@ -562,6 +746,10 @@ def attend_choujiang(analyser) -> bool:
"参与抽奖失败:并行OCR结果无效",
last_text=attend_button_text or "",
result="参与失败",
reason="parallel_ocr_invalid",
button_status=str(button_status or ""),
click_attempts=click_times,
decision="no_attend_click_sent",
)
try:
analyser._log_kv(
File diff suppressed because it is too large. Load diff
Whitespace-only changes.
@@ -0,0 +1,10 @@
"""粉丝团门槛分支入口(薄封装)。"""
from __future__ import annotations
from .fansclub_handler_impl import (
handle_fansclub_branch,
handle_reservation_prejoin_fansclub,
)
__all__ = ["handle_fansclub_branch", "handle_reservation_prejoin_fansclub"]
@@ -0,0 +1,162 @@
"""粉丝团门槛分支实现。"""
from __future__ import annotations
import time
from typing import Any
from douyin.fudai.core.coords import (
DETAIL_OUTSIDE_CLICK,
PARTICIPATE_BTN_CLICK,
FANSCLUB_JOIN_CLICK,
FANSCLUB_JOIN_FALLBACK_CLICK,
)
def handle_fansclub_branch(analyser: Any, attend_button_text: str) -> bool:
"""处理"需要粉丝团门槛"分支。"""
# 为减少当前重构风险,先复用原实现文件逻辑副本
from .fansclub_handler_legacy import handle_fansclub_branch as _legacy_impl
return _legacy_impl(analyser, attend_button_text)
def _scaled_point(analyser: Any, point: tuple[int, int]) -> tuple[int, int]:
try:
rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080)
ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400)
except Exception:
rx, ry = 1080, 2400
return int(point[0] * rx // 1080), int(point[1] * ry // 2400)
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)):
raw = default_seconds
seconds = float(raw or default_seconds)
except Exception:
seconds = default_seconds
seconds = max(float(min_seconds or 0.0), min(seconds, 3.0))
try:
analyser.operation.delay(seconds)
except Exception:
time.sleep(seconds)
def handle_reservation_prejoin_fansclub(
analyser: Any, attend_button_text: str
) -> bool:
"""预约记录前的粉丝团快路径:固定坐标点击,不做OCR和详情恢复。"""
start_ts = time.time()
try:
analyser.last_attend_fail_reason = "fansclub_required"
except Exception:
pass
try:
analyser.click(*PARTICIPATE_BTN_CLICK)
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:先点击参与按钮",
button_text=str(attend_button_text or "")[:80],
base_x=PARTICIPATE_BTN_CLICK[0],
base_y=PARTICIPATE_BTN_CLICK[1],
)
except Exception as exc:
try:
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:点击参与按钮失败",
error=str(exc),
error_type=type(exc).__name__,
level="WARNING",
)
except Exception:
pass
return False
_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)
try:
analyser.operation.click(analyser.device_id, click_x, click_y)
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:点击加入粉丝团固定坐标",
x=click_x,
y=click_y,
base_x=click_point[0],
base_y=click_point[1],
strategy="fixed_coord_no_ocr",
)
except Exception as exc:
fallback_point = FANSCLUB_JOIN_FALLBACK_CLICK
fallback_x, fallback_y = _scaled_point(analyser, fallback_point)
try:
analyser.operation.click(analyser.device_id, fallback_x, fallback_y)
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:固定坐标失败后使用备用坐标",
x=fallback_x,
y=fallback_y,
base_x=fallback_point[0],
base_y=fallback_point[1],
first_error=str(exc),
level="WARNING",
)
except Exception as fallback_exc:
try:
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:点击加入粉丝团失败",
error=str(fallback_exc),
error_type=type(fallback_exc).__name__,
first_error=str(exc),
level="WARNING",
)
except Exception:
pass
return False
_fast_delay(
analyser,
"reservation_prejoin_fansclub_confirm_wait_seconds",
1.6,
min_seconds=1.2,
)
try:
analyser.click(*DETAIL_OUTSIDE_CLICK)
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:关闭详情并跳过详情恢复",
action="close_detail_after_fast_prejoin",
elapsed_seconds=round(time.time() - start_ts, 2),
)
except Exception as exc:
try:
analyser._log_kv(
"预约",
"预约前粉丝团快速预处理:关闭详情失败",
error=str(exc),
error_type=type(exc).__name__,
elapsed_seconds=round(time.time() - start_ts, 2),
level="WARNING",
)
except Exception:
pass
return True
Loaded 100 of 495 files, more files were not shown because too many files have changed in this diff. Show more