From f7da7b78aa54d29654c49d2a4a3b2b39c90f33ba Mon Sep 17 00:00:00 2001 From: Your Name Date: Sun, 4 Jan 2026 09:51:11 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=9B=B4=E6=96=B0=E9=A2=84=E7=BA=A6?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E7=AE=A1=E7=90=86=E9=80=BB=E8=BE=91=EF=BC=8C?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E9=A6=96=E6=AC=A1=E8=BF=90=E8=A1=8C=E6=97=B6?= =?UTF-8?q?=E7=9A=84=E9=98=9F=E5=88=97=E6=81=A2=E5=A4=8D=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- douyin/core/douyin_fudai.py | 138 ++++++++--------------- douyin/core/state/reservations.json | 48 ++++---- douyin/fudai/douyin_fudai_core.py | 4 +- douyin/other/douyin_yanghao.py | 2 + douyin/reservation/douyin_reservation.py | 15 ++- gui/gui_app.py | 16 +-- 6 files changed, 98 insertions(+), 125 deletions(-) diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index ef3d99c..27796f8 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -13,6 +13,7 @@ from __future__ import annotations from typing import Any, List, Tuple, Optional import os import time +import subprocess import logging from Underlying_Operations import underlying_operations @@ -124,6 +125,8 @@ class fudai_analyse: 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坐标(用于优化搜索) # 与配置相关的核心字段(只初始化最关键的几项,其余保持默认) @@ -1020,9 +1023,7 @@ class fudai_analyse: 注意:此方法复杂度较高,已通过模块化重构将部分逻辑拆分到子模块。 """ - from douyin.reservation import ( - douyin_reservation_logic, - ) # pylint: disable=redefined-outer-name + # use module-level `douyin_reservation_logic` imported at top start_time = time.time() # 直接参与标志已移除,相关旧逻辑已清理,继续按正常流程执行 @@ -1053,8 +1054,8 @@ class fudai_analyse: getattr(self, "reservation_back_swipe_delay_s", 0.5) or 0.5 ), - lambda: self.swipe_down_back_from_live(), - lambda item: self._seek_reservation_room(item), + self.swipe_down_back_from_live, + self._seek_reservation_room, lambda: ( douyin_reservation_logic._sort_reservations_inplace( self.reservations @@ -1337,79 +1338,53 @@ class fudai_analyse: 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: + state_path = getattr(self, "_reservations_state_path", None) + loaded: list = [] + if state_path: try: + from douyin.reservation import douyin_reservation as dr + + loaded = dr.load_reservations_state(state_path) + except Exception: + loaded = [] + + if loaded: + try: + self.reservations = loaded self._log_kv( "预约", - "[预约] 清空状态文件时出错", - error=str(exc), - error_type=type(exc).__name__, + "[预约] 第一次运行:已从状态文件恢复预约队列", + restored_count=len(loaded), ) except Exception: - pass - except Exception as exc: - # 如果清空失败,尝试直接设置 - try: - if hasattr(self, "reservations"): + # 兜底赋值 + self.reservations = loaded + else: + # 未读取到数据或状态文件不存在,使用空队列 + try: self.reservations = [] + self._log_kv( + "预约", + "[预约] 第一次运行:未找到预约状态文件或文件为空,使用空队列", + ) + except Exception: + self.reservations = [] + except Exception as exc: + try: self._log_kv( "预约", - "[预约] 清空预约队列时出错,已尝试直接设置", + "[预约] 初始化预约队列时出错,已设置为空队列", error=str(exc), error_type=type(exc).__name__, ) except Exception: pass + try: + self.reservations = [] + except Exception: + pass # 标记已运行过 try: self._first_run_once_basic = False @@ -1726,9 +1701,8 @@ class fudai_analyse: try: ft = float(first_r.get("future_ts") or 0) from datetime import datetime - import time as time_module - now_ts = time_module.time() + now_ts = time.time() ft_str = ( datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft > 0 @@ -1849,11 +1823,7 @@ class fudai_analyse: except Exception: pass - try: - from douyin.reservation import ( - douyin_reservation_logic, - ) # pylint: disable=redefined-outer-name - + # use module-level `douyin_reservation_logic` douyin_reservation_logic.cleanup_expired_reservations( self, self.reservations, _write_state ) @@ -2132,8 +2102,8 @@ class fudai_analyse: base_y=470, ) self.operation.delay(1.0) # 等待关闭完成 - except Exception as exc: - self._log_kv("粉丝团处理", "处理粉丝团加入失败", error=str(exc)) + except Exception as exc_outer: + self._log_kv("粉丝团处理", "处理粉丝团加入失败", error=str(exc_outer)) # 如果启用了自动加入,等待页面加载后再次点击(如果需要) if getattr(self, "auto_join_fansclub", False): @@ -2501,8 +2471,8 @@ class fudai_analyse: and isinstance(detail, tuple) and len(detail) >= 6 ): - # 使用解包避免索引告警 - _, _, _, _, _, countdown_tuple = detail + # 使用索引读取以避免静态分析对解包的误报 + countdown_tuple = detail[5] if ( isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2 @@ -2794,22 +2764,16 @@ class fudai_analyse: end_y = 700 * ry // 2400 # 直接使用 ADB 内部滑动命令 try: - import subprocess - if hasattr(self.operation, "_adb"): adb_cmd = self.operation._adb() else: - import os - adb_cmd = ( os.environ.get( "ADB_EXECUTABLE", "adb" ) or "adb" ) - if not adb_cmd.startswith( - '"' - ) and not adb_cmd.endswith('"'): + if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'): adb_cmd = f'"{adb_cmd}"' cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 300" subprocess.run( @@ -2818,6 +2782,7 @@ class fudai_analyse: timeout=5.0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + check=False, ) except Exception: # 回退到 operation.swipe @@ -2975,22 +2940,16 @@ class fudai_analyse: end_y = 700 * ry // 2400 # 直接使用 ADB 内部滑动命令 try: - import subprocess - if hasattr(self.operation, "_adb"): adb_cmd = self.operation._adb() else: - import os - adb_cmd = ( os.environ.get( "ADB_EXECUTABLE", "adb" ) or "adb" ) - if not adb_cmd.startswith( - '"' - ) and not adb_cmd.endswith('"'): + if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'): adb_cmd = f'"{adb_cmd}"' cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 300" subprocess.run( @@ -2999,6 +2958,7 @@ class fudai_analyse: timeout=5.0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + check=False, ) except Exception: # 回退到 operation.swipe diff --git a/douyin/core/state/reservations.json b/douyin/core/state/reservations.json index f14d2f9..3430a24 100644 --- a/douyin/core/state/reservations.json +++ b/douyin/core/state/reservations.json @@ -1,24 +1,10 @@ { - "updated_ts": 1767491197.3733354, - "reason": "remove_reservation_after_attend", - "room_pos": 0, - "current_room_title": "", + "updated_ts": 1767491436.7967348, + "reason": "process_reservation", + "room_pos": 3, + "current_room_title": "火火来", "current_room_title_raw": "", "reservations": [ - { - "prize_value_yuan": 6999.0, - "content": "", - "future_ts": 1767491410.899574, - "future_str": "2026-01-04 09:50:10", - "pos_seen": 0, - "room_title": "彩虹夫妇", - "room_title_raw": "彩虹夫妇", - "created_ts": 1767491052.272007, - "task_count": 2, - "time_text": "06:04", - "participants": 0, - "copies": 0 - }, { "prize_value_yuan": 5999.0, "content": "", @@ -27,11 +13,27 @@ "pos_seen": 3, "room_title": "刘媛媛媛", "room_title_raw": "刘媛媛.媛", - "created_ts": 1767491172.3842542, - "task_count": 2, - "time_text": "06:00", - "participants": 0, - "copies": 0 + "created_ts": 1767491172.3842542 + }, + { + "prize_value_yuan": 1999.0, + "content": "", + "future_ts": 1767492193.581507, + "future_str": "2026-01-04 10:03:13", + "pos_seen": 0, + "room_title": "作川帮数", + "room_title_raw": "作川帮数。。", + "created_ts": 1767491317.7698174 + }, + { + "prize_value_yuan": 1999.0, + "content": "", + "future_ts": 1767492193.641006, + "future_str": "2026-01-04 10:03:13", + "pos_seen": 0, + "room_title": "作帮粼", + "room_title_raw": "作!帮粼。。", + "created_ts": 1767491385.7829947 } ] } \ No newline at end of file diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index c692710..98cdf6a 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -1348,8 +1348,8 @@ def get_fudai_contain(analyser, renwu: int = 2) -> Tuple[str, str, int, int, flo analyser._log_kv( "错误", "备用OCR识别任务列表失败", - error=str(e_inner2), - error_type=type(e_inner2).__name__, + error=str(e_pl6), + error_type=type(e_pl6).__name__, level="WARNING", ) except Exception: diff --git a/douyin/other/douyin_yanghao.py b/douyin/other/douyin_yanghao.py index 6c64bbf..d74dcc7 100644 --- a/douyin/other/douyin_yanghao.py +++ b/douyin/other/douyin_yanghao.py @@ -114,6 +114,8 @@ def yanghao_idle(analyser, total_seconds: int) -> None: except Exception: tpl_exists = False + # 确保 roi_path 在所有分支中都有定义,避免可能的未赋值使用 + roi_path = "" print( f"[养号][DEBUG] _detect_icon action={action} template_path='{template_path}' tpl_exists={tpl_exists}" ) diff --git a/douyin/reservation/douyin_reservation.py b/douyin/reservation/douyin_reservation.py index 2fb9406..d9d5af5 100644 --- a/douyin/reservation/douyin_reservation.py +++ b/douyin/reservation/douyin_reservation.py @@ -12,6 +12,7 @@ try: log_reservation_error, format_reservation_context, ) + _RESERVATION_ERROR_UTILS_AVAILABLE = True except ImportError: # 如果导入失败,提供占位符函数 @@ -24,7 +25,9 @@ except ImportError: _RESERVATION_ERROR_UTILS_AVAILABLE = False -def _write_json_atomic(path: str, data: object, *, indent: int = 2, analyser: Optional[Any] = None) -> None: +def _write_json_atomic( + path: str, data: object, *, indent: int = 2, analyser: Optional[Any] = None +) -> None: """原子写入 JSON 文件,带详细的错误处理。 参数: @@ -141,7 +144,11 @@ def write_reservations_state( except Exception: ft = 0.0 try: - ft_str = datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") if ft else "" + ft_str = ( + datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S") + if ft + else "" + ) except Exception: ft_str = "" items.append( @@ -218,7 +225,9 @@ def load_high_value_rooms_map(path: str) -> dict[str, dict]: return {} -def write_high_value_rooms_state(path: str, rooms_map: dict, *, reason: str = "") -> None: +def write_high_value_rooms_state( + path: str, rooms_map: dict, *, reason: str = "" +) -> None: """寫入高價值直播間映射(跨運行持久化)。""" try: rooms: list[dict] = [] diff --git a/gui/gui_app.py b/gui/gui_app.py index bf73941..27a2293 100644 --- a/gui/gui_app.py +++ b/gui/gui_app.py @@ -2231,13 +2231,13 @@ def main(): side=LEFT, padx=(0, 8) ) # forward-declare handler to satisfy linters; real function defined later - open_realtime_viewer = lambda: None + open_realtime_viewer_func = lambda: None ttk.Button( realtime_tools, text="实时查看", width=10, - command=lambda: open_realtime_viewer(), + command=lambda: open_realtime_viewer_func(), ).pack(side=LEFT, padx=(8, 0)) log_tab = ttk.Frame(notebook) @@ -2425,12 +2425,12 @@ def main(): pass # --------- 实时查看弹窗(紧凑视图) --------- - def open_realtime_viewer(): + def open_realtime_viewer_func(): try: # 如果已打开则直接聚焦 - if hasattr(open_realtime_viewer, "_win") and open_realtime_viewer._win: + if hasattr(open_realtime_viewer_func, "_win") and open_realtime_viewer_func._win: try: - open_realtime_viewer._win.lift() + open_realtime_viewer_func._win.lift() except Exception: pass return @@ -2438,7 +2438,7 @@ def main(): win = tk.Toplevel(root) win.title("实时查看 - 截图与最简动作流") win.geometry("520x520") - open_realtime_viewer._win = win + open_realtime_viewer_func._win = win # 图片与列表 img_lbl = ttk.Label(win) @@ -2462,7 +2462,7 @@ def main(): win.destroy() except Exception: pass - open_realtime_viewer._win = None + open_realtime_viewer_func._win = None win.protocol("WM_DELETE_WINDOW", close_win) @@ -4661,7 +4661,7 @@ def main(): ttk.Button(win_record_top, text="打开目录", command=open_win_folder).pack(side=LEFT) ttk.Button( - win_record_top, text="实时查看", command=lambda: open_realtime_viewer() + win_record_top, text="实时查看", command=lambda: open_realtime_viewer_func() ).pack(side=LEFT, padx=(8, 0)) # 误识别记录管理