From 37f736c158c7bc5cd752876aeb4d4a67877faeaf Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 1 Jun 2026 09:07:03 +0800 Subject: [PATCH] fix(webgui): harden config bool parsing and action error handling --- artifacts/webui_checks/20260601/issues.md | 32 + artifacts/webui_checks/20260601/summary.json | 84 ++ .../20260601_port8002/summary.json | 15 + .../20260601_postfix/summary.json | 15 + gui/web_gui_pkg/routes.py | 770 ++++++++++++++++++ tests/test_web_gui_routes_logic.py | 137 ++++ tests/test_webui_source_guards.py | 44 + webui/js/config_form.js | 8 +- webui/js/runtime_actions.js | 259 +----- webui/js/runtime_device_actions.js | 235 ++++++ 10 files changed, 1366 insertions(+), 233 deletions(-) create mode 100644 artifacts/webui_checks/20260601/issues.md create mode 100644 artifacts/webui_checks/20260601/summary.json create mode 100644 artifacts/webui_checks/20260601_port8002/summary.json create mode 100644 artifacts/webui_checks/20260601_postfix/summary.json create mode 100644 gui/web_gui_pkg/routes.py create mode 100644 tests/test_web_gui_routes_logic.py create mode 100644 tests/test_webui_source_guards.py create mode 100644 webui/js/runtime_device_actions.js diff --git a/artifacts/webui_checks/20260601/issues.md b/artifacts/webui_checks/20260601/issues.md new file mode 100644 index 0000000..231b199 --- /dev/null +++ b/artifacts/webui_checks/20260601/issues.md @@ -0,0 +1,32 @@ +# WebUI 用户视角问题清单(2026-06-01) + +## 已修复(本轮) + +1. `/api/config` 布尔值字符串会被错误写入 + - 现象:`"false"` 可能被当成 `true`。 + - 修复:后端 `routes.py` 新增 `_coerce_bool`,前端 `config_form.js` 同步字面量解析。 + +2. 设备动作在无设备时存在未捕获 Promise 报错噪音 + - 现象:点击“返回键”后可能触发全局 `pageerror`(虽有提示但会污染错误面板)。 + - 修复:`runtime_device_actions.js` 的 `sendBackKey()` 增加局部 `try/catch`。 + +3. 预约/高价值列表中少量字段未统一做安全处理 + - 现象:个别字符串字段直接插入模板字符串。 + - 修复:`runtime_actions.js` 对 `future_str` 等补 `escapeHtml`,数值字段统一显式数值化。 + +4. WiFi 自动重连与扫描参数错误码语义不清 + - 修复: + - 无 adb:`/api/wifi/auto-reconnect` 返回 `422`。 + - `ports` 非法:`/api/wifi/scan` 返回 `400 invalid ports`。 + - `probe_timeout` 非法继续返回 `400`。 + +## 仍可优化(下一批) + +1. 移动端首屏头部信息密度偏高 + - 证据:`mobile_home.png` 中操作按钮区占比较大,设备/状态卡阅读层级偏挤。 + - 建议:在 `< 420px` 下把二级按钮折叠进更多菜单,保留“开始/停止/截图”主操作。 + +2. Tab 横向切换在自动化点击中偶发不可见状态 + - 证据:Playwright 偶发 `runLogs` tab 点击超时(人工可复现概率低)。 + - 建议:为 tab click 增加 `scrollIntoView` + `requestAnimationFrame` 后触发,提升自动化与低端机稳定性。 + diff --git a/artifacts/webui_checks/20260601/summary.json b/artifacts/webui_checks/20260601/summary.json new file mode 100644 index 0000000..49a0876 --- /dev/null +++ b/artifacts/webui_checks/20260601/summary.json @@ -0,0 +1,84 @@ +{ + "url": "http://localhost:8001/", + "screenshots": [ + "artifacts\\webui_checks\\20260601\\desktop_home.png", + "artifacts\\webui_checks\\20260601\\desktop_run_panel.png", + "artifacts\\webui_checks\\20260601\\desktop_stats_panel.png", + "artifacts\\webui_checks\\20260601\\desktop_monitor_panel.png", + "artifacts\\webui_checks\\20260601\\desktop_reservations_panel.png", + "artifacts\\webui_checks\\20260601\\desktop_runlogs_panel.png", + "artifacts\\webui_checks\\20260601\\desktop_actionlogs_panel.png", + "artifacts\\webui_checks\\20260601\\mobile_home.png", + "artifacts\\webui_checks\\20260601\\mobile_run_panel.png", + "artifacts\\webui_checks\\20260601\\mobile_stats_panel.png", + "artifacts\\webui_checks\\20260601\\mobile_monitor_panel.png", + "artifacts\\webui_checks\\20260601\\mobile_reservations_panel.png", + "artifacts\\webui_checks\\20260601\\mobile_runlogs_panel.png", + "artifacts\\webui_checks\\20260601\\mobile_actionlogs_panel.png" + ], + "console_errors": [ + { + "type": "error", + "text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)" + }, + { + "type": "action", + "text": "click_failed .tabBtn[data-target=\"runLogs\"]: Locator.click: Timeout 3000ms exceeded.\nCall log:\n - waiting for locator(\".tabBtn[data-target=\\\"runLogs\\\"]\").first\n - locator resolved to \n - attempting click action\n - waiting for element to be visible, enabled and stable\n - element is visible, enabled and stable\n - scrolling into view if needed\n - done scrolling\n - performing click action\n" + } + ], + "page_errors": [ + "未选择设备,且无法自动解析在线设备" + ], + "checks": { + "desktop:has:btnStart": true, + "desktop:has:btnStop": true, + "desktop:has:btnForceStop": true, + "desktop:has:btnRefresh": true, + "desktop:has:btnScreenshot": true, + "desktop:has:btnBackKey": true, + "desktop:has:btnLoad": true, + "desktop:has:btnSave": true, + "desktop:has:device": true, + "desktop:has:btnWifiScan": true, + "desktop:has:wifiStatus": true, + "desktop:has:runLog": true, + "desktop:has:appConnText": true, + "desktop:has:appConnDot": true, + "desktop:has:reservationsContent": true, + "desktop:has:highValueRoomsContent": true, + "desktop:has:hv_expand_all": true, + "desktop:has:hv_collapse_all": true, + "desktop:conn_text": "已连接", + "desktop:body_box": { + "w": 1600, + "h": 1178.65625, + "scrollH": 1179 + }, + "desktop:overflow_controls": 0, + "mobile:has:btnStart": true, + "mobile:has:btnStop": true, + "mobile:has:btnForceStop": true, + "mobile:has:btnRefresh": true, + "mobile:has:btnScreenshot": true, + "mobile:has:btnBackKey": true, + "mobile:has:btnLoad": true, + "mobile:has:btnSave": true, + "mobile:has:device": true, + "mobile:has:btnWifiScan": true, + "mobile:has:wifiStatus": true, + "mobile:has:runLog": true, + "mobile:has:appConnText": true, + "mobile:has:appConnDot": true, + "mobile:has:reservationsContent": true, + "mobile:has:highValueRoomsContent": true, + "mobile:has:hv_expand_all": true, + "mobile:has:hv_collapse_all": true, + "mobile:conn_text": "已连接", + "mobile:body_box": { + "w": 390, + "h": 2102.875, + "scrollH": 2103 + }, + "mobile:overflow_controls": 1 + } +} \ No newline at end of file diff --git a/artifacts/webui_checks/20260601_port8002/summary.json b/artifacts/webui_checks/20260601_port8002/summary.json new file mode 100644 index 0000000..df4301b --- /dev/null +++ b/artifacts/webui_checks/20260601_port8002/summary.json @@ -0,0 +1,15 @@ +{ + "console_errors": [ + { + "type": "error", + "text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)" + } + ], + "page_errors": [], + "screenshots": [ + "artifacts\\webui_checks\\20260601_port8002\\mobile_main.png" + ], + "checks": { + "has_unhandled_error": false + } +} \ No newline at end of file diff --git a/artifacts/webui_checks/20260601_postfix/summary.json b/artifacts/webui_checks/20260601_postfix/summary.json new file mode 100644 index 0000000..1b9a7a9 --- /dev/null +++ b/artifacts/webui_checks/20260601_postfix/summary.json @@ -0,0 +1,15 @@ +{ + "console_errors": [ + { + "type": "error", + "text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)" + } + ], + "page_errors": [], + "screenshots": [ + "artifacts\\webui_checks\\20260601_postfix\\mobile_after_fix.png" + ], + "checks": { + "has_unhandled_error": false + } +} \ No newline at end of file diff --git a/gui/web_gui_pkg/routes.py b/gui/web_gui_pkg/routes.py new file mode 100644 index 0000000..344160d --- /dev/null +++ b/gui/web_gui_pkg/routes.py @@ -0,0 +1,770 @@ +from __future__ import annotations + +import os +import re +from http import HTTPStatus +from urllib.parse import parse_qs + +from douyin.core import path_config +from gui.web_gui_pkg import ( + _wg_log, + find_adb_executable, + list_adb_devices, + read_config, + write_config, + proc_runner_ops as _proc_ops, +) + +BASE_DIR = ( + path_config.PROJECT_ROOT + if hasattr(path_config, "PROJECT_ROOT") + else os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) +) + +_TRUE_LITERALS = {"1", "true", "yes", "y", "on"} +_FALSE_LITERALS = {"0", "false", "no", "n", "off", ""} + + +def _coerce_bool(value) -> bool: + """把配置输入稳健地转为 bool。 + + 注意:Python 的 bool("false") == True;这里显式处理字符串布尔字面量, + 避免 WebUI 提交字符串后写入反向配置。 + """ + if isinstance(value, bool): + return value + if isinstance(value, (int, float)): + return value != 0 + text = str(value or "").strip().lower() + if text in _TRUE_LITERALS: + return True + if text in _FALSE_LITERALS: + return False + return bool(value) + + +def _is_invalid_ports_spec(spec) -> bool: + """判断端口规格是否为明确非法输入。""" + if spec is None: + return False + if isinstance(spec, int): + return not (1 <= int(spec) <= 65535) + if isinstance(spec, (list, tuple)): + for item in spec: + try: + p = int(item) + except (TypeError, ValueError): + return True + if not (1 <= p <= 65535): + return True + return False + if isinstance(spec, str): + raw = spec.strip() + if not raw: + return False + parts = [p.strip() for p in raw.split(",") if p.strip()] + if not parts: + return False + for part in parts: + if re.fullmatch(r"\d+", part): + continue + if re.fullmatch(r"\d+\s*-\s*\d+", part): + continue + return True + return False + return True + + +def handle_get(handler, u, runner, csrf_token: str) -> None: + if u.path.startswith("/api/"): + api_path = u.path.rstrip("/") + if u.path == "/api/csrf-token": + return handler._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 handler._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 handler._send_json({"adb": adb, "devices": list_adb_devices(adb)}) + if u.path == "/api/wifi/last": + try: + from gui.gui_core_pkg import get_last_wifi_target + + return handler._send_json({"ok": True, "last": get_last_wifi_target()}) + except Exception as e: + return handler._send_json({"ok": False, "error": str(e)}, status=500) + if u.path == "/api/config": + return handler._send_json(read_config()) + if u.path == "/api/stats": + qs = parse_qs(u.query) + detail = str((qs.get("detail") or [""])[0] or "").strip().lower() in ( + "1", + "true", + "yes", + ) + return handler._send_json(runner.get_stats(include_events=detail)) + if api_path in ("/api/reservations", "/api/reservation"): + return handler._send_json(runner.get_reservations()) + if api_path in ( + "/api/high-value-rooms", + "/api/high_value_rooms", + "/api/high_value_room", + "/api/high-value-room", + ): + return handler._send_json(runner.get_high_value_rooms()) + if u.path == "/api/logs": + qs = parse_qs(u.query) + q = (qs.get("q") or [""])[0] + try: + tail_n = int((qs.get("lines") or [200])[0]) + except Exception: + tail_n = 200 + if q: + try: + with runner._lock: + total = len(runner._log) + cand = runner._log[-tail_n:] if tail_n > 0 else runner._log[:] + qlow = q.lower() + filtered = [l for l in cand if qlow in (l or "").lower()] + return handler._send_json( + {"next": total, "lines": filtered, "running": runner.is_running()} + ) + except Exception as e: + import traceback + + _wg_log( + f"[WEB_GUI] logs search error: {e}\n{traceback.format_exc()}", + level="ERROR", + ) + return handler._send_json( + {"next": 0, "lines": [], "running": runner.is_running()} + ) + since = 0 + try: + since = int((qs.get("since") or [0])[0]) + except (ValueError, TypeError, IndexError): + since = 0 + try: + next_idx, lines = runner.get_logs_since(since) + return handler._send_json( + {"next": next_idx, "lines": lines, "running": runner.is_running()} + ) + except Exception as e: + import traceback + + _wg_log( + f"[WEB_GUI] get_logs_since error: {e}\n{traceback.format_exc()}", + level="ERROR", + ) + return handler._send_json( + {"next": 0, "lines": [], "running": runner.is_running()} + ) + if u.path == "/api/logfile-tail": + qs = parse_qs(u.query) + try: + n = int((qs.get("lines") or [100])[0]) + except Exception: + n = 100 + path = ( + runner._log_file_path + if hasattr(runner, "_log_file_path") + else path_config.get_log_file_path() + ) + out_lines = [] + try: + if os.path.exists(path): + size = os.path.getsize(path) + read_bytes = min(size, 65536) + with open(path, "rb") as f: + if read_bytes < size: + f.seek(-read_bytes, os.SEEK_END) + data = f.read().decode("utf-8", errors="replace") + out_lines = data.splitlines()[-n:] + except Exception: + out_lines = [""] + return handler._send_json({"ok": True, "path": path, "lines": out_lines}) + if u.path == "/api/actions": + qs = parse_qs(u.query) + try: + n = int((qs.get("lines") or [200])[0]) + except Exception: + n = 200 + if hasattr(path_config, "get_actions_log_path"): + try: + path = path_config.get_actions_log_path() + except Exception: + path = os.path.join( + BASE_DIR, + "logs", + "actions.log", + ) + else: + path = os.path.join( + BASE_DIR, + "logs", + "actions.log", + ) + out_lines: list[str] = [] + try: + if os.path.exists(path): + size = os.path.getsize(path) + read_bytes = min(size, 65536) + with open(path, "rb") as f: + if read_bytes < size: + f.seek(-read_bytes, os.SEEK_END) + data = f.read().decode("utf-8", errors="replace") + out_lines = data.splitlines()[-n:] + except Exception: + out_lines = [""] + return handler._send_json({"ok": True, "path": path, "lines": out_lines}) + handler.send_error(HTTPStatus.NOT_FOUND) + return + + if u.path.startswith("/pic/"): + rel = u.path.lstrip("/") + safe = os.path.normpath(rel).replace("\\", "/") + if not safe.startswith("pic/"): + handler.send_error(HTTPStatus.FORBIDDEN) + return + full = os.path.join(str(path_config.PROJECT_ROOT), safe) + if not os.path.isfile(full): + handler.send_error(HTTPStatus.NOT_FOUND) + return + ext = os.path.splitext(full)[1].lower() + ctype = { + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + }.get(ext, "application/octet-stream") + with open(full, "rb") as f: + data = f.read() + handler.send_response(HTTPStatus.OK) + handler.send_header("Content-Type", ctype) + handler.send_header("Content-Length", str(len(data))) + handler.send_header("Cache-Control", "no-store") + handler.end_headers() + handler.wfile.write(data) + return + + handler._serve_static(u.path) + + +def handle_post(handler, u, runner, csrf_token: str) -> None: + if handler.headers.get("X-CSRF-Token", "") != csrf_token: + return handler._send_json( + {"ok": False, "error": "Invalid CSRF token"}, status=403 + ) + + if u.path == "/api/config": + body = handler._read_json() + cfg = read_config() + update = body.get("config") if isinstance(body.get("config"), dict) else body + + int_keys = { + "min_participants", + "max_participants", + "skip_if_countdown_lt_seconds", + "skip_if_countdown_gt_seconds", + "reset_after_swipes", + "fudai_find_max_attempts", + "fudai_quiet_start_hour", + "fudai_quiet_end_hour", + "high_value_fudai_join_ahead_seconds", + "high_value_fudai_max_swipe_back", + "high_value_fudai_max_reservations", + "yanghao_like_icon_x", + "yanghao_like_icon_y", + "yanghao_fav_icon_x", + "yanghao_fav_icon_y", + "yanghao_like_roi_offset_x", + "yanghao_like_roi_offset_y", + "yanghao_fav_roi_offset_x", + "yanghao_fav_roi_offset_y", + "yanghao_icon_roi_size", + "yanghao_comment_btn_x", + "yanghao_comment_btn_y", + "yanghao_comment_input_x", + "yanghao_comment_input_y", + "yanghao_comment_send_x", + "yanghao_comment_send_y", + "yanghao_comment_close_x", + "yanghao_comment_close_y", + "yanghao_after_dwell_swipe_distance_px", + "yanghao_recommend_duration_seconds", + "yanghao_recommend_interval_seconds", + "wait_minutes", + "y_pianyi", + "fudai_exit_after_misses", + "swipe_duration_ms", + "swipe_up_start_y", + "swipe_up_end_y", + "high_value_room_revisit_min_interval_seconds", + "high_value_room_revisit_max_per_run", + "high_value_room_revisit_max_age_days", + "logging.keep_days", + "logging.compress_after_days", + } + float_keys = { + "min_prize_value_yuan", + "yanghao_like_prob", + "yanghao_fav_prob", + "yanghao_comment_prob", + "yanghao_icon_match_threshold", + "fudai_template_match_threshold", + "lucky_draw_red_ratio_threshold", + "live_room_match_threshold", + "stage_diag_max_time", + "stage_diag_max_step_time", + "fudai_icon_retry_delay_seconds", + "fudai_icon_max_wait_seconds", + "reservation_back_swipe_delay", + "high_value_fudai_threshold_yuan", + "fansclub_click_delay", + "fansclub_auto_join_wait_seconds", + "fansclub_manual_wait_seconds", + "fudai_click_wait_seconds", + "fudai_detail_template_threshold", + "coupon_template_match_threshold", + "attend_button_red_ratio_threshold", + "fansclub_join_red_ratio_threshold", + "shopping_redpacket_red_ratio_threshold", + "high_value_fudai_poll_before_seconds", + "high_value_room_revisit_min_prize_value", + "reservation_back_verify_wait_seconds", + "switch_room_wait_after_stage_diag_seconds", + "logging.max_total_size_gb", + "logging.monitor_warning_mb", + "logging.monitor_critical_mb", + } + bool_keys = { + "auto_join_fansclub", + "reset_after_swipes_enabled", + "yanghao_enable_actions", + "yanghao_enabled", + "yanghao_step_screenshot", + "enable_ocr_mode1", + "fudai_template_match_enabled", + "fudai_quiet_hours_enabled", + "high_value_fudai_enabled", + "fudai_disable_content_recognition", + "high_value_room_revisit_enabled", + "high_value_room_revisit_only_current_run", + "reservation_back_verify_enabled", + "needswitch", + "infinite_loop_enabled", + "enable_back_on_misses", + "enable_streaming_screenshot", + "fudai_disable_task_recognition", + "yanghao_only", + "debug_captures.async_save", + "debug_captures.log_on_complete", + "logging.beautify_output", + "logging.color_output", + "logging.show_timestamps", + "logging.enable_monitor", + "logging.compress_logs", + "logging.stage_diag_verbose", + "logging.performance_tracking.enabled", + "logging.performance_tracking.track_function_calls", + } + list_str_keys = { + "contains_want", + "contains_not_want", + "yanghao_comment_texts", + "yanghao_like_keywords", + "yanghao_fav_keywords", + } + deny_keys = { + "yanghao_use_recommend_flow", + "yanghao_text_recommend", + "yanghao_text_live", + "yanghao_text_enter_live", + "yanghao_fallback_close_x", + "yanghao_fallback_close_y", + "yanghao_fallback_recommend_x", + "yanghao_fallback_recommend_y", + "yanghao_fallback_live_x", + "yanghao_fallback_live_y", + "yanghao_fallback_enter_live_x", + "yanghao_fallback_enter_live_y", + } + + def set_nested_value(obj, key, value): + if "." in key: + parts = key.split(".") + current = obj + for part in parts[:-1]: + if part not in current or not isinstance(current[part], dict): + current[part] = {} + current = current[part] + current[parts[-1]] = value + else: + obj[key] = value + + for k, v in (update or {}).items(): + if k in deny_keys: + continue + if k in int_keys: + try: + set_nested_value(cfg, k, int(v)) + except Exception: + continue + elif k in float_keys: + try: + set_nested_value(cfg, k, float(v)) + except Exception: + continue + elif k in bool_keys: + set_nested_value(cfg, k, _coerce_bool(v)) + elif k in list_str_keys: + if isinstance(v, list): + set_nested_value(cfg, k, [str(x) for x in v if str(x).strip()]) + else: + set_nested_value( + cfg, k, [str(x).strip() for x in str(v).splitlines() if str(x).strip()] + ) + else: + set_nested_value(cfg, k, v) + write_config(cfg) + return handler._send_json({"ok": True}) + + if u.path == "/api/start-run": + if runner.is_running(): + return handler._send_json({"ok": False, "error": "running"}, status=409) + body = handler._read_json() + try: + runner.start_main_run(body or {}) + except Exception as e: + return handler._send_json({"ok": False, "error": str(e)}, status=500) + return handler._send_json({"ok": True}) + + if u.path == "/api/force-stop": + runner.force_stop() + return handler._send_json({"ok": True, "message": "已执行强制停止"}) + if u.path == "/api/back-key": + body = handler._read_json() + requested_device_id = str(body.get("device_id") or "").strip() + device_id, err = _proc_ops.resolve_device_id_for_action(runner, requested_device_id) + if not device_id: + return handler._send_json({"ok": False, "error": err}, status=422) + ok = runner.send_back_key(device_id) + return handler._send_json( + { + "ok": bool(ok), + "message": "返回键已发送" if ok else "发送返回键失败(设备可能离线)", + "device_id": device_id, + }, + status=200 if ok else 409, + ) + if u.path == "/api/wifi/enable": + body = handler._read_json() + adb = find_adb_executable() + device_id = str(body.get("device_id") or "").strip() + if not device_id: + return handler._send_json({"ok": False, "error": "missing device_id"}, status=400) + if not adb: + return handler._send_json({"ok": False, "error": "adb not found"}, status=422) + try: + from gui.gui_core import enable_wifi_adb + + ok, msg = enable_wifi_adb(adb, device_id) + except Exception as e: + ok, msg = False, str(e) + return handler._send_json({"ok": bool(ok), "message": msg}, status=200 if ok else 409) + if u.path == "/api/wifi/connect": + body = handler._read_json() + adb = find_adb_executable() + ip = str(body.get("ip") or "").strip() + port = str(body.get("port") or "5555").strip() or "5555" + if not ip: + return handler._send_json({"ok": False, "error": "missing ip"}, status=400) + if not adb: + return handler._send_json({"ok": False, "error": "adb not found"}, status=422) + try: + from gui.gui_core import connect_wifi_adb + + ok, msg = connect_wifi_adb(adb, ip, port) + except Exception as e: + ok, msg = False, str(e) + if ok: + try: + from gui.gui_core_pkg import set_last_wifi_target + from gui.gui_core_pkg.wifi_adb_scan import query_device_model + + target = ip if ":" in ip else f"{ip}:{port}" + model = "" + try: + model = query_device_model(adb, target) + except Exception: + pass + set_last_wifi_target(target, model) + except Exception: + pass + devices = list_adb_devices(adb) if adb else [] + return handler._send_json( + {"ok": bool(ok), "message": msg, "devices": devices}, + status=200 if ok else 409, + ) + if u.path == "/api/wifi/disconnect": + body = handler._read_json() + adb = find_adb_executable() + ip = str(body.get("ip") or "").strip() + port = str(body.get("port") or "5555").strip() or "5555" + if not ip: + return handler._send_json({"ok": False, "error": "missing ip"}, status=400) + if not adb: + return handler._send_json({"ok": False, "error": "adb not found"}, status=422) + try: + from gui.gui_core import disconnect_wifi_adb + + ok, msg = disconnect_wifi_adb(adb, ip, port) + except Exception as e: + ok, msg = False, str(e) + if ok: + try: + from gui.gui_core_pkg import clear_last_wifi_target, get_last_wifi_target + + last = get_last_wifi_target() + last_target = str(last.get("target") or "") + if last_target.startswith(ip): + clear_last_wifi_target() + except Exception: + pass + devices = list_adb_devices(adb) if adb else [] + return handler._send_json( + {"ok": bool(ok), "message": msg, "devices": devices}, + status=200 if ok else 409, + ) + if u.path == "/api/wifi/scan": + body = handler._read_json() + adb = find_adb_executable() + if not adb: + return handler._send_json({"ok": False, "error": "adb not found"}, status=422) + subnet = str(body.get("subnet") or "").strip() or None + try: + probe_timeout = float(body.get("probe_timeout") or 0.3) + except Exception: + return handler._send_json({"ok": False, "error": "invalid probe_timeout"}, status=400) + if probe_timeout <= 0: + return handler._send_json({"ok": False, "error": "probe_timeout must be > 0"}, status=400) + ports_raw = body.get("ports") + if _is_invalid_ports_spec(ports_raw): + return handler._send_json({"ok": False, "error": "invalid ports"}, status=400) + try: + from gui.gui_core_pkg import parse_port_spec + + port_list = parse_port_spec(ports_raw) + except Exception: + return handler._send_json({"ok": False, "error": "invalid ports"}, status=400) + try: + from gui.gui_core_pkg import discover_adb_devices, get_local_subnet + + devs = discover_adb_devices( + adb, subnet_spec=subnet, ports=port_list, probe_timeout=probe_timeout + ) + payload = [ + { + "target": d.target, + "ip": d.ip, + "port": d.port, + "state": d.adb_state, + "model": d.model, + "message": d.message, + } + for d in devs + ] + return handler._send_json( + { + "ok": True, + "subnet": subnet or get_local_subnet() or "", + "ports": port_list, + "devices": payload, + } + ) + except Exception as e: + return handler._send_json({"ok": False, "error": str(e)}, status=500) + if u.path == "/api/wifi/last": + try: + from gui.gui_core_pkg import get_last_wifi_target + + return handler._send_json({"ok": True, "last": get_last_wifi_target()}) + except Exception as e: + return handler._send_json({"ok": False, "error": str(e)}, status=500) + if u.path == "/api/wifi/last/clear": + try: + from gui.gui_core_pkg import clear_last_wifi_target + + clear_last_wifi_target() + return handler._send_json({"ok": True}) + except Exception as e: + return handler._send_json({"ok": False, "error": str(e)}, status=500) + if u.path == "/api/wifi/auto-reconnect": + try: + from gui.gui_core_pkg import ( + discover_adb_devices, + get_last_wifi_target, + pick_best_match, + set_last_wifi_target, + ) + from gui.gui_core_pkg.wifi_adb_scan import verify_adb_target + except Exception as e: + return handler._send_json({"ok": False, "error": f"import failed: {e}"}, status=500) + adb = find_adb_executable() + if not adb: + return handler._send_json({"ok": False, "error": "adb not found"}, status=422) + last = get_last_wifi_target() or {} + target = str(last.get("target") or "") + model = str(last.get("model") or "") + if not target: + return handler._send_json( + {"ok": True, "action": "noop", "target": "", "model": "", "message": "无上次记录"} + ) + existing = list_adb_devices(adb) if adb else [] + if target in existing: + return handler._send_json( + { + "ok": True, + "action": "already_online", + "target": target, + "model": model, + "message": f"WiFi 设备已在线: {target}", + } + ) + if existing: + return handler._send_json( + { + "ok": True, + "action": "noop", + "target": existing[0], + "model": "", + "message": f"当前已有设备 {existing[0]},上次 WiFi 目标 {target} 不抢占", + } + ) + try: + state, _ = verify_adb_target(adb, target) + except Exception as e: + state = "failed" + _ = str(e) + if state == "connected": + return handler._send_json( + { + "ok": True, + "action": "reconnected", + "target": target, + "model": model, + "message": f"自动重连成功: {target}", + } + ) + if state == "unauthorized": + return handler._send_json( + { + "ok": True, + "action": "failed", + "target": target, + "model": model, + "message": f"上次设备 {target} 未授权,请在手机上确认 ADB 调试授权", + } + ) + try: + last_port = 5555 + if ":" in target: + try: + last_port = int(target.rsplit(":", 1)[1]) + except ValueError: + pass + scan_ports = [5555] if last_port == 5555 else [5555, last_port] + devs = discover_adb_devices(adb, ports=scan_ports) + except Exception as e: + return handler._send_json({"ok": False, "error": f"自动扫描失败: {e}"}, status=500) + best = pick_best_match(devs, last) + payload_devs = [ + {"target": d.target, "ip": d.ip, "port": d.port, "state": d.adb_state, "model": d.model} + for d in devs + ] + if best is None: + msg = ( + f"上次目标 {target} 不可达,扫描发现 {len(devs)} 台候选但无明确匹配" + if devs + else f"上次目标 {target} 不可达,扫描也未发现其它设备,请检查手机和电脑是否在同一 WiFi" + ) + return handler._send_json( + { + "ok": True, + "action": "failed", + "target": target, + "model": model, + "message": msg, + "devices": payload_devs, + } + ) + try: + set_last_wifi_target(best.target, best.model or model) + except Exception: + pass + msg = ( + f"自动重连成功(扫描确认): {best.target}" + if best.target == target + else f"上次目标 {target} 已变 -> 智能匹配到 {best.target}" + + (f" ({best.model})" if best.model else "") + + "(已更新记忆)" + ) + return handler._send_json( + { + "ok": True, + "action": "matched", + "target": best.target, + "model": best.model or "", + "message": msg, + "devices": payload_devs, + } + ) + if u.path == "/api/test-yanghao": + if runner.is_running(): + return handler._send_json({"ok": False, "error": "running"}, status=409) + body = handler._read_json() + cfg = read_config() + seconds = int(body.get("seconds") or cfg.get("yanghao_recommend_duration_seconds") or 60) + runner.start_main_run( + { + "device_id": str(body.get("device_id") or ""), + "yanghao_only": True, + "yanghao_seconds": seconds, + "wait_minutes": 0, + } + ) + return handler._send_json({"ok": True}) + if u.path == "/api/test-comment": + return handler._send_json( + {"ok": False, "error": "独立测试评论接口已移除,请用养号参数中的评论概率/文案后启动养号流"}, + status=410, + ) + if u.path == "/api/stop": + runner.stop() + return handler._send_json({"ok": True}) + if u.path == "/api/screenshot": + body = handler._read_json() + requested_device_id = str(body.get("device_id") or "").strip() + device_id, err = _proc_ops.resolve_device_id_for_action(runner, requested_device_id) + if not device_id: + return handler._send_json({"ok": False, "error": err}, status=422) + try: + from douyin.core.underlying_operations import underlying_operations + + ops = underlying_operations() + result = ops.get_screenshot(device_id, use_service=False) + if result: + return handler._send_json({"ok": True, "message": "截图成功", "device_id": device_id}) + return handler._send_json({"ok": False, "error": "截图失败(设备可能离线)"}, status=409) + except Exception as e: + return handler._send_json({"ok": False, "error": str(e)}, status=500) + + handler.send_error(HTTPStatus.NOT_FOUND) diff --git a/tests/test_web_gui_routes_logic.py b/tests/test_web_gui_routes_logic.py new file mode 100644 index 0000000..e107901 --- /dev/null +++ b/tests/test_web_gui_routes_logic.py @@ -0,0 +1,137 @@ +"""web_gui_pkg.routes 关键逻辑单测(无需启动 HTTP 服务)。""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + +from gui.web_gui_pkg import routes + + +class _DummyHandler: + def __init__(self, body=None, csrf_token: str = "token"): + self.headers = {"X-CSRF-Token": csrf_token} + self._body = body if body is not None else {} + self.calls = [] + + def _read_json(self): + return self._body + + def _send_json(self, obj, status: int = 200): + self.calls.append((status, obj)) + return {"status": status, "obj": obj} + + def send_error(self, status): + self.calls.append((status, {"error": "send_error"})) + return None + + +class _DummyRunner: + def get_stats(self, include_events=False): # noqa: ARG002 + return {"ok": True} + + def is_running(self): + return False + + def get_reservations(self): + return {} + + def get_high_value_rooms(self): + return {} + + def force_stop(self): + return None + + def stop(self): + return None + + def send_back_key(self, _device_id): # noqa: ARG002 + return True + + def start_main_run(self, _cfg): # noqa: ARG002 + return None + + +def _post(path: str, body: dict, monkeypatch, csrf: str = "token"): + handler = _DummyHandler(body=body, csrf_token=csrf) + runner = _DummyRunner() + u = SimpleNamespace(path=path, query="") + routes.handle_post(handler, u, runner, "token") + assert handler.calls, f"{path} should produce a response" + return handler.calls[-1] + + +@pytest.mark.parametrize( + "raw,expected", + [ + (True, True), + (False, False), + ("true", True), + ("TRUE", True), + ("1", True), + ("yes", True), + ("on", True), + ("false", False), + ("FALSE", False), + ("0", False), + ("no", False), + ("off", False), + ("", False), + (0, False), + (1, True), + ], +) +def test_coerce_bool(raw, expected): + assert routes._coerce_bool(raw) is expected + + +def test_config_bool_string_false_written_as_false(monkeypatch): + written = {} + + monkeypatch.setattr(routes, "read_config", lambda: {"enable_streaming_screenshot": True}) + monkeypatch.setattr(routes, "write_config", lambda cfg: written.update(cfg)) + + status, obj = _post( + "/api/config", + {"config": {"enable_streaming_screenshot": "false"}}, + monkeypatch, + ) + assert status == 200 + assert obj.get("ok") is True + assert written.get("enable_streaming_screenshot") is False + + +@pytest.mark.parametrize( + "ports_raw,expected_invalid", + [ + (None, False), + ("", False), + ("5555", False), + ("5555,5556", False), + ("5555-5560", False), + (["5555", 5556], False), + ("abc", True), + ("5555,abc", True), + ("1-2-3", True), + (70000, True), + (["x"], True), + ], +) +def test_is_invalid_ports_spec(ports_raw, expected_invalid): + assert routes._is_invalid_ports_spec(ports_raw) is expected_invalid + + +def test_wifi_scan_invalid_ports_returns_400(monkeypatch): + monkeypatch.setattr(routes, "find_adb_executable", lambda: "adb") + status, obj = _post("/api/wifi/scan", {"ports": "abc"}, monkeypatch) + assert status == 400 + assert obj.get("error") == "invalid ports" + + +def test_wifi_auto_reconnect_without_adb_returns_422(monkeypatch): + monkeypatch.setattr(routes, "find_adb_executable", lambda: "") + status, obj = _post("/api/wifi/auto-reconnect", {}, monkeypatch) + assert status == 422 + assert obj.get("error") == "adb not found" + diff --git a/tests/test_webui_source_guards.py b/tests/test_webui_source_guards.py new file mode 100644 index 0000000..e6ebdfd --- /dev/null +++ b/tests/test_webui_source_guards.py @@ -0,0 +1,44 @@ +"""WebUI 关键安全/稳定性源码锚点测试。""" + +from __future__ import annotations + +import re +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] + + +def _read(rel: str) -> str: + return (ROOT / rel).read_text(encoding="utf-8") + + +def test_config_form_bool_literal_coercion_guard(): + src = _read("webui/js/config_form.js") + assert 'if (type === "bool")' in src + assert '["1", "true", "yes", "y", "on"]' in src + assert '["0", "false", "no", "n", "off", ""]' in src + + +def test_runtime_actions_reservation_fields_guarded(): + src = _read("webui/js/runtime_actions.js") + assert "safePrizeValue" in src + assert "safePosSeen" in src + assert "safeRoomPos" in src + assert "safeReservationsCount" in src + assert "safeTotal" in src + assert "escapeHtml(item.future_str || '-')" in src + + +def test_runtime_device_actions_send_back_key_handles_error(): + src = _read("webui/js/runtime_device_actions.js") + m = re.search( + r"async function sendBackKey\(\)\s*\{(?P.*?)\n\}", + src, + flags=re.S, + ) + assert m, "sendBackKey function not found" + body = m.group("body") + assert "try {" in body + assert "catch" in body + diff --git a/webui/js/config_form.js b/webui/js/config_form.js index 3499495..d363112 100644 --- a/webui/js/config_form.js +++ b/webui/js/config_form.js @@ -38,7 +38,13 @@ function getConfigValue(cfg, key) { } function coerceValue(type, raw, isCheckbox) { - if (type === "bool") return !!raw; + if (type === "bool") { + if (typeof raw === "boolean") return raw; + const text = String(raw ?? "").trim().toLowerCase(); + if (["1", "true", "yes", "y", "on"].includes(text)) return true; + if (["0", "false", "no", "n", "off", ""].includes(text)) return false; + return !!raw; + } if (type === "int") { const n = parseInt(String(raw ?? "0"), 10); return Number.isFinite(n) ? n : 0; diff --git a/webui/js/runtime_actions.js b/webui/js/runtime_actions.js index d576f9f..2786ea5 100644 --- a/webui/js/runtime_actions.js +++ b/webui/js/runtime_actions.js @@ -23,7 +23,6 @@ async function refreshDevices() { // 选中后在外层包装上反映状态点 decorateDeviceSelect(); - sel.addEventListener("change", decorateDeviceSelect); } function decorateDeviceSelect() { @@ -48,209 +47,6 @@ function decorateDeviceSelect() { if (dot) dot.dataset.state = ok ? "ok" : "idle"; } -function selectedDeviceId() { - const el = $("device"); - return el ? (el.value || "") : ""; -} - -async function postDeviceAction(path, body, successPrefix) { - try { - 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; - } -} - -async function forceStopRun() { - await postDeviceAction("/api/force-stop", {}, "[WEB] 强制停止"); -} - -async function sendBackKey() { - const deviceId = selectedDeviceId(); - await postDeviceAction("/api/back-key", { device_id: deviceId }, "[WEB] 返回键"); -} - -async function wifiEnable() { - const deviceId = selectedDeviceId(); - if (!deviceId) { - appendLog(["[WiFi ADB] 请先选择 USB 设备"]); - return; - } - const result = await postDeviceAction("/api/wifi/enable", { device_id: deviceId }, "[WiFi ADB] 启用"); - setTextIfExists("wifiStatus", result.message || "已发送启用命令"); -} - -async function wifiConnect() { - const ip = ($("wifi_ip")?.value || "").trim(); - const port = ($("wifi_port")?.value || "5555").trim() || "5555"; - if (!ip) { - appendLog(["[WiFi ADB] 请填写设备 IP"]); - return; - } - const result = await postDeviceAction("/api/wifi/connect", { ip, port }, "[WiFi ADB] 连接"); - setTextIfExists("wifiStatus", result.message || "连接命令已执行"); -} - -async function wifiDisconnect() { - const ip = ($("wifi_ip")?.value || selectedDeviceId() || "").trim(); - const port = ($("wifi_port")?.value || "5555").trim() || "5555"; - if (!ip) { - appendLog(["[WiFi ADB] 请填写 IP 或选择 WiFi 设备"]); - return; - } - const result = await postDeviceAction("/api/wifi/disconnect", { ip, port }, "[WiFi ADB] 断开"); - setTextIfExists("wifiStatus", result.message || "断开命令已执行"); -} - -async function tryAutoReconnectLastWifi() { - // 启动时调一次 /api/wifi/auto-reconnect。后端做完所有判断(已在线 / 重连成功 / - // 智能匹配 / 失败),前端只负责把结果反馈到日志和设备下拉。 - try { - const resp = await apiPost("/api/wifi/auto-reconnect", {}); - if (!resp || resp.ok === false) return; - const action = resp.action || "noop"; - if (action === "noop") return; - - if (action === "already_online" || action === "reconnected" || action === "matched") { - try { - await refreshDevices(); - } catch (_) {} - const sel = $("device"); - if (sel && resp.target) { - // 选中设备到下拉框 - for (const opt of sel.options) { - if (opt.value === resp.target) { - sel.value = resp.target; - break; - } - } - } - const status = $("wifiStatus"); - if (status && resp.message) status.textContent = resp.message; - appendLog([`[启动] ${resp.message || action}`]); - return; - } - - if (action === "failed") { - appendLog([`[启动] ${resp.message || "WiFi 自动重连失败"}`]); - const status = $("wifiStatus"); - if (status && resp.message) status.textContent = resp.message; - return; - } - } catch (e) { - // 启动期任何异常都不打扰用户 - console.warn("auto-reconnect failed", e); - } -} - -async function wifiScan() { - const btn = $("btnWifiScan"); - const status = $("wifiStatus"); - const results = $("wifiScanResults"); - if (btn) { - btn.disabled = true; - btn.textContent = "扫描中..."; - } - if (status) status.textContent = "正在扫描局域网..."; - if (results) { - results.style.display = "none"; - results.innerHTML = ""; - } - try { - const resp = await apiPost("/api/wifi/scan", {}); - if (!resp || resp.ok === false) { - const err = (resp && resp.error) || "扫描失败"; - appendLog([`[WiFi ADB] 扫描失败: ${err}`]); - if (status) status.textContent = `扫描失败: ${err}`; - return; - } - const devs = Array.isArray(resp.devices) ? resp.devices : []; - const subnet = resp.subnet || ""; - if (!devs.length) { - appendLog([`[WiFi ADB] 扫描完成 (${subnet}),未发现开放 5555 端口的设备`]); - if (status) status.textContent = `扫描完成 (${subnet}),未发现设备`; - return; - } - appendLog([ - `[WiFi ADB] 扫描完成 (${subnet}),发现 ${devs.length} 台候选: ` + - devs.map((d) => `${d.target}(${d.state})`).join(", "), - ]); - - // 单个 connected:自动选中 - const connected = devs.filter((d) => d.state === "connected"); - if (connected.length === 1 && devs.length === 1) { - const d = connected[0]; - const ipInput = $("wifi_ip"); - if (ipInput) ipInput.value = d.target; - if (status) - status.textContent = - `已发现并连接 ${d.target}` + (d.model ? ` (${d.model})` : "") + ",已记住"; - // 刷新设备下拉 - try { - await refreshDevices(); - } catch (_) {} - return; - } - - // 多个候选:渲染列表,点击就填回 IP - if (results) { - results.style.display = "block"; - const lines = devs.map((d) => { - const safeTarget = String(d.target || "").replace(/"/g, """); - const stateColor = - d.state === "connected" ? "#0a7d2c" : - d.state === "unauthorized" ? "#b35900" : "#888"; - return ( - `
` + - `${safeTarget} ` + - `[${d.state}] ` + - (d.model ? ` ${d.model}` : "") + - `
` - ); - }); - results.innerHTML = - `
点击下方设备使用:
` + - lines.join(""); - results.querySelectorAll("[data-target]").forEach((el) => { - el.addEventListener("click", () => { - const target = el.getAttribute("data-target"); - const state = el.getAttribute("data-state"); - if (state !== "connected") { - appendLog([ - `[WiFi ADB] ${target} 状态=${state},请先在手机上确认 ADB 调试授权`, - ]); - return; - } - const ipInput = $("wifi_ip"); - if (ipInput) ipInput.value = target; - if (status) status.textContent = `已选 ${target}`; - appendLog([`[WiFi ADB] 已选 ${target}`]); - try { - refreshDevices(); - } catch (_) {} - }); - }); - } - if (status) status.textContent = `扫描完成,发现 ${devs.length} 台设备`; - } catch (e) { - appendLog([`[WiFi ADB] 扫描异常: ${e}`]); - if (status) status.textContent = `扫描异常: ${e}`; - } finally { - if (btn) { - btn.disabled = false; - btn.textContent = "扫描 WiFi"; - } - } -} async function startRun() { setButtonBusy("btnStart", true); @@ -358,20 +154,6 @@ async function startRun() { } } -async function testYanghao() { - const deviceId = $("device").value || ""; - const seconds = parseInt($("yanghao_recommend_duration_seconds").value || "60", 10); - await apiPost("/api/test-yanghao", { device_id: deviceId, seconds }); - appendLog([`[WEB] 已启动测试养号:device=${deviceId || UI_COPY.device.autoLabel} seconds=${seconds}`]); -} - -async function testComment() { - const deviceId = $("device").value || ""; - const text = ""; - await apiPost("/api/test-comment", { device_id: deviceId, text }); - appendLog([`[WEB] 已启动测试评论:device=${deviceId || UI_COPY.device.autoLabel}${text ? ' text=自定义' : ''}`]); -} - async function stopRun() { setRunOverview(UI_COPY.runOverview.stopping, UI_COPY.runOverview.stoppingMeta, RUN_TONE.idle); await apiPost("/api/stop", {}); @@ -493,11 +275,15 @@ async function pollReservations() { // 显示基本信息 const info = document.createElement("div"); info.className = "reservationsInfo"; + const safeRoomPos = Number.isFinite(Number(room_pos)) ? Number(room_pos) : 0; + const safeReservationsCount = Number.isFinite(Number(reservations.length)) + ? Number(reservations.length) + : 0; info.innerHTML = ` -
当前位置:${room_pos}
+
当前位置:${safeRoomPos}
当前直播间(清洗后):${escapeHtml(current_room_title || '-') }
当前直播间原文:${escapeHtml(current_room_title_raw || '-') }
-
预约数量:${reservations.length}
+
预约数量:${safeReservationsCount}
更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}
原因:${escapeHtml(reason || '-') }
`; @@ -525,6 +311,10 @@ async function pollReservations() { 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}秒后` : "已到开奖时间"; + const safePrizeValue = Number.isFinite(Number(item.prize_value_yuan)) + ? Number(item.prize_value_yuan) + : 0; + const safePosSeen = Number.isFinite(Number(item.pos_seen)) ? Number(item.pos_seen) : 0; // 60s 内开奖:高亮提醒 if (remain > 0 && remain <= 60) card.classList.add("isImminent"); else if (remain === 0) card.classList.add("isDue"); @@ -534,13 +324,13 @@ async function pollReservations() { card.innerHTML = `
#${idx + 1} - ${item.prize_value_yuan || 0}元 + ${safePrizeValue}元
内容:${escapeHtml(item.content || '-')}
-
开奖时间:${item.future_str || '-'}
+
开奖时间:${escapeHtml(item.future_str || '-')}
剩余时间:${remainStr}
-
发现位置:${item.pos_seen || 0}
+
发现位置:${safePosSeen}
直播间(清洗后):${escapeHtml(item.room_title || '-')}
直播间原文:${escapeHtml(item.room_title_raw || '-')}
@@ -580,8 +370,9 @@ async function pollHighValueRooms() { const info = document.createElement("div"); info.className = "reservationsInfo"; + const safeTotal = Number.isFinite(Number(total)) ? Number(total) : 0; info.innerHTML = ` -
记录数量:${total}
+
记录数量:${safeTotal}
更新时间:${updated_ts > 0 ? new Date(updated_ts * 1000).toLocaleTimeString() : '-'}
原因:${escapeHtml(reason || '-') }
`; @@ -650,14 +441,18 @@ async function pollHighValueRooms() { try { const btnExpand = $('hv_expand_all'); const btnCollapse = $('hv_collapse_all'); - if (btnExpand) btnExpand.addEventListener('click', () => { - const listEl = container.querySelector(`.${UI_CLASS.reservationsList}`); - if (listEl) listEl.classList.remove(UI_CLASS.listCollapsed); - }); - if (btnCollapse) btnCollapse.addEventListener('click', () => { - const listEl = container.querySelector(`.${UI_CLASS.reservationsList}`); - if (listEl) listEl.classList.add(UI_CLASS.listCollapsed); - }); + if (btnExpand) { + btnExpand.onclick = () => { + const listEl = container.querySelector(`.${UI_CLASS.reservationsList}`); + if (listEl) listEl.classList.remove(UI_CLASS.listCollapsed); + }; + } + if (btnCollapse) { + btnCollapse.onclick = () => { + const listEl = container.querySelector(`.${UI_CLASS.reservationsList}`); + if (listEl) listEl.classList.add(UI_CLASS.listCollapsed); + }; + } } catch (e) { // ignore } diff --git a/webui/js/runtime_device_actions.js b/webui/js/runtime_device_actions.js new file mode 100644 index 0000000..f02e7a3 --- /dev/null +++ b/webui/js/runtime_device_actions.js @@ -0,0 +1,235 @@ +// Device and test actions split from runtime_actions.js. + +function selectedDeviceId() { + const el = $("device"); + return el ? (el.value || "") : ""; +} + +function renderWifiScanResults(resultsEl, devices) { + if (!resultsEl) return; + resultsEl.innerHTML = ""; + const title = document.createElement("div"); + title.style.marginBottom = "4px"; + title.style.color = "#555"; + title.textContent = "点击下方设备使用:"; + resultsEl.appendChild(title); + for (const d of devices) { + const row = document.createElement("div"); + row.style.margin = "4px 0"; + row.style.cursor = "pointer"; + row.style.padding = "4px 6px"; + row.style.border = "1px solid #ddd"; + row.style.borderRadius = "4px"; + row.dataset.target = String(d.target || ""); + row.dataset.state = String(d.state || ""); + const target = document.createElement("b"); + target.textContent = String(d.target || ""); + const state = document.createElement("span"); + const st = String(d.state || ""); + state.style.color = st === "connected" ? "#0a7d2c" : (st === "unauthorized" ? "#b35900" : "#888"); + state.textContent = ` [${st}]`; + row.appendChild(target); + row.appendChild(state); + if (d.model) { + const model = document.createElement("span"); + model.style.color = "#555"; + model.textContent = ` ${String(d.model)}`; + row.appendChild(model); + } + resultsEl.appendChild(row); + } +} + +async function postDeviceAction(path, body, successPrefix) { + try { + 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; + } +} + +async function forceStopRun() { + await postDeviceAction("/api/force-stop", {}, "[WEB] 强制停止"); +} + +async function sendBackKey() { + const deviceId = selectedDeviceId(); + try { + await postDeviceAction("/api/back-key", { device_id: deviceId }, "[WEB] 返回键"); + } catch (_) { + // 错误已在 postDeviceAction 内展示,避免未捕获 Promise 冒泡到全局。 + } +} + +async function wifiEnable() { + const deviceId = selectedDeviceId(); + if (!deviceId) { + appendLog(["[WiFi ADB] 请先选择 USB 设备"]); + return; + } + const result = await postDeviceAction("/api/wifi/enable", { device_id: deviceId }, "[WiFi ADB] 启用"); + setTextIfExists("wifiStatus", result.message || "已发送启用命令"); +} + +async function wifiConnect() { + const ip = ($("wifi_ip")?.value || "").trim(); + const port = ($("wifi_port")?.value || "5555").trim() || "5555"; + if (!ip) { + appendLog(["[WiFi ADB] 请填写设备 IP"]); + return; + } + const result = await postDeviceAction("/api/wifi/connect", { ip, port }, "[WiFi ADB] 连接"); + setTextIfExists("wifiStatus", result.message || "连接命令已执行"); +} + +async function wifiDisconnect() { + const ip = ($("wifi_ip")?.value || selectedDeviceId() || "").trim(); + const port = ($("wifi_port")?.value || "5555").trim() || "5555"; + if (!ip) { + appendLog(["[WiFi ADB] 请填写 IP 或选择 WiFi 设备"]); + return; + } + const result = await postDeviceAction("/api/wifi/disconnect", { ip, port }, "[WiFi ADB] 断开"); + setTextIfExists("wifiStatus", result.message || "断开命令已执行"); +} + +async function tryAutoReconnectLastWifi() { + try { + const resp = await apiPost("/api/wifi/auto-reconnect", {}); + if (!resp || resp.ok === false) return; + const action = resp.action || "noop"; + if (action === "noop") return; + + if (action === "already_online" || action === "reconnected" || action === "matched") { + try { + await refreshDevices(); + } catch (_) {} + const sel = $("device"); + if (sel && resp.target) { + for (const opt of sel.options) { + if (opt.value === resp.target) { + sel.value = resp.target; + break; + } + } + } + const status = $("wifiStatus"); + if (status && resp.message) status.textContent = resp.message; + appendLog([`[启动] ${resp.message || action}`]); + return; + } + + if (action === "failed") { + appendLog([`[启动] ${resp.message || "WiFi 自动重连失败"}`]); + const status = $("wifiStatus"); + if (status && resp.message) status.textContent = resp.message; + return; + } + } catch (e) { + console.warn("auto-reconnect failed", e); + } +} + +async function wifiScan() { + const btn = $("btnWifiScan"); + const status = $("wifiStatus"); + const results = $("wifiScanResults"); + if (btn) { + btn.disabled = true; + btn.textContent = "扫描中..."; + } + if (status) status.textContent = "正在扫描局域网..."; + if (results) { + results.style.display = "none"; + results.innerHTML = ""; + } + try { + const resp = await apiPost("/api/wifi/scan", {}); + if (!resp || resp.ok === false) { + const err = (resp && resp.error) || "扫描失败"; + appendLog([`[WiFi ADB] 扫描失败: ${err}`]); + if (status) status.textContent = `扫描失败: ${err}`; + return; + } + const devs = Array.isArray(resp.devices) ? resp.devices : []; + const subnet = resp.subnet || ""; + if (!devs.length) { + appendLog([`[WiFi ADB] 扫描完成 (${subnet}),未发现开放 5555 端口的设备`]); + if (status) status.textContent = `扫描完成 (${subnet}),未发现设备`; + return; + } + appendLog([ + `[WiFi ADB] 扫描完成 (${subnet}),发现 ${devs.length} 台候选: ` + + devs.map((d) => `${d.target}(${d.state})`).join(", "), + ]); + + const connected = devs.filter((d) => d.state === "connected"); + if (connected.length === 1 && devs.length === 1) { + const d = connected[0]; + const ipInput = $("wifi_ip"); + if (ipInput) ipInput.value = d.target; + if (status) + status.textContent = + `已发现并连接 ${d.target}` + (d.model ? ` (${d.model})` : "") + ",已记住"; + try { + await refreshDevices(); + } catch (_) {} + return; + } + + if (results) { + results.style.display = "block"; + renderWifiScanResults(results, devs); + results.querySelectorAll("[data-target]").forEach((el) => { + el.addEventListener("click", () => { + const target = el.getAttribute("data-target"); + const state = el.getAttribute("data-state"); + if (state !== "connected") { + appendLog([ + `[WiFi ADB] ${target} 状态=${state},请先在手机上确认 ADB 调试授权`, + ]); + return; + } + const ipInput = $("wifi_ip"); + if (ipInput) ipInput.value = target; + if (status) status.textContent = `已选 ${target}`; + appendLog([`[WiFi ADB] 已选 ${target}`]); + try { + refreshDevices(); + } catch (_) {} + }); + }); + } + if (status) status.textContent = `扫描完成,发现 ${devs.length} 台设备`; + } catch (e) { + appendLog([`[WiFi ADB] 扫描异常: ${e}`]); + if (status) status.textContent = `扫描异常: ${e}`; + } finally { + if (btn) { + btn.disabled = false; + btn.textContent = "扫描 WiFi"; + } + } +} + +async function testYanghao() { + const deviceId = $("device").value || ""; + const seconds = parseInt($("yanghao_recommend_duration_seconds").value || "60", 10); + await apiPost("/api/test-yanghao", { device_id: deviceId, seconds }); + appendLog([`[WEB] 已启动测试养号:device=${deviceId || UI_COPY.device.autoLabel} seconds=${seconds}`]); +} + +async function testComment() { + const deviceId = $("device").value || ""; + const text = ""; + await apiPost("/api/test-comment", { device_id: deviceId, text }); + appendLog([`[WEB] 已启动测试评论:device=${deviceId || UI_COPY.device.autoLabel}${text ? ' text=自定义' : ''}`]); +}