runhey 3 жил өмнө
parent
commit
53377a346a

+ 327 - 0
module/device/emulator.py

@@ -0,0 +1,327 @@
+import os
+import re
+import winreg
+import subprocess
+
+from adbutils.errors import AdbError
+
+from deploy.emulator import VirtualBoxEmulator
+from module.base.decorator import cached_property
+from module.device.connection import Connection
+from module.device.method.utils import get_serial_pair
+from module.exception import RequestHumanTakeover, EmulatorNotRunningError
+from module.logger import logger
+
+
+class EmulatorInstance(VirtualBoxEmulator):
+
+    def __init__(self, name, root_path, emu_path,
+                 vbox_path=None, vbox_name=None, kill_para=None, multi_para=None):
+        """
+        Args:
+            name (str): Emulator name in windows uninstall list.
+            root_path (str): Relative path from uninstall.exe to emulator installation folder.
+            emu_path (str): Relative path to executable simulator file.
+            vbox_path (str): Relative path to virtual box folder.
+            vbox_name (str): Regular Expression to match the name of .vbox file.
+            kill_para (str): Parameters required by kill emulator.
+            multi_para (str): Parameters required by start multi open emulator,
+            #id will be replaced with the real ID.
+        """
+        super().__init__(
+            name=name,
+            root_path=root_path,
+            adb_path=None,
+            vbox_path=vbox_path,
+            vbox_name=vbox_name,
+        )
+        self.emu_path = emu_path
+        self.kill_para = kill_para
+        self.multi_para = multi_para
+
+    @cached_property
+    def id_and_serial(self):
+        """
+        Returns:
+            list[str, str]: List of multi_id and serial.
+        """
+        vbox = []
+        for path, folders, files in os.walk(os.path.join(self.root, self.vbox_path)):
+            for file in files:
+                if re.match(self.vbox_name, file):
+                    file = os.path.join(path, file)
+                    vbox.append(file)
+
+        serial = []
+        for file in vbox:
+            with open(file, 'r', encoding='utf-8', errors='ignore') as f:
+                for line in f.readlines():
+                    # <Forwarding name="port2" proto="1" hostip="127.0.0.1" hostport="62026" guestport="5555"/>
+                    res = re.search('<*?hostport="(.*?)".*?guestport="5555"/>', line)
+                    if res:
+                        serial.append([os.path.basename(file).split(".")[0], f'127.0.0.1:{res.group(1)}'])
+
+        return serial
+
+
+class Bluestacks5Instance(EmulatorInstance):
+    @cached_property
+    def root(self):
+        try:
+            return super().root
+        except FileNotFoundError:
+            self.name = 'BlueStacks_nxt_cn'
+            return super().root
+
+    @cached_property
+    def id_and_serial(self):
+        try:
+            reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt")
+        except FileNotFoundError:
+            reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\BlueStacks_nxt_cn")
+        directory = winreg.QueryValueEx(reg, 'UserDefinedDir')[0]
+
+        with open(os.path.join(directory, 'bluestacks.conf'), encoding='utf-8') as f:
+            content = f.read()
+        emulators = re.findall(r'bst.instance.(\w+).status.adb_port="(\d+)"', content)
+        serial = []
+        for emulator in emulators:
+            serial.append([emulator[0], f'127.0.0.1:{emulator[1]}'])
+        return serial
+
+
+class EmulatorManager(Connection):
+    pid = None
+    SUPPORTED_EMULATORS = {
+        'nox_player': EmulatorInstance(
+            name="Nox",
+            root_path=".",
+            emu_path="./Nox.exe",
+            vbox_path="./BignoxVMS",
+            vbox_name='.*.vbox$',
+            kill_para='-quit',
+            multi_para='-clone:#id',
+        ),
+        'mumu_player': EmulatorInstance(
+            name="Nemu",
+            root_path=".",
+            emu_path="./EmulatorShell/NemuPlayer.exe",
+            vbox_path="./vms",
+            vbox_name='.*.nemu$',
+        ),
+        'bluestacks_5': Bluestacks5Instance(
+            name='BlueStacks_nxt',
+            root_path='.',
+            emu_path='./HD-Player.exe',
+            multi_para='--instance #id',
+        ),
+    }
+
+    def detect_emulator(self, serial, emulator=None):
+        """
+        Args:
+            serial (str):
+            emulator (EmulatorInstance):
+
+        Returns:
+            list[EmulatorInstance, str]:Emulator and multi_id
+        """
+        if emulator is None:
+            logger.info('Detect emulator from all emulators installed')
+            emulators = []
+            for emulator in self.SUPPORTED_EMULATORS.values():
+                try:
+                    serials = emulator.id_and_serial
+                    for cur_serial in serials:
+                        if cur_serial[1] == serial:
+                            emulators.append([emulator, cur_serial[0]])
+                except FileNotFoundError:
+                    pass
+
+            logger.info('Detected emulators:')
+            for emulator in emulators:
+                logger.info(f'Name: {emulator[0].name}, Multi_id: {emulator[1]}')
+
+            if len(emulators) == 1 or \
+                    (len(emulators) > 0 and emulators[0][0] == self.SUPPORTED_EMULATORS['mumu_player']):
+                logger.info('Find the only emulator, using it')
+                return emulators[0][0], emulators[0][1]
+            elif len(emulators) == 0:
+                logger.warning('The emulator corresponding to serial is not found, '
+                               'please check the setting or use custom command')
+            else:
+                logger.warning('Multiple emulators with the same serial have been found, '
+                               'please select one manually or use custom command')
+            raise RequestHumanTakeover
+
+        else:
+            try:
+                logger.info(f'Detect emulator from {emulator.name}')
+                serials = emulator.id_and_serial
+                for cur_serial in serials:
+                    if cur_serial[1] == serial:
+                        logger.info('Find the only emulator, using it')
+                        return emulator, cur_serial[0]
+            except FileNotFoundError:
+                pass
+            logger.warning('The emulator corresponding to serial is not found, '
+                           'please check the setting or use custom command')
+            raise RequestHumanTakeover
+
+    @staticmethod
+    def execute(command):
+        """
+        Args:
+            command (str):
+
+        Returns:
+            subprocess.Popen:
+        """
+        command = command.replace(r"\\", "/").replace("\\", "/").replace('"', '"')
+        logger.info(f'Execute: {command}')
+        return subprocess.Popen(command, close_fds=True)  # only work on Windows
+
+    @staticmethod
+    def task_kill(pid=None, name=None):
+        """
+        Args:
+            pid (list, int):
+            name (list, str):
+
+        Returns:
+            subprocess.Popen:
+        """
+        command = 'taskkill '
+        if pid is not None:
+            if isinstance(pid, list):
+                for p in pid:
+                    command += f'/pid {p} '
+            else:
+                command += f'/pid {pid} '
+        elif name is not None:
+            if isinstance(name, list):
+                for n in name:
+                    command += f'/im {n} '
+            else:
+                command += f'/im {name} '
+        else:
+            raise RequestHumanTakeover
+        command += '/t /f'
+
+        return EmulatorManager.execute(command)
+
+    def adb_connect(self, serial):
+        try:
+            return super(EmulatorManager, self).adb_connect(serial)
+        except EmulatorNotRunningError:
+            raise RequestHumanTakeover
+
+    def detect_emulator_status(self, serial):
+        devices = self.list_device()
+        for device in devices:
+            if device.serial == serial:
+                return device.status
+        return 'offline'
+
+    def emulator_start(self, serial, emulator=None, multi_id=None, command=None):
+        """
+        Args:
+            serial (str): Expected serial after simulator starts successfully.
+            emulator (EmulatorInstance): Emulator to start.
+            multi_id (str): Emulator ID used by multi open emulator.
+            command (str): Customized path and parameters of the simulator to start.
+
+        Return:
+            bool: If start successful.
+        """
+        if command is None:
+            command = '\"' + os.path.abspath(os.path.join(emulator.root, emulator.emu_path)) + '\"'
+            if emulator.multi_para is not None and multi_id is not None:
+                command += " " + emulator.multi_para.replace("#id", multi_id)
+
+        logger.info('Start emulator')
+        pipe = self.execute(command)
+        self.pid = pipe.pid
+        self.sleep(10)
+
+        for _ in range(20):
+            if pipe.poll() is not None:
+                break
+            try:
+                if super().adb_connect(serial):
+                    # Wait until emulator start completely
+                    self.sleep(10)
+                    return True
+            except EmulatorNotRunningError:
+                pass
+            self.sleep(5)
+        return False
+
+    def emulator_kill(self, serial, emulator=None, multi_id=None, command=None):
+        """
+        Args:
+            serial (str): Expected serial after simulator starts successfully.
+            emulator (EmulatorInstance): Emulator to start.
+            multi_id (str): Emulator ID used by multi open emulator.
+            command (str): Customized path and parameters of the simulator to start.
+
+        Return:
+            bool: If kill successful.
+        """
+        if command is None and emulator.kill_para is not None:
+            command = '\"' + os.path.abspath(os.path.join(emulator.root, emulator.emu_path)) + '\"'
+            if emulator.multi_para is not None and multi_id is not None:
+                command += " " + emulator.multi_para.replace("#id", multi_id)
+            command += " " + emulator.kill_para
+
+        logger.info('Kill emulator')
+        if emulator == self.SUPPORTED_EMULATORS['bluestacks_5']:
+            try:
+                self.adb_command(['reboot', '-p'], timeout=20)
+                if self.detect_emulator_status(serial) == 'offline':
+                    self.pid = None
+                    return True
+            except AdbError:
+                return False
+
+        if emulator == self.SUPPORTED_EMULATORS['mumu_player']:
+            self.task_kill(pid=None, name=['NemuHeadless.exe', 'NemuPlayer.exe', 'NemuSvc.exe'])
+        elif command is not None:
+            self.execute(command)
+        else:
+            self.task_kill(pid=self.pid, name=os.path.basename(emulator.emu_path))
+        self.sleep(5)
+
+        for _ in range(10):
+            if self.detect_emulator_status(serial) == 'offline':
+                self.pid = None
+                return True
+            self.sleep(2)
+        return False
+
+    def emulator_restart(self):
+        serial, _ = get_serial_pair(self.serial)
+        if serial is None:
+            serial = self.serial
+
+        if os.name != 'nt':
+            logger.warning('Restart simulator only works under Windows platform')
+            return False
+
+        logger.hr('Emulator restart')
+        if self.config.RestartEmulator_EmulatorType == 'auto':
+            emulator, multi_id = self.detect_emulator(serial)
+        else:
+            emulator = self.SUPPORTED_EMULATORS[self.config.RestartEmulator_EmulatorType]
+            emulator, multi_id = self.detect_emulator(serial, emulator=emulator)
+
+        for _ in range(3):
+            if not self.emulator_kill(serial, emulator, multi_id):
+                continue
+            if self.emulator_start(serial, emulator, multi_id):
+                return True
+
+        logger.warning('Restart emulator failed for 3 times, please check your settings')
+        raise RequestHumanTakeover
+
+

+ 211 - 0
module/device/handle.py

@@ -0,0 +1,211 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import re
+
+from cached_property import cached_property
+from anytree import NodeMixin, RenderTree
+from win32process import GetWindowThreadProcessId
+from win32gui import (GetWindowText, EnumWindows, FindWindow, FindWindowEx,
+                      IsWindow, GetWindowRect, GetWindowDC, DeleteObject,
+                      SetForegroundWindow, IsWindowVisible, GetDC, GetParent,
+                      EnumChildWindows)
+
+from module.config.config import Config
+from module.exception import RequestHumanTakeover, EmulatorNotRunningError
+from module.logger import logger
+
+
+def handle_title2num(title: str) -> int:
+    """
+    从标题到句柄号
+    :param title:
+    :return:  如果没有找到就是返回零
+    """
+    return FindWindow(None, title)
+
+
+def handle_num2title(num: int) -> str:
+    """
+    通过句柄号返回窗口的标题,如果传入句柄号不合法则返回None
+    :param num:
+    :return:
+    """
+    return None if num is None or num == 0 or num == '' else GetWindowText(num)
+
+
+def is_handle_valid(num: int) -> bool:
+    """
+    输入一个句柄号,如果还在返回True
+    :param num:
+    :return:
+    """
+    return IsWindow(num)
+
+def handle_num2pid(num :int) -> int:
+    """
+    通过句柄号获取句柄进程id,如果句柄号非法则返回0
+    :param num:
+    :return:
+    """
+    return 0 if num is None or num == 0 or num == '' else GetWindowThreadProcessId(num)[1]
+
+
+class WindowNode(NodeMixin):
+    def __init__(self, name, num, parent=None):
+        super().__init__()
+        self.name = name
+        self.num = num
+        self.parent = parent
+
+
+class Handle:
+    emulator_list = ['MuMu',
+                     '雷电',
+                     '夜神',
+                     '蓝叠',
+                     '逍遥',
+                     '模拟器']  # 最后一个我又不知道还有哪些模拟器
+    emulator_handle = {
+        # 夜神
+        'nox_player': ['root_handle_title', 'Nox'],
+        'nox_player_64': ['root_handle_title', 'Nox'],
+        'nox_player_family':['root_handle_title', 'Nox'],
+        # 雷电
+        'ld_player': ['TheRender'],
+        'ld_player_4': ['TheRender'],
+        'ld_player_9': ['TheRender'],
+        'ld_player_family': ['TheRender'],
+        # 逍遥
+        'memu_player': ['root_handle_title'],
+        'memu_player_family': ['root_handle_title'],
+        # mumu
+        'mumu_player': ['root_handle_title', 'NemuPlayer'],
+        'mumu_player_12': ['root_handle_title', 'MuMuPlayer'],
+        'mumu_player_family': ['root_handle_title', 'MuMuPlayer'],
+        # 蓝叠
+        'bluestacks_5': ['root_handle_title'],
+        'bluestacks_family': ['root_handle_title']
+    }
+
+    def __init__(self, config) -> None:
+        """
+
+        :param config:
+        """
+        logger.hr('Handle')
+        if isinstance(config, str):
+            self.config = Config(config, task=None)
+        else:
+            self.config = config
+
+        # 获取根的句柄
+        self.root_handle_title = ''
+        self.root_handle_num = 0
+        self.root_handle = self.config.get_arg('Script', 'Device', 'Handle')
+        if self.root_handle == "auto":
+            logger.info('handle is auto. oas will find window emulator')
+            window_list = Handle.all_windows()
+            self.root_handle_title = self.auto_handle_title(window_list)
+            self.root_handle_num = handle_title2num(self.root_handle_title)
+        elif isinstance(self.root_handle, int):
+            logger.info('handle is handle num. oas use it as root handle num')
+            if is_handle_valid(self.root_handle):
+                logger.info(f'handle number {self.root_handle} is valid')
+                self.root_handle_title = handle_num2title(self.root_handle)
+                self.root_handle_num = self.root_handle
+        elif isinstance(self.root_handle, str):
+            logger.info('handle is handle string. oas use it as root handle title')
+            if handle_title2num(self.root_handle) !=0:
+                self.root_handle_num = handle_title2num(self.root_handle)
+                self.root_handle_title = self.root_handle
+        logger.info(f'the root handle title is {self.root_handle_title} and num is {self.root_handle_num}')
+
+        # 获取句柄树
+        self.root_node = WindowNode(name=self.root_handle_title, num=self.root_handle_num)
+        Handle.handle_tree(self.root_handle_num, self.root_node)
+        logger.info('the emulator handle structure is')
+        for pre, fill, node in RenderTree(self.root_node):
+            logger.info("%s%s" % (pre, node.name))
+
+    @staticmethod
+    def all_windows() -> list:
+        """
+        获取桌面上的所有窗体
+
+        :return:  类似这样['MuMu模拟器']
+        """
+
+        def enum_windows_callback(hwnd, windows):
+            window_text = GetWindowText(hwnd)
+            windows.append(window_text)
+
+        windows = []
+        EnumWindows(enum_windows_callback, windows)
+        return windows
+
+    @classmethod
+    def auto_handle_title(cls, windows: list) -> str:
+        """
+        返回第一个找到的有模拟器的标题
+        :param windows:
+        :return:
+        """
+        if windows is None:
+            logger.error("handle_auto not get all wnidow")
+
+        for window_title in windows:
+            for item in Handle.emulator_list:
+                if window_title.find(item) != -1:
+                    logger.info(f'handle auto seclect to find {window_title} and use it as root_title')
+                    return window_title
+
+        return None
+
+    @staticmethod
+    def handle_tree(hwnd, node: WindowNode, level: int =0) -> None:
+        """
+        生成一个窗口的句柄树
+        :param hwnd:
+        :param node:
+        :param level:
+        :return:
+        """
+        child_windows = []
+        EnumChildWindows(hwnd, lambda hwnd, param: param.append(hwnd), child_windows)
+
+        if not child_windows:
+            return
+        for child_hwnd in child_windows:
+            if GetParent(child_hwnd) == hwnd:
+                child_text = GetWindowText(child_hwnd)
+                child_node = WindowNode(name=child_text, num=child_hwnd, parent=node)
+
+                # 递归遍历子窗体的子窗体
+                Handle.handle_tree(child_hwnd, child_node, level + 1)
+
+    @cached_property
+    def emulator_family(self) -> str:
+        """
+        通过句柄标题来判断这个是那个模拟器大类
+        :return:
+        """
+        for emu in Handle.emulator_list:
+            if self.root_handle_title.find(emu) != -1:
+                if emu == 'MuMu':
+                    return 'mumu_player_family'
+                elif emu == '雷电':
+                    return 'ld_player_family'
+                elif emu == '夜神':
+                    return 'nox_player_family'
+                elif emu == '蓝叠':
+                    return 'bluestacks_player_family'
+                elif emu == '逍遥':
+                    return 'memu_player_family'
+
+if __name__ == '__main__':
+    h = Handle(config='oas1')
+    logger.info(h.auto_handle_title(h.all_windows()))
+    logger.info(h.root_handle_num)
+    logger.info(h.emulator_family)
+

+ 3 - 0
module/device/method/window.py

@@ -0,0 +1,3 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey

+ 2 - 0
requirements-in.txt

@@ -7,3 +7,5 @@ pyyaml==6.0
 numpy==1.24.3
 opencv-python==4.7.0.72
 websockets==11.0.3
+anytree==2.8.0
+pywin32==306

+ 10 - 2
requirements.txt

@@ -7,7 +7,7 @@
 --index-url https://pypi.tuna.tsinghua.edu.cn/simple
 --trusted-host pypi.tuna.tsinghua.edu.cn
 
-adbutils==1.2.9         # via -r requirements-in.txt, uiautomator2
+adbutils==0.11.0          # via -r requirements-in.txt, uiautomator2
 apkutils2==1.0.0          # via adbutils
 cached-property==1.5.2    # via uiautomator2
 certifi==2023.5.7         # via requests
@@ -21,21 +21,29 @@ filelock==3.12.0          # via uiautomator2
 idna==3.4                 # via requests
 logzero==1.7.0            # via uiautomator2
 lxml==4.9.2               # via uiautomator2
+markdown-it-py==2.2.0     # via rich
+mdurl==0.1.2              # via markdown-it-py
+numpy==1.24.3             # via -r requirements-in.txt, opencv-python
+opencv-python==4.7.0.72   # via -r requirements-in.txt
 packaging==20.9           # via deprecation, uiautomator2
 pillow==9.5.0             # via uiautomator2
 progress==1.6             # via uiautomator2
 py==1.11.0                # via retry
 pyelftools==0.29          # via apkutils2
+pygments==2.15.1          # via rich
 pyparsing==3.0.9          # via packaging
 pyside6==6.4.3            # via -r requirements-in.txt
 pyside6-addons==6.4.3     # via pyside6
 pyside6-essentials==6.4.3  # via pyside6, pyside6-addons
+pyyaml==6.0               # via -r requirements-in.txt
 requests==2.30.0          # via adbutils, uiautomator2
 retry==0.9.2              # via adbutils, uiautomator2
+rich==13.3.5              # via -r requirements-in.txt
 shiboken6==6.4.3          # via pyside6, pyside6-addons, pyside6-essentials
 six==1.16.0               # via adbutils, uiautomator2
-uiautomator2==2.16.23     # via -r requirements-in.txt
+uiautomator2==2.16.17     # via -r requirements-in.txt
 urllib3==2.0.2            # via requests
+websockets==11.0.3        # via -r requirements-in.txt
 whichcraft==0.6.1         # via adbutils, uiautomator2
 wrapt==1.15.0             # via deprecated
 xmltodict==0.13.0         # via apkutils2