You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

264 lines
8.0 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
  1. import datetime
  2. import json
  3. import os
  4. import re
  5. import shutil
  6. import subprocess
  7. import time
  8. from load_things import loaded
  9. from decode_parcel import decode_parcel
  10. debug = True
  11. defaults = loaded.defaults
  12. keycodes = loaded.keycodes
  13. exe = defaults.exe
  14. exists = '''if [ -e "{file}" ]; then
  15. if [ -d "{file}" ]; then
  16. echo "directory"
  17. elif [ -f "{file}" ]; then
  18. echo "file"
  19. else
  20. echo "error"
  21. fi
  22. else
  23. echo "na"
  24. fi'''
  25. def merge(src, dst,log = False):
  26. if not os.path.exists(dst):
  27. return False
  28. ok = True
  29. for path, dirs, files in os.walk(src):
  30. relPath = os.path.relpath(path, src)
  31. destPath = os.path.join(dst, relPath)
  32. if not os.path.exists(destPath):
  33. os.makedirs(destPath)
  34. for file in files:
  35. destFile = os.path.join(destPath, file)
  36. if os.path.isfile(destFile):
  37. if log:
  38. print("Skipping existing file: " + os.path.join(relPath, file))
  39. ok = False
  40. continue
  41. srcFile = os.path.join(path, file)
  42. shutil.move(srcFile, destFile)
  43. for path, dirs, files in os.walk(src, False):
  44. if len(files) == 0 and len(dirs) == 0:
  45. os.rmdir(path)
  46. return ok
  47. def _adb(*args,out = False):
  48. args = [exe] + list(args)
  49. if out:
  50. return subprocess.check_output(args,shell = False).decode().rstrip('\r\n')
  51. else:
  52. ret = subprocess.call(args,shell = False)
  53. if ret:
  54. raise subprocess.CalledProcessError(ret,args)
  55. def get_info():
  56. thing = _adb("devices","-l",out = True)
  57. formed = list(filter(bool,thing.split("\r\n")))[1:]
  58. main = {}
  59. for device in formed:
  60. categories = re.split(" +",device)
  61. device_dict = {
  62. "serial":categories[0],
  63. "mode":categories[1]
  64. }
  65. device_dict.update(dict(category.split(":") for category in categories[2:]))
  66. main[categories[0]] = device_dict
  67. return main
  68. class Device:
  69. def connect(ip,port=5555):
  70. if not re.match(r'(\d{1,3}\.){3}\d{1,3}',ip):
  71. raise TypeError("Invalid ip")
  72. if not all(int(n) <= 255 and int(n) >= 0 for n in ip.split('.')):
  73. raise TypeError("Invalid ip")
  74. if not (port >= 0 and port <= 2**16-1):
  75. raise TyperError("Port must be in the range 0-65536")
  76. id = '{}:{}'.format(ip,port)
  77. _adb('connect','{}:{}'.format(ip,port))
  78. dev = Device(id)
  79. dev.tcip = True
  80. return dev
  81. def disconnect(self):
  82. if self.tcip:
  83. _adb('disconnect',self.serial)
  84. def prim_device():
  85. cont = True
  86. while cont:
  87. try:
  88. d = Device()
  89. cont = False
  90. except IndexError:
  91. time.sleep(1)
  92. return d
  93. def __init__(self,serial=None):
  94. self.tcip = False
  95. if serial:
  96. self.serial = serial
  97. info = get_info()[serial]
  98. else:
  99. serial,info = list(get_info().items())[0]
  100. self.__dict__.update(info)
  101. def adb(self,*args,out = False):
  102. args = ['-s',self.serial]+ list(args)
  103. return _adb(*args,out = out)
  104. def shell(self,*args,out=False):
  105. args = ('shell',)+args
  106. return self.adb(*args,out=out)
  107. def sudo(self,*args,out = False):
  108. if self.mode == 'recovery':
  109. return self.shell(*args,out=out)
  110. else:
  111. args = '"{}"'.format(' '.join(args).replace('"','\\"'))
  112. return self.shell('su','-c',args,out = out)
  113. def type(self,file):
  114. e = exists.format(file = file)
  115. res = self.sudo(e,out=True)
  116. return res
  117. def exists(self,file):
  118. return self.type(file) != "na"
  119. def isfile(self,file):
  120. return self.type(file) == 'file'
  121. def isdir(self,file):
  122. return self.type(file) == 'directory'
  123. def delete(self,path):
  124. return self.sudo("rm","-rf",path,out=True)
  125. def copy(self,remote,local,del_duplicates = True,ignore_error=True):
  126. remote_type = self.type(remote)
  127. if remote_type != "na":
  128. if remote_type == "directory" and not remote.endswith('/'):
  129. remote += '/'
  130. merge_flag = False
  131. if os.path.exists(local):
  132. last = os.path.split(local)[-1]
  133. real_dir = local
  134. local = os.path.join(defaults['local']['temp'],last)
  135. merge_flag = True
  136. try:
  137. self.adb("pull","-a",remote,local)
  138. except subprocess.CalledProcessError as e:
  139. if ignore_error:
  140. pass
  141. else:
  142. raise e
  143. if merge_flag:
  144. merge(local,real_dir)
  145. if os.path.exists(local) and del_duplicates:
  146. shutil.rmtree(local)
  147. else:
  148. print("File not found: {}".format(remote))
  149. def move(self,remote,local,del_duplicates = True,ignore_error=False):
  150. if self.exists(remote):
  151. self.copy(remote,local,del_duplicates = del_duplicates,ignore_error=ignore_error)
  152. self.delete(remote)
  153. else:
  154. print("File not found: {}".format(remote))
  155. def push(self,local,remote):
  156. self.adb('push',local,remote)
  157. def reboot(self,mode = None):
  158. if mode:
  159. if mode == "soft":
  160. if self.mode != 'recovery':
  161. pid = self.shell("pidof","zygote",out = True)
  162. return self.sudo("kill",pid,out=False)
  163. else:
  164. return self.reboot()
  165. else:
  166. self.adb("reboot",mode)
  167. else:
  168. self.adb("reboot")
  169. while True:
  170. infos = get_info()
  171. if len(infos) > 0:
  172. self.__dict__.update(infos[self.serial])
  173. break
  174. time.sleep(1)
  175. def send_keycode(self,code):
  176. try:
  177. keycode = keycodes[code]
  178. except KeyError:
  179. keycode = str(code)
  180. self.shell("input","keyevent",keycode)
  181. def unlock_phone(self,password):
  182. if self.mode != 'recovery':
  183. if not decode_parcel(self.shell('service','call', 'power','12',out=True),'int'):
  184. self.send_keycode('power')
  185. if decode_parcel(self.shell('service','call','trust','7',out=True),'int'):
  186. self.send_keycode('space')
  187. self.shell("input","text",str(password))
  188. self.send_keycode('enter')
  189. def backup(self,*partitions,name = None):
  190. if self.mode != 'recovery':
  191. self.reboot('recovery')
  192. backupdir = defaults['local']['TWRP']
  193. options_dict = {
  194. "system": "S",
  195. "data": "D",
  196. "cache": "C",
  197. "recovery": "R",
  198. "spec_part_1": "1",
  199. "spec_part_2": "2",
  200. "spec_part_3": "3",
  201. "boot": "B",
  202. "as": "A"
  203. }
  204. options = "".join(options_dict[option] for option in partitions)
  205. if not name:
  206. name = "backup_"+datetime.datetime.today().strftime(defaults['date_format'])
  207. filename = os.path.join(backupdir,name)
  208. self.shell("twrp","backup",options,name)
  209. phone_dir = "/data/media/0/TWRP/BACKUPS/{serial}/{name}".format(serial = self.serial,name = name)
  210. self.move(phone_dir,filename)
  211. def wipe(self,partition):
  212. if self.mode != 'recovery':
  213. self.reboot('recovery')
  214. self.shell("twrp","wipe",partition)
  215. def install(self,name):
  216. if self.mode != 'recovery':
  217. self.reboot('recovery')
  218. if os.path.exists(name):
  219. local_name = name
  220. name = os.path.split(name)[-1]
  221. update_path = '{}/{}'.format(defaults['remote']['updates'],name)
  222. if not self.exists(update_path):
  223. self.push(local_name,defaults['remote']['updates'])
  224. else:
  225. update_path = '{}/{}'.format(defaults['remote']['updates'],name)
  226. self.shell("twrp","install",update_path)
  227. if __name__ == "__main__" and debug:
  228. d = Device.prim_device()