diff --git a/douyin/fudai/douyin_fudai_core.py b/douyin/fudai/douyin_fudai_core.py index e70211e..ec84477 100644 --- a/douyin/fudai/douyin_fudai_core.py +++ b/douyin/fudai/douyin_fudai_core.py @@ -3783,2424 +3783,17 @@ def _is_short_countdown_text(time_text: str) -> bool: # noqa: F811 return _impl(time_text) -def should_skip_fudai_by_config(analyser: Any, detail: Tuple) -> Tuple[bool, str]: - """根据 config.json 中的阈值与关键词,判断是否应丢弃当前福袋。 - - 返回: - (skip, reason) 其中 reason 为简单文字原因,便于日志查看。 - """ - start_time = time.time() - # 单间模式(needswitch=False):忽略所有福袋阈值配置,永远不因为配置而跳过 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if not needswitch: - try: - analyser._log_kv( - "筛选", - "单间模式:忽略所有福袋阈值配置,直接参与", - needswitch=0, - ) - except Exception: - pass - return False, "single_room_mode" - - if not isinstance(detail, tuple) or len(detail) < 6: - return False, "detail_tuple_invalid" - - content = str(detail[0] or "") - - # 优先检查是否为"观看X分钟"类任务:若是,直接放弃 - if is_watch_task_fudai(content): - try: - analyser._log_kv( - "筛选", - "检测到'观看X分钟'类任务,自动放弃", - content=content[:80] if content else "", - reason="watch_task_detected", - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "筛选", - "should_skip_fudai_by_config完成(观看任务)", - elapsed_seconds=round(elapsed, 2), - ) - return True, "watch_task_detected" - time_text = str(detail[1] or "") - try: - participants = int(detail[2] or 0) - except Exception: - participants = 0 - try: - copies = int(detail[3] or 0) - except Exception: - copies = 0 - try: - prize_value_yuan = float(detail[4] or 0.0) - except Exception: - prize_value_yuan = 0.0 - - cd_start, cd_end = None, None - if isinstance(detail[5], (tuple, list)) and len(detail[5]) >= 2: - cd_start, cd_end = detail[5][0], detail[5][1] - now = time.time() - remain_seconds = None - try: - if isinstance(cd_end, (int, float)) and cd_end > now: - remain_seconds = float(cd_end - now) - try: - analyser._log_kv( - "筛选", - "倒计时计算成功", - cd_end=cd_end, - now=now, - 剩余秒数=remain_seconds, - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "倒计时计算失败或已过期", - cd_end=cd_end, - now=now, - cd_end类型=type(cd_end).__name__, - cd_end大于now=( - bool(isinstance(cd_end, (int, float)) and cd_end > now) - if isinstance(cd_end, (int, float)) - else False - ), - ) - except Exception: - pass - except Exception as e_inner: - remain_seconds = None - try: - analyser._log_kv( - "筛选", - "倒计时计算异常", - 异常=str(e_inner), - 异常类型=type(e_inner).__name__, - ) - except Exception: - pass - - # 读取配置阈值 - try: - min_value = float(getattr(analyser, "min_prize_value_yuan", 0.0) or 0.0) - except Exception: - min_value = 0.0 - try: - min_participants = int(getattr(analyser, "min_participants", 0) or 0) - except Exception: - min_participants = 0 - try: - max_participants = int(getattr(analyser, "max_participants", 0) or 0) - except Exception: - max_participants = 0 - skip_if_gt = 0 # Initialize before try block - try: - skip_if_gt = int(getattr(analyser, "skip_if_countdown_gt_seconds", 0) or 0) - except Exception: - skip_if_gt = 0 - skip_if_lt = 0 # Initialize before try block - try: - skip_if_lt = int(getattr(analyser, "skip_if_countdown_lt_seconds", 0) or 0) - except Exception: - skip_if_lt = 0 - - # 获取按钮文本,用于记录 - button_text = str(getattr(analyser, "button_text_raw", "") or "").strip() - - # 记录所有配置值和实际值,便于调试 - try: - analyser._log_kv( - "筛选", - "should_skip_fudai_by_config 开始检查", - ) - analyser._log_kv( - "筛选", - "配置参数", - 最小价值=min_value, - 最小参与人数=min_participants, - 最大参与人数=max_participants, - 倒计时大于秒数=skip_if_gt, - 倒计时小于秒数=skip_if_lt, - ) - analyser._log_kv( - "筛选", - "实际数据", - 价值=prize_value_yuan, - 参与人数=participants, - 份数=copies, - 剩余秒数=int(remain_seconds) if remain_seconds is not None else None, - 内容=content[:60] if content else "", - 按钮文本=button_text if button_text else "未识别", - ) - except Exception: - pass - - # 并行检查所有筛选条件,收集所有不符合的原因 - skip_reasons = [] - - # 1) 价值过滤 - if min_value > 0: - if prize_value_yuan > 0: - if prize_value_yuan < min_value: - skip_reasons.append(f"value_lt_{min_value}") - try: - analyser._log_kv( - "筛选", - "价值过滤:不符合(价值过低)", - 实际价值=prize_value_yuan, - 配置最小价值=min_value, - 判断条件=f"{prize_value_yuan} < {min_value} = True", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "价值过滤:通过", - 实际价值=prize_value_yuan, - 配置最小价值=min_value, - 判断条件=f"{prize_value_yuan} >= {min_value} = True", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "价值过滤:跳过(未识别到价值)", - 实际价值=prize_value_yuan, - ) - except Exception: - pass - - # 2) 参与人数过滤 - if min_participants > 0: - if participants > 0: - if participants < min_participants: - skip_reasons.append(f"participants_lt_{min_participants}") - try: - analyser._log_kv( - "筛选", - "参与人数过滤:不符合(小于最小值)", - 实际参与人数=participants, - 配置最小参与人数=min_participants, - 判断条件=f"{participants} < {min_participants} = True", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "参与人数过滤:通过(最小值检查)", - 实际参与人数=participants, - 配置最小参与人数=min_participants, - 判断条件=f"{participants} >= {min_participants} = True", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "参与人数过滤:跳过(未识别到参与人数)", - 实际参与人数=participants, - ) - except Exception: - pass - - if max_participants > 0: - if participants > 0: - if participants > max_participants: - skip_reasons.append(f"participants_gt_{max_participants}") - try: - analyser._log_kv( - "筛选", - "参与人数过滤:不符合(大于最大值)", - 实际参与人数=participants, - 配置最大参与人数=max_participants, - 判断条件=f"{participants} > {max_participants} = True", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "参与人数过滤:通过(最大值检查)", - 实际参与人数=participants, - 配置最大参与人数=max_participants, - 判断条件=f"{participants} <= {max_participants} = True", - ) - except Exception: - pass - - # 2.5) 倒计时文本过滤:如果OCR识别的倒计时文本表示剩余时间很短,直接跳过 - if _is_short_countdown_text(time_text): - skip_reasons.append("countdown_text_short") - try: - analyser._log_kv( - "筛选", - "倒计时文本过滤:不符合(OCR识别到剩余时间很短)", - 倒计时文本=time_text, - 实际剩余秒数=( - int(remain_seconds) if remain_seconds is not None else None - ), - ) - except Exception: - pass - - # 3) 倒计时过滤 - # 3.1) 倒计时小于阈值:直接丢弃(不参与) - if skip_if_lt > 0: - if remain_seconds is not None: - if remain_seconds < skip_if_lt: - skip_reasons.append(f"countdown_lt_{skip_if_lt}") - try: - analyser._log_kv( - "筛选", - "倒计时过滤:不符合(剩余秒数小于阈值)", - 实际剩余秒数=int(remain_seconds), - 配置阈值秒数=skip_if_lt, - 判断条件=f"{remain_seconds} < {skip_if_lt} = True", - ) - except Exception: - pass - - # 3.2) 倒计时大于阈值:不参与(但如果价值达到高价值阈值,可以预约) - if skip_if_gt > 0: - if remain_seconds is not None: - if remain_seconds > skip_if_gt: - skip_reasons.append(f"countdown_gt_{skip_if_gt}") - try: - analyser._log_kv( - "筛选", - "倒计时过滤:不符合(剩余秒数大于阈值)", - 实际剩余秒数=int(remain_seconds), - 配置阈值秒数=skip_if_gt, - 判断条件=f"{remain_seconds} > {skip_if_gt} = True", - 说明="如果价值达到高价值阈值,basic_join_decision 会记录预约", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "倒计时过滤:通过", - 实际剩余秒数=int(remain_seconds), - 配置阈值秒数=skip_if_gt, - 判断条件=f"{remain_seconds} <= {skip_if_gt} = True", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "倒计时过滤:跳过(未识别到倒计时或倒计时已过期)", - 剩余秒数=remain_seconds, - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "倒计时过滤:跳过(配置阈值为0,不启用倒计时过滤)", - 配置阈值秒数=skip_if_gt, - ) - except Exception: - pass - - # 4) 内容关键词过滤(复用 check_contain 逻辑) - content_check_result = check_contain(analyser, content) - if content_check_result: - skip_reasons.append("content_not_wanted") - try: - analyser._log_kv( - "筛选", - "内容关键词过滤:不符合", - 内容=content[:60] if content else "", - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "内容关键词过滤:通过", - 内容=content[:60] if content else "", - ) - except Exception: - pass - - # 5) 按钮文本过滤:检查按钮是否显示无法参与、还需看播等状态 - try: - if button_text: - # 检查是否包含无法参与的关键词 - unable_to_participate_keywords = [ - "无法参与", - "不能参与", - "不可参与", - "还没到时间", - "活动已结束", - "活动结束", - "已结束", - "已过期", - "已截止", - "时长不足", - ] - watch_required_keywords = [ - "还需看播", - "观看", - "看播", - "观看时长", - "观看分钟", - ] - - # 检查无法参与关键词 - for keyword in unable_to_participate_keywords: - if keyword in button_text: - skip_reasons.append("button_unable_to_participate") - try: - analyser._log_kv( - "筛选", - "按钮文本过滤:不符合(无法参与)", - 按钮文本=button_text, - 匹配关键词=keyword, - ) - except Exception: - pass - break - - # 检查观看要求关键词 - for keyword in watch_required_keywords: - if keyword in button_text: - skip_reasons.append("button_watch_required") - try: - analyser._log_kv( - "筛选", - "按钮文本过滤:不符合(观看任务)", - 按钮文本=button_text, - 匹配关键词=keyword, - ) - except Exception: - pass - break - - if not any(reason.startswith("button_") for reason in skip_reasons): - try: - analyser._log_kv( - "筛选", - "按钮文本过滤:通过", - 按钮文本=button_text, - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "筛选", - "按钮文本过滤:跳过(未识别到按钮文本)", - ) - except Exception: - pass - except Exception as e: - try: - analyser._log_kv( - "筛选", - "按钮文本过滤:异常", - 异常=str(e), - 异常类型=type(e).__name__, - ) - except Exception: - pass - - # 如果有任何不符合的条件,就跳过 - if skip_reasons: - elapsed = time.time() - start_time - try: - analyser._log_kv( - "筛选", - "should_skip_fudai_by_config完成(不符合条件,跳过)", - 不符合原因=skip_reasons, - 总原因数=len(skip_reasons), - elapsed_seconds=round(elapsed, 2), - ) - except Exception: - pass - # 返回第一个原因作为主要原因 - return True, skip_reasons[0] - - # 所有条件都通过 - try: - analyser._log_kv( - "筛选", - "should_skip_fudai_by_config 通过(所有检查项均通过)", - content=content[:60] if content else "", - participants=participants, - copies=copies, - value_yuan=prize_value_yuan, - remain_seconds=int(remain_seconds) if remain_seconds is not None else None, - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "筛选", - "should_skip_fudai_by_config完成(通过)", - elapsed_seconds=round(elapsed, 2), - ) - return False, "ok" - - -def basic_join_decision( - analyser: Any, detail: Tuple, skip_result: Tuple[bool, str] = None -) -> bool: - """基础版参与决策:根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。 - - 参数: - analyser: 分析器对象 - detail: 福袋详情元组 - skip_result: 可选的筛选结果 (skip, reason),如果已知可以避免重复筛选 - - 返回: - True 表示已经参与或已处理完成; - False 表示未参与(例如被配置筛掉或参与失败)。 - """ - # time 模块在文件开头已导入 - start_time = time.time() - # 解析 detail 字段:先提取价值信息,用于判断是否达到高价值阈值 - content = "" - prize_value_yuan = 0.0 - countdown_tuple = None - try: - if isinstance(detail, tuple) and len(detail) >= 6: - content = str(detail[0] or "") - prize_value_yuan = float(detail[4] or 0.0) - countdown_tuple = detail[5] - except Exception: - pass - - # 在福袋详情识别完成后,设置福袋信息并记录到映射表 - try: - analyser._current_fudai_content = content - analyser._last_fudai_detail_tuple = detail - - analyser._log_kv( - "福袋详情", - "basic_join_decision:设置福袋信息", - content=content[:50] if content else "", - prize_value_yuan=prize_value_yuan, - log_type="INFO", - ) - except Exception as e: - analyser._log_kv( - "福袋详情", - "basic_join_decision:设置福袋信息失败", - error=str(e), - log_type="WARNING", - ) - - # 强制参与标志已移除,始终按正常验证流程处理 - force_attend = False - - # 检查是否是优惠券弹窗或识别错误:如果检测到,应该直接跳过,不继续处理 - # 但如果设置了强制参与标志,则跳过状态检查(预约回退时使用预约记录,可能不满足验证条件) - try: - last_status = getattr(analyser, "_last_fudai_detail_status", "") - if not force_attend: # 只有在非强制参与模式下才检查状态 - if last_status == "coupon_popup": - try: - analyser._log_kv( - "参与", - "basic_join_decision:检测到优惠券弹窗,已关闭,跳过后续处理", - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(优惠券弹窗)", - elapsed_seconds=round(elapsed, 2), - ) - return False - elif last_status == "validation_failed": - try: - analyser._log_kv( - "参与", - "basic_join_decision:福袋详情数据验证失败,识别出错,跳过后续处理", - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(验证失败)", - elapsed_seconds=round(elapsed, 2), - ) - return False - except Exception: - pass - if force_attend: - try: - analyser._log_kv( - "参与", - "basic_join_decision:检测到强制参与标志(预约回退),跳过验证,直接参与", - ) - except Exception: - pass - # 跳过验证,直接进入参与逻辑 - else: - # 额外验证:使用验证函数检查数据合理性 - try: - # 在函数开头导入,避免作用域问题 - from douyin.fudai import douyin_fudai_detail as dfd_module - - is_valid, reason = dfd_module.validate_fudai_detail(detail, analyser) - if not is_valid: - try: - analyser._log_kv( - "参与", - "basic_join_decision:福袋详情数据验证失败,识别出错", - validation_reason=reason, - content=content[:50] if content else "", - prize_value_yuan=prize_value_yuan, - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(验证失败)", - elapsed_seconds=round(elapsed, 2), - ) - return False - except Exception: - pass - - # 兜底检查:如果价值为0且内容为空,也可能是优惠券弹窗或识别错误 - if not content and prize_value_yuan == 0.0: - try: - analyser._log_kv( - "参与", - "basic_join_decision:检测到无效详情(可能是优惠券弹窗或识别错误),跳过后续处理", - content=content, - prize_value_yuan=prize_value_yuan, - ) - except Exception: - pass - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(无效详情)", - elapsed_seconds=round(elapsed, 2), - ) - return False - - # 单间模式(needswitch=False):不做任何阈值过滤/高价值预约,直接尝试参与当前福袋 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if not needswitch: - try: - analyser._log_kv( - "参与", - "basic_join_decision:单间模式,忽略阈值与预约逻辑,直接参与当前福袋", - ) - except Exception: - pass - result = attend_choujiang(analyser) - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(单间模式参与)", - elapsed_seconds=round(elapsed, 2), - result=result, - ) - return result - - # 检查是否启用高价值预约,以及价值是否达到阈值 - try: - high_value_enabled = bool(getattr(analyser, "high_value_fudai_enabled", False)) - except Exception: - high_value_enabled = False - - try: - high_value_threshold = float( - getattr(analyser, "high_value_fudai_threshold_yuan", 500.0) or 500.0 - ) - except Exception: - high_value_threshold = 500.0 - - # 添加调试日志:输出配置值 - try: - analyser._log_kv( - "参与", - "basic_join_decision:配置检查", - high_value_enabled=high_value_enabled, - high_value_threshold=high_value_threshold, - min_prize_value_yuan=getattr(analyser, "min_prize_value_yuan", 0), - needswitch=getattr(analyser, "needswitch", True), - log_type="DEBUG", - ) - except Exception: - pass - - # 计算 future_timestamp(预计开奖时间戳) - future_ts = 0.0 - if isinstance(countdown_tuple, (tuple, list)) and len(countdown_tuple) >= 2: - try: - future_ts = float(countdown_tuple[1] or 0.0) - except Exception: - future_ts = 0.0 - - # 检查是否已经参与过这个福袋(通过 future_ts 匹配,避免重复参与) - if future_ts > 0: - try: - participated_fudai_ts = getattr( - analyser, "_participated_fudai_future_ts", set() - ) - if not isinstance(participated_fudai_ts, set): - participated_fudai_ts = set() - - # 检查是否已经参与过(允许5秒误差,因为倒计时可能略有变化) - for participated_ts in participated_fudai_ts: - if abs(future_ts - participated_ts) < 5.0: - try: - analyser._log_kv( - "参与", - "basic_join_decision:已参与过此福袋,跳过重复参与", - future_ts=future_ts, - participated_ts=participated_ts, - ) - except Exception: - pass - # 已参与过,关闭详情页后返回 True(表示已处理完成) - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(重复参与)", - action="close_detail", - ) - except Exception: - pass - return True - except Exception: - pass - - # 检查价值是否达到高价值阈值 - is_high_value = ( - high_value_enabled - and prize_value_yuan > 0 - and prize_value_yuan >= high_value_threshold - and future_ts > 0.0 +def should_skip_fudai_by_config(analyser, detail): # noqa: F811 — 兼容性 re-export + """[兼容] 已迁移到 douyin.fudai.core.fudai_filter。""" + from douyin.fudai.core.fudai_filter import ( + should_skip_fudai_by_config as _impl, ) - # 添加调试日志 - try: - analyser._log_kv( - "参与", - "basic_join_decision:高价值检查结果", - prize_value_yuan=prize_value_yuan, - high_value_threshold=high_value_threshold, - high_value_enabled=high_value_enabled, - future_ts=future_ts, - is_high_value=is_high_value, - content=content[:50] if content else "", - ) - except Exception: - pass + return _impl(analyser, detail) - # 如果是高价值福袋,在进行任何可能切换房间的操作之前,先读取当前直播间标题 - # 这样可以确保记录的是原始的高价值直播间标题,而不是切换后的标题 - current_room_title = "" - current_room_title_raw = "" - if is_high_value: - try: - revisit_enabled = bool( - getattr(analyser, "high_value_room_revisit_enabled", False) - ) - if revisit_enabled: - # 直接使用并行OCR已缓存的直播间标题,避免重复截图和OCR - current_room_title = str( - getattr(analyser, "current_room_title", "") or "" - ).strip() - current_room_title_raw = str( - getattr(analyser, "current_room_title_raw", "") or "" - ).strip() - # 无论缓存是否为空,都不再重新读取,直接使用并行OCR的结果 - # 这样可以避免重复识别,同时确保即使并行OCR失败也能有一致的处理 - try: - analyser._log_kv( - "预约", - "使用并行OCR已缓存的直播间标题", - title=current_room_title, - has_title=bool(current_room_title), - log_type="DEBUG", - ) - except Exception: - pass - else: - # 高价值房间回访未开启时,不读取标题以避免不必要的截图 - current_room_title = str( - getattr(analyser, "current_room_title", "") or "" - ) - current_room_title_raw = str( - getattr(analyser, "current_room_title_raw", "") or "" - ) - except Exception as e: - try: - analyser._log_kv( - "预约", - "读取当前直播间标题失败", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass +def basic_join_decision(analyser, detail): # noqa: F811 — 兼容性 re-export + """[兼容] 已迁移到 douyin.fudai.core.fudai_filter。""" + from douyin.fudai.core.fudai_filter import basic_join_decision as _impl - # 执行筛选检查 - if skip_result is not None: - skip, reason = skip_result - else: - skip, reason = should_skip_fudai_by_config(analyser, detail) - - # 记录原始筛选结果,避免后续分支覆盖后丢失上下文 - orig_skip = bool(skip) - orig_skip_reason = str(reason or "") - - # 特殊处理:如果被倒计时过滤筛掉(倒计时大于阈值),但价值达到高价值阈值 - # 需要检查剩余秒数是否在"预约参与阈值"内,如果在阈值内则立即参与,否则记录预约 - # 注意:如果是观看任务,不应该进入这个特殊处理逻辑(should_skip_fudai_by_config 已经返回 watch_task_detected) - if skip and reason.startswith("countdown_gt_") and is_high_value: - # 再次检查是否是观看任务(双重保险) - is_watch_task = False - try: - is_watch_task = is_watch_task_fudai(content) - if is_watch_task: - # 是观看任务,不记录预约,直接关闭详情页并返回 - try: - analyser._log_kv( - "预约", - "[预约] 特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃", - content=content[:80] if content else "", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - ) - except Exception: - pass - # 关闭详情页 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(观看任务)", - action="close_detail", - ) - except Exception: - pass - # 如果允许切换直播间,切换直播间 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if needswitch: - try: - analyser._log_kv( - "参与", - "basic_join_decision:观看任务后切换直播间", - reason="watch_task", - ) - except Exception: - pass - try: - # 优先使用封装好的上滑切房方法 - try: - # 在调用切换前再次检查:如果当前位置映射已经包含福袋信息, - # 则跳过切换以避免重复/多余的上滑操作(与 SwipeHandler 中的跳过保持一致) - room_pos = int(getattr(analyser, "room_pos", 0) or 0) - room_pos_map = ( - getattr(analyser, "_room_pos_to_title_map", {}) or {} - ) - entry = None - if isinstance(room_pos_map, dict): - entry = ( - room_pos_map.get(room_pos) - if room_pos in room_pos_map - else room_pos_map.get(str(room_pos)) - ) - if isinstance(entry, dict) and bool( - entry.get("has_fudai", False) - ): - try: - analyser._log_kv( - "预约", - "[预约] 切换前检测到当前位置已有福袋信息,跳过切换", - room_pos=room_pos, - ) - except Exception: - pass - else: - if hasattr(analyser, "swipe_up_to_next_live"): - analyser.swipe_up_to_next_live() - else: - # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) - 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 - start_x = 540 * rx // 1080 - start_y = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, - start_x, - start_y, - end_x, - end_y, - 300, - ) - except Exception: - # 如果内部检查或调用失败,尝试直接调用封装方法或兜底 swipe - try: - if hasattr(analyser, "swipe_up_to_next_live"): - analyser.swipe_up_to_next_live() - else: - rx = int( - getattr(analyser, "resolution_ratio_x", 1080) - or 1080 - ) - ry = int( - getattr(analyser, "resolution_ratio_y", 2400) - or 2400 - ) - start_x = 540 * rx // 1080 - start_y = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, - start_x, - start_y, - end_x, - end_y, - 300, - ) - except Exception: - pass - except Exception: - # 切房失败不影响主流程,直接返回 - pass - # 直接返回 False,不参与抽奖 - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(观看任务,已丢弃)", - elapsed_seconds=round(elapsed, 2), - ) - return False - except Exception: - # 如果检查观看任务时出错,记录日志但继续后续处理(容错处理) - pass - - # 计算剩余秒数 - 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 - - # 获取"预约参与阈值"配置 - try: - join_ahead_seconds = int( - getattr(analyser, "high_value_fudai_join_ahead_seconds", 100) or 100 - ) - except Exception: - join_ahead_seconds = 100 - - # 如果剩余秒数在"预约参与阈值"内,则立即参与而不是预约 - if remain_seconds is not None and remain_seconds <= join_ahead_seconds: - if orig_skip: - try: - analyser._log_kv( - "参与", - "basic_join_decision:原始筛选未通过,即使倒计时在阈值内也不参与", - reason=orig_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, - ) - except Exception: - pass - # 保持高价值预约逻辑,不走立即参与 - skip = False - reason = "high_value_reservation" - else: - try: - analyser._log_kv( - "参与", - "basic_join_decision:倒计时在预约参与阈值内,立即参与", - reason=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, - ) - except Exception: - pass - # 不关闭详情,继续走立即参与逻辑 - skip = False - reason = ( - "high_value_immediate_join" - if not force_attend - else "reservation_back_force_attend" - ) - # 如果是强制参与,设置 is_high_value = False,跳过后续的高价值处理逻辑(避免再次记录预约) - # 注意:强制参与标志会在参与成功后清除(在 attend_choujiang 返回后),避免影响后续福袋 - if force_attend: - try: - # 设置 is_high_value = False,跳过后续的高价值处理逻辑 - is_high_value = False - analyser._log_kv( - "参与", - "basic_join_decision:强制参与模式,跳过后续高价值处理逻辑,直接参与", - force_attend=force_attend, - ) - except Exception: - pass - else: - # 剩余秒数大于"预约参与阈值",但在记录预约之前再次检查是否是观看任务 - is_watch_task_check = False - try: - is_watch_task_check = is_watch_task_fudai(content) - if is_watch_task_check: - # 是观看任务,不记录预约,直接关闭详情页并返回 - try: - analyser._log_kv( - "预约", - "[预约] 特殊处理中检测到'观看X分钟'类任务,不记录预约,直接丢弃", - content=content[:80] if content else "", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - ) - except Exception: - pass - # 关闭详情页 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(观看任务)", - action="close_detail", - ) - except Exception: - pass - # 如果允许切换直播间,切换直播间 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if needswitch: - try: - analyser._log_kv( - "参与", - "basic_join_decision:观看任务后切换直播间", - reason="watch_task", - ) - except Exception: - pass - try: - # 优先使用封装好的上滑切房方法 - if hasattr(analyser, "swipe_up_to_next_live"): - analyser.swipe_up_to_next_live() - else: - # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) - 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 - start_x = 540 * rx // 1080 - start_y = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, - start_x, - start_y, - end_x, - end_y, - 300, - ) - except Exception: - # 切房失败不影响主流程,直接返回 - pass - # 直接返回 False,不参与抽奖 - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(观看任务,已丢弃)", - elapsed_seconds=round(elapsed, 2), - ) - return False - except Exception: - # 如果检查观看任务时出错,记录日志但继续后续处理(容错处理) - pass - - # 剩余秒数大于"预约参与阈值",记录预约 - try: - analyser._log_kv( - "参与", - "basic_join_decision:倒计时大于阈值,但价值达到高价值阈值,记录预约", - reason=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, - ) - except Exception: - pass - # 不关闭详情,继续走预约逻辑 - skip = False - reason = "high_value_reservation" - - if skip: - try: - analyser._log_kv( - "参与", - "basic_join_decision:按配置丢弃福袋", - reason=reason, - ) - except Exception: - pass - # 丢弃时,尽量关闭详情,避免停留在详情页 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", "basic_join_decision:已关闭详情", action="close_detail" - ) - except Exception: - pass - - # 如果允许切换直播间,筛选不通过直接切换直播间 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if needswitch: - try: - analyser._log_kv( - "参与", "basic_join_decision:丢弃后切换直播间", reason=reason - ) - except Exception: - pass - try: - # 优先使用封装好的上滑切房方法 - if hasattr(analyser, "swipe_up_to_next_live"): - analyser.swipe_up_to_next_live() - else: - # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) - 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 - start_x = 540 * rx // 1080 - start_y = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, start_x, start_y, end_x, end_y, 300 - ) - except Exception: - # 切房失败不影响主流程,直接返回 - pass - - return False - - # 未被筛掉:根据配置决定"直接参与"或"记录为高价值预约" - # 注意:content, prize_value_yuan, countdown_tuple, future_ts, high_value_enabled, high_value_threshold, is_high_value 已在前面提取 - # 仅当启用高价值预约、识别到价值且未来时间合理时,才考虑记入预约队列 - if is_high_value: - # 添加调试日志:进入高价值处理逻辑 - try: - analyser._log_kv( - "预约", - "basic_join_decision:进入高价值处理逻辑", - prize_value_yuan=prize_value_yuan, - future_ts=future_ts, - content=content[:50] if content else "", - ) - except Exception: - pass - - # 价值达到高价值阈值:检查剩余秒数,如果在"预约参与阈值"内则立即参与,否则记录预约 - # 计算剩余秒数 - 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 - - # 添加调试日志:剩余秒数计算结果 - try: - analyser._log_kv( - "预约", - "basic_join_decision:剩余秒数计算结果", - countdown_tuple=countdown_tuple, - remain_seconds=remain_seconds, - now=int(time.time()), - ) - except Exception: - pass - - # 获取"预约参与阈值"配置(high_value_fudai_join_ahead_seconds) - # 如果剩余秒数 <= 这个阈值,立即参与;否则记录预约 - try: - join_ahead_seconds = int( - getattr(analyser, "high_value_fudai_join_ahead_seconds", 100) or 100 - ) - except Exception: - join_ahead_seconds = 100 - - # 如果剩余秒数在"预约参与阈值"内(<= 阈值),立即参与而不是记录预约 - if remain_seconds is not None and remain_seconds <= join_ahead_seconds: - if orig_skip: - try: - analyser._log_kv( - "参与", - "basic_join_decision:原始筛选未通过,高价值不走立即参与", - reason=orig_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, - ) - except Exception: - pass - else: - try: - analyser._log_kv( - "参与", - "basic_join_decision:价值达到高价值阈值,剩余秒数在预约参与阈值内,立即参与", - 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, - ) - except Exception: - pass - # 不记录预约,继续执行后续的立即参与逻辑 - is_high_value = False - else: - # 剩余秒数大于"预约参与阈值",记录预约 - try: - analyser._log_kv( - "预约", - "basic_join_decision:价值达到高价值阈值,剩余秒数大于预约参与阈值,准备记录预约", - 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, - ) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:价值达到高价值阈值,但剩余秒数大于预约参与阈值,记录预约", - 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, - ) - except Exception: - pass - - if is_high_value: - # 价值达到高价值阈值且剩余秒数大于阈值:记录预约而不是立即参与 - # 在记录预约之前,先检查是否是观看任务 - is_watch_task = False - try: - is_watch_task = is_watch_task_fudai(content) - if is_watch_task: - # 是观看任务,不记录预约,直接关闭详情页并返回 - try: - analyser._log_kv( - "预约", - "[预约] 检测到'观看X分钟'类任务,不记录预约,直接丢弃", - content=content[:80] if content else "", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - ) - except Exception: - pass - # 关闭详情页 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(观看任务)", - action="close_detail", - ) - except Exception: - pass - # 如果允许切换直播间,切换直播间 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if needswitch: - try: - analyser._log_kv( - "参与", - "basic_join_decision:观看任务后切换直播间", - reason="watch_task", - ) - except Exception: - pass - try: - # 优先使用封装好的上滑切房方法 - if hasattr(analyser, "swipe_up_to_next_live"): - analyser.swipe_up_to_next_live() - else: - # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) - 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 - start_x = 540 * rx // 1080 - start_y = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, - start_x, - start_y, - end_x, - end_y, - 300, - ) - except Exception: - # 切房失败不影响主流程,直接返回 - pass - # 直接返回 False,不参与抽奖 - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(观看任务,已丢弃)", - elapsed_seconds=round(elapsed, 2), - ) - return False - except Exception as e_inner: - # 如果检查观看任务时出错,记录日志但继续后续检查(容错处理) - try: - analyser._log_kv( - "预约", - "[预约] 检查观看任务时出错,继续后续检查", - error=str(e_inner), - error_type=type(e_inner).__name__, - ) - except Exception: - pass - - # 在记录预约之前,先检查福袋内容是否在黑名单中 - try: - # 检查内容是否命中黑名单 - content_hit_blacklist = check_contain(analyser, content) - if content_hit_blacklist: - # 命中黑名单,不记录预约,直接关闭详情页并返回 - try: - analyser._log_kv( - "预约", - "[预约] 福袋内容命中黑名单,不记录预约,直接丢弃", - content=content[:80] if content else "", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - ) - except Exception: - pass - # 关闭详情页 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(命中黑名单)", - action="close_detail", - ) - except Exception: - pass - # 如果允许切换直播间,切换直播间 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - if needswitch: - try: - analyser._log_kv( - "参与", - "basic_join_decision:命中黑名单后切换直播间", - reason="content_blacklist", - ) - except Exception: - pass - try: - # 优先使用封装好的上滑切房方法 - if hasattr(analyser, "swipe_up_to_next_live"): - analyser.swipe_up_to_next_live() - else: - # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) - 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 - start_x = 540 * rx // 1080 - start_y = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, - start_x, - start_y, - end_x, - end_y, - 300, - ) - except Exception: - # 切房失败不影响主流程,直接返回 - pass - # 直接返回 False,不参与抽奖 - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(命中黑名单,已丢弃)", - elapsed_seconds=round(elapsed, 2), - ) - return False - except Exception as e_inner: - # 如果检查黑名单时出错,记录日志但继续记录预约(容错处理) - try: - analyser._log_kv( - "预约", - "[预约] 检查黑名单时出错,继续记录预约", - error=str(e_inner), - error_type=type(e_inner).__name__, - ) - except Exception: - pass - - if is_high_value: - # 未命中黑名单,继续记录预约 - try: - # 预约抢占最小价值(若配置了,则低于该值的预约不会抢占当前任务) - # 初始化预约队列容器 - reservations = getattr(analyser, "reservations", None) - if reservations is None: - reservations = [] - try: - analyser.reservations = reservations # type: ignore[attr-defined] - except Exception: - pass - else: - # 在已有预约队列的情况下,先立即清理已过期的预约,保证队列始终是“未过期”的 - try: - rl_cleanup = douyin_reservation_logic - - rl_cleanup.cleanup_expired_reservations( - analyser, - reservations, - write_state_callback=None, - ) - except Exception: - pass - - # room_pos:当前直播间位置计数 - try: - room_pos = int(getattr(analyser, "room_pos", 0) or 0) - except Exception: - room_pos = 0 - - # 使用预先读取的直播间标题(避免在可能切换房间后读取到错误的标题) - room_title = current_room_title - room_title_raw = current_room_title_raw - - # 优先使用映射表中刚刚记录的直播间标题(如果存在) - # 这样可以确保高价值预约使用的是当前直播间的正确标题 - try: - room_pos_to_title_map = getattr( - analyser, "_room_pos_to_title_map", {} - ) - if room_pos in room_pos_to_title_map: - map_info = room_pos_to_title_map[room_pos] - if isinstance(map_info, dict): - mapped_title = str(map_info.get("title", "")).strip() - mapped_title_raw = str( - map_info.get("title_raw", "") - ).strip() - if mapped_title: - room_title = mapped_title - room_title_raw = mapped_title_raw - try: - analyser._log_kv( - "预约", - "使用映射表中的直播间标题", - room_pos=room_pos, - room_title=room_title[:50], - room_title_raw=room_title_raw[:50], - ) - except Exception: - pass - except Exception as e: - # 如果从映射表获取失败,继续使用缓存的标题 - try: - analyser._log_kv( - "预约", - "从映射表获取标题失败,使用缓存标题", - error=str(e), - room_pos=room_pos, - ) - except Exception: - pass - - # 记录高价值预约(仅负责入队和写状态,不立即改变当前直播间) - # 使用全局导入的模块(已在文件顶部导入) - # 定义写入状态文件的回调函数(格式与 douyin_reservation.py 中的 write_reservations_state 一致) - def _write_reservation_state() -> None: - try: - import json - from datetime import datetime - - state_path = getattr( - analyser, "_reservations_state_path", None - ) - if not state_path: - # 使用path_config统一路径 - try: - state_path = path_config.get_reservations_path() - except Exception: - # 回退到旧路径(向后兼容) - state_path = os.path.join( - os.path.dirname(__file__), - "state", - "reservations.json", - ) - # 确保目录存在 - os.makedirs(os.path.dirname(state_path), exist_ok=True) - - # 格式化预约队列数据(与 douyin_reservation.py 格式一致) - items = [] - for r in 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), - "task_count": int(r.get("task_count") or 2), - "time_text": str(r.get("time_text") or ""), - "participants": int(r.get("participants") or 0), - "copies": int(r.get("copies") or 0), - } - ) - - # 获取当前直播间标题(用于状态文件) - current_title = str( - getattr(analyser, "current_room_title", "") - or room_title - or "" - ) - current_title_raw = str( - getattr(analyser, "current_room_title_raw", "") - or room_title_raw - or "" - ) - - # 写入完整的状态数据 - data = { - "updated_ts": time.time(), - "reason": "record_reservation", - "room_pos": int(room_pos), - "current_room_title": current_title, - "current_room_title_raw": current_title_raw, - "reservations": items, - } - - with open(state_path, "w", encoding="utf-8") as f: - json.dump(data, f, ensure_ascii=False, indent=2) - try: - analyser._log_kv( - "预约", - "已写入预约队列状态文件", - path=state_path, - queue_len=( - len(reservations) - if reservations is not None - else 0 - ), - ) - except Exception: - pass - except Exception as e_inner: - try: - analyser._log_kv( - "预约", - "写入预约队列状态文件失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - ) - except Exception: - pass - - # 记录高价值直播间(在记录预约之前) - try: - from douyin.other import douyin_high_value_room - - if hasattr(douyin_high_value_room, "touch_high_value_room"): - douyin_high_value_room.touch_high_value_room( # type: ignore[attr-defined] - analyser=analyser, - title_norm=room_title, - title_raw=room_title_raw, - prize_value_yuan=prize_value_yuan, - reason="reservation", - increment=True, - content=content, - pos_seen=room_pos, - ) - - # 同时添加到本次运行的高价值房间列表 - try: - current_run_rooms = getattr( - analyser, "_current_run_high_value_rooms", [] - ) - room_info = { - "room_title": room_title, - "room_title_raw": room_title_raw, - "max_prize_value_yuan": prize_value_yuan, - "last_seen_ts": time.time(), - "pos_seen": room_pos, - "seen_count": 1, - } - current_run_rooms.append(room_info) - analyser._current_run_high_value_rooms = ( - current_run_rooms - ) - except Exception: - pass - except Exception: - pass - - # 记录预约,并检查队列是否已满 - queue_full_flag = [False] - - def _add_reservation_with_flag(res_list, item) -> None: - max_reservations = None - try: - max_reservations = int( - getattr( - analyser, "high_value_fudai_max_reservations", 3 - ) - or 3 - ) - except Exception: - max_reservations = 3 - queue_full = ( - douyin_reservation_logic.add_reservation_core_logic( - res_list, - item, - max_reservations=max_reservations, - analyser=analyser, - write_state_callback=_write_reservation_state, - ) - ) - try: - queue_full_flag[0] = bool(queue_full) - except Exception: - pass - - # 检查预约队列中是否已经存在相同的福袋 - existing_reservation = None - try: - if reservations: - for r in reservations: - r_ft = float(r.get("future_ts") or 0.0) - r_content = str(r.get("content") or "") - - # 检查是否是同一个福袋:开奖时间相同且内容相同 - if abs(r_ft - future_ts) < 5.0 and r_content == content: - existing_reservation = r - try: - analyser._log_kv( - "预约", - "basic_join_decision:福袋已在预约队列中,将更新为最新预约", - future_ts=int(future_ts), - content=content[:50] if content else "", - existing_future_ts=int(r_ft), - existing_content=( - r_content[:50] if r_content else "" - ), - ) - except Exception: - pass - break - except Exception as e: - try: - analyser._log_kv( - "预约", - "basic_join_decision:检查重复预约时出错,继续记录", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - - # 如果已经预约过,更新现有预约;否则新增预约 - need_record = True - if existing_reservation is not None: - need_record = False - # 更新现有预约的信息 - try: - existing_reservation.update( - { - "prize_value_yuan": prize_value_yuan, - "content": content, - "future_ts": future_ts, - "pos_seen": room_pos, - "room_title": room_title, - "room_title_raw": room_title_raw, - "updated_ts": time.time(), - } - ) - # 重新排序预约队列 - douyin_reservation_logic._sort_reservations_inplace(reservations) # type: ignore[attr-defined] - # 写入状态文件 - _write_reservation_state() - try: - analyser._log_kv( - "预约", - "basic_join_decision:已更新预约队列中的福袋信息,继续进行决策", - value_yuan=prize_value_yuan, - future_ts=int(future_ts), - room_pos=room_pos, - queue_len=len(reservations), - ) - except Exception: - pass - - # 更新预约成功后,继续进行决策而不是直接返回 - # 设置标志表示预约已更新,后续决策会考虑这个信息 - reservation_updated = True - - # 即使更新预约,也设置标志强制切换,避免循环 - try: - analyser._just_recorded_reservation = True - except Exception: - pass - - # 更新预约后关闭详情页,避免影响后续预约回退 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(更新预约后)", - action="close_detail_after_reservation_update", - ) - except Exception: - pass - - # 更新预约后返回False,触发切换直播间 - return False - - except Exception as e: - try: - analyser._log_kv( - "预约", - "basic_join_decision:更新现有预约失败,继续新增", - error=str(e), - error_type=type(e).__name__, - ) - except Exception: - pass - existing_reservation = None # 强制新增 - need_record = True - - time_text = "" - participants = 0 - copies = 0 - task_count = 2 - try: - # 优先从缓存的福袋详情中获取信息 - cached_detail = getattr( - analyser, "_last_fudai_detail_tuple", None - ) - if ( - cached_detail - and isinstance(cached_detail, tuple) - and len(cached_detail) >= 6 - ): - time_text = str(cached_detail[1] or "") - participants = int(cached_detail[2] or 0) - copies = int(cached_detail[3] or 0) - - # 从阶段检测结果获取任务数量(如果还没有被清除) - task_count_from_stage = getattr( - analyser, "_fudai_detail_task_count_from_stage", None - ) - if task_count_from_stage is not None: - task_count = int(task_count_from_stage or 0) - try: - analyser._log_kv( - "福袋详情", - "douyin_fudai_core:从阶段检测获取任务数量", - log_type="OP", - 任务数量=task_count, - 原始值=task_count_from_stage, - ) - except Exception: - pass - # 清除标志,避免影响后续调用 - analyser._fudai_detail_task_count_from_stage = None - try: - analyser._log_kv( - "福袋详情", - "douyin_fudai_core:清除任务数量标志", - log_type="DEBUG", - ) - except Exception: - pass - else: - # 如果阶段检测结果已被清除,尝试从缓存的详情中获取任务数量 - try: - cached_extra = getattr( - analyser, "_last_fudai_detail_extra", None - ) - if cached_extra and isinstance(cached_extra, dict): - cached_task_count = cached_extra.get("task_count") - if cached_task_count is not None: - task_count = int(cached_task_count or 0) - try: - analyser._log_kv( - "福袋详情", - "douyin_fudai_core:从缓存详情获取任务数量", - log_type="OP", - 任务数量=task_count, - 来源="缓存详情", - ) - except Exception: - pass - else: - # 警告:未获取到任务数量,使用默认值0 - task_count = 0 - try: - analyser._log_kv( - "福袋详情", - "douyin_fudai_core:警告:未从缓存获取任务数量,使用默认值0", - log_type="WARNING", - 可能原因="缓存详情不完整或任务数量缺失", - 建议="检查福袋详情识别是否正常", - ) - except Exception: - pass - else: - # 警告:未获取到任务数量,使用默认值0 - task_count = 0 - try: - analyser._log_kv( - "福袋详情", - "douyin_fudai_core:警告:未从阶段检测获取任务数量,使用默认值0", - log_type="WARNING", - 可能原因="阶段检测未触发或像素检测失败", - 建议="检查点击验证阶段检测是否正常执行", - ) - except Exception: - pass - except Exception as e: - # 获取缓存失败,使用默认值 - task_count = 0 - try: - analyser._log_kv( - "福袋详情", - "douyin_fudai_core:从缓存获取任务数量失败,使用默认值", - error=str(e), - 使用默认值=True, - ) - except Exception: - pass - - # 限制任务数量在合理范围内 - if task_count not in (1, 2, 3): - task_count = 2 - except Exception: - task_count = 2 - - if need_record: - douyin_reservation_logic.record_high_value_reservation( # type: ignore[attr-defined] - analyser=analyser, - fudai_content_text=content, - prize_value_yuan=prize_value_yuan, - lastsecond=0, - future_timestamp=future_ts, - x=0, - needswitch=True, - wait_minutes=0, - post_switch_delay_s=0.0, - room_pos=room_pos, - reservations=reservations, - reservation_focus_until_ts_ref=[ - float( - getattr(analyser, "reservation_focus_until_ts", 0.0) - or 0.0 - ) - ], - close_detail_callback=lambda: None, - swipe_up_switch_callback=lambda: None, - swipe_down_back_callback=lambda: None, - add_reservation_callback=_add_reservation_with_flag, - sort_reservations_callback=lambda: ( - douyin_reservation_logic._sort_reservations_inplace( # type: ignore[attr-defined] - reservations if reservations is not None else [] # type: ignore[arg-type] - ) - ), - write_state_callback=_write_reservation_state, - room_title=room_title, - room_title_raw=room_title_raw, - task_count=task_count, - time_text=time_text, - participants=participants, - copies=copies, - ) - - # 如果队列已满,设置标志以便主循环处理 - if queue_full_flag[0]: - try: - analyser.queue_full_waiting_at_earliest = ( - False # 重置标志,让主循环处理 - ) - except Exception: - pass - - try: - analyser._log_kv( - "预约", - "basic_join_decision:命中高价值阈值,已记录为预约,不立即参与", - value_yuan=prize_value_yuan, - threshold=high_value_threshold, - future_ts=int(future_ts), - room_pos=room_pos, - queue_len=len(reservations), - ) - except Exception: - pass - - # 关闭当前详情,避免长时间停留 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情", - action="close_detail", - ) - except Exception: - pass - - # 记录预约后,切换直播间继续找别的福袋 - # 注意:如果已经在锁定期内(已回退到预约直播间),不应该切换直播间 - try: - needswitch = bool(getattr(analyser, "needswitch", True)) - except Exception: - needswitch = True - - # 检查是否在锁定期内 - in_lock_period = False - try: - focus_until = float( - getattr(analyser, "reservation_focus_until_ts", 0.0) - or 0.0 - ) - now_ts = time.time() - if focus_until > 0 and now_ts < focus_until: - in_lock_period = True - try: - analyser._log_kv( - "预约", - "[预约] 记录预约后:在锁定期内,不切换直播间", - focus_until=int(focus_until), - remain_seconds=int(focus_until - now_ts), - ) - except Exception: - pass - except Exception: - pass - - if needswitch and not in_lock_period: - try: - analyser._log_kv( - "参与", - "basic_join_decision:记录预约后切换直播间", - reason="high_value_reservation", - ) - except Exception: - pass - try: - # 优先使用封装好的上滑切房方法 - if hasattr(analyser, "swipe_up_to_next_live"): - analyser.swipe_up_to_next_live() - else: - # 兜底:直接调用底层 swipe(基于 1080x2400 基准坐标) - 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 - start_x = 540 * rx // 1080 - start_y = 1200 * ry // 2400 - end_x = 540 * rx // 1080 - end_y = 600 * ry // 2400 - analyser.operation.swipe( - analyser.device_id, - start_x, - start_y, - end_x, - end_y, - 300, - ) - except Exception: - # 切房失败不影响主流程,直接返回 - pass - elif in_lock_period: - # 在锁定期内,不切换直播间,但记录日志说明原因 - try: - analyser._log_kv( - "参与", - "basic_join_decision:记录预约后不切换直播间(锁定期内)", - reason="lock_period_active", - ) - except Exception: - pass - - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(记录预约)", - elapsed_seconds=round(elapsed, 2), - ) - - # 记录预约后关闭详情页,避免影响后续预约回退 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - try: - analyser._log_kv( - "参与", - "basic_join_decision:已关闭详情(记录预约后)", - action="close_detail_after_reservation", - ) - except Exception: - pass - - # 设置标志,强制下次 run_once_basic 切换直播间,避免在同一直播间循环 - try: - analyser._just_recorded_reservation = True - except Exception: - pass - - # 记录预约后返回False,触发切换直播间继续找别的福袋 - return False - except Exception as e: - # 若预约逻辑异常:对“倒计时>阈值”的原始筛选场景,避免退化为直接参与 - try: - analyser._log_kv( - "预约", - "basic_join_decision:记录预约时异常", - error=str(e), - error_type=type(e).__name__, - orig_skip=orig_skip, - orig_reason=orig_skip_reason, - ) - except Exception: - pass - if orig_skip and orig_skip_reason.startswith("countdown_gt_"): - try: - analyser._log_kv( - "参与", - "basic_join_decision:原始筛选为倒计时>阈值,预约异常时不参与", - reason=orig_skip_reason, - ) - except Exception: - pass - # 尽量关闭详情页,避免停留 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - return False - # 其它场景保持原行为:退化为直接参与抽奖 - try: - analyser._log_kv( - "预约", - "basic_join_decision:记录预约异常,继续尝试直接参与", - level="WARNING", - ) - except Exception: - pass - - # 默认分支:未进入预约路径或预约失败,直接参与抽奖 - if orig_skip: - try: - analyser._log_kv( - "参与", - "basic_join_decision:原始筛选未通过,放弃参与", - reason=orig_skip_reason, - ) - except Exception: - pass - # 尽量关闭详情页,避免停留 - try: - analyser.click(500, 470) - except Exception: - try: - analyser.operation.click_back(analyser.device_id) - except Exception: - pass - return False - try: - analyser._log_kv("参与", "basic_join_decision:尝试参与抽奖") - except Exception: - pass - - # 获取当前福袋的 future_ts(用于参与成功后从预约队列中移除) - current_future_ts = getattr(analyser, "_current_fudai_future_ts", 0.0) or 0.0 - - result = attend_choujiang(analyser) - - # 更新连续参与失败计数器 - if result: - # 参与成功,重置计数器 - analyser._consecutive_attend_failures = 0 - else: - # 参与失败,增加计数器 - analyser._consecutive_attend_failures = ( - getattr(analyser, "_consecutive_attend_failures", 0) + 1 - ) - - # 如果参与成功,记录参与结果(不再使用已废弃的强制参与标志) - if result: - try: - analyser._log_kv( - "参与", - "basic_join_decision:参与成功", - ) - except Exception: - pass - - # 如果参与成功,从预约队列中移除该预约(如果存在) - if result and current_future_ts > 0: - try: - reservations = getattr(analyser, "reservations", None) - if ( - reservations - and isinstance(reservations, list) - and len(reservations) > 0 - ): - # 查找并移除匹配的预约(通过 future_ts 匹配,允许5秒误差) - removed_count = 0 - remaining_reservations = [] - for res in reservations: - try: - res_future_ts = float(res.get("future_ts") or 0.0) - if ( - res_future_ts > 0 - and abs(res_future_ts - current_future_ts) <= 5.0 - ): - # 匹配的预约,移除 - removed_count += 1 - analyser._log_kv( - "预约", - "[预约] 参与成功,从预约队列中移除该预约", - future_ts=int(res_future_ts), - value_yuan=res.get("prize_value_yuan", 0), - content=( - res.get("content", "")[:50] - if res.get("content") - else "" - ), - ) - else: - # 保留不匹配的预约 - remaining_reservations.append(res) - except Exception: - # 如果解析预约项时出错,保留该项(容错处理) - remaining_reservations.append(res) - - if removed_count > 0: - analyser.reservations = remaining_reservations - # 写入预约状态(供 GUI/Web 端查看) - # 使用内联的写入逻辑(与 _write_reservation_state 类似,但需要适配当前作用域) - try: - import json - from datetime import datetime - - state_path = getattr(analyser, "_reservations_state_path", None) - if not state_path: - # 使用path_config统一路径 - try: - state_path = path_config.get_reservations_path() - except Exception: - # 回退到旧路径(向后兼容) - state_path = os.path.join( - os.path.dirname(__file__), - "state", - "reservations.json", - ) - os.makedirs(os.path.dirname(state_path), exist_ok=True) - - # 格式化预约队列数据 - items = [] - for r in remaining_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), - "task_count": int(r.get("task_count") or 2), - "time_text": str(r.get("time_text") or ""), - "participants": int(r.get("participants") or 0), - "copies": int(r.get("copies") or 0), - } - ) - - # 获取当前直播间标题 - current_title = str( - getattr(analyser, "current_room_title", "") or "" - ) - current_title_raw = str( - getattr(analyser, "current_room_title_raw", "") or "" - ) - - # 写入完整的状态数据 - data = { - "updated_ts": time.time(), - "reason": "remove_reservation_after_attend", - "room_pos": 0, - "current_room_title": current_title, - "current_room_title_raw": current_title_raw, - "reservations": items, - } - - with open(state_path, "w", encoding="utf-8") as f: - json.dump(data, f, ensure_ascii=False, indent=2) - try: - analyser._log_kv( - "预约", - "已写入预约队列状态文件(移除预约后)", - path=state_path, - queue_len=len(remaining_reservations), - ) - except Exception: - pass - except Exception as e_inner: - analyser._log_kv( - "预约", - "[预约] 写入预约状态失败", - error=str(e_inner), - error_type=type(e_inner).__name__, - ) - except Exception as e_inner: - analyser._log_kv( - "预约", - "[预约] 从预约队列中移除预约时出错", - error=str(e_inner), - error_type=type(e_inner).__name__, - ) - - elapsed = time.time() - start_time - analyser._log_kv( - "参与", - "basic_join_decision完成(参与抽奖)", - elapsed_seconds=round(elapsed, 2), - result=result, - ) - return result + return _impl(analyser, detail)