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 douyin.license.license_manager import ( get_default_activation_url, get_license_status_payload, install_license_or_activate, ) 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", ""} _EMPTY_PNG_BYTES = bytes.fromhex( "89504e470d0a1a0a0000000d4948445200000001000000010806000000" "1f15c4890000000a49444154789c636000000200015dc1b2ea00000000" "49454e44ae426082" ) def _is_local_request(handler) -> bool: try: host = str((handler.client_address or ("",))[0] or "").strip() except Exception: return False return host in {"127.0.0.1", "::1", "localhost"} 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 _license_activation_settings() -> tuple[str, int]: cfg = read_config() section = cfg.get("license") if isinstance(cfg.get("license"), dict) else {} activation_url = str(section.get("activation_url") or "").strip() or get_default_activation_url() try: timeout_seconds = int(section.get("timeout_seconds") or 10) except (TypeError, ValueError): timeout_seconds = 10 return activation_url, max(1, timeout_seconds) 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 _coerce_region_values(value) -> list[int] | None: if not isinstance(value, (list, tuple)): return None if len(value) != 4: return None try: return [int(item) for item in value] except Exception: return None def handle_get(handler, u, runner, csrf_token: str) -> None: if u.path.startswith("/api/"): if not _is_local_request(handler): return handler._send_json( {"ok": False, "error": "Local access only"}, status=403 ) 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/license": return handler._send_json(get_license_status_payload()) 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(), "paused": runner.is_paused(), } ) 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(), "paused": runner.is_paused(), } ) 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(), "paused": runner.is_paused(), } ) 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(), "paused": runner.is_paused(), } ) 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/"): if not _is_local_request(handler): return handler._send_json( {"ok": False, "error": "Local access only"}, status=403 ) 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): if safe == "pic/screenshot.png": handler.send_response(HTTPStatus.OK) handler.send_header("Content-Type", "image/png") handler.send_header("Content-Length", str(len(_EMPTY_PNG_BYTES))) handler.send_header("Cache-Control", "no-store") handler.end_headers() handler.wfile.write(_EMPTY_PNG_BYTES) return 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 if not _is_local_request(handler): handler.send_error(HTTPStatus.FORBIDDEN) return handler._serve_static(u.path) def handle_post(handler, u, runner, csrf_token: str) -> None: if not _is_local_request(handler): return handler._send_json( {"ok": False, "error": "Local access only"}, status=403 ) 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", "fudai_detail_body_bluepurple_threshold", "fudai_detail_body_dark_threshold", "fudai_task_status_template_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", "fudai_detail_save_debug_images", "region_coords_edit_enabled", "fudai_detail_ocr_content_enabled", "fudai_detail_ocr_value_enabled", "fudai_detail_ocr_countdown_enabled", "fudai_detail_ocr_task_enabled", "fudai_detail_ocr_task_count_enabled", "fudai_detail_ocr_button_enabled", "fudai_detail_ocr_participants_enabled", "fudai_detail_ocr_live_title_enabled", "pixel_detect_fudai_icon_enabled", "pixel_detect_coupon_popup_enabled", "pixel_detect_shopping_redpacket_enabled", "pixel_detect_lottery_result_enabled", "pixel_detect_attend_button_enabled", "pixel_detect_fansclub_join_enabled", "pixel_detect_fudai_detail_enabled", "pixel_detect_live_room_enabled", "ocr_lottery_result_enabled", "ocr_coupon_popup_enabled", "ocr_shopping_redpacket_enabled", "ocr_stage_page_enabled", "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", } enum_str_keys = { "reset_after_swipes_action", "reenter_live_entry_mode", "fudai_detail_ui_mode", "logging.log_format_mode", } region_list_keys = { "fudai_detail_regions.legacy.content", "fudai_detail_regions.legacy.value", "fudai_detail_regions.legacy.countdown_full", "fudai_detail_regions.legacy.task_list", "fudai_detail_regions.legacy.task_count", "fudai_detail_regions.legacy.participants", "fudai_detail_regions.legacy.button", "fudai_detail_regions.legacy.live_title", "fudai_detail_regions.v2_0_two_task.content", "fudai_detail_regions.v2_0_two_task.value", "fudai_detail_regions.v2_0_two_task.countdown_full", "fudai_detail_regions.v2_0_two_task.task_list", "fudai_detail_regions.v2_0_two_task.task_count", "fudai_detail_regions.v2_0_two_task.participants", "fudai_detail_regions.v2_0_two_task.button", "fudai_detail_regions.v2_0_two_task.live_title", "fudai_detail_regions.v2_0_one_task.content", "fudai_detail_regions.v2_0_one_task.value", "fudai_detail_regions.v2_0_one_task.countdown_full", "fudai_detail_regions.v2_0_one_task.info_line", "fudai_detail_regions.v2_0_one_task.task_list", "fudai_detail_regions.v2_0_one_task.task_count", "fudai_detail_regions.v2_0_one_task.participants", "fudai_detail_regions.v2_0_one_task.button", "fudai_detail_regions.v2_0_one_task.live_title", "pixel_regions.lottery_result.button", "pixel_regions.lottery_result.pixel", "pixel_regions.lottery_result.click", "pixel_regions.attend_button", "pixel_regions.fansclub_join", "pixel_regions.coupon_popup", "pixel_regions.shopping_redpacket", "pixel_regions.fudai_detail_body", "pixel_regions.fudai_task_status", "pixel_regions.live_room_icon_bbox", } derived_logging_keys = { "logging.debug_detail_level", "logging.error_detail_level", "logging.action_log_format", } 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 def get_nested_value(obj, key, default=None): current = obj for part in key.split("."): if not isinstance(current, dict) or part not in current: return default current = current[part] return current def normalize_log_format_mode(value): mode = str(value or "simple").strip().lower() return mode if mode in ("simple", "detailed") else "simple" def apply_derived_logging_fields(): mode = normalize_log_format_mode( get_nested_value(cfg, "logging.log_format_mode", "simple") ) set_nested_value(cfg, "logging.log_format_mode", mode) if mode == "detailed": set_nested_value(cfg, "logging.debug_detail_level", "detailed") set_nested_value(cfg, "logging.action_log_format", "detailed") else: set_nested_value(cfg, "logging.debug_detail_level", "normal") set_nested_value(cfg, "logging.action_log_format", "concise") set_nested_value(cfg, "logging.error_detail_level", "full") for k, v in (update or {}).items(): if k in deny_keys: continue if k in derived_logging_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()] ) elif k in region_list_keys: parsed = _coerce_region_values(v) if parsed is None: continue set_nested_value(cfg, k, parsed) elif k in enum_str_keys: val = str(v or "").strip().lower() if k == "reset_after_swipes_action": if val not in ("swipe", "back"): continue if k == "reenter_live_entry_mode": if val not in ("follow_list", "screen_center"): continue if k == "fudai_detail_ui_mode": if val not in ("auto", "legacy", "v2_0"): continue if k == "logging.log_format_mode": if val not in ("simple", "detailed"): continue set_nested_value(cfg, k, val) else: set_nested_value(cfg, k, v) apply_derived_logging_fields() write_config(cfg) return handler._send_json({"ok": True}) if u.path == "/api/license": body = handler._read_json() text = str(body.get("license_text") or "").strip() if not text: return handler._send_json( {"ok": False, "error": "missing license_text"}, status=400, ) activation_url, timeout_seconds = _license_activation_settings() status = install_license_or_activate( text, activation_url=activation_url, timeout_seconds=timeout_seconds, ) payload = get_license_status_payload() payload.update( {"ok": status.ok, "reason": status.reason, "message": status.message} ) return handler._send_json(payload, status=200 if status.ok else 400) 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/pause": ok = runner.pause() return handler._send_json( { "ok": bool(ok), "running": runner.is_running(), "paused": runner.is_paused(), "message": "已暂停" if ok else "暂停失败", }, status=200 if ok else 409, ) if u.path == "/api/resume": ok = runner.resume() return handler._send_json( { "ok": bool(ok), "running": runner.is_running(), "paused": runner.is_paused(), "message": "已继续" if ok else "继续失败", }, status=200 if ok else 409, ) 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 "") disconnect_target = ip if ":" in ip else f"{ip}:{port}" if last_target == disconnect_target: 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.12) 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) ports_for_scan = None if ports_raw is None or str(ports_raw).strip() == "" else port_list 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, get_local_subnets devs = discover_adb_devices( adb, subnet_spec=subnet, ports=ports_for_scan, probe_timeout=probe_timeout ) tried_subnets = [subnet] if subnet else (get_local_subnets() or []) 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 "", "subnets": tried_subnets, "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}", } ) selected_target = existing[0] if existing else "" background_mode = bool(existing) 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_background" if background_mode else "reconnected", "target": target, "model": model, "selected_target": selected_target, "message": ( f"后台重连成功: {target},当前选择仍为 {selected_target}" if background_mode else f"自动重连成功: {target}" ), } ) if state == "unauthorized": return handler._send_json( { "ok": True, "action": "failed", "target": target, "model": model, "selected_target": selected_target, "message": f"上次设备 {target} 未授权,请在手机上确认 ADB 调试授权", } ) try: light_ports = [5555, 44219] try: if ":" in target: hinted_port = int(target.rsplit(":", 1)[1]) light_ports.insert(0, hinted_port) except Exception: pass deduped_ports = [] for port in light_ports: if port not in deduped_ports: deduped_ports.append(port) devs = discover_adb_devices(adb, ports=deduped_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, "selected_target": selected_target, "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 "", "selected_target": selected_target, "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)