diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index c2a80fe..85a4bbf 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -454,7 +454,7 @@ class fudai_analyse: "养号", "_yanghao_recommend_flow skipped - yanghao_enabled=0" ) except Exception: - print("[养号] _yanghao_recommend_flow skipped - yanghao_enabled=0") + logging.info("[养号] _yanghao_recommend_flow skipped - yanghao_enabled=0") return from douyin.other import douyin_yanghao @@ -595,7 +595,7 @@ class fudai_analyse: wait_minutes=wait_minutes, ) except Exception: - print( + logging.warning( f"[DEBUG] entered fudai_choujiang device_id={device_id} wait_minutes={wait_minutes}" ) self.device_id = device_id or self.device_id @@ -625,7 +625,7 @@ class fudai_analyse: error=str(e), ) except Exception: - print( + logging.warning( f"[DEBUG] get_device_resolution attempt {attempt+1} failed: {e}" ) time.sleep(1.0) diff --git a/douyin/handlers/douyin_screenshot_manager.py b/douyin/handlers/douyin_screenshot_manager.py index 67c7369..84d433d 100644 --- a/douyin/handlers/douyin_screenshot_manager.py +++ b/douyin/handlers/douyin_screenshot_manager.py @@ -13,6 +13,33 @@ from __future__ import annotations import os import shutil from typing import Optional, Tuple + +import logging as _logging + +# 模块级 logger:原代码用 print 输出截图管理 / 调试图像清理日志,统一走 logging。 +# 保留消息中已有的 "[截图管理]"/"[调试图像清理]" 前缀,避免改变历史搜索习惯。 +_LOGGER = _logging.getLogger("douyin.handlers.douyin_screenshot_manager") + + +def _mgr_log(msg: str, level: str = "INFO") -> None: + """统一截图管理日志出口;失败兜底 stdout。""" + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + _mgr_log(str(msg)) + except Exception: + pass + + from PIL import Image from douyin.core import path_config import threading @@ -585,7 +612,7 @@ def save_latest_attempt(image: Image.Image, operation_type: str = "") -> bool: return True except Exception as e: try: - print(f"[截图管理] 保存 latest_attempt_{operation_type}.png 失败: {e}") + _mgr_log(f"[截图管理] 保存 latest_attempt_{operation_type}.png 失败: {e}") except Exception: pass return False @@ -608,7 +635,7 @@ def save_last_success(image: Image.Image, operation_type: str = "") -> bool: return True except Exception as e: try: - print(f"[截图管理] 保存 last_success_{operation_type}.png 失败: {e}") + _mgr_log(f"[截图管理] 保存 last_success_{operation_type}.png 失败: {e}") except Exception: pass return False @@ -631,7 +658,7 @@ def save_attempt_from_file(source_path: str, operation_type: str = "") -> bool: return save_latest_attempt(image, operation_type) except Exception as e: try: - print(f"[截图管理] 从文件保存 latest_attempt.png 失败: {e}") + _mgr_log(f"[截图管理] 从文件保存 latest_attempt.png 失败: {e}") except Exception: pass return False @@ -654,7 +681,7 @@ def save_success_from_file(source_path: str, operation_type: str = "") -> bool: return save_last_success(image, operation_type) except Exception as e: try: - print(f"[截图管理] 从文件保存 last_success.png 失败: {e}") + _mgr_log(f"[截图管理] 从文件保存 last_success.png 失败: {e}") except Exception: pass return False @@ -697,7 +724,7 @@ def ensure_debug_captures_dir() -> None: # 其他未知错误 error_type = type(e).__name__ try: - print(f"[截图管理] 创建调试图像目录失败({error_type}): {e}") + _mgr_log(f"[截图管理] 创建调试图像目录失败({error_type}): {e}") except Exception: pass raise @@ -827,7 +854,7 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int: dirs_info.remove(dir_info) except Exception as e: try: - print(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}") + _mgr_log(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}") except Exception: pass @@ -852,7 +879,7 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int: dirs_info.remove(dir_info) except Exception as e: try: - print(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}") + _mgr_log(f"[调试图像清理] 删除目录失败 {dir_info['path']}: {e}") except Exception: pass @@ -870,12 +897,12 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int: reason_parts.append(f"超过{keep_days}天") reason = ",".join(reason_parts) if reason_parts else "自动清理" - print( + _mgr_log( f"[调试图像清理] 已删除 {deleted_count} 个调试图像目录: {', '.join(deleted_dirs)}" ) - print(f"[调试图像清理] 清理原因: {reason}") + _mgr_log(f"[调试图像清理] 清理原因: {reason}") if size_mb > 0.1: # 只显示大于0.1MB的清理 - print(f"[调试图像清理] 释放空间: {size_mb:.2f} MB") + _mgr_log(f"[调试图像清理] 释放空间: {size_mb:.2f} MB") except Exception: pass @@ -883,7 +910,7 @@ def cleanup_debug_captures(keep_days: int = 7, max_files: int = 2000) -> int: except Exception as e: # 清理失败不应影响程序运行 try: - print(f"[调试图像清理] 清理旧调试图像时出错: {e}") + _mgr_log(f"[调试图像清理] 清理旧调试图像时出错: {e}") except Exception: pass return 0 @@ -1152,7 +1179,7 @@ def save_debug_image( # type: ignore if current_count > max_files: # 文件数量超过限制,立即清理 try: - print( + _mgr_log( f"[调试图像清理] 检测到文件数量 {current_count} 超过限制 {max_files},立即清理" ) except Exception: @@ -1308,7 +1335,7 @@ def save_debug_image( # type: ignore except Exception as dir_error: # 记录目录创建失败 try: - print( + _mgr_log( f"[截图管理] 创建目录失败(重试 {attempt + 1}/{max_retries}): {dir_error}" ) except Exception: @@ -1319,14 +1346,14 @@ def save_debug_image( # type: ignore except PermissionError as e: # 权限错误,不重试 try: - print(f"[截图管理] 保存图像权限错误: {path}, 错误: {e}") + _mgr_log(f"[截图管理] 保存图像权限错误: {path}, 错误: {e}") except Exception: pass raise except OSError as e: # 系统级错误(磁盘空间不足等),不重试 try: - print(f"[截图管理] 保存图像系统错误: {path}, 错误: {e}") + _mgr_log(f"[截图管理] 保存图像系统错误: {path}, 错误: {e}") except Exception: pass raise @@ -1622,7 +1649,7 @@ def save_debug_image( # type: ignore # 权限或系统错误,尝试保存原图 try: try: - print(f"[截图管理] 保存标注图像失败,尝试保存原图: {e}") + _mgr_log(f"[截图管理] 保存标注图像失败,尝试保存原图: {e}") except Exception: pass save_image_with_retry(image, file_path) @@ -1633,7 +1660,7 @@ def save_debug_image( # type: ignore # 其他标注错误,尝试保存原图 try: try: - print(f"[截图管理] 图像标注失败,尝试保存原图: {e}") + _mgr_log(f"[截图管理] 图像标注失败,尝试保存原图: {e}") except Exception: pass save_image_with_retry(image, file_path) @@ -1647,21 +1674,21 @@ def save_debug_image( # type: ignore except FileNotFoundError as e: # 文件或目录不存在 try: - print(f"[截图管理] 保存调试图像失败(文件/目录不存在): {e}") + _mgr_log(f"[截图管理] 保存调试图像失败(文件/目录不存在): {e}") except Exception: pass return None except PermissionError as e: # 权限错误 try: - print(f"[截图管理] 保存调试图像失败(权限错误): {e}") + _mgr_log(f"[截图管理] 保存调试图像失败(权限错误): {e}") except Exception: pass return None except OSError as e: # 系统级错误(磁盘空间不足、路径过长等) try: - print(f"[截图管理] 保存调试图像失败(系统错误): {e}") + _mgr_log(f"[截图管理] 保存调试图像失败(系统错误): {e}") except Exception: pass return None @@ -1669,7 +1696,7 @@ def save_debug_image( # type: ignore # 其他未知错误 try: error_type = type(e).__name__ - print(f"[截图管理] 保存调试图像失败({error_type}): {e}") + _mgr_log(f"[截图管理] 保存调试图像失败({error_type}): {e}") except Exception: pass return None diff --git a/douyin/other/douyin_robot.py b/douyin/other/douyin_robot.py index 15789da..b557a01 100644 --- a/douyin/other/douyin_robot.py +++ b/douyin/other/douyin_robot.py @@ -8,6 +8,39 @@ from PIL import Image # type: ignore[import] from douyin.fudai.core.coords import LIVE_VERIFY1, LIVE_VERIFY2, ROBOT_VERIFY from douyin.utils.ocr_preprocess import preprocess_for_ocr # type: ignore +import logging as _logging + +# 模块级日志:优先走 analyser._log_kv,回退到 logging。 +_LOGGER = _logging.getLogger("douyin.other.douyin_robot") + + +def _robot_log(analyser, msg: str, level: str = "INFO") -> None: + """统一人机校验日志出口;失败兜底 stdout。""" + try: + log_kv = getattr(analyser, "_log_kv", None) if analyser is not None else None + if callable(log_kv): + log_kv("人机校验", str(msg), level=str(level or "INFO")) + return + except Exception: + pass + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + print(str(msg)) + except Exception: + pass + + + def _to_rgb_tuple(color: Any) -> tuple[int, int, int]: if isinstance(color, (int, float)): @@ -35,17 +68,17 @@ def check_have_robot_analyse(analyser) -> int | bool: name_live = preprocess_for_ocr(analyser, "直播验证") result = analyser.operation.analyse_pic_word(name_live, 0) if "验证" in result: - print("存在滑动图片人机校验,需要等待完成验证。") + _robot_log(analyser, "存在滑动图片人机校验,需要等待完成验证。") return 1 if "形状相同" in result: - print("存在点击图片人机校验,需要等待完成验证。") + _robot_log(analyser, "存在点击图片人机校验,需要等待完成验证。") return 2 analyser.cut_pic(*LIVE_VERIFY2, "", "直播验证") name_live2 = preprocess_for_ocr(analyser, "直播验证") result = analyser.operation.analyse_pic_word(name_live2) if "开始检测" in result: - print("存在人脸识别人机校验,需要等待完成验证。") + _robot_log(analyser, "存在人脸识别人机校验,需要等待完成验证。") return 3 return False @@ -57,7 +90,7 @@ def deal_swipe_robot_analyse(analyser, distance: int = 400) -> None: else: targetx = 622 * analyser.resolution_ratio_x // 1080 analyser.swipe(222, 1444, targetx, 1444, 300) - print("滑轨滑动{}距离解锁人机验证".format(distance)) + _robot_log(analyser, "滑轨滑动{}距离解锁人机验证".format(distance)) analyser.operation.delay(1) @@ -72,12 +105,12 @@ def deal_robot_analyse(analyser) -> None: analyser.operation.delay(10) analyser._shot_and_diagnose("人机校验", "校验后复查", analyser.device_id) elif robot_result == 2: - print("无法处理图片验证的人机,点击关闭退出验证,等待30分钟") + _robot_log(analyser, "无法处理图片验证的人机,点击关闭退出验证,等待30分钟", level="WARNING") analyser.click(910, 800) # 点击关闭 analyser.operation.delay(1800) break elif robot_result == 3: - print("无法处理人脸识别验证的人机,点击返回退出验证,等待30分钟") + _robot_log(analyser, "无法处理人脸识别验证的人机,点击返回退出验证,等待30分钟", level="WARNING") analyser.operation.click_back(analyser.device_id) analyser.operation.delay(2) analyser.operation.click_back(analyser.device_id) @@ -87,7 +120,7 @@ def deal_robot_analyse(analyser) -> None: break swipe_times += 1 if swipe_times >= 10: - print("无法处理图片验证的人机,点击关闭退出验证,等待30分钟") + _robot_log(analyser, "无法处理图片验证的人机,点击关闭退出验证,等待30分钟", level="WARNING") analyser.click(910, 800) # 点击关闭 analyser.operation.delay(1800) @@ -133,7 +166,7 @@ def check_robot_pic_distance(analyser) -> int: for x in range(5, width - 40): r, g, b = _to_rgb_tuple(img.getpixel((x, y))) if r > 240 and g > 240 and b > 240: - print(x, y) + _robot_log(analyser, f"找到首像素 ({x}, {y})", level="DEBUG") first_x = x first_y = y found_first = True @@ -147,8 +180,8 @@ def check_robot_pic_distance(analyser) -> int: for x1 in range(first_x, width - 40): r, g, b = _to_rgb_tuple(img.getpixel((x1, first_y))) if r < 50 and g < 55 and b < 85 and (r + g + b) < 150: - print(x1, first_y) - print("需要滑动的距离为{}".format(x1 - first_x)) + _robot_log(analyser, f"找到末像素 ({x1}, {first_y})", level="DEBUG") + _robot_log(analyser, "需要滑动的距离为{}".format(x1 - first_x)) return x1 - first_x return 0 diff --git a/douyin/other/douyin_yanghao.py b/douyin/other/douyin_yanghao.py index 1bb81a4..5323d17 100644 --- a/douyin/other/douyin_yanghao.py +++ b/douyin/other/douyin_yanghao.py @@ -11,6 +11,40 @@ cv2: Any = _cv2 import numpy as np +# 模块级日志:优先走 analyser._log_kv,回退到 logging(避免裸 print 散落到 stdout) +import logging as _logging + +_LOGGER = _logging.getLogger("douyin.other.douyin_yanghao") + + +def _yanghao_log(analyser, msg: str, level: str = "INFO") -> None: + """统一养号日志出口。 + + - 当 analyser 提供 `_log_kv` 时,优先用它(与项目统一日志体系一致)。 + - 否则回退到模块 logger;最后兜底到 stdout 以避免静默丢日志。 + """ + try: + log_kv = getattr(analyser, "_log_kv", None) + if callable(log_kv): + log_kv("养号", str(msg), level=str(level or "INFO")) + return + except Exception: + pass + try: + if str(level).upper() == "ERROR": + _LOGGER.error(str(msg)) + elif str(level).upper() == "WARNING": + _LOGGER.warning(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + _yanghao_log(analyser, str(msg)) + except Exception: + pass + + + def _scaled_click(analyser, base_x: int, base_y: int) -> None: """模块级点击封装:根据基准坐标缩放并点击(兼容原嵌套实现)。""" sx, sy = analyser._scale_from_base(int(base_x), int(base_y)) @@ -28,14 +62,14 @@ def _do_comment(analyser) -> None: # 步骤1: 点击评论按钮 btn_x = int(getattr(analyser, "yanghao_comment_btn_x", 540) or 540) btn_y = int(getattr(analyser, "yanghao_comment_btn_y", 2000) or 2000) - print(f"[养号][评论] Step1: 点击评论按钮 coord=({btn_x},{btn_y})") + _yanghao_log(analyser, f"[养号][评论] Step1: 点击评论按钮 coord=({btn_x},{btn_y})") _scaled_click(analyser, btn_x, btn_y) analyser.operation.delay(1.0) # 步骤2: 点击输入框 input_x = int(getattr(analyser, "yanghao_comment_input_x", 144) or 144) input_y = int(getattr(analyser, "yanghao_comment_input_y", 2179) or 2179) - print(f"[养号][评论] Step2: 点击输入框 coord=({input_x},{input_y})") + _yanghao_log(analyser, f"[养号][评论] Step2: 点击输入框 coord=({input_x},{input_y})") _scaled_click(analyser, input_x, input_y) analyser.operation.delay(1.0) @@ -44,7 +78,7 @@ def _do_comment(analyser) -> None: if not comment_texts: comment_texts = ["加油", "不错", "很好看"] selected_text = random.choice(comment_texts) - print(f"[养号][评论] Step3: 选择文本 -> {selected_text}") + _yanghao_log(analyser, f"[养号][评论] Step3: 选择文本 -> {selected_text}") ix, iy = analyser._scale_from_base(input_x, input_y) ok_input = bool( @@ -52,23 +86,23 @@ def _do_comment(analyser) -> None: analyser.device_id, ix, iy, selected_text, ensure_focus=False ) ) - print(f"[养号][评论] paste_text_at -> ok={ok_input} scaled_coord=({ix},{iy})") + _yanghao_log(analyser, f"[养号][评论] paste_text_at -> ok={ok_input} scaled_coord=({ix},{iy})") analyser.operation.delay(1.0) # 步骤4: 发送评论 ok_send = bool(analyser.operation.confirm_from_keyboard(analyser.device_id)) - print(f"[养号][评论] Step4: 发送评论 -> ok={ok_send}") + _yanghao_log(analyser, f"[养号][评论] Step4: 发送评论 -> ok={ok_send}") analyser.operation.delay(1.0) # 步骤5: 关闭评论窗口 close_x = int(getattr(analyser, "yanghao_comment_close_x", 900) or 900) close_y = int(getattr(analyser, "yanghao_comment_close_y", 300) or 300) - print(f"[养号][评论] Step5: 关闭评论窗口 coord=({close_x},{close_y})") + _yanghao_log(analyser, f"[养号][评论] Step5: 关闭评论窗口 coord=({close_x},{close_y})") _scaled_click(analyser, close_x, close_y) analyser.operation.delay(1.0) except Exception as e: - print(f"[养号] 评论操作失败: {e}") + _yanghao_log(analyser, f"[养号] 评论操作失败: {e}") def yanghao_idle(analyser, total_seconds: int) -> None: @@ -120,7 +154,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: y1 = y_mid - int(dist / 2) y2 = y_mid + int(dist / 2) analyser.swipe(x, y1, x, y2, 180) - print( + _yanghao_log(analyser, "[养号] 动作: 下滑/切换 direction={} dist={}px".format( getattr(analyser, "yanghao_after_dwell_swipe_direction", "up"), dist ) @@ -170,33 +204,33 @@ def yanghao_idle(analyser, total_seconds: int) -> None: except Exception: tpl_exists = False - print( + _yanghao_log(analyser, f"[养号] 检测: {action} -> 模板文件={template_path} tpl_exists={tpl_exists}" ) # 真实的模板匹配检测,直接在full screenshot上进行 try: if not tpl_exists or not os.path.exists(str(template_path or "")): - print(f"[养号] {action}: 模板文件不存在,假设图标存在") + _yanghao_log(analyser, f"[养号] {action}: 模板文件不存在,假设图标存在") return True, 1.0 # 使用共享的full screenshot,不做ROI截图 if not shared_screenshot_path or not os.path.exists( shared_screenshot_path ): - print(f"[养号] {action}: 截图文件不存在,假设图标存在") + _yanghao_log(analyser, f"[养号] {action}: 截图文件不存在,假设图标存在") return True, 1.0 # 读取full screenshot pic = cv2.imread(shared_screenshot_path) if pic is None: - print(f"[养号] {action}: 读取截图失败,假设图标存在") + _yanghao_log(analyser, f"[养号] {action}: 读取截图失败,假设图标存在") return True, 1.0 # 读取模板 template = cv2.imread(str(template_path)) if template is None: - print(f"[养号] {action}: 读取模板失败,假设图标存在") + _yanghao_log(analyser, f"[养号] {action}: 读取模板失败,假设图标存在") return True, 1.0 # 灰度化处理 @@ -215,19 +249,19 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) if max_val >= threshold: - print(f"[养号] {action}: 模板匹配成功 (分数={max_val:.3f})") + _yanghao_log(analyser, f"[养号] {action}: 模板匹配成功 (分数={max_val:.3f})") return True, float(max_val) else: - print( + _yanghao_log(analyser, f"[养号] {action}: 模板匹配失败 (分数={max_val:.3f} < {threshold})" ) return False, float(max_val) except Exception as e: - print(f"[养号] {action}: 模板匹配异常 {e},假设图标存在") + _yanghao_log(analyser, f"[养号] {action}: 模板匹配异常 {e},假设图标存在") return True, 1.0 end_ts = time.time() + int(max(1, total_seconds)) - print(f"[养号] 开始养号模式,总时长 {total_seconds}s") + _yanghao_log(analyser, f"[养号] 开始养号模式,总时长 {total_seconds}s") # 连续未检测到任何模板时的自救阈值(超过此次数尝试按返回键一次) consecutive_miss = 0 @@ -285,19 +319,19 @@ def yanghao_idle(analyser, total_seconds: int) -> None: try: if not action_detected: consecutive_miss += 1 - print( + _yanghao_log(analyser, f"[养号] 连续未检测到模板次数={consecutive_miss}/{miss_recover_threshold}" ) else: consecutive_miss = 0 if consecutive_miss >= miss_recover_threshold: - print("[养号] 连续多次未检测到模板,尝试按一次返回键进行自救") + _yanghao_log(analyser, "[养号] 连续多次未检测到模板,尝试按一次返回键进行自救") try: analyser.operation.keyevent(analyser.device_id, 4) analyser.operation.delay(1.0) except Exception as e: - print(f"[养号] 自救按返回键失败: {e}") + _yanghao_log(analyser, f"[养号] 自救按返回键失败: {e}") consecutive_miss = 0 except Exception: # 任何自救逻辑异常都不应影响主循环 @@ -322,7 +356,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: # 跨天区间,例如 23-6 in_quiet = now_h >= start_h or now_h < end_h if in_quiet: - print( + _yanghao_log(analyser, f"[养号] 定时禁抢生效({start_h}:00-{end_h}:00),当前小时={now_h},跳过爱心/收藏/评论" ) # 避免频繁循环,做一次随机短等待再继续 @@ -350,7 +384,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: or "com.ss.android.ugc" in top_pkg ) if top_pkg and not is_douyin_pkg: - print( + _yanghao_log(analyser, f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}" ) try: @@ -407,11 +441,11 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) analyser.operation.delay(2.0) - print("[养号] 自救: 恢复操作完成") + _yanghao_log(analyser, "[养号] 自救: 恢复操作完成") except Exception as e: - print(f"[养号] 自救: 恢复操作失败: {e}") + _yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}") except Exception as e: - print(f"[养号] 自救: 桌面检测异常: {e}") + _yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}") except Exception: pass @@ -429,7 +463,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) did_like = True analyser.operation.delay(1.0) # 延迟1秒 - print( + _yanghao_log(analyser, "[养号] 动作: 点爱心(prob={})".format( getattr(analyser, "yanghao_like_prob", 0) ) @@ -437,9 +471,9 @@ def yanghao_idle(analyser, total_seconds: int) -> None: else: prob = getattr(analyser, "yanghao_like_prob", 0) if like_ok: - print("[养号] 动作: 跳过点爱心(prob={prob})") + _yanghao_log(analyser, f"[养号] 动作: 跳过点爱心(prob={prob})") else: - print("[养号] 动作: 跳过点爱心(未检测到图标)") + _yanghao_log(analyser, "[养号] 动作: 跳过点爱心(未检测到图标)") # 根据概率点击收藏 if ( @@ -455,7 +489,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) did_fav = True analyser.operation.delay(1.0) # 延迟1秒 - print( + _yanghao_log(analyser, "[养号] 动作: 点收藏(prob={})".format( getattr(analyser, "yanghao_fav_prob", 0) ) @@ -463,9 +497,9 @@ def yanghao_idle(analyser, total_seconds: int) -> None: else: prob = getattr(analyser, "yanghao_fav_prob", 0) if fav_ok: - print("[养号] 动作: 跳过点收藏(prob={prob})") + _yanghao_log(analyser, f"[养号] 动作: 跳过点收藏(prob={prob})") else: - print("[养号] 动作: 跳过点收藏(未检测到图标)") + _yanghao_log(analyser, "[养号] 动作: 跳过点收藏(未检测到图标)") # 根据概率评论 # 仅在爱心和收藏都实际触发(都被点击)时才考虑评论 @@ -485,7 +519,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: pass _do_comment(analyser) did_comment = True - print( + _yanghao_log(analyser, "[养号] 动作: 评论(prob={})".format( getattr(analyser, "yanghao_comment_prob", 0) ) @@ -493,9 +527,9 @@ def yanghao_idle(analyser, total_seconds: int) -> None: else: prob = getattr(analyser, "yanghao_comment_prob", 0) if not (did_like and did_fav): - print("[养号] 动作: 跳过评论(爱心/收藏未同时触发)") + _yanghao_log(analyser, "[养号] 动作: 跳过评论(爱心/收藏未同时触发)") else: - print("[养号] 动作: 跳过评论(prob={prob})") + _yanghao_log(analyser, f"[养号] 动作: 跳过评论(prob={prob})") # 只有在实际执行了任意动作(爱心/收藏/评论)时才停留;仅检测到图标但未执行任何动作则直接跳过 if did_like or did_fav or did_comment: @@ -507,14 +541,14 @@ def yanghao_idle(analyser, total_seconds: int) -> None: or 30 ) dwell_time = random.uniform(dwell_min, dwell_max) - print(f"[养号] 检测到动作,停留 {dwell_time:.1f}s") + _yanghao_log(analyser, f"[养号] 检测到动作,停留 {dwell_time:.1f}s") analyser.operation.delay(dwell_time) else: # 每次操作后随机等待,避免行为太机械 _human_delay(2.0, 6.0) except Exception as e: - print(f"[养号] 循环异常: {e}") + _yanghao_log(analyser, f"[养号] 循环异常: {e}") analyser.operation.delay(1) return @@ -537,7 +571,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) if top_pkg and not is_douyin_pkg: - print(f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}") + _yanghao_log(analyser, f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}") # 执行自救操作 try: @@ -569,17 +603,17 @@ def yanghao_idle(analyser, total_seconds: int) -> None: analyser.operation.click(analyser.device_id, enter_x, enter_y) analyser.operation.delay(2.0) - print("[养号] 自救: 恢复操作完成") + _yanghao_log(analyser, "[养号] 自救: 恢复操作完成") return True except Exception as e: - print(f"[养号] 自救: 恢复操作失败: {e}") + _yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}") return False else: return False except Exception as e: - print(f"[养号] 自救: 桌面检测异常: {e}") + _yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}") return False while True: @@ -595,10 +629,10 @@ def yanghao_idle(analyser, total_seconds: int) -> None: try: # 桌面检测与恢复逻辑 if _yanghao_check_and_recover_from_desktop(analyser): - print("[养号] 检测到不在抖音前台,已尝试恢复") + _yanghao_log(analyser, "[养号] 检测到不在抖音前台,已尝试恢复") analyser.operation.delay(1) except Exception as e: - print(f"[养号] 桌面检测异常: {e}") + _yanghao_log(analyser, f"[养号] 桌面检测异常: {e}") # 分段等待(避免一次 sleep 太久,看起来更自然) remaining = int(total_seconds - (time.time() - start_ts)) @@ -633,7 +667,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: y1 = y_mid - int(dist / 2) y2 = y_mid + int(dist / 2) analyser.swipe(x, y1, x, y2, 180) - print( + _yanghao_log(analyser, "[养号] 动作: 下滑/切换 direction={} dist={}px".format( getattr(analyser, "yanghao_after_dwell_swipe_direction", "up"), dist ) @@ -666,7 +700,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) if top_pkg and not is_douyin_pkg: - print(f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}") + _yanghao_log(analyser, f"[养号] 自救: 检测到不在抖音前台,前台包名={top_pkg}") # 执行自救操作 try: @@ -704,17 +738,17 @@ def yanghao_idle(analyser, total_seconds: int) -> None: analyser.operation.click(analyser.device_id, enter_x, enter_y) analyser.operation.delay(2.0) - print("[养号] 自救: 恢复操作完成") + _yanghao_log(analyser, "[养号] 自救: 恢复操作完成") return True except Exception as e: - print(f"[养号] 自救: 恢复操作失败: {e}") + _yanghao_log(analyser, f"[养号] 自救: 恢复操作失败: {e}") return False else: return False except Exception as e: - print(f"[养号] 自救: 桌面检测异常: {e}") + _yanghao_log(analyser, f"[养号] 自救: 桌面检测异常: {e}") return False def _detect_icon( @@ -753,7 +787,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: except Exception: tpl_exists = False - print( + _yanghao_log(analyser, f"[养号][DEBUG] _detect_icon action={action} template_path='{template_path}' tpl_exists={tpl_exists}" ) if int(base_x or 0) <= 0 or int(base_y or 0) <= 0: @@ -823,7 +857,7 @@ def yanghao_idle(analyser, total_seconds: int) -> None: ) # 只截图不识别,总是假设图标存在并返回高置信度 - print(f"[养号] 检测: {action} -> 只截图不识别,假设图标存在") + _yanghao_log(analyser, f"[养号] 检测: {action} -> 只截图不识别,假设图标存在") return True, 1.0 @@ -839,29 +873,29 @@ def yanghao_recommend_flow(analyser, total_seconds: int) -> None: resy = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) except Exception: resx, resy = 1080, 2400 - print(f"设备分辨率为:{resx}*{resy}") - print(f"[YANGHAO-ONLY] device_id={analyser.device_id} res={resx}x{resy}") - print("[养号] 开始推荐页养号流程") + _yanghao_log(analyser, f"设备分辨率为:{resx}*{resy}") + _yanghao_log(analyser, f"[YANGHAO-ONLY] device_id={analyser.device_id} res={resx}x{resy}") + _yanghao_log(analyser, "[养号] 开始推荐页养号流程") # 步骤1: 发送系统返回键退出当前直播间 - print("[养号] 步骤1: 发送系统返回键退出直播间") + _yanghao_log(analyser, "[养号] 步骤1: 发送系统返回键退出直播间") analyser.operation.keyevent(analyser.device_id, 4) # KEYCODE_BACK = 4 analyser.operation.delay(3.0) # 步骤2: 再次发送返回键确保退出 - print("[养号] 步骤2: 再次发送返回键") + _yanghao_log(analyser, "[养号] 步骤2: 再次发送返回键") analyser.operation.keyevent(analyser.device_id, 4) # KEYCODE_BACK = 4 analyser.operation.delay(3.0) # 步骤3: 在推荐页执行养号 - print(f"[养号] 步骤3: 在推荐页养号 {total_seconds} 秒") + _yanghao_log(analyser, f"[养号] 步骤3: 在推荐页养号 {total_seconds} 秒") analyser.operation.delay(3.0) yanghao_idle(analyser, total_seconds) - print("[养号] 推荐页养号流程完成") + _yanghao_log(analyser, "[养号] 推荐页养号流程完成") except Exception as e: - print(f"[养号] 推荐页养号流程失败: {e}") + _yanghao_log(analyser, f"[养号] 推荐页养号流程失败: {e}") # 失败时退化为普通养号 yanghao_idle(analyser, total_seconds) @@ -873,7 +907,7 @@ def yanghao_wait(analyser, total_seconds: int) -> None: # 检查是否启用养号 if not bool(getattr(analyser, "yanghao_enabled", True)): - print("[养号] yanghao_enabled=0,跳过推荐页养号(快速继续)") + _yanghao_log(analyser, "[养号] yanghao_enabled=0,跳过推荐页养号(快速继续)") return # 执行推荐页养号流程 diff --git a/gui/components/log_viewer.py b/gui/components/log_viewer.py index eae9839..3f9bc07 100644 --- a/gui/components/log_viewer.py +++ b/gui/components/log_viewer.py @@ -7,6 +7,7 @@ from __future__ import annotations from typing import Any, Callable, Optional, List, Dict, Tuple +import logging import queue import re import threading @@ -16,6 +17,9 @@ import tkinter as tk from tkinter import ttk from tkinter.scrolledtext import ScrolledText +# 模块级 logger:内部错误(日志线程异常 / 刷新显示异常)走 logging,避免裸 print +_LOGVIEW_LOGGER = logging.getLogger("gui.components.log_viewer") + try: from ttkbootstrap.scrolled import ScrolledText as TBSrolledText ScrolledText = TBSrolledText @@ -230,7 +234,7 @@ class EnhancedLogViewer(ttk.Frame): break except Exception as e: - print(f"日志处理错误: {e}") + _LOGVIEW_LOGGER.exception("日志处理错误: %s", e) time.sleep(0.1) # 避免CPU占用过高 @@ -343,7 +347,7 @@ class EnhancedLogViewer(ttk.Frame): self.log_text.see("end") except Exception as e: - print(f"刷新显示错误: {e}") + _LOGVIEW_LOGGER.exception("刷新显示错误: %s", e) def _insert_colored_line(self, line: str) -> None: """插入带颜色的日志行""" diff --git a/gui/web_gui.py b/gui/web_gui.py index 2e34710..451e99d 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -23,6 +23,32 @@ BASE_DIR = path_config.PROJECT_ROOT CONFIG_PATH = path_config.get_config_path() WEBUI_DIR = path_config.get_webui_dir() +import logging as _logging + +# 模块级 logger:内部错误统一走 logging。 +# 启动横幅和中断消息保留 print(属于交互/CLI 输出,不是日志事件)。 +_LOGGER = _logging.getLogger("gui.web_gui") + + +def _wg_log(msg: str, level: str = "INFO") -> None: + """统一 web_gui 内部错误日志出口;失败兜底 stdout。""" + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + print(str(msg)) + except Exception: + pass + + # CSRF token for POST request protection (local-only server) _CSRF_TOKEN = secrets.token_hex(32) @@ -219,14 +245,14 @@ class ProcRunner: except PermissionError as e: # 权限错误,只输出一次警告避免刷屏 if not self._log_permission_warned: - print(f"[WEB_GUI] 警告:日志文件写入权限错误: {self._log_file_path}") - print(f"[WEB_GUI] 错误详情: {e}") + _wg_log(f"[WEB_GUI] 警告:日志文件写入权限错误: {self._log_file_path}", level="WARNING") + _wg_log(f"[WEB_GUI] 错误详情: {e}", level="WARNING") self._log_permission_warned = True except Exception as e: # 其他文件写失败不应影响主流程,但记录第一次错误以便调试 if not self._log_write_error_warned: - print(f"[WEB_GUI] 警告:日志文件写入失败: {self._log_file_path}") - print(f"[WEB_GUI] 错误详情: {e}") + _wg_log(f"[WEB_GUI] 警告:日志文件写入失败: {self._log_file_path}", level="WARNING") + _wg_log(f"[WEB_GUI] 错误详情: {e}", level="WARNING") self._log_write_error_warned = True def _inc(self, key: str, n: int = 1) -> None: @@ -1728,7 +1754,7 @@ class Handler(BaseHTTPRequestHandler): except FileNotFoundError: self.send_error(HTTPStatus.NOT_FOUND) except Exception as e: - print(f"[WEB_GUI] Error serving static file {rel_path}: {e}") + _wg_log(f"[WEB_GUI] Error serving static file {rel_path}: {e}", level="ERROR") self.send_error(HTTPStatus.INTERNAL_SERVER_ERROR) def do_GET(self): @@ -1738,6 +1764,16 @@ class Handler(BaseHTTPRequestHandler): # 提供 CSRF token 给前端 if u.path == "/api/csrf-token": return self._send_json({"token": _CSRF_TOKEN}) + if u.path == "/api/version": + try: + from version import APP_VERSION, APP_BUILD_DATE, APP_NAME + except Exception: + APP_VERSION, APP_BUILD_DATE, APP_NAME = "?", "?", "douyin_guaji" + return self._send_json({ + "name": APP_NAME, + "version": str(APP_VERSION).lstrip("Vv"), + "build": APP_BUILD_DATE, + }) if u.path == "/api/devices": adb = find_adb_executable() return self._send_json({"adb": adb, "devices": list_adb_devices(adb)}) @@ -1792,8 +1828,9 @@ class Handler(BaseHTTPRequestHandler): except Exception as e: import traceback - print( - f"[WEB_GUI] logs search error: {e}\n{traceback.format_exc()}" + _wg_log( + f"[WEB_GUI] logs search error: {e}\n{traceback.format_exc()}", + level="ERROR", ) return self._send_json( {"next": 0, "lines": [], "running": RUNNER.is_running()} @@ -1818,8 +1855,9 @@ class Handler(BaseHTTPRequestHandler): # 记录错误但不中断请求,返回空日志 import traceback - print( - f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}" + _wg_log( + f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}", + level="ERROR", ) return self._send_json( {"next": 0, "lines": [], "running": RUNNER.is_running()} diff --git a/operations/ocr_operations.py b/operations/ocr_operations.py index 028ed20..45ccfad 100644 --- a/operations/ocr_operations.py +++ b/operations/ocr_operations.py @@ -24,6 +24,33 @@ cpu_count = os_module.cpu_count() or 4 optimal_omp_threads = min(4, max(2, cpu_count // 3)) os.environ.setdefault("OMP_NUM_THREADS", str(optimal_omp_threads)) +import logging as _logging + +# 模块级 logger:原代码用 print 输出 OCR 引擎初始化日志,统一走 logging。 +# 保留消息中已有的 "[OCR]" 前缀,避免改变历史搜索习惯。 +_LOGGER = _logging.getLogger("operations.ocr_operations") + + +def _ocr_log(msg: str, level: str = "INFO") -> None: + """统一 OCR 操作日志出口;失败兜底 stdout。""" + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + _ocr_log(str(msg)) + except Exception: + pass + + + class OCRProcessor: """OCR处理器类""" @@ -63,10 +90,10 @@ class OCRProcessor: ) self.ocr_type = "easyocr" - print(f"[OCR] 使用 EasyOCR(CPU模式)") + _ocr_log(f"[OCR] 使用 EasyOCR(CPU模式)") except Exception as e: # EasyOCR初始化失败,回退到PaddleOCR - print(f"[OCR] EasyOCR初始化失败: {e},回退到PaddleOCR") + _ocr_log(f"[OCR] EasyOCR初始化失败: {e},回退到PaddleOCR") devnull = None try: devnull = open(os.devnull, "w") @@ -87,8 +114,8 @@ class OCRProcessor: use_textline_orientation=False, ) self.ocr_type = "paddleocr" - print(f"[OCR] EasyOCR不可用,使用 PaddleOCR(CPU模式)") - print( + _ocr_log(f"[OCR] EasyOCR不可用,使用 PaddleOCR(CPU模式)") + _ocr_log( f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr" ) except Exception: @@ -124,7 +151,7 @@ class OCRProcessor: ) self.ocr_type = "easyocr" gpu_status = "CPU模式" - print(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})") + _ocr_log(f"[OCR] 延迟初始化:使用 EasyOCR({gpu_status})") except Exception: # EasyOCR失败,回退到PaddleOCR try: @@ -154,9 +181,9 @@ class OCRProcessor: use_textline_orientation=False, ) self.ocr_type = "paddleocr" - print(f"[OCR] 延迟初始化:EasyOCR不可用,使用 PaddleOCR(CPU模式)") + _ocr_log(f"[OCR] 延迟初始化:EasyOCR不可用,使用 PaddleOCR(CPU模式)") except Exception as e: - print(f"[OCR] OCR引擎初始化失败: {e}") + _ocr_log(f"[OCR] OCR引擎初始化失败: {e}") self.ocr = None self.ocr_type = None finally: diff --git a/operations/scrcpy_screenshot.py b/operations/scrcpy_screenshot.py deleted file mode 100644 index 5aab0d7..0000000 --- a/operations/scrcpy_screenshot.py +++ /dev/null @@ -1,100 +0,0 @@ -"""使用 scrcpy server 模式进行截图(高性能替代方案) - -scrcpy 通过 server 模式可以实现比 adb screencap 更快的截图速度。 -""" - -from __future__ import annotations - -import os -import subprocess -import time -import tempfile -from typing import Optional -from datetime import datetime - -from operations.screenshot_operations import ScreenshotOperations - - -class ScrcpyScreenshot: - """使用 scrcpy server 进行截图""" - - def __init__(self): - self._scrcpy_path: Optional[str] = None - self._server_path: Optional[str] = None - self._find_scrcpy() - - def _find_scrcpy(self): - """查找 scrcpy 可执行文件""" - import shutil - - # 先检查 PATH - which_path = shutil.which('scrcpy') - if which_path: - self._scrcpy_path = which_path - return - - # 检查常见安装位置 - candidates = [ - os.path.join(os.getenv('LOCALAPPDATA', ''), 'Programs', 'scrcpy', 'scrcpy.exe'), - os.path.join(os.getenv('USERPROFILE', ''), 'AppData', 'Local', 'Programs', 'scrcpy', 'scrcpy.exe'), - r'C:\Program Files\scrcpy\scrcpy.exe', - r'C:\Program Files (x86)\scrcpy\scrcpy.exe', - ] - - for path in candidates: - if path and os.path.exists(path): - self._scrcpy_path = path - # server 文件通常在同一目录 - server_path = os.path.join(os.path.dirname(path), 'scrcpy-server') - if os.path.exists(server_path): - self._server_path = server_path - break - - def is_available(self) -> bool: - """检查 scrcpy 是否可用""" - return self._scrcpy_path is not None and os.path.exists(self._scrcpy_path) - - def get_screenshot(self, device_id: str, output_path: str) -> bool: - """使用 scrcpy 进行截图 - - 注意:scrcpy 本身不直接支持单次截图,这里使用变通方法: - 1. 启动 scrcpy server(如果支持) - 2. 或使用 scrcpy 的录制功能提取帧 - - 参数: - device_id: 设备ID - output_path: 输出文件路径 - - 返回: - 是否成功 - """ - if not self.is_available(): - return False - - timetag = datetime.now().strftime("%H:%M:%S") - start_time = time.time() - - try: - # 方法1: 使用 scrcpy 的 --record 功能(需要停止机制,较复杂) - # 方法2: 使用 scrcpy server 模式(推荐,但需要额外配置) - # 方法3: 回退到 adb screencap(当前实现) - - # 由于 scrcpy 不直接支持单次截图,这里先记录日志 - # 实际实现需要集成 scrcpy server 或使用第三方库 - print(f"[{timetag}] [scrcpy] 注意: scrcpy 不直接支持单次截图") - print(f"[{timetag}] [scrcpy] 需要使用 scrcpy server 模式或集成到截图流程") - - # 暂时回退到标准截图方法 - ops = ScreenshotOperations() - return ops._get_screenshot_direct(device_id, os.path.dirname(output_path)) - - except Exception as e: - elapsed = (time.time() - start_time) * 1000 - print(f"[{timetag}] [scrcpy] 截图失败: {e},耗时: {elapsed:.0f}ms") - return False - - -def get_scrcpy_screenshot(device_id: str, output_path: str) -> bool: - """获取 scrcpy 截图(便捷函数)""" - scrcpy = ScrcpyScreenshot() - return scrcpy.get_screenshot(device_id, output_path) diff --git a/operations/screenshot_operations.py b/operations/screenshot_operations.py index 26d49cc..8814228 100644 --- a/operations/screenshot_operations.py +++ b/operations/screenshot_operations.py @@ -19,6 +19,33 @@ from douyin.core.underlying_operations import _safe_replace_file, _mirror_screen _last_service_fallback_log_ts: float = 0.0 _SERVICE_FALLBACK_LOG_INTERVAL = 10.0 # seconds +import logging as _logging + +# 模块级 logger:原代码用 print 输出截图操作日志,统一走 logging。 +# 保留消息中已有的 "[截图]"/"[截图操作]" 前缀,避免改变历史搜索习惯。 +_LOGGER = _logging.getLogger("operations.screenshot_operations") + + +def _ops_log(msg: str, level: str = "INFO") -> None: + """统一截图操作日志出口;失败兜底 stdout。""" + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + _ops_log(str(msg)) + except Exception: + pass + + + class ScreenshotOperations: """截图操作类""" @@ -68,7 +95,7 @@ class ScreenshotOperations: global _last_service_fallback_log_ts if now - _last_service_fallback_log_ts > _SERVICE_FALLBACK_LOG_INTERVAL: timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图操作] 后台服务未提供有效截图,回退到直接截图") + _ops_log(f"[{timetag}] [截图操作] 后台服务未提供有效截图,回退到直接截图") _last_service_fallback_log_ts = now return self._get_screenshot_direct(device_id, path) except Exception: @@ -77,7 +104,7 @@ class ScreenshotOperations: except Exception as e: # 服务不可用时,回退到直接截图 timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图操作] ⚠️ 服务模式失败,回退到直接截图: {e}") + _ops_log(f"[{timetag}] [截图操作] ⚠️ 服务模式失败,回退到直接截图: {e}") # 原有的直接截图逻辑(保持向后兼容) return self._get_screenshot_direct(device_id, path) @@ -185,11 +212,11 @@ class ScreenshotOperations: t_exec_end = time.time() exec_ms = (t_exec_end - t_exec_start) * 1000 timetag2 = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms (device_id={device_id})") + _ops_log(f"[{timetag2}] [DEBUG] exec-out duration: {exec_ms:.0f}ms (device_id={device_id})") except subprocess.TimeoutExpired: # Popen 超时,记录并重新抛出异常 - print(f"[截图] exec-out 流式读取超时") + _ops_log(f"[截图] exec-out 流式读取超时") raise if _valid_png(tmp_file): # 使用安全的文件替换函数并二次验证目标文件,避免写入截断导致后续读取失败 @@ -198,11 +225,11 @@ class ScreenshotOperations: if _valid_png(out_file): _mirror_screenshot_to_external(out_file) elapsed = (time.time() - direct_start) * 1000 - print(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (exec-out,耗时: {elapsed:.0f}ms)") + _ops_log(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (exec-out,耗时: {elapsed:.0f}ms)") return True else: # 替换后目标文件不完整,记录并尝试回退到 pull - print(f"[{timetag}] [截图] 警告:替换后目标文件不完整,回退到 pull") + _ops_log(f"[{timetag}] [截图] 警告:替换后目标文件不完整,回退到 pull") try: if os.path.exists(out_file): os.remove(out_file) @@ -211,10 +238,10 @@ class ScreenshotOperations: # 不立即返回,继续尝试回退方案 else: # 如果替换失败,但临时文件有效,记录并尝试回退方案 - print(f"[{timetag}] [截图] 文件替换失败,但截图已保存到临时文件,将尝试回退方案") + _ops_log(f"[{timetag}] [截图] 文件替换失败,但截图已保存到临时文件,将尝试回退方案") except subprocess.TimeoutExpired: # 超时异常,记录并继续重试 - print(f"[截图] exec-out 超时,尝试重试或回退方案") + _ops_log(f"[截图] exec-out 超时,尝试重试或回退方案") try: if os.path.exists(tmp_file): os.remove(tmp_file) @@ -223,12 +250,12 @@ class ScreenshotOperations: except subprocess.CalledProcessError as e: # 特殊处理adb错误 if e.returncode == 4294967295: - print(f"[截图] exec-out 异常:设备连接失败或ADB服务异常 (设备ID: {device_id})") + _ops_log(f"[截图] exec-out 异常:设备连接失败或ADB服务异常 (设备ID: {device_id})") else: - print(f"[截图] exec-out 异常:{e}") + _ops_log(f"[截图] exec-out 异常:{e}") except Exception as e: # 继续回退/重试 - print(f"[截图] exec-out 异常:{e}") + _ops_log(f"[截图] exec-out 异常:{e}") try: if os.path.exists(tmp_file): os.remove(tmp_file) @@ -267,30 +294,30 @@ class ScreenshotOperations: shell_ms = (t_shell_end - t_shell_start) * 1000 pull_ms = (t_pull_end - t_pull_start) * 1000 timetag3 = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag3}] [DEBUG] shell_screencap: {shell_ms:.0f}ms, pull: {pull_ms:.0f}ms (device_id={device_id})") + _ops_log(f"[{timetag3}] [DEBUG] shell_screencap: {shell_ms:.0f}ms, pull: {pull_ms:.0f}ms (device_id={device_id})") if _valid_png(tmp_file): # 使用安全的文件替换函数 if _safe_replace_file(tmp_file, out_file): _mirror_screenshot_to_external(out_file) elapsed = (time.time() - direct_start) * 1000 - print(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (回退方案,耗时: {elapsed:.0f}ms)") + _ops_log(f"[{timetag}] [截图] [OK] 获取屏幕截图成功 (回退方案,耗时: {elapsed:.0f}ms)") return True else: - print("[截图] 回退方案文件替换失败") + _ops_log("[截图] 回退方案文件替换失败") return False else: - print("[截图] 回退方案截图无效") + _ops_log("[截图] 回退方案截图无效") return False except subprocess.CalledProcessError as e: # 特殊处理adb错误 if e.returncode == 4294967295: - print(f"[截图] 回退方案失败:设备连接失败或ADB服务异常 (设备ID: {device_id})") + _ops_log(f"[截图] 回退方案失败:设备连接失败或ADB服务异常 (设备ID: {device_id})") else: - print(f"[截图] 回退方案失败:ADB命令错误 (返回码: {e.returncode})") + _ops_log(f"[截图] 回退方案失败:ADB命令错误 (返回码: {e.returncode})") except subprocess.TimeoutExpired: - print(f"[截图] 回退方案失败:操作超时 (设备ID: {device_id})") + _ops_log(f"[截图] 回退方案失败:操作超时 (设备ID: {device_id})") except Exception as e: - print(f"[截图] 回退方案失败:{e}") + _ops_log(f"[截图] 回退方案失败:{e}") return False def _find_pic_path(self, picname: str, for_reading: bool = True) -> Optional[str]: diff --git a/operations/screenshot_service.py b/operations/screenshot_service.py index 67dd842..4ebd3ef 100644 --- a/operations/screenshot_service.py +++ b/operations/screenshot_service.py @@ -17,6 +17,33 @@ from datetime import datetime from douyin.core import path_config from operations.screenshot_operations import ScreenshotOperations +import logging as _logging + +# 模块级 logger:原代码用 print 输出截图服务日志,这里统一走 logging。 +# 保留消息中已有的"[截图服务]"前缀,避免改变历史搜索习惯。 +_LOGGER = _logging.getLogger("operations.screenshot_service") + + +def _svc_log(msg: str, level: str = "INFO") -> None: + """统一截图服务日志出口;失败兜底 stdout 以避免静默丢失。""" + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + _svc_log(str(msg)) + except Exception: + pass + + + class ScreenshotService: """后台截图服务:持续截图,避免主流程等待""" @@ -68,7 +95,7 @@ class ScreenshotService: self._thread.start() self._last_screenshot_time = time.time() - self._cache_valid_duration - 1.0 timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 已启动后台截图服务,设备: {device_id}, 间隔: {interval}秒") + _svc_log(f"[{timetag}] [截图服务] 已启动后台截图服务,设备: {device_id}, 间隔: {interval}秒") def stop(self): """停止后台截图服务""" @@ -80,7 +107,7 @@ class ScreenshotService: if self._thread and self._thread.is_alive(): self._thread.join(timeout=2.0) timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 已停止后台截图服务") + _svc_log(f"[{timetag}] [截图服务] 已停止后台截图服务") def _screenshot_loop(self): """后台截图循环""" @@ -111,22 +138,22 @@ class ScreenshotService: if header == b'\x89PNG': self._last_screenshot_time = time.time() self._last_success = True - print(f"[{timetag}] [截图服务] 后台截图完成 #{loop_count},耗时: {screenshot_elapsed:.0f}ms,文件大小: {file_size/1024:.1f}KB") + _svc_log(f"[{timetag}] [截图服务] 后台截图完成 #{loop_count},耗时: {screenshot_elapsed:.0f}ms,文件大小: {file_size/1024:.1f}KB") else: self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图文件格式错误 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") + _svc_log(f"[{timetag}] [截图服务] 后台截图文件格式错误 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") else: self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图文件太小 #{loop_count} ({file_size}B),耗时: {screenshot_elapsed:.0f}ms") + _svc_log(f"[{timetag}] [截图服务] 后台截图文件太小 #{loop_count} ({file_size}B),耗时: {screenshot_elapsed:.0f}ms") except (OSError, IOError, ValueError) as e: self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图文件验证失败 #{loop_count}: {e},耗时: {screenshot_elapsed:.0f}ms") + _svc_log(f"[{timetag}] [截图服务] 后台截图文件验证失败 #{loop_count}: {e},耗时: {screenshot_elapsed:.0f}ms") else: self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图文件不存在 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") + _svc_log(f"[{timetag}] [截图服务] 后台截图文件不存在 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") else: self._last_success = False - print(f"[{timetag}] [截图服务] 后台截图失败 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") + _svc_log(f"[{timetag}] [截图服务] 后台截图失败 #{loop_count},耗时: {screenshot_elapsed:.0f}ms") # 等待间隔时间,确保不小于0.5秒 remaining_interval = max(0.5, self._screenshot_interval - screenshot_elapsed / 1000) @@ -134,7 +161,7 @@ class ScreenshotService: except Exception as e: try: timetag = datetime.now().strftime("%H:%M:%S") - print(f"[{timetag}] [截图服务] 后台截图异常: {e}") + _svc_log(f"[{timetag}] [截图服务] 后台截图异常: {e}") import traceback traceback.print_exc() except Exception: @@ -156,7 +183,7 @@ class ScreenshotService: # 如果设备ID不同,需要重新启动服务 if self._current_device_id != device_id: - print(f"[{timetag}] [截图服务] 设备ID变更,重新启动服务: {device_id}") + _svc_log(f"[{timetag}] [截图服务] 设备ID变更,重新启动服务: {device_id}") self.start(device_id) # 等待第一次截图完成 time.sleep(0.1) @@ -194,46 +221,46 @@ class ScreenshotService: footer = f.read(read_size) if b'IEND' in footer: elapsed = (time.time() - request_start) * 1000 - print(f"[{timetag}] [截图服务] [OK] 缓存命中,耗时: {elapsed:.1f}ms (距离上次截图: {time_since_last*1000:.0f}ms, 文件大小: {file_size/1024:.1f}KB)") + _svc_log(f"[{timetag}] [截图服务] [OK] 缓存命中,耗时: {elapsed:.1f}ms (距离上次截图: {time_since_last*1000:.0f}ms, 文件大小: {file_size/1024:.1f}KB)") return True elif retry < 2: # 文件可能还在写入,等待一下 time.sleep(0.1) continue else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件不完整(文件尾验证失败),等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件不完整(文件尾验证失败),等待后台截图") except (OSError, IOError) as e: if retry < 2: time.sleep(0.1) continue else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件读取失败: {e},等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件读取失败: {e},等待后台截图") else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件格式错误,等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件格式错误,等待后台截图") break else: if retry < 2: time.sleep(0.05) continue else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件太小 ({file_size}B),等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件太小 ({file_size}B),等待后台截图") except (OSError, IOError) as e: if retry < 2: time.sleep(0.05) continue else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件检查失败: {e},等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件检查失败: {e},等待后台截图") except ValueError as e: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件检查异常: {e},等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件检查异常: {e},等待后台截图") break else: - print(f"[{timetag}] [截图服务] [WARN] 缓存文件不存在,等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存文件不存在,等待后台截图") else: - print(f"[{timetag}] [截图服务] [WARN] 缓存已过期 (距离上次: {time_since_last*1000:.0f}ms > {self._cache_valid_duration*1000:.0f}ms),等待后台截图") + _svc_log(f"[{timetag}] [截图服务] [WARN] 缓存已过期 (距离上次: {time_since_last*1000:.0f}ms > {self._cache_valid_duration*1000:.0f}ms),等待后台截图") # 缓存无效或强制刷新 if force: - print(f"[{timetag}] [截图服务] 🔄 强制刷新,忽略缓存") + _svc_log(f"[{timetag}] [截图服务] 🔄 强制刷新,忽略缓存") # 等待后台截图完成 if self._running: @@ -244,7 +271,7 @@ class ScreenshotService: time_since_last_before_wait = 0 elif time_since_last_before_wait > 86400: time_since_last_before_wait = 10.0 - print(f"[{timetag}] [截图服务] [WAIT] 缓存未命中,等待后台截图 (距离上次: {time_since_last_before_wait*1000:.0f}ms)") + _svc_log(f"[{timetag}] [截图服务] [WAIT] 缓存未命中,等待后台截图 (距离上次: {time_since_last_before_wait*1000:.0f}ms)") # 等待最多6秒,让后台线程完成截图(适应较慢的截图操作) max_wait_time = 6.0 @@ -266,7 +293,7 @@ class ScreenshotService: wait_elapsed = (time.time() - wait_start) * 1000 total_elapsed = (time.time() - request_start) * 1000 status = "[OK]" if self._last_success else "[FAIL]" - print(f"[{timetag}] [截图服务] {status} 后台截图完成,等待耗时: {wait_elapsed:.1f}ms,总耗时: {total_elapsed:.1f}ms,文件大小: {file_size/1024:.1f}KB") + _svc_log(f"[{timetag}] [截图服务] {status} 后台截图完成,等待耗时: {wait_elapsed:.1f}ms,总耗时: {total_elapsed:.1f}ms,文件大小: {file_size/1024:.1f}KB") return self._last_success # 文件尾验证失败,继续等待 # 文件太小或格式错误,继续等待 @@ -277,7 +304,7 @@ class ScreenshotService: # 等待超时 wait_elapsed = (time.time() - wait_start) * 1000 - print(f"[{timetag}] [截图服务] [TIMEOUT] 等待超时 ({wait_elapsed:.1f}ms),回退到直接截图") + _svc_log(f"[{timetag}] [截图服务] [TIMEOUT] 等待超时 ({wait_elapsed:.1f}ms),回退到直接截图") # 如果后台服务未运行或等待超时,直接执行截图(禁用服务模式,避免递归) direct_start = time.time() @@ -285,7 +312,7 @@ class ScreenshotService: direct_elapsed = (time.time() - direct_start) * 1000 total_elapsed = (time.time() - request_start) * 1000 status = "[OK]" if result else "[FAIL]" - print(f"[{timetag}] [截图服务] {status} 直接截图完成,耗时: {direct_elapsed:.0f}ms,总耗时: {total_elapsed:.1f}ms") + _svc_log(f"[{timetag}] [截图服务] {status} 直接截图完成,耗时: {direct_elapsed:.0f}ms,总耗时: {total_elapsed:.1f}ms") return result def is_running(self) -> bool: diff --git a/tools/diagnostics/check_web_gui_config_sync.py b/tools/diagnostics/check_web_gui_config_sync.py index 8f83d84..bbca2b2 100644 --- a/tools/diagnostics/check_web_gui_config_sync.py +++ b/tools/diagnostics/check_web_gui_config_sync.py @@ -19,10 +19,10 @@ import re import sys from pathlib import Path -ROOT = Path(__file__).resolve().parents[1] +ROOT = Path(__file__).resolve().parents[2] GUI_APP = ROOT / "gui" / "gui_app.py" WEB_INDEX = ROOT / "webui" / "index.html" -MANIFEST_PATH = ROOT / "tools" / "web_gui_config_manifest.json" +MANIFEST_PATH = ROOT / "tools" / "dev" / "web_gui_config_manifest.json" IGNORED_CONTAINER_KEYS = { "debug_captures", diff --git a/webui/app.js b/webui/app.js index 2bbf5c7..a12beda 100644 --- a/webui/app.js +++ b/webui/app.js @@ -240,7 +240,9 @@ function initTheme() { btn.addEventListener("click", () => { const next = root.getAttribute("data-theme") === "dark" ? "light" : "dark"; try { localStorage.setItem("ui-theme", next); } catch (_) {} + root.classList.add("isThemeSwitching"); apply(next); + setTimeout(() => root.classList.remove("isThemeSwitching"), 260); }); } @@ -256,16 +258,444 @@ function initTheme() { } } +function ensureToastContainer() { + let c = document.getElementById("toastContainer"); + if (!c) { + c = document.createElement("div"); + c.id = "toastContainer"; + c.className = "toastContainer"; + c.setAttribute("role", "status"); + c.setAttribute("aria-live", "polite"); + document.body.appendChild(c); + } + return c; +} + +function toast(message, kind = "info", { duration = 3500 } = {}) { + if (!message) return; + const container = ensureToastContainer(); + const t = document.createElement("div"); + t.className = `toast toast-${kind}`; + const icon = document.createElement("span"); + icon.className = "toastIcon"; + icon.setAttribute("aria-hidden", "true"); + const ICONS = { + success: '', + error: '', + warn: '', + info: '', + }; + icon.innerHTML = ICONS[kind] || ICONS.info; + const body = document.createElement("div"); + body.className = "toastBody"; + body.textContent = String(message); + const close = document.createElement("button"); + close.className = "toastClose"; + close.type = "button"; + close.setAttribute("aria-label", "关闭"); + close.innerHTML = ''; + t.append(icon, body, close); + container.appendChild(t); + let timer = setTimeout(remove, duration); + function remove() { + if (timer) { clearTimeout(timer); timer = null; } + t.classList.add("isLeaving"); + setTimeout(() => t.remove(), 220); + } + close.addEventListener("click", remove); + t.addEventListener("mouseenter", () => { if (timer) { clearTimeout(timer); timer = null; } }); + t.addEventListener("mouseleave", () => { if (!timer) timer = setTimeout(remove, 1500); }); + return remove; +} + +function initConfigSearch() { + const input = $("configSearch"); + const clear = $("configSearchClear"); + const empty = $("configSearchEmpty"); + if (!input) return; + + // Cache: rows = [.row], with their lower-case search text + parent panel + const rows = Array.from(document.querySelectorAll(".panels .panel .row")); + const rowMeta = rows.map((row) => { + const textParts = []; + row.querySelectorAll(".label, .check span, .hint, span").forEach((el) => { + const t = (el.textContent || "").trim(); + if (t) textParts.push(t); + }); + row.querySelectorAll("input[data-key], select[data-key], textarea[data-key]").forEach((el) => { + if (el.dataset.key) textParts.push(el.dataset.key); + }); + return { row, panel: row.closest(".panel"), text: textParts.join(" ").toLowerCase() }; + }); + + // Section titles: when filtering, hide sections that have no visible row after them + const allSectionTitles = Array.from(document.querySelectorAll(".panels .panel .sectionTitle")); + + const apply = (q) => { + const query = q.trim().toLowerCase(); + if (clear) clear.toggleAttribute("hidden", !query); + const countBadge = document.getElementById("configSearchCount"); + + if (!query) { + // Restore all + rowMeta.forEach(({ row }) => row.classList.remove("isSearchHidden")); + allSectionTitles.forEach((s) => s.classList.remove("isSearchHidden")); + document.querySelectorAll(".panel").forEach((p) => p.classList.remove("isSearchAllHidden")); + if (empty) empty.hidden = true; + if (countBadge) countBadge.hidden = true; + // Re-apply normal tab visibility (panels may have been forced visible) + const activeTab = document.querySelector(".tabBtn.active[data-target]"); + if (activeTab) { + const target = activeTab.dataset.target; + document.querySelectorAll(".panel[data-panel]").forEach((p) => { + const on = p.dataset.panel === target; + p.toggleAttribute("hidden", !on); + p.classList.toggle("active", on); + }); + } + return; + } + + // While searching: show ALL panels (panels normally hide via [hidden]), then filter rows. + document.querySelectorAll(".panel[data-panel]").forEach((p) => { + p.removeAttribute("hidden"); + p.classList.add("active"); + }); + + let totalVisible = 0; + const visibleByPanel = new Map(); + rowMeta.forEach(({ row, panel, text }) => { + const match = text.includes(query); + row.classList.toggle("isSearchHidden", !match); + if (match) { + totalVisible++; + visibleByPanel.set(panel, (visibleByPanel.get(panel) || 0) + 1); + } + }); + + // Hide section titles that have no visible row in their following sibling group + allSectionTitles.forEach((title) => { + let next = title.nextElementSibling; + let anyVisible = false; + while (next && !next.matches(".sectionTitle")) { + if (next.matches(".row") && !next.classList.contains("isSearchHidden")) { anyVisible = true; break; } + next = next.nextElementSibling; + } + title.classList.toggle("isSearchHidden", !anyVisible); + }); + + // Hide panels that have zero visible rows + document.querySelectorAll(".panel[data-panel]").forEach((p) => { + const visible = visibleByPanel.get(p) || 0; + p.toggleAttribute("hidden", visible === 0); + }); + + if (empty) empty.hidden = totalVisible > 0; + if (countBadge) { + countBadge.hidden = false; + countBadge.textContent = `${totalVisible} 项`; + } + }; + + let debounceTimer; + input.addEventListener("input", () => { + clearTimeout(debounceTimer); + debounceTimer = setTimeout(() => apply(input.value), 80); + }); + + if (clear) { + clear.addEventListener("click", () => { + input.value = ""; + apply(""); + input.focus(); + }); + } + + // Platform-aware kbd hint label + const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || ""); + const kbdMod = $("configSearchKbdMod"); + if (kbdMod) kbdMod.textContent = isMac ? "⌘" : "Ctrl"; + + // ⌘K / Ctrl+K to focus, ESC to clear/blur + document.addEventListener("keydown", (e) => { + const mod = isMac ? e.metaKey : e.ctrlKey; + if (mod && e.key.toLowerCase() === "k") { + e.preventDefault(); + input.focus(); + input.select(); + return; + } + if (e.key === "Escape" && document.activeElement === input) { + if (input.value) { + input.value = ""; + apply(""); + } else { + input.blur(); + } + } + }); +} + +function initFooter() { + // 版本号尝试从 /api/version 拿;拿不到就用 cache-bust 标识做 fallback + const verEl = document.getElementById("appFooterVersion"); + const buildEl = document.getElementById("appFooterBuild"); + (async () => { + try { + const data = await apiGet("/api/version"); + if (verEl && data?.version) verEl.textContent = "v" + data.version; + if (buildEl && data?.build) buildEl.textContent = data.build; + } catch (_) { + // fallback:从当前 script 的 cache-bust 提取 + const tag = (document.currentScript?.src || document.querySelector('script[src*="app.js"]')?.src || "") + .split("v=")[1] || ""; + if (verEl) verEl.textContent = tag ? tag.split("-").pop() : "—"; + if (buildEl) buildEl.textContent = "本地"; + } + })(); +} + +function attachCopyButtons() { + // 给指定 statValue 元素绑定一键复制(hover 显示按钮,点击复制文本) + const ids = ["statPid", "statTraceId"]; + for (const id of ids) { + const el = document.getElementById(id); + if (!el || el.dataset.copyBound === "1") continue; + el.dataset.copyBound = "1"; + el.classList.add("hasCopy"); + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = "copyBtn"; + btn.setAttribute("aria-label", "复制"); + btn.setAttribute("data-tooltip", "复制"); + btn.setAttribute("data-tooltip-pos", "bottom"); + btn.innerHTML = ''; + btn.addEventListener("click", async (e) => { + e.stopPropagation(); + const text = (el.textContent || "").trim(); + if (!text || text === "-") { + toast("暂无可复制内容", "warn", { duration: 1800 }); + return; + } + try { + await navigator.clipboard.writeText(text); + toast("已复制:" + (text.length > 24 ? text.slice(0, 24) + "…" : text), "success", { duration: 1800 }); + } catch (err) { + // fallback for non-secure context + const ta = document.createElement("textarea"); + ta.value = text; + ta.style.position = "fixed"; + ta.style.opacity = "0"; + document.body.appendChild(ta); + ta.select(); + try { document.execCommand("copy"); toast("已复制", "success", { duration: 1800 }); } + catch (_) { toast("复制失败", "error", { duration: 2400 }); } + document.body.removeChild(ta); + } + }); + el.appendChild(btn); + } +} + +function initKeyboardShortcuts() { + const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || ""); + document.addEventListener("keydown", (e) => { + const mod = isMac ? e.metaKey : e.ctrlKey; + if (!mod) return; + const key = e.key.toLowerCase(); + // ⌘S / Ctrl+S → 保存配置 + if (key === "s") { + e.preventDefault(); + const btn = document.getElementById("btnSave"); + if (btn && !btn.disabled) btn.click(); + return; + } + // ⌘Enter / Ctrl+Enter → 启动运行 + if (key === "enter") { + e.preventDefault(); + const btn = document.getElementById("btnStart"); + if (btn && !btn.disabled) btn.click(); + return; + } + }); +} + +function initHeaderScroll() { + const header = document.querySelector(".header"); + const scrollTop = document.getElementById("btnScrollTop"); + const onScroll = () => { + if (header) header.classList.toggle("isScrolled", window.scrollY > 8); + if (scrollTop) scrollTop.toggleAttribute("hidden", window.scrollY < 240); + }; + window.addEventListener("scroll", onScroll, { passive: true }); + if (scrollTop) { + scrollTop.addEventListener("click", () => { + window.scrollTo({ top: 0, behavior: "smooth" }); + }); + } + onScroll(); +} + +function initShotFullscreen() { + const btn = document.getElementById("btnShotFullscreen"); + const img = document.getElementById("liveShot"); + if (!btn || !img) return; + btn.addEventListener("click", () => { + const target = img.closest(".preview") || img; + if (document.fullscreenElement) { + document.exitFullscreen?.(); + } else if (target.requestFullscreen) { + target.requestFullscreen().catch(() => { + // fallback:在新标签打开 + window.open(img.src, "_blank", "noopener"); + }); + } else { + window.open(img.src, "_blank", "noopener"); + } + }); +} + +function applyKbdHints() { + // 给 [data-kbd-mod="1"] 的按钮自动注入平台对应的修饰键前缀 + const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || ""); + const prefix = isMac ? "⌘ " : "Ctrl "; + document.querySelectorAll('[data-kbd-mod="1"]').forEach((el) => { + el.setAttribute("data-kbd-prefix", prefix); + }); +} + +function initStickySectionShadow() { + // 当 .sectionTitle 真正贴住 sticky top 时加 .isStuck 类 + const titles = Array.from(document.querySelectorAll(".sectionTitle")) + .filter((el) => !el.matches(".cardTitle, summary, summary *")); + if (!titles.length || !("IntersectionObserver" in window)) return; + const io = new IntersectionObserver( + (entries) => { + for (const e of entries) { + // intersectionRatio < 1 && top 已到达 sentinel:贴住状态 + e.target.classList.toggle("isStuck", e.intersectionRatio < 1 && e.boundingClientRect.top <= 65); + } + }, + { threshold: [1], rootMargin: "-65px 0px 0px 0px" } + ); + titles.forEach((t) => io.observe(t)); +} + +function initShortcutsHelp() { + const isMac = /Mac|iPhone|iPad|iPod/i.test(navigator.platform || navigator.userAgent || ""); + const mod = isMac ? "⌘" : "Ctrl"; + let overlay = null; + const ITEMS = [ + { keys: [mod, "K"], desc: "聚焦配置搜索" }, + { keys: [mod, "S"], desc: "保存配置" }, + { keys: [mod, "Enter"], desc: "开始运行" }, + { keys: ["Esc"], desc: "清空搜索 / 关闭弹层" }, + { keys: ["?"], desc: "显示此帮助" }, + ]; + const open = () => { + if (overlay) return; + overlay = document.createElement("div"); + overlay.className = "shortcutsOverlay"; + overlay.innerHTML = ` + + `; + document.body.appendChild(overlay); + requestAnimationFrame(() => overlay.classList.add("isVisible")); + overlay.addEventListener("click", (e) => { + if (e.target === overlay || e.target.closest(".shortcutsClose")) close(); + }); + }; + const close = () => { + if (!overlay) return; + overlay.classList.remove("isVisible"); + const ref = overlay; + setTimeout(() => { try { ref.remove(); } catch (_) {} }, 160); + overlay = null; + }; + document.addEventListener("keydown", (e) => { + // 输入框聚焦时不拦截 ? 字符 + const inField = /^(INPUT|TEXTAREA|SELECT)$/i.test(document.activeElement?.tagName || ""); + if (e.key === "?" && !inField && !e.metaKey && !e.ctrlKey) { + e.preventDefault(); + overlay ? close() : open(); + return; + } + if (e.key === "Escape" && overlay) { + e.preventDefault(); + close(); + } + }); +} + +function updateTabBadge(target, count) { + const btn = document.querySelector(`.tabBtn[data-target="${target}"]`); + if (!btn) return; + const n = Math.max(0, Number(count) || 0); + if (n > 0) btn.setAttribute("data-badge", n > 99 ? "99+" : String(n)); + else btn.removeAttribute("data-badge"); +} + +function startReservationsCountdownTick() { + // 每秒 tick 更新预约卡倒计时与高亮类,无需等待 stats 轮询 + setInterval(() => { + const items = document.querySelectorAll(".reservationItem[data-future-ts]"); + if (!items.length) return; + const now = Date.now() / 1000; + items.forEach((card) => { + const fut = Number(card.dataset.futureTs) || 0; + if (!fut) return; + const remain = Math.max(0, Math.floor(fut - now)); + const remainEl = card.querySelector(".reservationRemain"); + if (remainEl) { + remainEl.textContent = remain > 0 + ? `${Math.floor(remain / 60)}分${remain % 60}秒后` + : "已到开奖时间"; + } + card.classList.toggle("isImminent", remain > 0 && remain <= 60); + card.classList.toggle("isDue", remain === 0); + }); + }, 1000); +} + function initTabs() { const tabButtons = Array.from(document.querySelectorAll(".tabBtn[data-target]")); const panels = Array.from(document.querySelectorAll(".panel[data-panel]")); + const sideNav = document.querySelector(".sideNav"); if (tabButtons.length === 0 || panels.length === 0) return; + const updateIndicator = (btn) => { + if (!sideNav || !btn || sideNav.offsetParent === null) return; + // 横向布局(移动端 row)下不绘制竖条 + const isRow = getComputedStyle(sideNav).flexDirection !== "column"; + if (isRow) { + sideNav.style.setProperty("--tab-indicator-opacity", "0"); + return; + } + const navRect = sideNav.getBoundingClientRect(); + const btnRect = btn.getBoundingClientRect(); + const top = (btnRect.top - navRect.top) + (btnRect.height - 16) / 2; + sideNav.style.setProperty("--tab-indicator-y", `${top}px`); + sideNav.style.setProperty("--tab-indicator-h", `16px`); + sideNav.style.setProperty("--tab-indicator-opacity", "1"); + }; + const setActive = (target) => { + let activeBtn = null; for (const btn of tabButtons) { const isActive = btn.dataset.target === target; btn.classList.toggle("active", isActive); btn.setAttribute("aria-selected", isActive ? "true" : "false"); + if (isActive) activeBtn = btn; } for (const panel of panels) { const isActive = panel.dataset.panel === target; @@ -273,6 +703,7 @@ function initTabs() { panel.classList.toggle("active", isActive); } document.body.dataset.activePanel = target || ""; + updateIndicator(activeBtn); }; for (const btn of tabButtons) { @@ -281,45 +712,92 @@ function initTabs() { const defaultTarget = tabButtons.find(b => b.classList.contains("active"))?.dataset.target || tabButtons[0].dataset.target; setActive(defaultTarget); + + // 窗口尺寸变化或字体加载完成时重新计算位置 + let resizeTimer; + window.addEventListener("resize", () => { + clearTimeout(resizeTimer); + resizeTimer = setTimeout(() => { + const cur = document.querySelector(".tabBtn.active[data-target]"); + if (cur) updateIndicator(cur); + }, 80); + }); + if (document.fonts && document.fonts.ready) { + document.fonts.ready.then(() => { + const cur = document.querySelector(".tabBtn.active[data-target]"); + if (cur) updateIndicator(cur); + }); + } +} + +function classifyLogLine(line) { + const s = String(line || ""); + if (!s) return ""; + // 错误优先 + if (/\b(ERROR|FATAL|CRITICAL|TRACEBACK|EXCEPTION|FAILED|FAIL\b)\b/i.test(s)) return "logError"; + if (/(失败|错误|异常|未知错误|超时|崩溃)/.test(s)) return "logError"; + if (/❌/.test(s)) return "logError"; + // 警告 + if (/\b(WARN(ING)?)\b/i.test(s)) return "logWarn"; + if (/(警告|注意)/.test(s)) return "logWarn"; + if (/⚠️/.test(s)) return "logWarn"; + // 成功 + if (/\b(SUCCESS|OK|DONE|COMPLETED?)\b/i.test(s)) return "logSuccess"; + if (/(成功|已保存|完成|启动成功)/.test(s)) return "logSuccess"; + if (/(✅|✓)/.test(s)) return "logSuccess"; + // Debug + if (/\b(DEBUG|TRACE)\b/i.test(s)) return "logDebug"; + // INFO 默认 + if (/\b(INFO)\b/i.test(s)) return "logInfo"; + return ""; +} + +function renderLogLineNode(line) { + const cls = classifyLogLine(line); + if (!cls) { + // 普通行:直接文本节点(性能最佳) + return document.createTextNode(String(line ?? "") + "\n"); + } + const span = document.createElement("span"); + span.className = "logLine " + cls; + span.textContent = String(line ?? "") + "\n"; + return span; } function appendLog(lines) { const log = $("runLog"); if (!lines || lines.length === 0) return; - + // 记录更新前与底部的距离,用于在非底部时保持视图位置 const distanceFromBottom = log.scrollHeight - log.scrollTop - log.clientHeight; // 是否严格位于底部(仅在几像素内视为底部),避免每次刷新都跳到底部 const wasAtBottom = distanceFromBottom < UI_LIMITS.scrollBottomThresholdPx; - // 性能优化:批量追加文本,减少重排次数 - const newText = lines.join("\n") + "\n"; // 直接追加到 DOM,同时维护 runLogBuffer 以便支持搜索 - const toAppend = lines; - for (const ln of toAppend) runLogBuffer.push(ln); + for (const ln of lines) runLogBuffer.push(ln); // 限制缓冲 if (runLogBuffer.length > runLogMaxLines) runLogBuffer = runLogBuffer.slice(-runLogMaxLines); // 如果当前处于 run search 结果显示状态,则不改变显示(保持搜索结果不被实时追加打断) if (runSearchActive && runLogMode === 'search') { // 仍保持缓冲更新,但不修改 DOM + } else if (runLogFilter) { + // 有过滤器时重渲染整个视图 + renderRunLog(); } else { - // 如果没有过滤器,直接将文本拼接(性能优先) - if (!runLogFilter) { - log.textContent += newText; - } else { - // 有过滤器时重渲染整个视图 - renderRunLog(); - } + // 批量追加:用 fragment + 行级 span 着色 + const frag = document.createDocumentFragment(); + for (const ln of lines) frag.appendChild(renderLogLineNode(ln)); + log.appendChild(frag); } - + // 性能优化:限制日志长度,避免内存溢出(保留最近较多字符以便桌面端查看) const maxLength = UI_LIMITS.runLogMaxChars; if (log.textContent.length > maxLength) { - // 在截断文本时,保留用户原来的距离(除非用户确实在底部) - log.textContent = log.textContent.slice(-maxLength); + // 直接基于缓冲重渲染(截断到最新行) + runLogBuffer = runLogBuffer.slice(-Math.ceil(runLogMaxLines * 0.6)); + renderRunLog(); if (!wasAtBottom) { - // 调整 scrollTop 保持原先距离 const newScrollTop = log.scrollHeight - log.clientHeight - distanceFromBottom; log.scrollTop = Math.max(0, newScrollTop); } @@ -334,12 +812,21 @@ function appendLog(lines) { function renderRunLog() { const el = $("runLog"); if (!el) return; + const renderInto = (lines) => { + el.textContent = ""; + if (!lines.length) return; + const frag = document.createDocumentFragment(); + for (const ln of lines) frag.appendChild(renderLogLineNode(ln)); + el.appendChild(frag); + }; + // 如果处于搜索结果显示状态,优先显示 search 返回的结果 if (runSearchActive && runLogMode === 'search') { const lines = runSearchResultsBuffer || []; const prevScrollBottom = el.scrollHeight - el.scrollTop - el.clientHeight; - el.textContent = lines.join("\n") + (lines.length ? "\n" : ""); - if (prevScrollBottom < UI_LIMITS.scrollBottomThresholdPx) el.scrollTop = el.scrollHeight; else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); + renderInto(lines); + if (prevScrollBottom < UI_LIMITS.scrollBottomThresholdPx) el.scrollTop = el.scrollHeight; + else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); return; } @@ -349,9 +836,9 @@ function renderRunLog() { lines = runLogBuffer.filter(l => String(l || "").toLowerCase().includes(filter)); } const prevScrollBottom = el.scrollHeight - el.scrollTop - el.clientHeight; - el.textContent = lines.join("\n") + (lines.length ? "\n" : ""); - // 尽量保持原来滚动位置;若位于底部则滚到底部 - if (prevScrollBottom < UI_LIMITS.scrollBottomThresholdPx) el.scrollTop = el.scrollHeight; else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); + renderInto(lines); + if (prevScrollBottom < UI_LIMITS.scrollBottomThresholdPx) el.scrollTop = el.scrollHeight; + else el.scrollTop = Math.max(0, el.scrollHeight - el.clientHeight - prevScrollBottom); } function appendRunLogLines(lines) { @@ -382,6 +869,63 @@ function renderActionsLog() { el.scrollTop = el.scrollHeight; } +function attachNumberSteppers() { + // 给所有 .input[type=number] 包裹 .numStepperWrap + 添加 +/- 按钮 + const SVG_UP = ''; + const SVG_DOWN = ''; + document.querySelectorAll('input.input[type="number"]').forEach((input) => { + if (input.dataset.stepperBound === "1") return; + if (input.closest(".inline2")) return; // inline2 内不加,避免连体边框冲突 + input.dataset.stepperBound = "1"; + const wrap = document.createElement("div"); + wrap.className = "numStepperWrap"; + input.parentNode.insertBefore(wrap, input); + wrap.appendChild(input); + const btns = document.createElement("span"); + btns.className = "numStepperBtns"; + const up = document.createElement("button"); + up.type = "button"; + up.tabIndex = -1; + up.className = "numStepperBtn"; + up.setAttribute("aria-label", "增加"); + up.innerHTML = SVG_UP; + const down = document.createElement("button"); + down.type = "button"; + down.tabIndex = -1; + down.className = "numStepperBtn"; + down.setAttribute("aria-label", "减少"); + down.innerHTML = SVG_DOWN; + btns.append(up, down); + wrap.appendChild(btns); + const fire = (dir) => { + try { dir > 0 ? input.stepUp() : input.stepDown(); } catch (_) {} + input.dispatchEvent(new Event("input", { bubbles: true })); + input.dispatchEvent(new Event("change", { bubbles: true })); + }; + const bindHold = (btn, dir) => { + let holdTimer, repeatTimer; + const cancel = () => { + if (holdTimer) { clearTimeout(holdTimer); holdTimer = null; } + if (repeatTimer) { clearInterval(repeatTimer); repeatTimer = null; } + }; + btn.addEventListener("pointerdown", (e) => { + if (e.button !== 0) return; + e.preventDefault(); + fire(dir); + holdTimer = setTimeout(() => { + repeatTimer = setInterval(() => fire(dir), 80); + }, 500); + }); + btn.addEventListener("pointerup", cancel); + btn.addEventListener("pointerleave", cancel); + btn.addEventListener("pointercancel", cancel); + btn.addEventListener("blur", cancel); + }; + bindHold(up, 1); + bindHold(down, -1); + }); +} + function fmtTime(ts) { if (!ts) return "-"; try { @@ -396,9 +940,10 @@ function fmtDuration(seconds) { const h = Math.floor(s / 3600); const m = Math.floor((s % 3600) / 60); const sec = s % 60; - if (h > 0) return `${h}小时${m}分${sec}秒`; - if (m > 0) return `${m}分${sec}秒`; - return `${sec}秒`; + const pad = (n) => String(n).padStart(2, "0"); + // mono 格式:HH:MM:SS(>1h)/ MM:SS(其他),方便 tabular-nums 对齐 + if (h > 0) return `${pad(h)}:${pad(m)}:${pad(sec)}`; + return `${pad(m)}:${pad(sec)}`; } function pollShot() { @@ -433,7 +978,13 @@ function startShotPolling() { img.addEventListener("load", () => { img.dataset.loading = "false"; if (preview) preview.classList.remove(UI_CLASS.shotEmpty); - if (status) status.textContent = `已更新:${new Date().toLocaleTimeString()}`; + const ts = new Date().toLocaleTimeString(); + if (status) status.textContent = `已更新:${ts}`; + const tsBadge = document.getElementById("liveShotTs"); + if (tsBadge) { + tsBadge.textContent = ts; + tsBadge.hidden = false; + } }); img.addEventListener("error", () => { img.dataset.loading = "false"; @@ -450,7 +1001,49 @@ function startShotPolling() { function setTextIfExists(id, text) { const el = $(id); if (!el) return; - el.textContent = String(text ?? "-"); + const next = String(text ?? "-"); + // 仅取文本节点(跳过子元素如 .copyBtn / .statTrend)来比较和读取当前值 + const getTextOnly = (node) => { + let s = ""; + for (const ch of node.childNodes) if (ch.nodeType === Node.TEXT_NODE) s += ch.textContent; + return s; + }; + const prev = getTextOnly(el); + // 仅对 statValue 有效:值变化时短暂高亮 + 趋势箭头 + if (el.classList.contains("statValue") && prev !== next && next !== "-") { + el.classList.remove("isFlash"); + void el.offsetWidth; + el.classList.add("isFlash"); + setTimeout(() => el.classList.remove("isFlash"), 700); + // 数字字段才显示趋势 + const prevNum = Number(prev); + const nextNum = Number(next); + if (Number.isFinite(prevNum) && Number.isFinite(nextNum) && prevNum !== nextNum) { + let trend = el.querySelector(".statTrend"); + if (!trend) { + trend = document.createElement("span"); + trend.className = "statTrend"; + el.appendChild(trend); + } + const isUp = nextNum > prevNum; + trend.textContent = isUp ? "▲" : "▼"; + trend.classList.toggle("isUp", isUp); + trend.classList.toggle("isDown", !isUp); + trend.classList.remove("isFading"); + void trend.offsetWidth; + trend.classList.add("isFading"); + // 1s 后自动消失 + clearTimeout(trend._fadeTimer); + trend._fadeTimer = setTimeout(() => { + if (trend) trend.remove(); + }, 1100); + } + } + // 替换:保留所有非文本子节点(如 .copyBtn / .statTrend),仅更新文本 + for (const ch of Array.from(el.childNodes)) { + if (ch.nodeType === Node.TEXT_NODE) ch.remove(); + } + el.insertBefore(document.createTextNode(next), el.firstChild || null); } function setButtonBusy(id, busy) { @@ -654,12 +1247,26 @@ function renderTimeline(containerId, timeline) { axis.setAttribute("fill", "none"); svg.appendChild(axis); + // 水平网格线(4 等分),淡色 dashed + const gridSteps = 4; + for (let i = 1; i <= gridSteps; i++) { + const gy = padT + ((H - padT - padB) * i / gridSteps); + const gline = document.createElementNS("http://www.w3.org/2000/svg", "path"); + gline.setAttribute("d", `M ${padL} ${gy.toFixed(2)} L ${W - padR} ${gy.toFixed(2)}`); + gline.setAttribute("stroke", "var(--border)"); + gline.setAttribute("stroke-opacity", "0.5"); + gline.setAttribute("stroke-dasharray", "2 4"); + gline.setAttribute("fill", "none"); + svg.appendChild(gline); + } + const mkText = (x, y, txt, anchor = "start") => { const el = document.createElementNS("http://www.w3.org/2000/svg", "text"); el.setAttribute("x", String(x)); el.setAttribute("y", String(y)); el.setAttribute("fill", "var(--muted)"); - el.setAttribute("font-size", "11"); + el.setAttribute("font-size", "10"); + el.setAttribute("font-family", "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace"); el.setAttribute("text-anchor", anchor); el.textContent = txt; return el; @@ -677,8 +1284,13 @@ function renderTimeline(containerId, timeline) { return (H - padB) - (vv / maxY) * h; }; - // y 轴 max 标记 - svg.appendChild(mkText(padL, padT + 10, String(maxY), "start")); + // y 轴刻度(0 / mid / max) + const yMid = Math.round(maxY / 2); + svg.appendChild(mkText(padL - 6, padT + 4, String(maxY), "end")); + if (yMid > 0 && yMid < maxY) { + svg.appendChild(mkText(padL - 6, padT + (H - padT - padB) / 2 + 4, String(yMid), "end")); + } + svg.appendChild(mkText(padL - 6, H - padB + 4, "0", "end")); // x 轴 3 个时间刻度 const fmtShort = (ts) => { @@ -710,18 +1322,188 @@ function renderTimeline(containerId, timeline) { svg.appendChild(p); } + // Crosshair hover layer:垂直线 + 当前 bin 的 dot 圆 + tooltip + const NS = "http://www.w3.org/2000/svg"; + const crossLine = document.createElementNS(NS, "line"); + crossLine.setAttribute("y1", String(padT)); + crossLine.setAttribute("y2", String(H - padB)); + crossLine.setAttribute("stroke", "var(--text)"); + crossLine.setAttribute("stroke-opacity", "0.25"); + crossLine.setAttribute("stroke-dasharray", "2 3"); + crossLine.setAttribute("pointer-events", "none"); + crossLine.setAttribute("visibility", "hidden"); + svg.appendChild(crossLine); + // 容器(外层 root)作为相对定位锚点 + root.style.position = "relative"; + + const tip = document.createElement("div"); + tip.className = "timelineTip"; + tip.hidden = true; + root.appendChild(tip); + + const fmtTimeOf = (i) => { + if (!startTs || !binSec) return ""; + try { return new Date((startTs + i * binSec) * 1000).toLocaleTimeString(); } catch { return ""; } + }; + const SERIES_LABEL = { + fudai_open_detail: "打开详情", + fudai_attend_ok: "参与成功", + fudai_attend_fail: "参与失败", + fudai_result_win: "中奖", + fudai_result_no_win: "未中奖", + fudai_skip: "跳过", + switch_room: "切换直播间", + }; + + const onMove = (ev) => { + const rect = svg.getBoundingClientRect(); + const xRatio = (ev.clientX - rect.left) / rect.width; + if (xRatio < 0 || xRatio > 1) return; + const xCoord = padL + (W - padL - padR) * xRatio; + // 找最近的 bin + let i = Math.round(((xCoord - padL) / Math.max(1, W - padL - padR)) * (bins - 1)); + if (i < 0) i = 0; else if (i >= bins) i = bins - 1; + const xOnAxis = xAt(i); + crossLine.setAttribute("x1", String(xOnAxis)); + crossLine.setAttribute("x2", String(xOnAxis)); + crossLine.setAttribute("visibility", "visible"); + + // 生成 tip 内容 + const lines = []; + let total = 0; + for (const k of TIMELINE_SERIES_KEYS) { + const arr = Array.isArray(series[k]) ? series[k] : []; + const v = Number(arr[i]) || 0; + total += v; + if (v > 0) lines.push(`${SERIES_LABEL[k] || k}${v}`); + } + if (total === 0) lines.push(`无事件`); + tip.innerHTML = `
${fmtTimeOf(i)}
${lines.join("")}
`; + tip.hidden = false; + + // tip 位置:根据当前 svg 实际宽度比例换算到 root 内 px + const actualX = (xOnAxis / W) * rect.width; + let leftPx = actualX + 8; + if (leftPx + 160 > rect.width) leftPx = actualX - 168; + if (leftPx < 0) leftPx = 4; + tip.style.left = `${Math.max(0, leftPx)}px`; + tip.style.top = `${rect.height * 0.06}px`; + }; + const onLeave = () => { + crossLine.setAttribute("visibility", "hidden"); + tip.hidden = true; + }; + svg.addEventListener("mousemove", onMove); + svg.addEventListener("mouseleave", onLeave); + root.appendChild(svg); const legend = document.createElement("div"); legend.className = "hint"; - legend.textContent = "图例:实线/虚线区分同色不同事件"; + legend.textContent = "图例:实线/虚线区分同色不同事件 · 鼠标悬停查看明细"; root.appendChild(legend); } +// API 连接状态:连续失败 N 次才算 error,避免轻微抖动闪烁 +let _apiFailStreak = 0; +const _apiFailThreshold = 2; +function setConnState(state) { + const dot = document.getElementById("appConnDot"); + const txt = document.getElementById("appConnText"); + if (!dot || !txt) return; + if (state === "ok") { + dot.dataset.state = "ok"; + txt.textContent = "已连接"; + dot.title = "API 通信正常"; + } else if (state === "error") { + dot.dataset.state = "error"; + txt.textContent = "连接异常"; + dot.title = "API 请求连续失败,检查后端是否运行"; + } else { + dot.dataset.state = "idle"; + txt.textContent = "就绪"; + dot.title = "等待首个 API 请求"; + } +} +function notifyApiOk() { + _apiFailStreak = 0; + setConnState("ok"); +} +function notifyApiFail() { + _apiFailStreak++; + if (_apiFailStreak >= _apiFailThreshold) setConnState("error"); +} + +function renderOverviewSparkline(svgId, timeline) { + const svg = document.getElementById(svgId); + if (!svg) return; + // 把 fudai_open_detail + fudai_attend_ok 两个序列合成一条迷你折线 + const series = (timeline && timeline.series) || {}; + const keys = ["fudai_open_detail", "fudai_attend_ok"]; + const arrs = keys.map((k) => Array.isArray(series[k]) ? series[k] : []); + const len = Math.max(...arrs.map((a) => a.length), 0); + if (len < 2) { + svg.innerHTML = ""; + svg.classList.remove("hasData"); + return; + } + const combined = new Array(len).fill(0); + for (const arr of arrs) { + for (let i = 0; i < arr.length; i++) combined[i] += Number(arr[i]) || 0; + } + const maxY = Math.max(1, ...combined); + // 100x24 viewBox:留 1px 边 + const W = 100, H = 24, padY = 1.5; + const xAt = (i) => (W * i) / (len - 1); + const yAt = (v) => H - padY - ((H - padY * 2) * v) / maxY; + let d = ""; + for (let i = 0; i < len; i++) { + const x = xAt(i).toFixed(2), y = yAt(combined[i]).toFixed(2); + d += (i === 0 ? "M" : " L") + x + " " + y; + } + // 渐变填充区 + const dArea = d + ` L ${W} ${H} L 0 ${H} Z`; + const NS = "http://www.w3.org/2000/svg"; + svg.setAttribute("viewBox", `0 0 ${W} ${H}`); + svg.innerHTML = ""; + // gradient defs + const defs = document.createElementNS(NS, "defs"); + const gid = svgId + "Grad"; + const grad = document.createElementNS(NS, "linearGradient"); + grad.setAttribute("id", gid); + grad.setAttribute("x1", "0"); grad.setAttribute("y1", "0"); + grad.setAttribute("x2", "0"); grad.setAttribute("y2", "1"); + grad.innerHTML = ``; + defs.appendChild(grad); + svg.appendChild(defs); + const area = document.createElementNS(NS, "path"); + area.setAttribute("d", dArea); + area.setAttribute("fill", `url(#${gid})`); + svg.appendChild(area); + const line = document.createElementNS(NS, "path"); + line.setAttribute("d", d); + line.setAttribute("fill", "none"); + line.setAttribute("stroke", "currentColor"); + line.setAttribute("stroke-width", "1.25"); + line.setAttribute("stroke-linecap", "round"); + line.setAttribute("stroke-linejoin", "round"); + svg.appendChild(line); + svg.classList.add("hasData"); +} + async function apiGet(path) { - const res = await fetch(path, { cache: "no-store" }); - if (!res.ok) throw new Error(await res.text()); - return await res.json(); + try { + const res = await fetch(path, { cache: "no-store" }); + if (!res.ok) { + notifyApiFail(); + throw new Error(await res.text()); + } + notifyApiOk(); + return await res.json(); + } catch (e) { + notifyApiFail(); + throw e; + } } // CSRF token 缓存 @@ -741,24 +1523,31 @@ async function getCsrfToken() { } async function apiPost(path, body) { - const token = await getCsrfToken(); - const res = await fetch(path, { - method: "POST", - headers: { - "Content-Type": "application/json", - "X-CSRF-Token": token, - }, - body: JSON.stringify(body || {}), - }); - const data = await res.json(); - if (!res.ok) { - const errorMsg = data.error || data.message || res.statusText; - const error = new Error(errorMsg); - error.status = res.status; - error.data = data; - throw error; + try { + const token = await getCsrfToken(); + const res = await fetch(path, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-CSRF-Token": token, + }, + body: JSON.stringify(body || {}), + }); + const data = await res.json(); + if (!res.ok) { + notifyApiFail(); + const errorMsg = data.error || data.message || res.statusText; + const error = new Error(errorMsg); + error.status = res.status; + error.data = data; + throw error; + } + notifyApiOk(); + return data; + } catch (e) { + notifyApiFail(); + throw e; } - return data; } async function refreshDevices() { @@ -782,6 +1571,32 @@ async function refreshDevices() { $("adbStatus").textContent = data.adb ? `adb: ${data.adb}` : "未找到 adb.exe(请安装 platform-tools)"; deviceOverviewState = { devices, adb: data.adb || "" }; updateDeviceOverview(); + + // 选中后在外层包装上反映状态点 + decorateDeviceSelect(); + sel.addEventListener("change", decorateDeviceSelect); +} + +function decorateDeviceSelect() { + const sel = document.getElementById("device"); + if (!sel) return; + const wrap = sel.closest(".deviceSelectWrap") || (() => { + const w = document.createElement("div"); + w.className = "deviceSelectWrap"; + sel.parentNode.insertBefore(w, sel); + w.appendChild(sel); + const dot = document.createElement("span"); + dot.className = "deviceSelectDot"; + dot.setAttribute("aria-hidden", "true"); + w.appendChild(dot); + return w; + })(); + const dot = wrap.querySelector(".deviceSelectDot"); + const hasDevices = (deviceOverviewState.devices || []).length > 0; + const selected = sel.value; + // 选中具体设备 → 绿;选 auto + 有在线设备 → 绿;无设备 → 灰 + const ok = !!(selected || hasDevices); + if (dot) dot.dataset.state = ok ? "ok" : "idle"; } function getConfigBoundElements() { @@ -883,8 +1698,9 @@ async function loadConfig() { try { const cfg = await apiGet("/api/config"); applyConfigToUI(cfg); - appendLog(["[WEB] 配置已加载"]); + toast("配置已加载", "success"); } catch (e) { + toast("配置加载失败:" + e.message, "error", { duration: 5000 }); appendLog(["[WEB] 配置加载失败: " + e.message]); } } @@ -894,7 +1710,10 @@ async function saveConfig() { try { const cfgUpdate = collectConfigFromUI(); await apiPost("/api/config", cfgUpdate); - appendLog(["[WEB] 配置已保存到 config.json"]); + toast("配置已保存", "success"); + } catch (e) { + toast("保存失败:" + (e?.message || e), "error", { duration: 5000 }); + throw e; } finally { setButtonBusy("btnSave", false); } @@ -910,10 +1729,13 @@ async function postDeviceAction(path, body, successPrefix) { const result = await apiPost(path, body || {}); const msg = result.message || result.output || result.error || "完成"; appendLog([`${successPrefix}: ${msg}`]); + if (!result.error) toast(`${successPrefix}: ${msg}`, "success"); + else toast(`${successPrefix}: ${msg}`, "warn"); if (result.devices) await refreshDevices(); return result; } catch (e) { appendLog([`${successPrefix}失败: ${e?.message || e}`]); + toast(`${successPrefix}失败:${e?.message || e}`, "error", { duration: 5000 }); throw e; } } @@ -1010,13 +1832,15 @@ async function startRun() { if (result && result.ok === false) { const errorMsg = result.error || "未知错误"; appendLog([`[WEB] 启动失败: ${errorMsg}`]); + toast("启动失败:" + (errorMsg === "running" ? "已有进程在运行" : errorMsg), "error", { duration: 5000 }); if (errorMsg === "running") { appendLog([`[WEB] 提示:已有进程在运行中,请先点击"停止"按钮`]); } return; } - + appendLog([`[WEB] 已开始运行:device=${deviceId || UI_COPY.device.autoLabel}`]); + toast(`已开始运行 · ${deviceId || "自动"}`, "success"); // 启动时自动截图 if (deviceId) { @@ -1052,6 +1876,7 @@ async function startRun() { console.error("[WEB] startRun error:", e); const errorMsg = e.message || String(e); appendLog([`[WEB] 启动失败: ${errorMsg}`]); + toast("启动失败:" + errorMsg, "error", { duration: 5000 }); setRunOverview(UI_COPY.runOverview.failed, errorMsg, RUN_TONE.error); // 如果是"running"错误,显示友好提示 if (errorMsg === "running" || (e.status === 409)) { @@ -1207,6 +2032,8 @@ async function pollReservations() { `; container.appendChild(info); + updateTabBadge("reservations", reservations.length); + if (reservations.length === 0) { const hint = document.createElement("div"); hint.className = "hint"; @@ -1222,12 +2049,17 @@ async function pollReservations() { reservations.forEach((item, idx) => { const card = document.createElement("div"); card.className = "reservationItem"; - + const now = Date.now() / 1000; const future_ts = item.future_ts || 0; const remain = Math.max(0, Math.floor(future_ts - now)); const remainStr = remain > 0 ? `${Math.floor(remain / 60)}分${remain % 60}秒后` : "已到开奖时间"; - + // 60s 内开奖:高亮提醒 + if (remain > 0 && remain <= 60) card.classList.add("isImminent"); + else if (remain === 0) card.classList.add("isDue"); + // 把 future_ts 存到卡片,供倒计时 tick 实时刷新 + if (future_ts) card.dataset.futureTs = String(future_ts); + card.innerHTML = `
#${idx + 1} @@ -1236,7 +2068,7 @@ async function pollReservations() {
内容:${escapeHtml(item.content || '-')}
开奖时间:${item.future_str || '-'}
-
剩余时间:${remainStr}
+
剩余时间:${remainStr}
发现位置:${item.pos_seen || 0}
直播间(清洗后):${escapeHtml(item.room_title || '-')}
直播间原文:${escapeHtml(item.room_title_raw || '-')}
@@ -1373,8 +2205,15 @@ async function pollHighValueRooms() { async function pollStats() { try { const s = await apiGet(`/api/stats?t=${Date.now()}`); + // 数据到位,去掉骨架 + document.querySelectorAll(".stat .statValue.skeleton, .stat .statHint.skeleton").forEach((el) => el.classList.remove("skeleton")); const running = s.running ? "运行中" : "未运行"; setTextIfExists("statRunning", running); + const runningEl = document.getElementById("statRunning"); + if (runningEl) { + runningEl.classList.toggle("stateOk", !!s.running); + runningEl.classList.toggle("stateMuted", !s.running); + } setTextIfExists("statPid", s.pid ?? "-"); setTextIfExists("statUptime", fmtDuration(s.uptime_seconds)); setTextIfExists("statLogLen", s.log_len ?? "-"); @@ -1395,6 +2234,11 @@ async function pollStats() { s.running ? RUN_TONE.running : RUN_TONE.idle ); document.body.classList.toggle("is-running", !!s.running); + // 页面标题随运行状态更新 + try { + const baseTitle = "抖音挂机控制台"; + document.title = s.running ? `● ${baseTitle} · 运行中` : baseTitle; + } catch (_) {} setTextIfExists("topLogState", UI_COPY.overview.logLines(s.log_len)); setTextIfExists("topLogMeta", UI_COPY.overview.lastLog(s.last_log_ts)); @@ -1404,6 +2248,19 @@ async function pollStats() { setTextIfExists("statFudaiAttendFail", getC("fudai_attend_fail")); setTextIfExists("statFudaiNoWin", getC("fudai_result_no_win")); setTextIfExists("statFudaiWin", getC("fudai_result_win")); + // 福袋统计语义着色 + const colorize = (id, kind, n) => { + const el = document.getElementById(id); + if (!el) return; + el.classList.toggle("stateOk", kind === "ok" && n > 0); + el.classList.toggle("stateError", kind === "error" && n > 0); + el.classList.toggle("stateWarn", kind === "warn" && n > 0); + el.classList.toggle("stateMuted", kind === "muted" && n > 0); + }; + colorize("statFudaiAttendOk", "ok", getC("fudai_attend_ok")); + colorize("statFudaiWin", "ok", getC("fudai_result_win")); + colorize("statFudaiAttendFail", "error", getC("fudai_attend_fail")); + colorize("statFudaiNoWin", "muted", getC("fudai_result_no_win")); setTextIfExists("topFudaiState", UI_COPY.overview.fudaiState(getC("fudai_open_detail"), getC("fudai_attend_ok"))); setTextIfExists("topFudaiMeta", UI_COPY.overview.fudaiMeta(getC("fudai_seen"), getC("fudai_result_win"))); @@ -1481,6 +2338,7 @@ async function pollStats() { }; renderTimeline("chartTimeline", agg.timeline); + renderOverviewSparkline("topFudaiSparkline", agg.timeline); renderBars("chartSkipReason", agg.skip_reason || {}, reasonName); renderBars("chartSwitchReason", agg.switch_reason || {}, switchName); renderBars("chartValueBuckets", agg.value_buckets || {}); @@ -1513,7 +2371,33 @@ function startStatsPolling() { window.addEventListener("DOMContentLoaded", async () => { initTheme(); initTabs(); - $("btnRefresh").addEventListener("click", refreshDevices); + initConfigSearch(); + initFooter(); + attachCopyButtons(); + initShotFullscreen(); + initHeaderScroll(); + initKeyboardShortcuts(); + initShortcutsHelp(); + initStickySectionShadow(); + attachNumberSteppers(); + applyKbdHints(); + startReservationsCountdownTick(); + // 首屏统计数字加骨架,待第一次 pollStats 成功后移除 + document.querySelectorAll(".stat .statValue").forEach((el) => { + if ((el.textContent || "").trim() === "-") el.classList.add("skeleton"); + }); + $("btnRefresh").addEventListener("click", async () => { + setButtonBusy("btnRefresh", true); + try { + await refreshDevices(); + const n = (deviceOverviewState.devices || []).length; + toast(n > 0 ? `已刷新 · ${n} 台在线` : "已刷新 · 无在线设备", n > 0 ? "success" : "warn"); + } catch (e) { + toast("刷新失败:" + (e?.message || e), "error", { duration: 4000 }); + } finally { + setButtonBusy("btnRefresh", false); + } + }); $("btnLoad").addEventListener("click", async () => { await loadConfig(); }); $("btnSave").addEventListener("click", async () => { await saveConfig(); }); $("btnStart").addEventListener("click", async () => { await startRun(); }); diff --git a/webui/index.html b/webui/index.html index aa48d6a..cdc3a8f 100644 --- a/webui/index.html +++ b/webui/index.html @@ -4,6 +4,7 @@ 抖音挂机 - Web GUI + - +
- +
抖音挂机控制台
-
设备调度、运行控制与实时观察
+
设备调度 · 运行控制 · 实时观察
- - -
-
配置项按当前标签自然铺排,短页不再继承长页高度。
+
+ + + + + +
+
@@ -206,9 +226,11 @@
- - - +
+ + + +
先用 USB 设备启用 TCP/IP,再按 IP 连接。
@@ -232,7 +254,7 @@
-