emulator.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. import asyncio
  2. import filecmp
  3. import os
  4. import re
  5. import shutil
  6. import subprocess
  7. import winreg
  8. from deploy.logger import logger
  9. from deploy.utils import cached_property
  10. asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
  11. class VirtualBoxEmulator:
  12. UNINSTALL_REG = "SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
  13. UNINSTALL_REG_2 = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
  14. def __init__(self, name, root_path, adb_path, vbox_path, vbox_name):
  15. """
  16. Args:
  17. name (str): Emulator name in windows uninstall list.
  18. root_path (str): Relative path from uninstall.exe to emulator installation folder.
  19. adb_path (str, list[str]): Relative path to adb.exe. List of str if there are multiple adb in emulator.
  20. vbox_path (str): Relative path to virtual box folder.
  21. vbox_name (str): Regular Expression to match the name of .vbox file.
  22. """
  23. self.name = name
  24. self.root_path = root_path
  25. self.adb_path = adb_path if isinstance(adb_path, list) else [adb_path]
  26. self.vbox_path = vbox_path
  27. self.vbox_name = vbox_name
  28. @cached_property
  29. def root(self):
  30. """
  31. Returns:
  32. str: Root installation folder of emulator.
  33. Raises:
  34. FileNotFoundError: If emulator not installed.
  35. """
  36. if self.name == 'LDPlayer4':
  37. root = self.get_install_dir_from_reg('SOFTWARE\\leidian\\ldplayer', 'InstallDir')
  38. if root is not None:
  39. return root
  40. if self.name == 'LDPlayer9':
  41. root = self.get_install_dir_from_reg('SOFTWARE\\leidian\\ldplayer9', 'InstallDir')
  42. if root is not None:
  43. return root
  44. try:
  45. reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, f'{self.UNINSTALL_REG}\\{self.name}', 0)
  46. except FileNotFoundError:
  47. reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, f'{self.UNINSTALL_REG_2}\\{self.name}', 0)
  48. res = winreg.QueryValueEx(reg, 'UninstallString')[0]
  49. file = re.search('"(.*?)"', res)
  50. file = file.group(1) if file else res
  51. root = os.path.abspath(os.path.join(os.path.dirname(file), self.root_path))
  52. return root
  53. def get_install_dir_from_reg(self, path, key):
  54. """
  55. Args:
  56. path (str): f'SOFTWARE\\leidian\\ldplayer'
  57. key (str): 'InstallDir'
  58. Returns:
  59. str: Installation dir or None
  60. """
  61. try:
  62. reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path, 0)
  63. root = winreg.QueryValueEx(reg, key)[0]
  64. if os.path.exists(root):
  65. return root
  66. except FileNotFoundError:
  67. pass
  68. try:
  69. reg = winreg.OpenKey(winreg.HKEY_CURRENT_USER, path, 0)
  70. root = winreg.QueryValueEx(reg, key)[0]
  71. if os.path.exists(root):
  72. return root
  73. except FileNotFoundError:
  74. pass
  75. return None
  76. @cached_property
  77. def adb_binary(self):
  78. return [os.path.abspath(os.path.join(self.root, a)) for a in self.adb_path]
  79. @cached_property
  80. def adb_backup(self):
  81. files = []
  82. for adb in self.adb_binary:
  83. for n in range(10):
  84. backup = f'{adb}.bak{n}' if n else f'{adb}.bak'
  85. if os.path.exists(backup):
  86. continue
  87. else:
  88. files.append(backup)
  89. break
  90. return files
  91. @cached_property
  92. def serial(self):
  93. """
  94. Returns:
  95. list[str]: Such as ['127.0.0.1:62001', '127.0.0.1:62025']
  96. """
  97. vbox = []
  98. for path, folders, files in os.walk(os.path.join(self.root, self.vbox_path)):
  99. for file in files:
  100. if re.match(self.vbox_name, file):
  101. file = os.path.join(path, file)
  102. vbox.append(file)
  103. serial = []
  104. for file in vbox:
  105. with open(file, 'r', encoding='utf-8', errors='ignore') as f:
  106. for line in f.readlines():
  107. # <Forwarding name="port2" proto="1" hostip="127.0.0.1" hostport="62026" guestport="5555"/>
  108. res = re.search('<*?hostport="(.*?)".*?guestport="5555"/>', line)
  109. if res:
  110. serial.append(f'127.0.0.1:{res.group(1)}')
  111. return serial
  112. def adb_replace(self, adb):
  113. """
  114. Backup the adb in emulator folder to xxx.bak, replace it with your adb.
  115. Need to call `adb kill-server` before replacing.
  116. Args:
  117. adb (str): Absolute path to adb.exe
  118. """
  119. for ori, bak in zip(self.adb_binary, self.adb_backup):
  120. logger.info(f'Replacing {ori}')
  121. if os.path.exists(ori):
  122. if filecmp.cmp(adb, ori, shallow=True):
  123. logger.info(f'{adb} is same as {ori}, skip')
  124. else:
  125. logger.info(f'{ori} -----> {bak}')
  126. shutil.move(ori, bak)
  127. logger.info(f'{adb} -----> {ori}')
  128. shutil.copy(adb, ori)
  129. else:
  130. logger.info(f'{ori} not exists, skip')
  131. def adb_recover(self):
  132. """ Revert adb replacement """
  133. for ori in self.adb_binary:
  134. logger.info(f'Recovering {ori}')
  135. bak = f'{ori}.bak'
  136. if os.path.exists(bak):
  137. logger.info(f'Delete {ori}')
  138. if os.path.exists(ori):
  139. os.remove(ori)
  140. logger.info(f'{bak} -----> {ori}')
  141. shutil.move(bak, ori)
  142. else:
  143. logger.info(f'Not exists {bak}, skip')
  144. # NoxPlayer 夜神模拟器
  145. nox_player = VirtualBoxEmulator(
  146. name="Nox",
  147. root_path=".",
  148. adb_path=["./adb.exe", "./nox_adb.exe"],
  149. vbox_path="./BignoxVMS",
  150. vbox_name='.*.vbox$'
  151. )
  152. nox_player_64 = VirtualBoxEmulator(
  153. name="Nox64",
  154. root_path=".",
  155. adb_path=["./adb.exe", "./nox_adb.exe"],
  156. vbox_path="./BignoxVMS",
  157. vbox_name='.*.vbox$'
  158. )
  159. # LDPlayer 雷电模拟器
  160. ld_player = VirtualBoxEmulator(
  161. name="LDPlayer",
  162. root_path=".",
  163. adb_path="./adb.exe",
  164. vbox_path="./vms",
  165. vbox_name='.*.vbox$'
  166. )
  167. ld_player_4 = VirtualBoxEmulator(
  168. name="LDPlayer4",
  169. root_path=".",
  170. adb_path="./adb.exe",
  171. vbox_path="./vms",
  172. vbox_name='.*.vbox$'
  173. )
  174. ld_player_9 = VirtualBoxEmulator(
  175. name="LDPlayer9",
  176. root_path=".",
  177. adb_path="./adb.exe",
  178. vbox_path="./vms",
  179. vbox_name='.*.vbox$'
  180. )
  181. # MemuPlayer 逍遥模拟器
  182. memu_player = VirtualBoxEmulator(
  183. name="MEmu",
  184. root_path="../",
  185. adb_path="./adb.exe",
  186. vbox_path="./MemuHyperv VMs",
  187. vbox_name='.*.memu$'
  188. )
  189. # MumuPlayer MuMu模拟器
  190. mumu_player = VirtualBoxEmulator(
  191. name="Nemu",
  192. root_path=".",
  193. adb_path="./vmonitor/bin/adb_server.exe",
  194. vbox_path="./vms",
  195. vbox_name='.*.nemu$'
  196. )
  197. mumu12_player = VirtualBoxEmulator(
  198. name="Nemu12",
  199. root_path=".",
  200. adb_path="./shell/adb.exe",
  201. vbox_path="./vms",
  202. vbox_name='.*.nemu$'
  203. )
  204. class EmulatorConnect:
  205. SUPPORTED_EMULATORS = [
  206. nox_player,
  207. nox_player_64,
  208. ld_player,
  209. ld_player_4,
  210. ld_player_9,
  211. memu_player,
  212. mumu_player,
  213. mumu12_player
  214. ]
  215. def __init__(self, adb='adb.exe'):
  216. self.adb_binary = adb
  217. def _execute(self, cmd, timeout=10, output=True):
  218. """
  219. Returns:
  220. Object: Stdout(str) of cmd if output,
  221. return code(int) of cmd if not output.
  222. """
  223. if not output:
  224. cmd.extend(['>nul', '2>nul'])
  225. logger.info(' '.join(cmd))
  226. process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)
  227. try:
  228. stdout, stderr = process.communicate(timeout=timeout)
  229. ret_code = process.returncode
  230. except subprocess.TimeoutExpired:
  231. process.kill()
  232. stdout, stderr = process.communicate()
  233. ret_code = 1
  234. logger.info(f'TimeoutExpired, stdout={stdout}, stderr={stderr}')
  235. if output:
  236. return stdout
  237. else:
  238. return ret_code
  239. @cached_property
  240. def emulators(self):
  241. """
  242. Returns:
  243. list: List of installed emulators on current computer.
  244. """
  245. emulators = []
  246. for emulator in self.SUPPORTED_EMULATORS:
  247. try:
  248. serial = emulator.serial
  249. emulators.append(emulator)
  250. except FileNotFoundError:
  251. continue
  252. if len(serial):
  253. logger.info(f'Emulator {emulator.name} found, instances: {serial}')
  254. return emulators
  255. def devices(self):
  256. """
  257. Returns:
  258. list[str]: Connected devices in adb
  259. """
  260. result = self._execute([self.adb_binary, 'devices']).decode()
  261. devices = []
  262. for line in result.replace('\r\r\n', '\n').replace('\r\n', '\n').split('\n'):
  263. if line.startswith('List') or '\t' not in line:
  264. continue
  265. serial, status = line.split('\t')
  266. if status == 'device':
  267. devices.append(serial)
  268. logger.info(f'Devices: {devices}')
  269. return devices
  270. def adb_kill(self):
  271. # self._execute([self.adb_binary, 'devices'])
  272. # self._execute([self.adb_binary, 'kill-server'])
  273. # Just kill it, because some adb don't obey.
  274. logger.info('Kill all known ADB')
  275. for exe in [
  276. # Most emulator use this
  277. 'adb.exe',
  278. # NoxPlayer 夜神模拟器
  279. 'nox_adb.exe',
  280. # MumuPlayer MuMu模拟器
  281. 'adb_server.exe',
  282. # Bluestacks 蓝叠模拟器
  283. 'HD-Adb.exe'
  284. ]:
  285. ret_code = self._execute(['taskkill', '/f', '/im', exe], output=False)
  286. if ret_code == 0:
  287. logger.info(f'Task {exe} killed')
  288. elif ret_code == 128:
  289. logger.info(f'Task {exe} not found')
  290. else:
  291. logger.info(f'Error occurred when killing task {exe}, return code {ret_code}')
  292. @cached_property
  293. def serial(self):
  294. """
  295. Returns:
  296. list[str]: All available emulator serial on current computer.
  297. """
  298. serial = ['127.0.0.1:7555']
  299. for emulator in self.emulators:
  300. serial += emulator.serial
  301. for s in emulator.serial:
  302. ip, port = s.split(':')
  303. port = int(port) - 1
  304. if 5554 <= int(port) < 5600:
  305. serial.append(f'emulator-{port}')
  306. return serial
  307. def brute_force_connect(self):
  308. """ Brute-force connect all available emulator instances """
  309. self.devices()
  310. async def connect():
  311. await asyncio.gather(
  312. *[asyncio.create_subprocess_exec(self.adb_binary, 'connect', serial) for serial in self.serial]
  313. )
  314. asyncio.run(connect())
  315. return self.devices()
  316. def adb_replace(self, adb=None):
  317. """
  318. Different version of ADB will kill each other when starting.
  319. Chinese emulators (NoxPlayer, LDPlayer, MemuPlayer, MuMuPlayer) use their own adb,
  320. instead of the one in system PATH, so when they start they kill the adb.exe Alas is using.
  321. Replacing the ADB in emulator is the simplest way to solve this.
  322. Args:
  323. adb (str): Absolute path to adb.exe
  324. """
  325. self.adb_kill()
  326. for emulator in self.emulators:
  327. emulator.adb_replace(adb if adb is not None else self.adb_binary)
  328. self.brute_force_connect()
  329. def adb_recover(self):
  330. """ Revert adb replacement """
  331. self.adb_kill()
  332. for emulator in self.emulators:
  333. emulator.adb_recover()
  334. self.brute_force_connect()
  335. if __name__ == '__main__':
  336. emu = EmulatorConnect()
  337. logger.info(emu.brute_force_connect())