utils.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import random
  2. import re
  3. import socket
  4. import time
  5. import uiautomator2 as u2
  6. from adbutils import AdbTimeout, _AdbStreamConnection
  7. from lxml import etree
  8. from module.base.decorator import cached_property
  9. from module.logger import logger
  10. RETRY_TRIES = 5
  11. RETRY_DELAY = 3
  12. def is_port_using(port_num):
  13. """ if port is using by others, return True. else return False """
  14. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  15. s.settimeout(2)
  16. try:
  17. s.bind(('127.0.0.1', port_num))
  18. return False
  19. except OSError:
  20. # Address already bind
  21. return True
  22. finally:
  23. s.close()
  24. def random_port(port_range):
  25. """ get a random port from port set """
  26. new_port = random.choice(list(range(*port_range)))
  27. if is_port_using(new_port):
  28. return random_port(port_range)
  29. else:
  30. return new_port
  31. def recv_all(stream, chunk_size=4096, recv_interval=0.000) -> bytes:
  32. """
  33. Args:
  34. stream:
  35. chunk_size:
  36. recv_interval (float): Default to 0.000, use 0.001 if receiving as server
  37. Returns:
  38. bytes:
  39. Raises:
  40. AdbTimeout
  41. """
  42. if isinstance(stream, _AdbStreamConnection):
  43. stream = stream.conn
  44. stream.settimeout(10)
  45. else:
  46. stream.settimeout(10)
  47. try:
  48. fragments = []
  49. while 1:
  50. chunk = stream.recv(chunk_size)
  51. if chunk:
  52. fragments.append(chunk)
  53. # See https://stackoverflow.com/questions/23837827/python-server-program-has-high-cpu-usage/41749820#41749820
  54. time.sleep(recv_interval)
  55. else:
  56. break
  57. return remove_shell_warning(b''.join(fragments))
  58. except socket.timeout:
  59. raise AdbTimeout('adb read timeout')
  60. def possible_reasons(*args):
  61. """
  62. Show possible reasons
  63. Possible reason #1: <reason_1>
  64. Possible reason #2: <reason_2>
  65. """
  66. for index, reason in enumerate(args):
  67. index += 1
  68. logger.critical(f'Possible reason #{index}: {reason}')
  69. class PackageNotInstalled(Exception):
  70. pass
  71. class ImageTruncated(Exception):
  72. pass
  73. def retry_sleep(trial):
  74. # First trial
  75. if trial == 0:
  76. pass
  77. # Failed once, fast retry
  78. elif trial == 1:
  79. pass
  80. # Failed twice
  81. elif trial == 2:
  82. time.sleep(1)
  83. # Failed more
  84. else:
  85. time.sleep(RETRY_DELAY)
  86. def handle_adb_error(e):
  87. """
  88. Args:
  89. e (Exception):
  90. Returns:
  91. bool: If should retry
  92. """
  93. text = str(e)
  94. if 'not found' in text:
  95. # When you call `adb disconnect <serial>`
  96. # Or when adb server was killed (low possibility)
  97. # AdbError(device '127.0.0.1:59865' not found)
  98. logger.error(e)
  99. return True
  100. elif 'timeout' in text:
  101. # AdbTimeout(adb read timeout)
  102. logger.error(e)
  103. return True
  104. elif 'closed' in text:
  105. # AdbError(closed)
  106. # Usually after AdbTimeout(adb read timeout)
  107. # Disconnect and re-connect should fix this.
  108. logger.error(e)
  109. return True
  110. elif 'device offline' in text:
  111. # AdbError(device offline)
  112. # When a device that has been connected wirelessly is disconnected passively,
  113. # it does not disappear from the adb device list,
  114. # but will be displayed as offline.
  115. # In many cases, such as disconnection and recovery caused by network fluctuations,
  116. # or after VMOS reboot when running Alas on a phone,
  117. # the device is still available, but it needs to be disconnected and re-connected.
  118. logger.error(e)
  119. return True
  120. elif 'is offline' in text:
  121. # RuntimeError: USB device 127.0.0.1:7555 is offline
  122. # Raised by uiautomator2 when current adb service is killed by another version of adb service.
  123. logger.error(e)
  124. return True
  125. elif 'unknown host service' in text:
  126. # AdbError(unknown host service)
  127. # Another version of ADB service started, current ADB service has been killed.
  128. # Usually because user opened a Chinese emulator, which uses ADB from the Stone Age.
  129. logger.error(e)
  130. return True
  131. else:
  132. # AdbError()
  133. logger.exception(e)
  134. possible_reasons(
  135. 'If you are using BlueStacks or LD player or WSA, please enable ADB in the settings of your emulator',
  136. 'Emulator died, please restart emulator',
  137. 'Serial incorrect, no such device exists or emulator is not running'
  138. )
  139. return False
  140. def get_serial_pair(serial):
  141. """
  142. Args:
  143. serial (str):
  144. Returns:
  145. str, str: `127.0.0.1:5555+{X}` and `emulator-5554+{X}`, 0 <= X <= 32
  146. """
  147. if serial.startswith('127.0.0.1:'):
  148. try:
  149. port = int(serial[10:])
  150. if 5555 <= port <= 5555 + 32:
  151. return f'127.0.0.1:{port}', f'emulator-{port - 1}'
  152. except (ValueError, IndexError):
  153. pass
  154. if serial.startswith('emulator-'):
  155. try:
  156. port = int(serial[9:])
  157. if 5554 <= port <= 5554 + 32:
  158. return f'127.0.0.1:{port + 1}', f'emulator-{port}'
  159. except (ValueError, IndexError):
  160. pass
  161. return None, None
  162. def remove_prefix(s, prefix):
  163. """
  164. Remove prefix of a string or bytes like `string.removeprefix(prefix)`, which is on Python3.9+
  165. Args:
  166. s (str, bytes):
  167. prefix (str, bytes):
  168. Returns:
  169. str, bytes:
  170. """
  171. return s[len(prefix):] if s.startswith(prefix) else s
  172. def remove_shell_warning(s):
  173. """
  174. Remove warnings from shell
  175. Args:
  176. s (str, bytes):
  177. Returns:
  178. str, bytes:
  179. """
  180. # WARNING: linker: [vdso]: unused DT entry: type 0x70000001 arg 0x0\n\x89PNG\r\n\x1a\n\x00\x00\x00\rIH
  181. if isinstance(s, bytes):
  182. if s.startswith(b'WARNING'):
  183. try:
  184. s = s.split(b'\n', maxsplit=1)[1]
  185. except IndexError:
  186. pass
  187. return s
  188. # return re.sub(b'^WARNING.+\n', b'', s)
  189. elif isinstance(s, str):
  190. if s.startswith('WARNING'):
  191. try:
  192. s = s.split('\n', maxsplit=1)[1]
  193. except IndexError:
  194. pass
  195. return s
  196. class IniterNoMinicap(u2.init.Initer):
  197. @property
  198. def minicap_urls(self):
  199. """
  200. Don't install minicap on emulators, return empty urls.
  201. binary from https://github.com/openatx/stf-binaries
  202. only got abi: armeabi-v7a and arm64-v8a
  203. """
  204. return []
  205. class Device(u2.Device):
  206. def show_float_window(self, show=True):
  207. """
  208. Don't show float windows.
  209. """
  210. pass
  211. # Monkey patch
  212. u2.init.Initer = IniterNoMinicap
  213. u2.Device = Device
  214. class HierarchyButton:
  215. """
  216. Convert UI hierarchy to an object like the Button in Alas.
  217. """
  218. _name_regex = re.compile('@.*?=[\'\"](.*?)[\'\"]')
  219. def __init__(self, hierarchy: etree._Element, xpath: str):
  220. self.hierarchy = hierarchy
  221. self.xpath = xpath
  222. self.nodes = hierarchy.xpath(xpath)
  223. @cached_property
  224. def name(self):
  225. res = HierarchyButton._name_regex.findall(self.xpath)
  226. if res:
  227. return res[0]
  228. else:
  229. return 'HierarchyButton'
  230. @cached_property
  231. def count(self):
  232. return len(self.nodes)
  233. @cached_property
  234. def exist(self):
  235. return self.count == 1
  236. @cached_property
  237. def area(self):
  238. if self.exist:
  239. bounds = self.nodes[0].attrib.get("bounds")
  240. lx, ly, rx, ry = map(int, re.findall(r"\d+", bounds))
  241. return lx, ly, rx, ry
  242. else:
  243. return None
  244. @cached_property
  245. def button(self):
  246. return self.area
  247. def __bool__(self):
  248. return self.exist
  249. def __str__(self):
  250. return self.name
  251. @cached_property
  252. def focused(self):
  253. if self.exist:
  254. return self.nodes[0].attrib.get("focused").lower() == 'true'
  255. else:
  256. return False