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.

200 lines
6.3 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
  1. import datetime
  2. import json
  3. import os
  4. import re
  5. import shutil
  6. import subprocess
  7. import time
  8. debug = True
  9. path = os.path.dirname(__file__)
  10. with open(os.path.join(path,'defaults.json')) as d,open(os.path.join(path,'keycodes.json')) as k:
  11. defaults = json.load(d)
  12. keycodes = json.load(k)
  13. exe = defaults['exe']
  14. for key,value in defaults['local'].items():
  15. defaults['local'][key] = os.path.expandvars(value)
  16. def merge(src, dst,log = False):
  17. if not os.path.exists(dst):
  18. return False
  19. ok = True
  20. for path, dirs, files in os.walk(src):
  21. relPath = os.path.relpath(path, src)
  22. destPath = os.path.join(dst, relPath)
  23. if not os.path.exists(destPath):
  24. os.makedirs(destPath)
  25. for file in files:
  26. destFile = os.path.join(destPath, file)
  27. if os.path.isfile(destFile):
  28. if log:
  29. print("Skipping existing file: " + os.path.join(relPath, file))
  30. ok = False
  31. continue
  32. srcFile = os.path.join(path, file)
  33. shutil.move(srcFile, destFile)
  34. for path, dirs, files in os.walk(src, False):
  35. if len(files) == 0 and len(dirs) == 0:
  36. os.rmdir(path)
  37. return ok
  38. def _adb(*args,out = False):
  39. args = [exe] + list(args)
  40. if out:
  41. return subprocess.check_output(args,shell = False).decode().rstrip('\r\n')
  42. else:
  43. subprocess.call(args,shell = False)
  44. def get_info():
  45. thing = _adb("devices","-l",out = True)
  46. formed = list(filter(bool,thing.split("\r\n")))[1:]
  47. main = {}
  48. for device in formed:
  49. categories = re.split(" +",device)
  50. device_dict = {
  51. "serial":categories[0],
  52. "mode":categories[1]
  53. }
  54. device_dict.update(dict(category.split(":") for category in categories[2:]))
  55. main[categories[0]] = device_dict
  56. return main
  57. class device:
  58. def prim_device():
  59. while True:
  60. prim_device_serial = get_info()
  61. if len(prim_device_serial.keys()) > 0:
  62. return device(list(prim_device_serial.keys())[0])
  63. def __init__(self,serial=None):
  64. if serial:
  65. self.serial = serial
  66. self.info = get_info()[serial]
  67. else:
  68. self.serial,self.info = get_info().items()[0]
  69. def adb(self,*args,out = False):
  70. args = ['-s',self.serial]+ list(args)
  71. return _adb(*args,out = out)
  72. def sudo(self,*args,out = False):
  73. if self.info['mode'] == 'recovery':
  74. return self.adb(*(["shell"]+list(args)),out=out)
  75. else:
  76. args = '"{}"'.format(" ".join(args))
  77. return self.adb("shell","su","-c",args,out = out)
  78. def exists(self,file):
  79. exists = '''if [ -e {} ]
  80. then
  81. echo "True"
  82. else
  83. echo "False"
  84. fi'''
  85. e = exists.format(file)
  86. res = self.sudo(e,out=True)
  87. return res == "True"
  88. def reboot(self,mode = None):
  89. if mode:
  90. if mode == "soft":
  91. pid = self.adb("shell","pidof","zygote",out = True)
  92. return self.sudo("kill",pid,out=True)
  93. else:
  94. self.adb("reboot",mode)
  95. else:
  96. self.adb("reboot")
  97. def delete(self,path):
  98. return self.sudo("rm","-rf",path,out=True)
  99. def copy(self,remote,local,del_duplicates = True,ignore_error=True):
  100. if self.exists(remote):
  101. flag = False
  102. if os.path.exists(local):
  103. last = os.path.split(local)[-1]
  104. real_dir = local
  105. local = os.path.join(defaults['local']['temp'],last)
  106. flag = True
  107. try:
  108. self.adb("pull","-a",remote,local,out=True)
  109. except subprocess.CalledProcessError as e:
  110. if ignore_error:
  111. pass
  112. else:
  113. raise e
  114. if flag:
  115. merge(local,real_dir)
  116. if os.path.exists(local) and del_duplicates:
  117. shutil.rmtree(local)
  118. else:
  119. print("File not found: {}".format(remote))
  120. def send_keycode(self,code):
  121. try:
  122. keycode = keycodes[code]
  123. except KeyError:
  124. keycode = str(code)
  125. self.adb("shell","input","keyevent",keycode)
  126. def move(self,remote,local,del_duplicates = True,ignore_error=False):
  127. if self.exists(remote):
  128. self.copy(remote,local,del_duplicates = del_duplicates,ignore_error=ignore_error)
  129. self.delete(remote)
  130. else:
  131. print("File not found: {}".format(remote))
  132. def push(self,local,remote):
  133. self.adb('push',local,remote)
  134. def backup(self,*partitions,name = None):
  135. backupdir = defaults['local']['TWRP']
  136. options_dict = {
  137. "system": "S",
  138. "data": "D",
  139. "cache": "C",
  140. "recovery": "R",
  141. "spec_part_1": "1",
  142. "spec_part_2": "2",
  143. "spec_part_3": "3",
  144. "boot": "B",
  145. "as": "A"
  146. }
  147. options = "".join(options_dict[option] for option in partitions)
  148. if not name:
  149. name = "backup_"+datetime.datetime.today().strftime(defaults['date_format'])
  150. filename = os.path.join(backupdir,name)
  151. self.adb("shell","twrp","backup",options,name)
  152. phone_dir = "/data/media/0/TWRP/BACKUPS/{serial}/{name}".format(serial = self.serial,name = name)
  153. self.move(phone_dir,filename)
  154. def wipe(self,partition):
  155. self.adb("shell","twrp","wipe",partition)
  156. def unlock_phone(self,pin):
  157. self.send_keycode('power')
  158. self.send_keycode('space')
  159. self.adb("shell","input","text",str(pin))
  160. self.send_keycode('enter')
  161. def install(self,name):
  162. if os.path.exists(name):
  163. local_name = name
  164. name = os.path.split(name)[-1]
  165. update_path = '{}/{}'.format(defaults['remote']['updates'],name)
  166. if not self.exists(update_path):
  167. self.push(local_name,defaults['remote']['updates'])
  168. else:
  169. update_path = '{}/{}'.format(defaults['remote']['updates'],name)
  170. self.adb("shell","twrp","install",update_path)
  171. if __name__ == "__main__" and debug:
  172. d = device.prim_device()