From c8df6a158882f202007cc92a7cb8144282bcd23d Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 22 May 2026 08:01:51 +0800 Subject: [PATCH] =?UTF-8?q?refactor(fudai):=20=E6=8F=90=E5=8F=96=20fudai?= =?UTF-8?q?=5Fchoujiang=20=E4=B8=AD=203=20=E4=B8=AA=E7=8B=AC=E7=AB=8B?= =?UTF-8?q?=E5=AD=90=E5=9D=97=E5=88=B0=20fudai=5Fchoujiang=5Fhelpers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将 douyin_fudai.py:fudai_choujiang 内 3 个无业务状态依赖的独立块抽出: - cleanup_stale_screenshot:启动时清理旧截图 - resolve_device_resolution:分辨率解析(5 次重试 + 默认回退) - write_actions_log:写运行起止标记到 actions.log(原代码重复 3 次) douyin_fudai.py: 3861 → 3760 行 (-101) 新增 fudai_choujiang_helpers.py: 97 行 验证: - pytest 1013 passed - compile OK Co-Authored-By: Claude Opus 4.7 (1M context) --- douyin/core/douyin_fudai.py | 121 ++---------------- .../fudai_modules/fudai_choujiang_helpers.py | 97 ++++++++++++++ 2 files changed, 107 insertions(+), 111 deletions(-) create mode 100644 douyin/core/fudai_modules/fudai_choujiang_helpers.py diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index 3e0239c..8cf9700 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -565,30 +565,13 @@ class fudai_analyse: wait_minutes: int = 15, ) -> None: """兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。""" - # 程序启动时清理旧截图文件,避免复用过期的截图 - try: - from douyin.core import path_config - import os + from douyin.core.fudai_modules.fudai_choujiang_helpers import ( + cleanup_stale_screenshot, + resolve_device_resolution, + write_actions_log, + ) - 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 + cleanup_stale_screenshot(self) # DEBUG: 记录函数入口 try: @@ -610,56 +593,10 @@ class fudai_analyse: except Exception: # 兜底:若赋值失败,则保持原有行为(默认允许切换) self.needswitch = True - # 尝试获取设备分辨率;若设备未连接则重试数次再回退到默认分辨率 - 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 + resolve_device_resolution(self) - start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] - try: - actions_log_path = os.path.join( - os.path.dirname(__file__), "logs", "actions.log" - ) - 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 + write_actions_log("程序开始运行", __file__) # 捕获并记录未被捕获的异常以便排查立即退出问题 try: # 原有后续逻辑继续... @@ -718,23 +655,7 @@ class fudai_analyse: time.sleep(1.0) # 记录运行结束(定时模式) - try: - end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] - - actions_log_path = os.path.join( - os.path.dirname(__file__), "logs", "actions.log" - ) - 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"{end_time} - [GUI] - [运行] 程序运行结束(时间到)\n") - f.flush() - except Exception: - pass + write_actions_log("程序运行结束(时间到)", __file__) else: # 无限循环模式(wait_minutes <= 0) @@ -745,29 +666,7 @@ class fudai_analyse: except KeyboardInterrupt: # 允许 Ctrl+C 退出 self._log_kv("循环", "收到中断信号,退出循环") - # 记录运行结束 - try: - end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] - - actions_log_path = os.path.join( - os.path.dirname(__file__), "logs", "actions.log" - ) - 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"{end_time} - [GUI] - [运行] 程序运行结束(中断退出)\n" - ) - f.flush() - except Exception: - pass + write_actions_log("程序运行结束(中断退出)", __file__) raise except Exception as exc: # 捕获异常,记录日志,但继续循环 diff --git a/douyin/core/fudai_modules/fudai_choujiang_helpers.py b/douyin/core/fudai_modules/fudai_choujiang_helpers.py new file mode 100644 index 0000000..e9aa695 --- /dev/null +++ b/douyin/core/fudai_modules/fudai_choujiang_helpers.py @@ -0,0 +1,97 @@ +"""fudai_choujiang 辅助函数 + +从 douyin_fudai.py:fudai_choujiang 中提取的独立子块: +- cleanup_stale_screenshot:清理启动时残留的旧截图 +- resolve_device_resolution:解析设备分辨率(带重试和默认回退) +- write_actions_log:写运行起止标记到 actions.log +""" +from __future__ import annotations + +import logging +import os +import time +from datetime import datetime + + +def cleanup_stale_screenshot(analyser) -> None: + """启动时清理旧截图文件,避免复用过期截图。""" + try: + from douyin.core import path_config + + pic_path = path_config.get_screenshot_path() + if os.path.exists(pic_path): + os.remove(pic_path) + analyser._log_kv( + "启动", + "清理旧截图文件,避免复用过期截图", + path=pic_path, + log_type="SCREENSHOT", + ) + except Exception as e: + try: + analyser._log_kv( + "启动", + f"清理旧截图文件失败 - {str(e)}", + level="WARNING", + error=str(e), + ) + except Exception: + pass + + +def resolve_device_resolution(analyser) -> None: + """获取设备分辨率(重试 5 次),失败回退到 1080x2400 默认值。 + + 直接写入 analyser.resolution_ratio_x / analyser.resolution_ratio_y。 + """ + resolved = False + if analyser.device_id: + for attempt in range(5): + try: + rx, ry = analyser.operation.get_device_resolution(analyser.device_id) + analyser.resolution_ratio_x = int(rx or 1080) + analyser.resolution_ratio_y = int(ry or 2400) + resolved = True + break + except Exception as e: + try: + analyser._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: + analyser._log_kv("截图", "使用默认分辨率回退", width=1080, height=2400) + except Exception: + pass + analyser.resolution_ratio_x, analyser.resolution_ratio_y = 1080, 2400 + + +def write_actions_log(message: str, log_dir_anchor: str) -> None: + """写一条带时间戳的标记到 logs/actions.log。 + + log_dir_anchor 用于定位 logs 目录(通常是 douyin_fudai 模块所在目录)。 + """ + try: + ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] + actions_log_path = os.path.join( + os.path.dirname(log_dir_anchor), "logs", "actions.log" + ) + 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"{ts} - [GUI] - [运行] {message}\n") + f.flush() + except Exception: + pass