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)