Example #1
0
 def __init__(self, oauth2_access_token=oauth2_access_token, root_path=location, timeout=timeout,
              write_mode=write_mode):
     if oauth2_access_token is None:
         raise ImproperlyConfigured("You must configure an auth token at"
                                    "'settings.DROPBOX_OAUTH2_TOKEN'.")
     if write_mode not in ["add", "overwrite",  "update"]:
         raise ImproperlyConfigured("DROPBOX_WRITE_MODE must be set to either: 'add', 'overwrite' or 'update'")
     self.root_path = root_path
     self.write_mode = write_mode
     self.client = Dropbox(oauth2_access_token, timeout=timeout)
Example #2
0
    def __init__(self,
                 oauth2_access_token=oauth2_access_token,
                 root_path=location,
                 timeout=timeout):
        if oauth2_access_token is None:
            raise ImproperlyConfigured("You must configure an auth token at"
                                       "'settings.DROPBOX_OAUTH2_TOKEN'.")

        self.root_path = root_path
        self.client = Dropbox(oauth2_access_token, timeout=timeout)
Example #3
0
 def __init__(self, accessToken, folder, proxyHost=None, proxyPort=None, proxyUser=None, proxyPassword=None):
     proxies = _proxies(proxyHost, proxyPort, proxyUser, proxyPassword)
     self.__token = accessToken
     self.__basePath = folder
     self.__notesPath = folder + "/entries"
     self.__removedNotesPath = self.__notesPath + "/deleted"
     self.__photosPath = folder + "/photos"
     self.__client = Dropbox(self.__token, session=create_session(proxies=proxies))
     self.__notesCache = {}
     self.__dayOneFlavor = folder == SyncFolder.DayOne
Example #4
0
 def get_auth(self, auth_code):
     try:
         access_token, user_id = self.auth_flow.finish(auth_code)
     except Exception as e:
         print('Error: %s' % (e,))
         return False
     else:
         self.dbx = Dropbox(access_token)
         self.setup_tree(self.tree.root, '')
         return True
Example #5
0
 def test_check_refresh_with_invalid_grant(self,
                                           invalid_grant_session_instance):
     dbx = Dropbox(oauth2_refresh_token=REFRESH_TOKEN,
                   app_key=APP_KEY,
                   app_secret=APP_SECRET,
                   session=invalid_grant_session_instance)
     with pytest.raises(AuthError) as e:
         dbx.check_and_refresh_access_token()
         invalid_grant_session_instance.post.assert_called_once()
         assert e.error.is_invalid_access_token()
Example #6
0
    def get_handler(api_key: str) -> Dropbox:
        """
        Returns a Cloudstore handler.

        :param api_key:
        :return:
        """

        dbx = Dropbox(api_key)
        return dbx
Example #7
0
    def __init__(self, oauth2_access_token=None, root_path=None, timeout=None):
        oauth2_access_token = oauth2_access_token or setting(
            'DROPBOX_OAUTH2_TOKEN')
        if oauth2_access_token is None:
            raise ImproperlyConfigured("You must configure an auth token at"
                                       "'settings.DROPBOX_OAUTH2_TOKEN'.")

        self.root_path = root_path or setting('DROPBOX_ROOT_PATH', '/')
        timeout = timeout or setting('DROPBOX_TIMEOUT', _DEFAULT_TIMEOUT)
        self.client = Dropbox(oauth2_access_token, timeout=timeout)
Example #8
0
 def test_check_refresh_with_valid_offline_token(self, session_instance):
     # Test Offline Case w/ valid access
     dbx = Dropbox(oauth2_access_token=ACCESS_TOKEN,
                   oauth2_refresh_token=REFRESH_TOKEN,
                   oauth2_access_token_expiration=EXPIRATION,
                   app_key=APP_KEY,
                   app_secret=APP_SECRET,
                   session=session_instance)
     dbx.check_and_refresh_access_token()
     session_instance.post.assert_not_called()
Example #9
0
def pull_from_dropbox(branch_name, symbol, gui):
    global settings  # Read

    if settings["CONFIRM"]:
        confirm = simpledialog.askstring(
            "Confirm",
            "Type in 'YES' if you wish to proceed. This will override existing worlds"
            " if a conflict is found")

        if not confirm == "YES":
            return "Pull cancelled"

    saves_path = settings["SAVES_DIR"]
    temp_dir = settings["TEMP_DIR"]
    source = "/" + branch_name + "/"

    if settings["OAUTH"] == 'null':
        return "Please type in /login to use this feature"

    println("Starting download... ", gui)
    println(
        "Do not close the app until 'done downloading' message is shown on the console",
        gui)

    # clear temp_dir
    for path_temp in listdir(temp_dir):
        if path.isdir(path.join(temp_dir, path_temp)):
            rmtree(path.join(temp_dir, path_temp))
        else:
            remove(path.join(temp_dir, path_temp))

    # download zip files
    dbx = Dropbox(settings["OAUTH"].access_token)
    for entry in dbx.files_list_folder(source).entries:
        file = source + entry.name
        with open(path.join(temp_dir, entry.name), "wb") as f:
            metadata, res = dbx.files_download(path=file)
            f.write(res.content)
            f.close()

    for path_temp in listdir(temp_dir):
        file = path.join(temp_dir, path_temp)
        name, extension = path.splitext(file)
        file_name, ext = path.splitext(path_temp)

        if file_name[0] == symbol and extension == ".zip":
            with zipfile.ZipFile(file, 'r') as zip_ref:
                z = path.join(saves_path, file_name)
                zip_ref.extractall(z)

        remove(file)

    save(settings)

    return "Done Downloading"
Example #10
0
 def start(self):
     instance = OnlineStorage.OnlineStorage
     if self.args.service == "google_drive":
         instance = GoogleDrive.GoogleDrive(self)
         instance.sync()
     if self.args.service == "dropbox":
         instance = Dropbox.Dropbox(self)
         instance.sync()
     if self.args.service == "gmail":
         instance = GMail.GMail(self)
         instance.sync()
Example #11
0
 def __init__(self, auth_obj):
     if auth_obj is None or '':
         dropbox_auth_obj = auth.DropboxAuth()
         credentials = dropbox_auth_obj.authorize()
         auth_obj = {
             'access_token': credentials.access_token,
             'account_id': credentials.account_id
         }
     self.auth_obj = auth_obj
     self.dropbox_obj = Dropbox(self.auth_obj['access_token'])
     self.execute_function = None
def get_dropbox_client(access_key):
    """
    Attempts to create the Dropbox Client with the associated
    """
    try:
        client = Dropbox(access_key)
        client.users_get_current_account()
        return client
    except AuthError as e:
        print(f'Failed to authenticate using key {access_key}')
        raise (e)
Example #13
0
 def load_token(self):
     with open('db.token', 'rb') as file:
         try:
             access_token = pickle.load(file)
             self.dbx = Dropbox(access_token)
             user_info = self.dbx.users_get_current_account()
             self.widgetOptions.labelName.setText(
                 user_info.name.display_name)
             return True
         except:
             return False
Example #14
0
 def test_check_refresh_with_expired_offline_token(self, session_instance):
     # Test Offline Case w/ invalid access
     dbx = Dropbox(oauth2_access_token=ACCESS_TOKEN,
                   oauth2_refresh_token=REFRESH_TOKEN,
                   oauth2_access_token_expiration=EXPIRATION -
                   timedelta(weeks=1),
                   app_key=APP_KEY,
                   app_secret=APP_SECRET,
                   session=session_instance)
     dbx.check_and_refresh_access_token()
     assert session_instance.post.call_count == 1
Example #15
0
def get_direct_link(filename="measurement_rois.png"):

    token = constants.token
    dbx = Dropbox(token)
    path = f'{constants.images_path}{filename}'

    link = dbx.sharing_create_shared_link(path=path, short_url=False)
    direct_url = link.url.replace('dl=0', 'raw=true')
    print(direct_url)

    return direct_url
Example #16
0
 def debug():
     """Debug todo synchronization code"""
     dropbox = db.session.query(models.Dropbox).first()  # type: models.Dropbox
     try:
         dbx = Dropbox(dropbox.access_token)
         md, res = dbx.files_download(path=dropbox.file_location)
     except ApiError as err:
         if err.error.is_path() and err.error.get_path().is_not_found():
             return 'File not found: ' + dropbox.file_location
         return 'Other error occurred'
     update_todos(content=res.content)
     return redirect(url_for('show_todos'))
Example #17
0
def download_db():
    dbx = Dropbox(token)
    if cfg['environment']['host'] == 'linux':
        print("Linux Environment")
        dbx.files_download_to_file(
            path.join(getcwd().strip('utilities'), 'costrajectory.db'),
            '/costrajectory.db')
    else:
        print("Windows Environment")
        dbx.files_download_to_file(getcwd() + '\\costrajectory.db',
                                   '/costrajectory.db')
    print('DB Successfully updated to remote')
Example #18
0
def main(api_token: str,
         download: str,
         upload: str,
         path: str,
         overwrite: bool = False,
         list_files: str = ''):

    dbx = Dropbox(api_token)
    logging.info(f'Thanks for entering your API token {dbx}')

    _list_files(dbx, list_files)
    _upload(dbx, upload, path, overwrite)
Example #19
0
 def __init__(self, accessToken):
     super().__init__()
     self.dropbox = Dropbox(accessToken)
     _meta = self._meta = {
         "case_insensitive": False,  # I think?
         "invalid_path_chars": ":",  # not sure what else
         "max_path_length": None,  # don't know what the limit is
         "max_sys_path_length": None,  # there's no syspath
         "network": True,
         "read_only": False,
         "supports_rename": False  # since we don't have a syspath...
     }
Example #20
0
def authorize_folder(emailAddress=None,
                     folderId=None,
                     folderName=None,
                     *args,
                     **kwargs):
    dbx = Dropbox(os.getenv('DROPBOX_TOKEN', None))
    if not folderId:
        folderId = get_shared_folder_by_name(folderName).shared_folder_id
    members = [
        dropbox.sharing.AddMember(
            dropbox.sharing.MemberSelector.email(emailAddress))
    ]
    return dbx.sharing_add_folder_member(folderId, members)
Example #21
0
def upload_to_dropbox(video_file_path):
    """
    Dropbox is an unoffical feature - This code worked at one point,
    but official support was removed for several reasons.
    """
    try:
        file_size = os.path.getsize(video_file_path)
        if file_size <= FILE_CHUNK_SIZE:
            dbx = Dropbox(DROPBOX_API_KEY)
            f = open(video_file_path, 'rb')
            dbx.files_upload(f, video_file_path)
        else:
            upload_dropbox_file_chucks(video_file_path, file_size)
    except Exception as e:
        print('Unhandled exception while uploading files - {}'.format(e))
Example #22
0
def upload_dropbox_file_chucks(file_path, file_size):
    dbx = Dropbox(DROPBOX_API_KEY)
    f = open(file_path, 'rb')
    session = dbx.files_upload_session_start(f.read(FILE_CHUNK_SIZE))
    cursor = dbx_files.UploadSessionCursor(session_id=session.session_id,
                                           offset=f.tell())
    commit = dbx_files.CommitInfo(path=file_path)
    while f.tell() < file_size:
        if ((file_size - f.tell()) <= FILE_CHUNK_SIZE):
            dbx.files_upload_session_finish(f.read(FILE_CHUNK_SIZE), cursor,
                                            commit)
        else:
            dbx.files_upload_session_append(f.read(FILE_CHUNK_SIZE),
                                            cursor.session_id, cursor.offset)
            cursor.offset = f.tell()
Example #23
0
    def __init__(self, oauth2_access_token: str = None, root_path: str = None):
        """
        The access token and root path may be provided here as well,
        if they are not provided here, program will check settings for environment variables

        :param oauth2_access_token: The OAUTH2 access token for the DropBox api
        :param root_path: The root path for storing the files in the DropBox storage, defaults '/'
        """
        oauth2_access_token = oauth2_access_token or settings.DROPBOX_OAUTH2_TOKEN
        self.root_path = root_path or settings.DROPBOX_ROOT_PATH or '/'
        if oauth2_access_token is None:
            raise ImproperlyConfigured(
                "You must configure an OATH2 access token ENV named "
                "'DROPBOX_OAUTH2_TOKEN'.")
        self.client = Dropbox(oauth2_access_token)
Example #24
0
 def authenticate(self):
     auth_code = self.widgetLogin.lineEdit.text()
     try:
         access_token, user_id = self.widgetLogin.auth_flow.finish(
             auth_code)
         self.dbx = Dropbox(access_token)
         user_info = self.dbx.users_get_current_account()
         self.widgetOptions.labelName.setText(user_info.name.display_name)
         self.widgetLogin.hide()
         self.widgetOptions.show()
         self.widgetOptions.dbx = self.dbx
         self.widgetOptions.thread.start()
         self.save_token(access_token)
     except:
         self.widgetLogin.labelError.setText('Invalid code, try again.')
    def chunk(self, path, filename, size, offset=0):
        """
        return one chunk of file

        :param str path: path on server
        :param str filename: name of file
        :param int size: chunk-size
        :param int offset: bits from the beginning
        :return: tuple(File obj, content)
        """
        p_session = session()
        dbx_p = Dropbox(oauth2_access_token=self._access_token, headers={
            "Range": "bytes=" + str(offset) + "-" + str(offset + size - 1)}, session=p_session)  # fetch chunks from dropbox
        meta, response = dbx_p.files_download(path+"/"+filename)
        f = File(meta.name, meta.path_lower, meta.client_modified, meta.client_modified)
        p_session.close()
        return f, response.content
Example #26
0
    def sync():
        challenge = request.args.get('challenge')
        if challenge is not None:
            return challenge

        """Synchronize database with todo.txt"""
        dropbox = db.session.query(models.Dropbox).first()  # type: models.Dropbox

        # Make sure this is a valid request from Dropbox
        signature = request.headers.get('X-Dropbox-Signature')
        if not hmac.compare_digest(signature, hmac.new(dropbox.secret.encode(), request.data, sha256).hexdigest()):
            app.logger.warn('Invalid sync request attempted')
            abort(403)

        dbx = Dropbox(dropbox.access_token)
        if dropbox.cursor is None:
            result = dbx.files_list_folder(path=os.path.dirname(dropbox.file_location))
        else:
            result = dbx.files_list_folder_continue(cursor=dropbox.cursor)

        # Check if todo.txt was changed
        found = False
        for metadata in result.entries:  # type: Metadata
            if metadata.path_lower == dropbox.file_location.lower():
                found = True
                break
        if not found:
            dropbox.cursor = result.cursor
            db.session.merge(dropbox)
            db.session.commit()
            return ''

        app.logger.info('Sync request made')

        try:
            md, res = dbx.files_download(path=dropbox.file_location)
        except ApiError as err:
            if err.error.is_path() and err.error.get_path().is_not_found():
                return 'File not found: ' + dropbox.file_location
            return 'Other error occurred'
        update_todos(content=res.content)

        dropbox.cursor = result.cursor
        db.session.merge(dropbox)
        db.session.commit()
        return ''
Example #27
0
def revisions():
	# Shared Link from Dropbox Chooser
	link = request.args['link']

	# Calling Dropbox API v1
	metadata = requests.post('https://api.dropbox.com/1/metadata/link', params={'link': link},
		headers={'Authorization': 'Bearer ' + str(session['access_token'])}).json()

	# Calling Dropbox API v2
	if not metadata.get('path'):
		return redirect(url_for('index'))
	else:
		dbx = Dropbox(session['access_token'])
		entries = sorted(dbx.files_list_revisions(metadata['path']).entries, key=lambda entry: entry.client_modified)
		entries.reverse()
		return render_template('revisions.html', path=metadata['path'], filename=os.path.split(metadata['path'])[1],
			revisions=entries)
Example #28
0
    def _update_secrets(self):
        """update secrets will look for a dropbox token in the environment at
           SREGISTRY_DROPBOX_TOKEN and if found, create a client. If not,
           an error message is returned and the client exits.
        """

        # Retrieve the user token. Exit if not found
        token = self._required_get_and_update("SREGISTRY_DROPBOX_TOKEN")

        # Create the dropbox client
        self.dbx = Dropbox(token)

        # Verify that the account is valid
        try:
            self.account = self.dbx.users_get_current_account()
        except:
            bot.exit("Account invalid. Exiting.")
    def __init__(self, rootdir, oauth2_access_token,
                 connection_kwargs=None, files_upload_kwargs=None,
                 files_list_folder_kwargs=None, rev=None):

        if connection_kwargs is None:
            connection_kwargs = {}
        if files_upload_kwargs is None:
            files_upload_kwargs = {'mode': WriteMode.overwrite}
        if files_list_folder_kwargs is None:
            files_list_folder_kwargs = {'recursive': True, 'include_non_downloadable_files': False}

        self._prefix = rootdir
        self._con = Dropbox(oauth2_access_token, **connection_kwargs)
        self._connection_kwargs = connection_kwargs
        self._files_upload_kwargs = files_upload_kwargs
        self._files_list_folder_kwargs = files_list_folder_kwargs
        self._rev = rev
Example #30
0
def get_list_of_files():
    get_or_create_folder()

    dbx = Dropbox(get_token())
    response = dbx.files_list_folder(path='/Mainstay')

    files = []

    for file in response.entries:
        files.append({
            'name': file.name,
            'extension': file.name.split('.')[-1],
            'size': round(int(file.size) / (1024 * 1024), 2),
            'date_modified': file.server_modified,
            'checksum': file.content_hash
        })

    return files