Skip to content

Instantly share code, notes, and snippets.

@ascheel
Created June 27, 2019 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ascheel/e04b9a1d10dc9063bba5ded0581680bf to your computer and use it in GitHub Desktop.
Save ascheel/e04b9a1d10dc9063bba5ded0581680bf to your computer and use it in GitHub Desktop.
# import dropbox
import dropbox
# from dropbox import DropboxOAuth2FlowNoRedirect
import os
import sys
import json
class Dropbox:
def __init__(self):
self.APP_KEY = 'XXXXXXXXXXXXXXX'
self.APP_SECRET = 'XXXXXXXXXXXXXXX'
self.ACCESS_TYPE = 'dropbox'
self.client = self.get_client()
def get_latest_revision(self, _object):
try:
revisions = self.client.files_list_revisions(_object.path_display, limit=30).entries
except dropbox.exceptions.ApiError as e:
return None
except Exception as e:
print(e)
sys.exit(1)
return sorted(revisions, key=lambda entry: entry.server_modified)[0].rev
def attempt_restore(self, _object):
path = _object.path_display
revision = self.get_latest_revision(_object)
if revision:
print("Restoring {}... ".format(_object.path_display), end="")
sys.stdout.flush()
try:
results = self.client.files_restore(_object.path_display, rev=revision)
except Exception as e:
print("Failed. {}".format(e))
return
print("Done.")
def get_deleted_objects(self, _dir):
deleted = []
contents = self.client.files_list_folder(_dir, recursive=True, include_deleted=True)
has_more = contents.has_more
while has_more:
cursor = contents.cursor
for entry in contents.entries:
# deleted.append(entry)
if isinstance(entry, dropbox.files.DeletedMetadata):
deleted.append(entry)
self.attempt_restore(entry)
contents = self.client.files_list_folder_continue(cursor)
has_more = contents.has_more
return deleted
def get_client(self):
access_token_file = os.path.join(os.environ["HOME"], ".dropbox-access-token")
access_token = None
try:
with open(access_token_file) as f_in:
access_token = f_in.read()
except (IOError, EOFError, KeyError) as e:
auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(self.APP_KEY, self.APP_SECRET)
authorize_url = auth_flow.start()
print("Please visit\n\n {}\n\n".format(authorize_url))
auth_code = input("Enter the authorization code here: ").strip()
try:
oauth_result = auth_flow.finish(auth_code)
except Exception as e:
print("Error: {}".format(e))
print("auth_code: {}".format(oauth_result))
return
access_token = oauth_result.access_token
with open(access_token_file, "w") as f_out:
f_out.write(access_token)
# print('Access token: {}'.format(oauth_result.access_token))
dbx = dropbox.Dropbox(access_token)
return dbx
def main():
dbx = Dropbox()
_dir = sys.argv[1]
contents = dbx.get_deleted_objects(_dir)
for content in contents:
print(content)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment