From e7a7d3f88816998a7d5c59ff33c61dba62581e31 Mon Sep 17 00:00:00 2001 From: Codex Date: Wed, 20 May 2026 18:43:58 +0800 Subject: [PATCH] Fix device selection and adb command safety --- .gitignore | 179 +++++++++++----- Underlying_Operations.py | 261 +++++++++++++++++------- douyin/core/douyin_fudai.py | 50 +++-- douyin/handlers/douyin_swipe_handler.py | 28 ++- douyin/handlers/douyin_swipe_ops.py | 38 ++-- gui/gui_core.py | 74 ++++--- gui/web_gui.py | 41 +++- tools/check_dependencies.py | 2 +- tools/install_dependencies.py | 4 +- 9 files changed, 454 insertions(+), 223 deletions(-) diff --git a/.gitignore b/.gitignore index 33bdc1c..29076fb 100644 --- a/.gitignore +++ b/.gitignore @@ -1,22 +1,101 @@ -# Python +# Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] +*$py.class -# Virtual env +# Python build artifacts +build/ +dist/ +downloads/ +eggs/ +.eggs/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# Virtual environments .venv/ +venv/ +env/ +ENV/ +.env +.env/ +.env.* +!.env.example -# Runtime artifacts +# Python tooling caches +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +.pyre/ +.pytype/ +.tox/ +.nox/ +.coverage +.coverage.* +coverage.xml +htmlcov/ +pip-wheel-metadata/ + +# Type check / lint reports +pylint_report.txt +pyright_report.txt +*.report +*.lint + +# Logs and runtime traces +logs/ *.log -pic/ +*.log.* +*.trace +*.pid +.web_gui_pid +git_lsremote_trace.txt +log_filter_result.txt +time_analysis_result.txt -# Tools generated reports -# Tools generated reports (ignore any large/temporary csv reports) +# Local runtime state and generated caches +state/ +pic/ +screenshots/ +captures/ +tmp/ +temp/ +.tmp/ +*.tmp +*.temp +*.cache +*.sqlite +*.sqlite3 +*.db +*.db-journal +*.db-shm +*.db-wal +*.jsonl +.stats_test_cache.json +.web_stats_cache.json + +# Local configuration and backups +config/*.json +!config/README.md +*.bak +*.backup +*.orig +*.swp +*.swo +*~ + +# Generated tool reports and samples tools/coords_report*.csv tools/*_report*.csv tools/*_report*.csv.gz tools/*.csv - -# Tools sample/ocr artifacts tools/ocr_failures* tools/ocr_failures/ tools/samples/ @@ -24,55 +103,43 @@ tools/*.zip tools/*.tar.gz tools/*.bundle -# Logs (keep local logs out of VCS) -logs/ -*.log* -logs/*.gz -*.log - -# Archive and backup files -*.zip -*.tar.gz -*.tgz -*.bak -*.bundle - -# Large DB / cache files -*.sqlite -*.db -*.db-journal - -# Editor/project user files -.idea/ -*.suo -*.user -*.sln.docstates - -# Code analysis reports -pylint_report.txt -pyright_report.txt -*.report -*.lint - -# Test coverage -.coverage -.coverage.* -htmlcov/ -.tox/ -.pytest_cache/ - -# VS Code -.vscode/ - -# Cursor IDE -.cursor/ -.specstory/ - -# OS -.DS_Store -Thumbs.db +# Project-specific generated state douyin/core/state/reservations.json -state/high_value_rooms.json douyin/core/state/room_pos_map.csv douyin/core/state/room_pos_map.json douyin/core/state/room_pos_map.md +state/high_value_rooms.json + +# Archives and bundles +*.zip +*.tar.gz +*.tgz +*.rar +*.7z +*.bundle + +# Node / frontend caches +node_modules/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +.parcel-cache/ +.next/ +.vite/ + +# IDE and editor files +.vscode/ +.idea/ +.cursor/ +.specstory/ +*.suo +*.user +*.userosscache +*.sln.docstates + +# OS files +.DS_Store +Thumbs.db +ehthumbs.db +Desktop.ini diff --git a/Underlying_Operations.py b/Underlying_Operations.py index 9777091..01f4240 100644 --- a/Underlying_Operations.py +++ b/Underlying_Operations.py @@ -1,6 +1,7 @@ import subprocess from datetime import datetime, timedelta import os +import sys import warnings # PaddleOCR 3.x 会在初始化/导入时进行模型源连通性检查;在国内网络环境下容易卡住。 @@ -314,7 +315,6 @@ class underlying_operations: self._screenshot_log_path = os.path.join( os.path.dirname(__file__), "logs", "screenshot_calls.jsonl" ) - @staticmethod def _adb() -> str: adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb") @@ -331,6 +331,13 @@ class underlying_operations: adb = adb[1:-1] return adb + def _adb_args(self, device_id: str, *args: object) -> list[str]: + return [self._adb_path(), "-s", str(device_id), *[str(arg) for arg in args]] + + @staticmethod + def _split_shell_cmd(shell_cmd: str) -> list[str]: + return shlex.split(str(shell_cmd or ""), posix=(os.name != "nt")) + def _ensure_ocr(self): if self.ocr is not None: return @@ -401,15 +408,22 @@ class underlying_operations: def select_device(self): """选择需要连接的设备""" - string = subprocess.Popen( - f"{self._adb()} devices", shell=True, stdout=subprocess.PIPE + result = subprocess.run( + [self._adb_path(), "devices", "-l"], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + encoding="utf-8", + errors="replace", + check=False, ) - assert string.stdout is not None - totalstring = string.stdout.read() - totalstring = totalstring.decode("utf-8") + totalstring = result.stdout or "" # print(totalstring) - pattern = r"(\b(?:[0-9]{1,3}(?:\.[0-9]{1,3}){3}(?::[0-9]+)?|[A-Za-z0-9]{8,})\b)\s*device\b" - devicelist = re.findall(pattern, totalstring) + devicelist = [] + for line in totalstring.splitlines()[1:]: + parts = line.split() + if len(parts) >= 2 and parts[1] == "device": + devicelist.append(parts[0]) # devicelist = re.compile(r'(\w*)\s*device\b').findall(totalstring) devicenum = len(devicelist) if devicenum == 0: @@ -422,16 +436,21 @@ class underlying_operations: print("当前存在多台设备连接! 输入数字选择对应设备:") dictdevice = {} for i in range(devicenum): - string = subprocess.Popen( - "%s -s %s shell getprop ro.product.device" - % (self._adb(), devicelist[i]), - shell=True, + prop = subprocess.run( + self._adb_args(devicelist[i], "shell", "getprop", "ro.product.device"), stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + encoding="utf-8", + errors="replace", + check=False, ) - assert string.stdout is not None - modestring = string.stdout.read().strip() # 去除掉自动生成的回车 + modestring = (prop.stdout or "").strip() print("%s:%s---%s" % (i + 1, devicelist[i], modestring)) dictdevice[i + 1] = devicelist[i] + if not sys.stdin.isatty(): + print("检测到多台设备且当前不是交互式终端,请通过 --device-id 明确指定设备。") + return False num = input() num = int(num) while not num in dictdevice.keys(): @@ -1194,26 +1213,38 @@ class underlying_operations: def click_confirm(self, device_id): """点击确认键""" - os.system("%s -s %s shell input keyevent 66" % (self._adb(), device_id)) + subprocess.run( + self._adb_args(device_id, "shell", "input", "keyevent", "66"), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + ) print("点击确认键") def click_back(self, device_id): """点击返回键""" - os.system("%s -s %s shell input keyevent 4" % (self._adb(), device_id)) + subprocess.run( + self._adb_args(device_id, "shell", "input", "keyevent", "4"), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + ) print("点击返回键") # 电量检测方法已删除 def get_device_resolution(self, device_id): """获取设备分辨率""" - resolution_info = subprocess.Popen( - "%s -s %s shell wm size" % (self._adb(), device_id), - shell=True, + resolution_info = subprocess.run( + self._adb_args(device_id, "shell", "wm", "size"), stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + encoding="utf-8", + errors="replace", + check=False, ) - assert resolution_info.stdout is not None - resolution_info_string = resolution_info.stdout.read() - resolution_info_string = bytes.decode(resolution_info_string) + resolution_info_string = resolution_info.stdout or "" match = re.search(r"Physical size: (\d+)x(\d+)", resolution_info_string) if match: width = int(match.group(1)) @@ -2603,20 +2634,29 @@ class underlying_operations: 执行命令:adb shell input swipe """ - adb_cmd = self._adb() # 注意:adb input swipe 的参数顺序是:start_x start_y end_x end_y duration_ms # 这里 left_up_x/y 是起始位置,right_down_x/y 是结束位置 - cmd = f"{adb_cmd} -s {device_id} shell input swipe {left_up_x} {left_up_y} {right_down_x} {right_down_y} {steps}" - + cmd = self._adb_args( + device_id, + "shell", + "input", + "swipe", + int(left_up_x), + int(left_up_y), + int(right_down_x), + int(right_down_y), + int(steps), + ) try: # 使用 subprocess 执行命令,捕获错误输出 result = subprocess.run( cmd, - shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=5.0, text=True, + encoding="utf-8", + errors="replace", check=False, ) @@ -2651,9 +2691,14 @@ class underlying_operations: except subprocess.TimeoutExpired: print("[警告] 滑动操作超时") except Exception as e: - # 降级到原来的 os.system 方法 + # 降级重试一次,保持旧逻辑的宽容行为。 try: - os.system(cmd) + subprocess.run( + cmd, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + ) except Exception: print(f"[警告] 滑动操作失败: {type(e).__name__}: {e}") @@ -2661,15 +2706,16 @@ class underlying_operations: """使用 sendevent 方法滑动(需要 root 权限)""" # 获取触摸设备路径 result = subprocess.run( - f"{self._adb()} -s {device_id} shell getevent -p | grep -A 5 ABS_MT", - shell=True, + self._adb_args(device_id, "shell", "getevent", "-p"), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, + encoding="utf-8", + errors="replace", check=False, ) - if "event" not in result.stdout.lower(): + if "ABS_MT" not in result.stdout or "event" not in result.stdout.lower(): raise FileNotFoundError("无法找到触摸设备") # 简化实现:直接使用 input 命令的替代参数 @@ -2685,12 +2731,10 @@ class underlying_operations: # 使用 uiautomator swipe 命令 # 注意:uiautomator 命令格式可能因 Android 版本而异 # Android 5.0+: uiautomator swipe [steps] - cmd = ( - f"{self._adb()} -s {device_id} shell uiautomator swipe {x1} {y1} {x2} {y2}" - ) result = subprocess.run( - cmd, - shell=True, + self._adb_args( + device_id, "shell", "uiautomator", "swipe", int(x1), int(y1), int(x2), int(y2) + ), stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=5.0, @@ -2712,11 +2756,12 @@ class underlying_operations: # 获取触摸设备路径(通常是 /dev/input/eventX) result = subprocess.run( - f"{self._adb()} -s {device_id} shell getevent -p 2>/dev/null | grep -A 10 ABS_MT", - shell=True, + self._adb_args(device_id, "shell", "getevent", "-p"), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, + encoding="utf-8", + errors="replace", timeout=3.0, check=False, ) @@ -2728,7 +2773,7 @@ class underlying_operations: # 3. 将屏幕坐标转换为设备坐标 # 4. 发送 DOWN -> MOVE -> UP 事件序列 - if "event" not in result.stdout.lower(): + if "ABS_MT" not in result.stdout or "event" not in result.stdout.lower(): raise FileNotFoundError("无法找到触摸设备(需要 root 权限)") # 注意:完整的 sendevent 实现非常复杂,需要: @@ -2751,7 +2796,12 @@ class underlying_operations: print(f"[Underlying] click: device_id={device_id} coord=({x},{y})") except Exception: pass - os.system("{} -s {} shell input tap {} {}".format(self._adb(), device_id, x, y)) + subprocess.run( + self._adb_args(device_id, "shell", "input", "tap", int(x), int(y)), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + ) def long_press( self, device_id: str, x: int, y: int, duration_ms: int = 900 @@ -2762,8 +2812,13 @@ class underlying_operations: d = 300 if d > 2000: d = 2000 - os.system( - f"{self._adb()} -s {device_id} shell input swipe {int(x)} {int(y)} {int(x)} {int(y)} {d}" + subprocess.run( + self._adb_args( + device_id, "shell", "input", "swipe", int(x), int(y), int(x), int(y), d + ), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, ) def _run_adb_shell( @@ -2772,8 +2827,7 @@ class underlying_operations: """运行 adb shell 命令,成功返回 True。""" try: r = subprocess.run( - f"{self._adb()} -s {device_id} shell {shell_cmd}", - shell=True, + self._adb_args(device_id, "shell", *self._split_shell_cmd(shell_cmd)), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout_seconds, @@ -2789,8 +2843,7 @@ class underlying_operations: """运行 adb shell 命令并捕获输出,返回 (ok, stdout)。""" try: r = subprocess.run( - f"{self._adb()} -s {device_id} shell {shell_cmd}", - shell=True, + self._adb_args(device_id, "shell", *self._split_shell_cmd(shell_cmd)), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=timeout_seconds, @@ -2836,10 +2889,6 @@ class underlying_operations: pass return "" - @staticmethod # type: ignore[misc] - def _escape_shell_double_quotes(text: str) -> str: - return str(text).replace("\\", "\\\\").replace('"', '\\"') - def set_clipboard_text(self, device_id: str, text: str) -> bool: """设置设备剪贴板文本(尽量支持中文)。 @@ -2850,20 +2899,47 @@ class underlying_operations: if not t: return False - # 1) cmd clipboard set "..." - esc = self._escape_shell_double_quotes(t) - if self._run_adb_shell( - device_id, f'cmd clipboard set "{esc}"', timeout_seconds=3.0 - ): - return True + # 1) cmd clipboard set + try: + if ( + subprocess.run( + self._adb_args(device_id, "shell", "cmd", "clipboard", "set", t), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=3.0, + check=False, + ).returncode + == 0 + ): + return True + except Exception: + pass # 2) Clipper broadcast: am broadcast -a clipper.set -e text "..." - if self._run_adb_shell( - device_id, - f'am broadcast -a clipper.set -e text "{esc}"', - timeout_seconds=3.0, - ): - return True + try: + if ( + subprocess.run( + self._adb_args( + device_id, + "shell", + "am", + "broadcast", + "-a", + "clipper.set", + "-e", + "text", + t, + ), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=3.0, + check=False, + ).returncode + == 0 + ): + return True + except Exception: + pass return False @@ -2886,11 +2962,19 @@ class underlying_operations: .replace(">", "\\>") .replace("|", "\\|") ) - return self._run_adb_shell( - device_id, - f'input text "{self._escape_shell_double_quotes(t)}"', - timeout_seconds=5.0, - ) + try: + return ( + subprocess.run( + self._adb_args(device_id, "shell", "input", "text", t), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=5.0, + check=False, + ).returncode + == 0 + ) + except Exception: + return False def paste_text(self, device_id: str, text: str) -> bool: """优先走剪贴板粘贴,其次兜底 input text。""" @@ -3005,11 +3089,22 @@ class underlying_operations: act = str(action or "").strip() if not act: return False - esc = self._escape_shell_double_quotes(str(msg or "")) # 这里不依赖 broadcast 的返回文本,只要命令成功执行就认为 ok - return self._run_adb_shell( - device_id, f'am broadcast -a {act} --es msg "{esc}"', timeout_seconds=3.0 - ) + try: + return ( + subprocess.run( + self._adb_args( + device_id, "shell", "am", "broadcast", "-a", act, "--es", "msg", str(msg or "") + ), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=3.0, + check=False, + ).returncode + == 0 + ) + except Exception: + return False def _adbkeyboard_broadcast_int( self, device_id: str, action: str, key: str, value: int @@ -3022,9 +3117,21 @@ class underlying_operations: v = int(value) except Exception: return False - return self._run_adb_shell( - device_id, f"am broadcast -a {act} --ei {k} {v}", timeout_seconds=3.0 - ) + try: + return ( + subprocess.run( + self._adb_args( + device_id, "shell", "am", "broadcast", "-a", act, "--ei", k, v + ), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=3.0, + check=False, + ).returncode + == 0 + ) + except Exception: + return False def keyevent(self, device_id: str, keycode: int) -> bool: try: @@ -3196,16 +3303,14 @@ class underlying_operations: try: remote = "/sdcard/window_dump.xml" subprocess.run( - f"{self._adb()} -s {device_id} shell uiautomator dump {remote}", - shell=True, + self._adb_args(device_id, "shell", "uiautomator", "dump", remote), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2, check=False, ) subprocess.run( - f'{self._adb()} -s {device_id} pull {remote} "{local_path}"', - shell=True, + [self._adb_path(), "-s", str(device_id), "pull", remote, str(local_path)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=2, diff --git a/douyin/core/douyin_fudai.py b/douyin/core/douyin_fudai.py index 6413ec2..d90a4ab 100644 --- a/douyin/core/douyin_fudai.py +++ b/douyin/core/douyin_fudai.py @@ -3240,8 +3240,8 @@ class fudai_analyse: end_y = 600 * ry // 2400 # 直接使用 ADB 内部滑动命令 try: - if hasattr(self.operation, "_adb"): - adb_cmd = self.operation._adb() + if hasattr(self.operation, "_adb_path"): + adb_cmd = self.operation._adb_path() else: adb_cmd = ( os.environ.get( @@ -3249,14 +3249,25 @@ class fudai_analyse: ) or "adb" ) - if not adb_cmd.startswith( + if adb_cmd.startswith( '"' - ) and not adb_cmd.endswith('"'): - adb_cmd = f'"{adb_cmd}"' - cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 300" + ) and adb_cmd.endswith('"'): + adb_cmd = adb_cmd[1:-1] + cmd = [ + adb_cmd, + "-s", + str(self.device_id), + "shell", + "input", + "swipe", + str(int(start_x)), + str(int(start_y)), + str(int(end_x)), + str(int(end_y)), + "300", + ] subprocess.run( cmd, - shell=True, timeout=5.0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, @@ -3491,8 +3502,8 @@ class fudai_analyse: end_y = 600 * ry // 2400 # 直接使用 ADB 内部滑动命令 try: - if hasattr(self.operation, "_adb"): - adb_cmd = self.operation._adb() + if hasattr(self.operation, "_adb_path"): + adb_cmd = self.operation._adb_path() else: adb_cmd = ( os.environ.get( @@ -3500,14 +3511,25 @@ class fudai_analyse: ) or "adb" ) - if not adb_cmd.startswith( + if adb_cmd.startswith( '"' - ) and not adb_cmd.endswith('"'): - adb_cmd = f'"{adb_cmd}"' - cmd = f"{adb_cmd} -s {self.device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} 300" + ) and adb_cmd.endswith('"'): + adb_cmd = adb_cmd[1:-1] + cmd = [ + adb_cmd, + "-s", + str(self.device_id), + "shell", + "input", + "swipe", + str(int(start_x)), + str(int(start_y)), + str(int(end_x)), + str(int(end_y)), + "300", + ] subprocess.run( cmd, - shell=True, timeout=5.0, stdout=subprocess.PIPE, stderr=subprocess.PIPE, diff --git a/douyin/handlers/douyin_swipe_handler.py b/douyin/handlers/douyin_swipe_handler.py index 5053792..f83b905 100644 --- a/douyin/handlers/douyin_swipe_handler.py +++ b/douyin/handlers/douyin_swipe_handler.py @@ -358,23 +358,29 @@ class SwipeHandler: getattr(analyser, "swipe_duration_ms", 300) or 300 ) try: - if hasattr(analyser.operation, "_adb"): - adb_cmd = analyser.operation._adb() + if hasattr(analyser.operation, "_adb_path"): + adb_cmd = analyser.operation._adb_path() else: import os adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb" - if not adb_cmd.startswith('"') and not adb_cmd.endswith( - '"' - ): - adb_cmd = f'"{adb_cmd}"' - cmd = ( - f"{adb_cmd} -s {analyser.device_id} shell input swipe " - f"{start_x} {start_y} {end_x} {end_y} {swipe_duration_ms}" - ) + if adb_cmd.startswith('"') and adb_cmd.endswith('"'): + adb_cmd = adb_cmd[1:-1] + cmd = [ + adb_cmd, + "-s", + str(analyser.device_id), + "shell", + "input", + "swipe", + str(int(start_x)), + str(int(start_y)), + str(int(end_x)), + str(int(end_y)), + str(int(swipe_duration_ms)), + ] subprocess.run( cmd, - shell=True, check=False, timeout=5.0, stdout=subprocess.PIPE, diff --git a/douyin/handlers/douyin_swipe_ops.py b/douyin/handlers/douyin_swipe_ops.py index a452981..f421039 100644 --- a/douyin/handlers/douyin_swipe_ops.py +++ b/douyin/handlers/douyin_swipe_ops.py @@ -1,8 +1,17 @@ from __future__ import annotations -from typing import Any import subprocess import os +from typing import Any + + +def _adb_path(operation=None) -> str: + if operation and hasattr(operation, "_adb_path"): + return operation._adb_path() + adb = str(os.environ.get("ADB_EXECUTABLE", "adb") or "adb") + if adb.startswith('"') and adb.endswith('"'): + adb = adb[1:-1] + return adb def _adb_swipe_direct( @@ -29,23 +38,28 @@ def _adb_swipe_direct( True 如果成功,False 如果失败 """ try: - # 获取 ADB 命令路径 - if operation and hasattr(operation, "_adb"): - adb_cmd = operation._adb() - else: - adb_cmd = os.environ.get("ADB_EXECUTABLE", "adb") or "adb" - if not adb_cmd.startswith('"') and not adb_cmd.endswith('"'): - adb_cmd = f'"{adb_cmd}"' - - # 直接使用 ADB 命令执行滑动 - cmd = f"{adb_cmd} -s {device_id} shell input swipe {start_x} {start_y} {end_x} {end_y} {duration_ms}" + cmd = [ + _adb_path(operation), + "-s", + str(device_id), + "shell", + "input", + "swipe", + str(int(start_x)), + str(int(start_y)), + str(int(end_x)), + str(int(end_y)), + str(int(duration_ms)), + ] result = subprocess.run( cmd, - shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=5.0, text=True, + encoding="utf-8", + errors="replace", + check=False, ) return result.returncode == 0 diff --git a/gui/gui_core.py b/gui/gui_core.py index 3a6dae5..3927f84 100644 --- a/gui/gui_core.py +++ b/gui/gui_core.py @@ -54,9 +54,26 @@ def list_adb_devices(adb_exe: str) -> list[str]: ) except FileNotFoundError: return [] - text = (proc.stdout or "") + "\n" + (proc.stderr or "") - pattern = r"(\b(?:[0-9]{1,3}(?:\.[0-9]{1,3}){3}(?::[0-9]+)?|[A-Za-z0-9]{8,})\b)\s*device\b" - return re.findall(pattern, text) + devices: list[str] = [] + for line in (proc.stdout or "").splitlines()[1:]: + parts = line.split() + if len(parts) >= 2 and parts[1] == "device": + devices.append(parts[0]) + return devices + + +def resolve_adb_device(adb_exe: str, requested_device_id: str = "") -> str: + device_id = str(requested_device_id or "").strip() + devices = list_adb_devices(adb_exe) + if device_id: + if device_id in devices: + return device_id + raise RuntimeError(f"指定的 device_id '{device_id}' 当前不可用") + if len(devices) == 1: + return devices[0] + if len(devices) > 1: + raise RuntimeError(f"检测到多台 adb 设备,请先明确选择 device_id: {', '.join(devices)}") + raise RuntimeError("未检测到可用的 adb 设备") def is_device_wifi_connected(adb_exe: str, device_id: str) -> bool: @@ -1364,37 +1381,19 @@ class Runner: "[警告] 未找到 adb.exe:请安装 platform-tools 或将 adb 加入 PATH" ) - # 如果用户指定了 device_id,但当前 adb 列表中没有该设备,则尝试回退到任意可用设备 + # Resolve the device before spawning run_cli so background runs never block + # on the interactive select_device() prompt. try: - if getattr(params, "device_id", None): - try: - available = list_adb_devices(adb_exe) - except Exception as _: - available = [] - - if params.device_id not in available: - if available: - fallback = available[0] - self._emit_line( - f"[警告] 配置的 device_id '{params.device_id}' 当前不可见,自动改用 '{fallback}'" - ) - # 将 cmd 中的 --device-id 参数替换为 fallback - try: - i = cmd.index("--device-id") - if i + 1 < len(cmd): - cmd[i + 1] = fallback - except ValueError: - # 没有找到 --device-id 则追加 - cmd += ["--device-id", fallback] - else: - # 没有任何设备在线,提示并中止启动 - self._emit_line( - f"[错误] 配置的 device_id '{params.device_id}' 不在线,且未检测到其它 adb 设备。请连接设备或指定正确的 device-id。" - ) - raise RuntimeError("没有可用的 adb 设备") + resolved_device_id = resolve_adb_device(adb_exe, params.device_id) + try: + i = cmd.index("--device-id") + if i + 1 < len(cmd): + cmd[i + 1] = resolved_device_id + except ValueError: + cmd += ["--device-id", resolved_device_id] except Exception as e: - # 仅记录告警,不阻塞后续的调试信息(启动进程时仍可能失败) - self._emit_line(f"[警告] 检查可用 adb 设备时发生异常: {e}") + self._emit_line(f"[错误] 设备选择失败: {e}") + raise try: p = subprocess.Popen( @@ -1493,7 +1492,7 @@ class Runner: """手动发送返回键到指定设备。 Args: - device_id: 设备ID,如果为空则使用第一个可用设备 + device_id: 设备ID,如果为空则仅在单设备在线时自动使用该设备 Returns: True if successful, False otherwise @@ -1504,13 +1503,12 @@ class Runner: self._emit_line("[错误] 未找到 adb.exe") return False - # 如果没有指定设备ID,尝试获取第一个可用设备 if not device_id or device_id.strip() == "": - devices = list_adb_devices(adb_exe) - if not devices: - self._emit_line("[错误] 未找到可用设备") + try: + device_id = resolve_adb_device(adb_exe) + except Exception as e: + self._emit_line(f"[错误] 设备选择失败: {e}") return False - device_id = devices[0] # 发送返回键 (keyevent 4) cmd = [adb_exe, "-s", device_id, "shell", "input", "keyevent", "4"] diff --git a/gui/web_gui.py b/gui/web_gui.py index 8bac9ef..5722479 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -66,9 +66,26 @@ def list_adb_devices(adb_exe: str) -> list[str]: ) except FileNotFoundError: return [] - text = (proc.stdout or "") + "\n" + (proc.stderr or "") - pattern = r"(\b(?:[0-9]{1,3}(?:\.[0-9]{1,3}){3}(?::[0-9]+)?|[A-Za-z0-9]{8,})\b)\s*device\b" - return re.findall(pattern, text) + devices: list[str] = [] + for line in (proc.stdout or "").splitlines()[1:]: + parts = line.split() + if len(parts) >= 2 and parts[1] == "device": + devices.append(parts[0]) + return devices + + +def resolve_adb_device(adb_exe: str, requested_device_id: str = "") -> str: + device_id = str(requested_device_id or "").strip() + devices = list_adb_devices(adb_exe) + if device_id: + if device_id in devices: + return device_id + raise RuntimeError(f"指定的 device_id '{device_id}' 当前不可用") + if len(devices) == 1: + return devices[0] + if len(devices) > 1: + raise RuntimeError(f"检测到多台 adb 设备,请先明确选择 device_id: {', '.join(devices)}") + raise RuntimeError("未检测到可用的 adb 设备") def read_config() -> dict: @@ -994,11 +1011,11 @@ class ProcRunner: self._append_log("[错误] 未找到 adb.exe") return False if not device_id: - devices = list_adb_devices(adb) - if not devices: - self._append_log("[错误] 未找到可用设备") + try: + device_id = resolve_adb_device(adb) + except Exception as e: + self._append_log(f"[错误] 设备选择失败: {e}") return False - device_id = devices[0] proc = subprocess.run( [adb, "-s", device_id, "shell", "input", "keyevent", "4"], capture_output=True, @@ -1268,8 +1285,8 @@ class ProcRunner: "--test-yanghao-flow-seconds", str(seconds), ] - if device_id: - cmd += ["--device-id", device_id] + device_id = resolve_adb_device(find_adb_executable(), device_id) + cmd += ["--device-id", device_id] self._start_process(cmd) @@ -1292,8 +1309,8 @@ class ProcRunner: ] if text: cmd += ["--test-comment-text", text] - if device_id: - cmd += ["--device-id", device_id] + device_id = resolve_adb_device(find_adb_executable(), device_id) + cmd += ["--device-id", device_id] self._start_process(cmd) @@ -1321,6 +1338,8 @@ class ProcRunner: return default device_id = str(_pick("device_id", "") or "").strip() + adb = find_adb_executable() + device_id = resolve_adb_device(adb, device_id) y_pianyi = int(_pick("y_pianyi", 0) or 0) needswitch = bool(_pick("needswitch", False)) reset_after_swipes_enabled = bool(_pick("reset_after_swipes_enabled", False)) diff --git a/tools/check_dependencies.py b/tools/check_dependencies.py index 7d9f578..75c6377 100644 --- a/tools/check_dependencies.py +++ b/tools/check_dependencies.py @@ -14,7 +14,7 @@ dependencies = { 'cv2': ('opencv-python', 'Computer Vision'), 'numpy': ('numpy', 'Numerical Computing'), 'paddleocr': ('paddleocr', 'OCR Recognition'), - 'paddlepaddle': ('paddlepaddle', 'Deep Learning'), + 'paddle': ('paddlepaddle', 'Deep Learning'), 'ttkbootstrap': ('ttkbootstrap', 'GUI Framework'), 'easyocr': ('easyocr', 'OCR Recognition (Optional)'), } diff --git a/tools/install_dependencies.py b/tools/install_dependencies.py index 550c733..e0fbe10 100644 --- a/tools/install_dependencies.py +++ b/tools/install_dependencies.py @@ -21,9 +21,9 @@ def main(): missing = [] try: - import paddlepaddle # type: ignore[import-untyped] + import paddle # type: ignore[import-untyped] except ImportError: - missing.append("paddlepaddle>=2.5.0,<3.0.0") + missing.append("paddlepaddle>=3.0.0") try: import ttkbootstrap