diff --git a/douyin/core/underlying_operations.py b/douyin/core/underlying_operations.py index 10897dc..32f0357 100644 --- a/douyin/core/underlying_operations.py +++ b/douyin/core/underlying_operations.py @@ -84,6 +84,10 @@ from douyin.core.underlying_operations_pkg import ( _pick_adbkeyboard_ime as _impl_pick_adbkeyboard_ime, check_countdown as _impl_check_countdown, extract_ocr_content as _impl_extract_ocr_content, + _adb_args as _impl_adb_args, + save_reward_pic as _impl_save_reward_pic, + set_clipboard_text as _impl_set_clipboard_text, + _swipe_with_sendevent_improved as _impl_swipe_sendevent_improved, ) class underlying_operations: """底层操作类""" @@ -155,8 +159,7 @@ class underlying_operations: def _adb_path() -> str: return _impl_adb_path() 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]] - + return _impl_adb_args(device_id, *args) @staticmethod def _split_shell_cmd(shell_cmd: str) -> list[str]: return shlex.split(str(shell_cmd or ""), posix=(os.name != "nt")) @@ -995,68 +998,7 @@ class underlying_operations: raise ValueError("Could not find resolution in adb output") def save_reward_pic(self, device_id): - try: - from douyin.core import path_config - - out_dir = path_config.get_pic_dir() - except Exception: - from douyin.core import path_config - - out_dir = path_config.get_pic_dir() - if not os.path.exists(out_dir): - os.makedirs(out_dir) - timepic = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") - out_file = os.path.join(out_dir, f"{timepic}.png") - - adb = self._adb_path() - - # 同样优先使用 exec-out,减少手机端 I/O - try: - with open(out_file, "wb") as f: - subprocess.run( - [adb, "-s", device_id, "exec-out", "screencap", "-p"], - stdout=f, - stderr=subprocess.DEVNULL, - check=True, - ) - _uo_log("中奖了,点击领奖,保存中奖图片{}.png".format(timepic)) - return - except Exception: - pass - - # 回退:shell screencap + pull - try: - subprocess.run( - [ - adb, - "-s", - device_id, - "shell", - "screencap", - "-p", - "/sdcard/DCIM/screenshot.png", - ], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - check=True, - ) - subprocess.run( - [adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", out_file], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - check=True, - ) - subprocess.run( - [adb, "-s", device_id, "shell", "rm", "/sdcard/DCIM/screenshot.png"], - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - check=False, - ) - _uo_log("中奖了,点击领奖,保存中奖图片{}.png".format(timepic)) - except Exception: - # 保存失败不打断主流程 - _uo_log("保存中奖截图失败") - + return _impl_save_reward_pic(device_id) def cut_pic(self, left_up=(0, 63), right_down=(1080, 1620), target="", name=""): """裁剪图片,获取需要的区域小图片方便识别 @@ -1866,42 +1808,7 @@ class underlying_operations: ) def _swipe_with_sendevent_improved(self, device_id, x1, y1, x2, y2, steps=50): - """使用 sendevent 方法滑动(需要 root 权限) - - 这是更底层的触摸事件模拟方式,通过直接向 /dev/input/eventX 写入事件。 - 优点:绕过部分权限检查 - 缺点:需要 root 权限,实现复杂,不同设备的事件格式可能不同 - """ - - # 获取触摸设备路径(通常是 /dev/input/eventX) - result = subprocess.run( - 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, - ) - - # 解析设备路径(简化版,实际需要更复杂的解析) - # 这里只是示例,完整实现需要: - # 1. 解析 getevent -p 输出找到触摸设备 - # 2. 计算触摸事件的坐标范围(ABS_MT_POSITION_X/Y 的 min/max) - # 3. 将屏幕坐标转换为设备坐标 - # 4. 发送 DOWN -> MOVE -> UP 事件序列 - - if "ABS_MT" not in result.stdout or "event" not in result.stdout.lower(): - raise FileNotFoundError("无法找到触摸设备(需要 root 权限)") - - # 注意:完整的 sendevent 实现非常复杂,需要: - # - 设备特定的坐标转换 - # - 正确的事件序列(SYN_REPORT 等) - # - 不同 Android 版本的事件格式可能不同 - - raise PermissionError("sendevent 需要 root 权限且实现复杂,暂不支持完整实现") - + return _impl_swipe_sendevent_improved(device_id, x1, y1, x2, y2, steps) def click(self, device_id, x=500, y=500, log: bool = True): """点击坐标位置 @@ -2009,62 +1916,7 @@ class underlying_operations: return "" def set_clipboard_text(self, device_id: str, text: str) -> bool: - """设置设备剪贴板文本(尽量支持中文)。 - - 优先:Android 10+ 的 `cmd clipboard set`。 - 兜底:Clipper(若设备装了 clipper app)。 - """ - t = str(text or "").strip() - if not t: - return False - - # 使用 shlex.quote 转义文本,防止 shell 注入 - safe_t = shlex.quote(t) - - # 1) cmd clipboard set - try: - if ( - subprocess.run( - self._adb_args(device_id, "shell", "cmd", "clipboard", "set", safe_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 "..." - try: - if ( - subprocess.run( - self._adb_args( - device_id, - "shell", - "am", - "broadcast", - "-a", - "clipper.set", - "-e", - "text", - safe_t, - ), - stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, - timeout=3.0, - check=False, - ).returncode - == 0 - ): - return True - except Exception: - pass - - return False - + return _impl_set_clipboard_text(device_id, text) def paste_from_clipboard(self, device_id: str) -> bool: """尝试触发“粘贴”操作(需要输入框已获得焦点)。""" # KEYCODE_PASTE=279(部分机型/系统可能不支持,但无副作用) diff --git a/douyin/core/underlying_operations_pkg/__init__.py b/douyin/core/underlying_operations_pkg/__init__.py index a967aea..29347ef 100644 --- a/douyin/core/underlying_operations_pkg/__init__.py +++ b/douyin/core/underlying_operations_pkg/__init__.py @@ -17,6 +17,11 @@ from .pic_path import _find_pic_path from .ocr_content import extract_ocr_content from .countdown import check_countdown from .bounds import _parse_bounds +from .reward_pic import save_reward_pic +from .swipe_sendevent import _swipe_with_sendevent_improved +from .clipboard import set_clipboard_text +from .adb_helpers import _adb_args + __all__ = [ "_adb_path", @@ -25,4 +30,8 @@ __all__ = [ "extract_ocr_content", "check_countdown", "_parse_bounds", + "save_reward_pic", + "_swipe_with_sendevent_improved", + "set_clipboard_text", + "_adb_args", ] diff --git a/douyin/core/underlying_operations_pkg/adb_helpers.py b/douyin/core/underlying_operations_pkg/adb_helpers.py index dbb6dfc..1c07b1b 100644 --- a/douyin/core/underlying_operations_pkg/adb_helpers.py +++ b/douyin/core/underlying_operations_pkg/adb_helpers.py @@ -32,3 +32,7 @@ def _pick_adbkeyboard_ime(imes: list[str]) -> str: return s return "" + +def _adb_args(device_id: str, *args: object) -> list[str]: + """构造 ``adb -s `` 的命令行参数列表。""" + return [_adb_path(), "-s", str(device_id), *[str(arg) for arg in args]] diff --git a/douyin/core/underlying_operations_pkg/clipboard.py b/douyin/core/underlying_operations_pkg/clipboard.py new file mode 100644 index 0000000..717d997 --- /dev/null +++ b/douyin/core/underlying_operations_pkg/clipboard.py @@ -0,0 +1,70 @@ +"""underlying_operations_pkg.clipboard - 设备剪贴板设置。 + +set_clipboard_text(device_id, text): 在设备上设置剪贴板内容(支持中文)。 +优先 ``cmd clipboard set``(Android 10+),失败回退到 Clipper broadcast。 +""" +from __future__ import annotations + +import shlex +import subprocess + +from .adb_helpers import _adb_args + + +def set_clipboard_text(device_id: str, text: str) -> bool: + """设置设备剪贴板文本(尽量支持中文)。 + + 优先:Android 10+ 的 `cmd clipboard set`。 + 兜底:Clipper(若设备装了 clipper app)。 + """ + t = str(text or "").strip() + if not t: + return False + + # 使用 shlex.quote 转义文本,防止 shell 注入 + safe_t = shlex.quote(t) + + # 1) cmd clipboard set + try: + if ( + subprocess.run( + _adb_args(device_id, "shell", "cmd", "clipboard", "set", safe_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 "..." + try: + if ( + subprocess.run( + _adb_args( + device_id, + "shell", + "am", + "broadcast", + "-a", + "clipper.set", + "-e", + "text", + safe_t, + ), + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + timeout=3.0, + check=False, + ).returncode + == 0 + ): + return True + except Exception: + pass + + return False + diff --git a/douyin/core/underlying_operations_pkg/reward_pic.py b/douyin/core/underlying_operations_pkg/reward_pic.py new file mode 100644 index 0000000..f26eab8 --- /dev/null +++ b/douyin/core/underlying_operations_pkg/reward_pic.py @@ -0,0 +1,97 @@ +"""underlying_operations_pkg.reward_pic - 中奖截图保存。 + +save_reward_pic(device_id): 中奖时保存当前屏幕截图到 ``pic/<时间>.png``。 +优先 exec-out 模式(更快),失败回退到 shell screencap + pull。 +""" +from __future__ import annotations + +import logging +import os +import subprocess +from datetime import datetime + +from douyin.core import path_config + +from .adb_helpers import _adb_path + +_LOGGER = logging.getLogger("douyin.core.underlying_operations") + + +def _uo_log(msg, level: str = "INFO") -> None: + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + pass + + +def save_reward_pic(device_id): + try: + from douyin.core import path_config + + out_dir = path_config.get_pic_dir() + except Exception: + from douyin.core import path_config + + out_dir = path_config.get_pic_dir() + if not os.path.exists(out_dir): + os.makedirs(out_dir) + timepic = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + out_file = os.path.join(out_dir, f"{timepic}.png") + + adb = _adb_path() + + # 同样优先使用 exec-out,减少手机端 I/O + try: + with open(out_file, "wb") as f: + subprocess.run( + [adb, "-s", device_id, "exec-out", "screencap", "-p"], + stdout=f, + stderr=subprocess.DEVNULL, + check=True, + ) + _uo_log("中奖了,点击领奖,保存中奖图片{}.png".format(timepic)) + return + except Exception: + pass + + # 回退:shell screencap + pull + try: + subprocess.run( + [ + adb, + "-s", + device_id, + "shell", + "screencap", + "-p", + "/sdcard/DCIM/screenshot.png", + ], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=True, + ) + subprocess.run( + [adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", out_file], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=True, + ) + subprocess.run( + [adb, "-s", device_id, "shell", "rm", "/sdcard/DCIM/screenshot.png"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + check=False, + ) + _uo_log("中奖了,点击领奖,保存中奖图片{}.png".format(timepic)) + except Exception: + # 保存失败不打断主流程 + _uo_log("保存中奖截图失败") + diff --git a/douyin/core/underlying_operations_pkg/swipe_sendevent.py b/douyin/core/underlying_operations_pkg/swipe_sendevent.py new file mode 100644 index 0000000..04032bc --- /dev/null +++ b/douyin/core/underlying_operations_pkg/swipe_sendevent.py @@ -0,0 +1,49 @@ +"""underlying_operations_pkg.swipe_sendevent - sendevent 滑动(占位实现)。 + +_swipe_with_sendevent_improved(...) 是更底层的触摸事件模拟方式,需要 root 权限 +且不同设备的事件格式可能不同。当前实现只做检测和异常抛出,主流程不依赖它。 +""" +from __future__ import annotations + +import subprocess + +from .adb_helpers import _adb_args + + +def _swipe_with_sendevent_improved(device_id, x1, y1, x2, y2, steps=50): + """使用 sendevent 方法滑动(需要 root 权限) + + 这是更底层的触摸事件模拟方式,通过直接向 /dev/input/eventX 写入事件。 + 优点:绕过部分权限检查 + 缺点:需要 root 权限,实现复杂,不同设备的事件格式可能不同 + """ + + # 获取触摸设备路径(通常是 /dev/input/eventX) + result = subprocess.run( + _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, + ) + + # 解析设备路径(简化版,实际需要更复杂的解析) + # 这里只是示例,完整实现需要: + # 1. 解析 getevent -p 输出找到触摸设备 + # 2. 计算触摸事件的坐标范围(ABS_MT_POSITION_X/Y 的 min/max) + # 3. 将屏幕坐标转换为设备坐标 + # 4. 发送 DOWN -> MOVE -> UP 事件序列 + + if "ABS_MT" not in result.stdout or "event" not in result.stdout.lower(): + raise FileNotFoundError("无法找到触摸设备(需要 root 权限)") + + # 注意:完整的 sendevent 实现非常复杂,需要: + # - 设备特定的坐标转换 + # - 正确的事件序列(SYN_REPORT 等) + # - 不同 Android 版本的事件格式可能不同 + + raise PermissionError("sendevent 需要 root 权限且实现复杂,暂不支持完整实现") +