From 9c823f48742ae9160628c779c322dc1ba3800cdf Mon Sep 17 00:00:00 2001 From: Codex Date: Fri, 22 May 2026 02:32:39 +0800 Subject: [PATCH] =?UTF-8?q?refactor(fudai):=20=E6=8B=86=E5=87=BA=E5=8F=82?= =?UTF-8?q?=E4=B8=8E=E6=88=90=E5=8A=9F=E5=90=8E=E5=96=84=E5=90=8E=E9=80=BB?= =?UTF-8?q?=E8=BE=91=EF=BC=883334=E2=86=923181=EF=BC=8C-153=20=E8=A1=8C?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 把 _handle_in_fudai_detail 中参与成功分支的善后动作抽到 fudai_detail_blocks: - handle_reservation_post_attend:清/延锁定期 + 移除完成的预约 + 重排队列 - close_detail_after_successful_attend:按 _detail_closed_by_attend 决定是否点返回键 - reset_fudai_detail_state_after_attend:清除 first_read / last_tuple / task_count 标志 主流程的参与成功分支从 ~180 行简化到 ~25 行。 新增 8 个单元测试覆盖:pending=False 跳过 / 无其他预约清 focus / 有其他预约设 保护期 / 移除已完成预约 / detail 已关闭跳过点返回 / 状态标志重置等。 1088 → 1096 用例全过。 Co-Authored-By: Claude Opus 4.7 (1M context) --- douyin/core/douyin_fudai.py | 165 +------------- .../core/fudai_modules/fudai_detail_blocks.py | 211 ++++++++++++++++++ tests/test_fudai_detail_blocks.py | 88 ++++++++ 3 files changed, 305 insertions(+), 159 deletions(-) diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index f2676ff..0885728 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -3018,117 +3018,9 @@ class fudai_analyse: # 检查是否是预约福袋,如果是,处理锁定期和移除预约 try: - if getattr(self, "reservation_after_action_pending", False): - # 这是预约福袋,参与成功后处理锁定期和移除预约 - 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: - # 还有其他预约,设置短暂保护期(10秒)确保依次参与 - 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 - - # 从预约队列中移除已完成的预约(匹配 future_ts,允许5秒误差) - if hasattr(self, "reservations") and self.reservations: - # use module-level `douyin_reservation_logic` - 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 + fudai_detail_blocks.handle_reservation_post_attend( + self, future_timestamp + ) except Exception as e: try: self._log_kv( @@ -3139,54 +3031,9 @@ class fudai_analyse: except Exception: pass - # 关闭详情页,返回直播间等待开奖 - # 检查 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 - - # 清除第一次读取标志,下次打开新福袋时重新识别 - try: - self._fudai_detail_first_read = False - self._last_fudai_detail_tuple = None - except Exception: - pass - - # 清除第一次读取标志,下次打开新福袋时重新识别 - 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 + # 关闭详情页 + 重置详情状态 + fudai_detail_blocks.close_detail_after_successful_attend(self) + fudai_detail_blocks.reset_fudai_detail_state_after_attend(self) # 返回,让主循环只检测开奖结果,不执行其他操作 # 步骤4结束计时 diff --git a/douyin/core/fudai_modules/fudai_detail_blocks.py b/douyin/core/fudai_modules/fudai_detail_blocks.py index 5ae7048..dfe12c9 100644 --- a/douyin/core/fudai_modules/fudai_detail_blocks.py +++ b/douyin/core/fudai_modules/fudai_detail_blocks.py @@ -389,3 +389,214 @@ def handle_task_count_zero_error(analyser: Any, start_time: float) -> bool: return True +def handle_reservation_post_attend(analyser: Any, future_timestamp: float) -> None: + """预约福袋参与成功后的善后:清/延锁定期 + 移除完成的预约 + 重排队列。 + + 仅当 ``analyser.reservation_after_action_pending`` 为 True 才会触发; + 其他情况下调用方应自行 short-circuit。 + """ + if not getattr(analyser, "reservation_after_action_pending", False): + return + + try: + analyser._log_kv( + "预约", + "[预约] 参与成功,处理锁定期并移除预约", + future_ts=int(future_timestamp), + current_focus_until=int( + getattr(analyser, "reservation_focus_until_ts", 0) + ), + ) + except Exception: + pass + + has_other_reservations = False + if hasattr(analyser, "reservations") and analyser.reservations: + for r in analyser.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 + analyser.reservation_focus_until_ts = max( + analyser.reservation_focus_until_ts, protection_until + ) + try: + analyser._log_kv( + "预约", + "[预约] 参与成功,设置保护期确保依次参与", + protection_seconds=10, + new_focus_until=int(analyser.reservation_focus_until_ts), + remaining_reservations=len( + [ + r + for r in analyser.reservations + if float(r.get("future_ts", 0)) > 0 + ] + ), + ) + except Exception: + pass + else: + analyser.reservation_focus_until_ts = 0.0 + try: + analyser._log_kv( + "预约", + "[预约] 参与成功,清除锁定期(无其他预约)", + future_ts=int(future_timestamp), + ) + except Exception: + pass + + analyser.reservation_after_action_pending = False + + if hasattr(analyser, "reservations") and analyser.reservations: + reservations_to_remove = [] + for idx, r in enumerate(analyser.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 = analyser.reservations.pop(idx) + try: + analyser._log_kv( + "预约", + "[预约] 已从队列中移除已完成的预约", + future_ts=int(removed.get("future_ts", 0)), + content=str(removed.get("content", ""))[:50], + ) + except Exception: + pass + except Exception: + pass + + if analyser.reservations: + try: + from douyin.reservation import douyin_reservation_logic + + douyin_reservation_logic._sort_reservations_inplace( + analyser.reservations + ) + except Exception: + pass + + +def close_detail_after_successful_attend(analyser: Any) -> None: + """参与成功后关闭详情页(如果尚未由 attend_choujiang 关闭)。""" + detail_already_closed = getattr(analyser, "_detail_closed_by_attend", False) + if not detail_already_closed: + try: + analyser.operation.click_back(analyser.device_id) + analyser.operation.delay(1.0) + analyser._log_kv("参与", "已关闭详情页,返回直播间等待开奖") + except Exception: + pass + else: + try: + analyser._log_kv( + "参与", + "详情页已由 attend_choujiang 关闭,跳过返回键点击", + ) + except Exception: + pass + + +def reset_fudai_detail_state_after_attend(analyser: Any) -> None: + """参与流程结束后重置详情状态:清除"第一次读取"标志 + 清除任务数量标志。""" + try: + analyser._fudai_detail_first_read = False + analyser._last_fudai_detail_tuple = None + except Exception: + pass + + try: + analyser._fudai_detail_task_count_from_stage = None + try: + analyser._log_kv( + "福袋详情", + "_handle_in_fudai_detail:清除任务数量标志", + log_type="DEBUG", + ) + except Exception: + pass + except Exception: + pass + + """last_status == "error" 且 reason == "task_count_zero" 的处理。 + + 返回 True 表示已处理(连续失败 3 次切换直播间,或单次失败跳过), + 主流程应 return。返回 False 表示不属于该分支。 + """ + try: + last_status = getattr(analyser, "_last_fudai_detail_status", "") + except Exception: + return False + if last_status != "error": + return False + + try: + last_extra = getattr(analyser, "_last_fudai_detail_extra", {}) + except Exception: + return False + if not isinstance(last_extra, dict) or last_extra.get("reason") != "task_count_zero": + return False + + consecutive_failures = ( + getattr(analyser, "_fudai_detail_consecutive_failures", 0) or 0 + ) + 1 + try: + analyser._fudai_detail_consecutive_failures = consecutive_failures + except Exception: + pass + + if consecutive_failures >= 3: + try: + analyser._log_kv( + "流程", + "_handle_in_fudai_detail:连续3次识别到任务数量为0,强制关闭详情页并切换直播间,避免卡死", + consecutive_failures=consecutive_failures, + ) + except Exception: + pass + + try: + from douyin.fudai import douyin_fudai_detail + + douyin_fudai_detail.close_fudai_detail(analyser) + try: + analyser.operation.delay(0.5) + except Exception: + pass + except Exception: + pass + + _force_swipe_to_next_live_with_adb_fallback(analyser) + + try: + analyser._fudai_detail_consecutive_failures = 0 + except Exception: + pass + + cleanup_and_log_completion(analyser, start_time, "连续失败") + return True + + cleanup_and_log_completion( + analyser, + start_time, + "任务数量为0", + pre_log_msg="_handle_in_fudai_detail:检测到任务数量为0,跳过后续处理", + pre_log_fields={"consecutive_failures": consecutive_failures}, + ) + return True + + diff --git a/tests/test_fudai_detail_blocks.py b/tests/test_fudai_detail_blocks.py index 575dc3d..dcaaf81 100644 --- a/tests/test_fudai_detail_blocks.py +++ b/tests/test_fudai_detail_blocks.py @@ -254,3 +254,91 @@ def test_task_count_zero_extra_not_dict_returns_false(): a._last_fudai_detail_status = "error" a._last_fudai_detail_extra = None assert fudai_detail_blocks.handle_task_count_zero_error(a, _time.time()) is False + + +# ---- handle_reservation_post_attend ---- # + +def test_post_attend_skips_when_pending_false(): + a = MagicMock() + a.reservation_after_action_pending = False + fudai_detail_blocks.handle_reservation_post_attend(a, future_timestamp=_time.time()) + # 不应改任何状态 + assert a.reservation_after_action_pending is False + + +def test_post_attend_no_other_reservations_clears_focus(): + a = MagicMock() + a.reservation_after_action_pending = True + a.reservation_focus_until_ts = 12345.0 + a.reservations = [] + fudai_detail_blocks.handle_reservation_post_attend( + a, future_timestamp=_time.time() + 100 + ) + assert a.reservation_focus_until_ts == 0.0 + assert a.reservation_after_action_pending is False + + +def test_post_attend_with_other_reservations_sets_protection(): + """剩余预约:focus_until_ts 设为 max(原值, now+10)""" + a = MagicMock() + a.reservation_after_action_pending = True + a.reservation_focus_until_ts = 0.0 + current_ts = _time.time() + a.reservations = [ + {"future_ts": current_ts + 200}, # 不同预约(>5s 差距) + ] + fudai_detail_blocks.handle_reservation_post_attend( + a, future_timestamp=current_ts + 100 + ) + # 设了保护期 + assert a.reservation_focus_until_ts > current_ts + + +def test_post_attend_removes_completed_reservation(): + a = MagicMock() + a.reservation_after_action_pending = True + a.reservation_focus_until_ts = 0.0 + target_ts = 1700000100.0 + a.reservations = [ + {"future_ts": target_ts, "content": "完成的"}, # 应被移除(差 < 5s) + {"future_ts": target_ts + 200, "content": "未完成"}, # 保留 + ] + fudai_detail_blocks.handle_reservation_post_attend(a, future_timestamp=target_ts) + assert len(a.reservations) == 1 + assert a.reservations[0]["content"] == "未完成" + + +# ---- close_detail_after_successful_attend ---- # + +def test_close_detail_when_not_already_closed(): + a = MagicMock() + a._detail_closed_by_attend = False + fudai_detail_blocks.close_detail_after_successful_attend(a) + a.operation.click_back.assert_called_once() + + +def test_close_detail_when_already_closed_skips(): + a = MagicMock() + a._detail_closed_by_attend = True + fudai_detail_blocks.close_detail_after_successful_attend(a) + a.operation.click_back.assert_not_called() + + +def test_close_detail_swallows_exceptions(): + a = MagicMock() + a._detail_closed_by_attend = False + a.operation.click_back.side_effect = RuntimeError("boom") + fudai_detail_blocks.close_detail_after_successful_attend(a) + + +# ---- reset_fudai_detail_state_after_attend ---- # + +def test_reset_state_clears_all_flags(): + a = MagicMock() + a._fudai_detail_first_read = True + a._last_fudai_detail_tuple = ("x",) + a._fudai_detail_task_count_from_stage = 3 + fudai_detail_blocks.reset_fudai_detail_state_after_attend(a) + assert a._fudai_detail_first_read is False + assert a._last_fudai_detail_tuple is None + assert a._fudai_detail_task_count_from_stage is None