Advertisement
Guest User

Untitled

a guest
Feb 7th, 2016
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.15 KB | None | 0 0
  1. #!/usb/bin/env python
  2.  
  3. import os
  4. import dropbox
  5. import shutil
  6. import zipfile
  7.  
  8. # Create a dropbox app and obtain App Key and Secret Key. Specify a folder
  9. # Create a folder called romsync in your specified Dropbox app folder
  10. # Store Dropbox App Key and Secret Key in system environment variables
  11. app_key = os.getenv('DROPBOX_ROMSYNC_APP_KEY')
  12. app_secret = os.getenv('DROPBOX_ROMSYNC_SECRET_KEY')
  13.  
  14. DEBUG = 0
  15. CFG_DEFAULT = os.path.join(os.getenv('HOME'), '.romsync')
  16.  
  17.  
  18. # A Config object to store and load settings
  19. class Config(object):
  20. settings = {}
  21. path = ''
  22.  
  23. def __init__(self, path=CFG_DEFAULT):
  24. self.path = path
  25. self.load()
  26.  
  27. # Return value of setting
  28. def get(self, key):
  29. return self.settings[key]
  30.  
  31. # Update the cursor
  32. def set_cursor(self, cursor):
  33. self.settings['cursor'] = cursor
  34.  
  35. # Write settings to config
  36. def save(self):
  37. open(self.path, 'w').close() # Flush config before writing
  38. with open(self.path, 'w') as cfg:
  39. for key in self.settings:
  40. cfg.write(key + '=' + self.settings[key] + '\n')
  41.  
  42. # Load settings from config
  43. # return: True if config exists, False otherwise
  44. def load(self):
  45. if os.path.isfile(self.path):
  46. with open(self.path, 'r') as cfg:
  47. for line in cfg:
  48. key = line.replace(" ", "").split('=')[0]
  49. value = line.replace(" ", "").split('=')[1].rstrip()
  50. self.settings[key] = value
  51. return True
  52. else:
  53. with open(self.path, 'w') as cfg:
  54. # Generate authorization code
  55. flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret)
  56. authorize_url = flow.start()
  57.  
  58. print('1. Go to: ' + authorize_url)
  59. print('2. Click "Allow" (you might have to log in first)')
  60. print('3. Copy the authorization code.')
  61. code = raw_input('Enter the authorization code here: ').strip()
  62. local_path = raw_input('Enter your local roms directory: ')
  63.  
  64. access_token, user_id = flow.finish(code)
  65.  
  66. # Write default settings to config
  67. cfg.write('access_token=' + access_token + '\n')
  68. cfg.write('db_roms=/romsync\n')
  69. cfg.write('local_roms=' + local_path + '\n')
  70. cfg.write('cursor= ' + '\n')
  71.  
  72. return False
  73.  
  74.  
  75. # Download/remove files and directories
  76. # return: dictionary of modified files
  77. def delta_sync(client, delta, config):
  78. dirs = []
  79. files = []
  80.  
  81. file_change = {'added': [], 'removed': []}
  82. entries = delta['entries']
  83. local_path = config.get('local_roms')
  84. db_path = config.get('db_roms')
  85.  
  86. for e in entries:
  87. path = e[0].replace(db_path, local_path)
  88. if e[1] is None:
  89. try:
  90. if e[1]['is_dir']:
  91. if len(path) > 0:
  92. os.makedirs(path)
  93. else:
  94. out = open(path, 'wb')
  95. with client.get_file(e[1]['path']) as rom:
  96. out.write(rom.read())
  97. file_change['added'].append(path.replace(local_path, ''))
  98. if out.endswith('.zip'):
  99. z = zipfile.ZipFile(out)
  100. z.extractall(path)
  101. z.close()
  102. del z
  103. os.unlink(out)
  104. print out.name + " extracted and deleted"
  105. except:
  106. if DEBUG:
  107. print(path, ' already exists')
  108. else:
  109. try:
  110. if os.path.isdir(path):
  111. shutil.rmtree(path)
  112. for child in os.listdir(path):
  113. file_change['removed'].append(child)
  114. else:
  115. os.remove(path)
  116. file_change['removed'].append(path.replace(local_path, ''))
  117. except:
  118. if DEBUG:
  119. print(path, ' does not exist')
  120.  
  121. return file_change
  122.  
  123.  
  124. def main():
  125. config = Config()
  126. config_exists = config.load()
  127.  
  128. # Get client
  129. client = dropbox.client.DropboxClient(config.get('access_token'))
  130. delta = client.delta(path_prefix=config.get('db_roms'), cursor=config.get('cursor'))
  131. if DEBUG:
  132. print(delta)
  133.  
  134. # Sync files
  135. # Report added and removed files
  136. if len(delta['entries']) > 0:
  137. print('Syncing roms...')
  138.  
  139. file_change = delta_sync(client, delta, config)
  140. added = len(file_change['added'])
  141. removed = len(file_change['removed'])
  142.  
  143. if added > 0:
  144. print('\n' + 'Fetched %s rom(s)' % str(added))
  145. for entry in file_change['added']:
  146. rom = entry.split(os.sep)
  147. print(rom[0] + ' - ' + rom[1])
  148. if removed > 0:
  149. print('\n' + 'Removed %s rom(s)' % str(removed))
  150. for entry in file_change['removed']:
  151. print(entry)
  152. print('')
  153. else:
  154. print('No need to sync')
  155.  
  156. # Update config with new cursor
  157. config.set_cursor(delta['cursor'])
  158. config.save()
  159.  
  160.  
  161. if __name__ == "__main__":
  162. main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement