utils.py 7.9 KB

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