Python dropbox.Dropbox() Examples

The following are 30 code examples of dropbox.Dropbox(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module dropbox , or try the search function .
Example #1
Source File: ff4d.py    From ff4d with BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
def readdir(self, path, fh):
    path = path.encode('utf-8')
    if debug == True: appLog('debug', 'Called: readdir() - Path: ' + path)

    # Fetch folder informations.
    fusefolder = ['.', '..']
    metadata = self.getDropboxMetadata(path, True)

    # Loop through the Dropbox API reply to build fuse structure.
    for item in metadata['entries']:
      # Append entry to fuse foldercontent.
      folderitem = os.path.basename(item['path'])
      fusefolder.append(folderitem)

    # Loop through the folder content.
    for item in fusefolder:
      yield item

  # Get properties for a directory or file. 
Example #2
Source File: ff4d.py    From ff4d with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def dbxStruct(self, obj):
    structname = obj.__class__.__name__
    data = {}

    for key in dir(obj):
      if not key.startswith('_'):
        if isinstance(getattr(obj, key), list):
          tmpdata = []
          for item in getattr(obj, key):
            tmpdata.append(self.dbxStruct(item))
          data.update({key: tmpdata})
        else:
          data.update({key: getattr(obj, key)})

    if structname == 'FolderMetadata':
      data.update({'.tag': 'folder'})
    if structname == 'FileMetadata':
      data.update({'.tag': 'file'})

    return data

  # Get Dropbox metadata of path. 
Example #3
Source File: __init__.py    From sregistry-cli with Mozilla Public License 2.0 7 votes vote down vote up
def _get_metadata(self, image_file=None, dbx_metadata=None):
        """this is a wrapper around the main client.get_metadata to first parse
           a Dropbox FileMetadata into a dicionary, then pass it on to the 
           primary get_metadata function.

           Parameters
           ==========
           image_file: the full path to the image file that had metadata
                       extracted
           metadata: the Dropbox FileMetadata to parse.

        """
        metadata = dict()

        if dbx_metadata is not None:
            for key in dbx_metadata.__dir__():
                value = getattr(dbx_metadata, key)
                if isinstance(value, (str, datetime.datetime, bool, int, float)):
                    metadata[key.strip("_")] = value

        return self.get_metadata(image_file, names=metadata) 
Example #4
Source File: application.py    From spellbook with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def db_sync():
    import dropbox
    dbx = dropbox.Dropbox(db_load_token())
    repo = db_repo_load()
    for book in dbx.files_list_folder('').entries:
        if book.name not in repo:
            db_download(dbx, book.name)
        elif repo[book.name] != book.rev:
            db_merge(dbx, book.name, book.rev)
            db_update(dbx, book.name, book.rev)
            repo.pop(book.name)
        elif repo[book.name] == book.rev:
            # TODO: prevent uploading unchanged files
            db_update(dbx, book.name, book.rev)
            repo.pop(book.name)
        else:
            print('dead end: %s' % book.name)

    for spellbook_name in repo:
        if repo[spellbook_name] is None:
            db_upload(dbx, spellbook_name)

    for spellbook_name in db_repo_removed_list():
        db_remove(dbx, spellbook_name) 
Example #5
Source File: __init__.py    From sregistry-cli with Mozilla Public License 2.0 7 votes vote down vote up
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.") 
Example #6
Source File: application.py    From spellbook with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def command_dropbox_connect(args):
    import dropbox

    if args.spellbook_name is not None:
        print('ERR: sync is only for all books')
        return

    app_key = 'ow3gosk8pb9bhkr'
    app_secret = 'w3eqoqx5scb64pd'
    flow = dropbox.DropboxOAuth2FlowNoRedirect(app_key, app_secret)
    # Have the user sign in and authorize this token
    authorize_url = flow.start()
    print('1. Go to: ' + authorize_url)
    print('2. Click "Allow" (you might have to log in first)')
    print('3. Copy the authorization code.')
    code = collect_str("the authorization code here")

    # This will fail if the user enters an invalid authorization code
    access_token, user_id = flow.finish(code)

    client = dropbox.Dropbox(access_token)
    print('successfully linked account: ', client.users_get_current_account().name.display_name)
    with open(DROPBOX_TOKEN_PATH, 'w') as fout:
        fout.write(access_token) 
Example #7
Source File: dropbox_dropper.py    From SecPi with GNU General Public License v3.0 7 votes vote down vote up
def notify(self, info):
		if not self.corrupted:
			#info_str = "Recieved alarm on sensor %s from worker %s: %s"%(info['sensor'], info['worker'], info['message'])
			latest_subdir = self.get_latest_subdir()

			dropbox_dir = "/%s" % latest_subdir.split("/")[-1] #pfui
			#self.dbx.files_create_folder(dropbox_dir) # shouldn't be necessary, automatically created 
			for file in os.listdir(latest_subdir):
				if os.path.isfile("%s/%s" % (latest_subdir, file)):
					f = open("%s/%s" % (latest_subdir, file), "rb")
					data = f.read()
					try:
						logging.info("Dropbox: Trying to upload file %s to %s" % (file, dropbox_dir))
						res = self.dbx.files_upload(data, "%s/%s" % (dropbox_dir, file))
						logging.info("Dropbox: Upload of file %s succeeded" % file)
					except dropbox.exceptions.ApiError as d:
						logging.error("Dropbox: API error: %s" % d)
					except Exception as e: # currently this catches wrong authorization, we should change this
						logging.error("Dropbox: Wasn't able to upload file: %s" % e)
					f.close()
		else:
			logging.error("Dropbox: Wasn't able to notify because there was an initialization error") 
Example #8
Source File: dropbox_dropper.py    From SecPi with GNU General Public License v3.0 7 votes vote down vote up
def __init__(self, id, params):
		super(Dropbox_Dropper, self).__init__(id, params)
		try:
			self.access_token = params["access_token"]
		except KeyError as k: # if config parameters are missing
			logging.error("Dropxbox: Error while trying to initialize notifier, it seems there is a config parameter missing: %s" % k)
			self.corrupted = True
			return

		try:
			self.dbx = dropbox.Dropbox(self.access_token)
		except Exception as e:
			logging.error("Dropbox: Error while connecting to Dropbox service: %s" % e)
			self.corrupted = True
			return

		self.data_dir = "/var/tmp/secpi/alarms/" #change this maybe?

		logging.info("Dropbox initialized") 
Example #9
Source File: proton_backup.py    From PROTON with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def process_backup(self, proton_backup_type):
        if self.proton_backup_args.date is not None and self.proton_backup_args.time is not None:
            dbx = dropbox.Dropbox(self.proton_backup_map[proton_backup_type]['token'])
            with open(self.proton_backup_map[proton_backup_type]['path'], 'rb') as proton_backup_file_read_handle:
                proton_backup_load = proton_backup_file_read_handle.read()

            with self.stopwatch('./reports/backup', proton_backup_type,
                                self.proton_backup_map[proton_backup_type]['stopwatch_message']):
                try:
                    res = dbx.files_upload(proton_backup_load,
                                           '/{}/{}'.format(self.proton_backup_args.date,
                                                           self.proton_backup_map[proton_backup_type]['upload_file_name']),
                                           dropbox.files.WriteMode.overwrite)
                except Exception as err:
                    print('[PROTON Backup]-[{}] - '
                          'API error\n'.format(self.proton_backup_map[proton_backup_type]['job_name']), err)
                    return None
                with open('./reports/backup/{}.txt'.format(proton_backup_type), 'a') as writer:
                    writer.write('{} successful\n'.format(self.proton_backup_map[proton_backup_type]['job_name']))
                    writer.write('Date & time of execution: {} @ {}\n'.format(self.proton_backup_args.date,
                                                                              self.proton_backup_args.time))
                # TODO: email res to PK.
                return res
        else:
            print('Backup process missing key date and time arguments. Backup cannot proceed.') 
Example #10
Source File: dbutils.py    From stash with MIT License 7 votes vote down vote up
def get_dropbox_client(username, setup=True, stdin=None, stdout=None):
    """
	checks wether a dropbox.dropbox.Dropbox is available for username.
	If it is, it is returned.
	Otherwise, if setup is True, a command-line setup is shown.
	The setup uses stdin and stout, both defaulting to the sys.std*.
	If no client was found and setup is False, None will be returned.
	"""
    if stdout is None:
        stdout = sys.stdout
    if stdin is None:
        stdin = sys.stdin
    data = load_dropbox_data(username)
    if data is None:
        stdout.write("\n")
        if not setup:
            return None
        dropbox_setup(username, stdin, stdout)
        data = load_dropbox_data(username)
    token = data["access_token"]
    dbclient = dropbox.dropbox.Dropbox(token)
    return dbclient 
Example #11
Source File: dropbox.py    From platypush with MIT License 7 votes vote down vote up
def move(self, from_path: str, to_path: str, allow_shared_folder=True, autorename=False,
             allow_ownership_transfer=False):
        """
        Move a file or folder to a different location in the user's Dropbox. If the source path is a folder all its
        contents will be moved.

        :param from_path: Source path
        :param to_path: Destination path
        :param bool allow_shared_folder: If true, :meth:`files_copy` will copy
            contents in shared folder, otherwise
            ``RelocationError.cant_copy_shared_folder`` will be returned if
            ``from_path`` contains shared folder. This field is always true for
            :meth:`files_move`.
        :param bool autorename: If there's a conflict, have the Dropbox server
            try to autorename the file to avoid the conflict.
        :param bool allow_ownership_transfer: Allow moves by owner even if it
            would result in an ownership transfer for the content being moved.
            This does not apply to copies.
        """

        dbx = self._get_instance()
        dbx.files_move_v2(from_path, to_path, allow_shared_folder=allow_shared_folder,
                          autorename=autorename, allow_ownership_transfer=allow_ownership_transfer) 
Example #12
Source File: plugin.py    From rbb_core with MIT License 7 votes vote down vote up
def authorize_step_1(self, flask_request, url):
        code = flask_request.form.get('dropbox_code')

        if code:
            try:
                flow = self._get_auth_flow()
                result = flow.finish(code)

                if result.access_token:
                    self._set_account_token(result.access_token)
                    self.save()
                    return "Authorization succeeded!"
                else:
                    return "Authorization failed!"
            except Exception as e:
                logging.exception("Dropbox authorization failed", e)
                return "Error occured (" + str(e) + ")"
        else:
            return "Invalid code!" 
Example #13
Source File: plugin.py    From rbb_core with MIT License 7 votes vote down vote up
def authorize_step_0(self, flask_request, url):

        flow = self._get_auth_flow()
        dropbox_auth_url = flow.start()
        next_step_url = url + "1"

        page_html = """
        <html>
            <head><title>Dropbox Authorization</title></head>
            <body>
                <p>Please get a dropbox authorization code at the following link, <a target="_blank" href="%s">%s</a></p>
                <p>Paste the code here:
                    <form action="%s" method="POST">
                        <input type="text" name="dropbox_code"></input><input type="submit"></input>
                    </form>
                </p>
            </body>
        </html>
        """ % (dropbox_auth_url, dropbox_auth_url, next_step_url)

        import flask
        return flask.Response(page_html) 
Example #14
Source File: backup-and-restore-example.py    From dropbox-sdk-python with MIT License 7 votes vote down vote up
def backup():
    with open(LOCALFILE, 'rb') as f:
        # We use WriteMode=overwrite to make sure that the settings in the file
        # are changed on upload
        print("Uploading " + LOCALFILE + " to Dropbox as " + BACKUPPATH + "...")
        try:
            dbx.files_upload(f.read(), BACKUPPATH, mode=WriteMode('overwrite'))
        except ApiError as err:
            # This checks for the specific error where a user doesn't have
            # enough Dropbox space quota to upload this file
            if (err.error.is_path() and
                    err.error.get_path().reason.is_insufficient_space()):
                sys.exit("ERROR: Cannot back up; insufficient space.")
            elif err.user_message_text:
                print(err.user_message_text)
                sys.exit()
            else:
                print(err)
                sys.exit()

# Change the text string in LOCALFILE to be new_content
# @param new_content is a string 
Example #15
Source File: app.py    From mdwebhook with Apache License 2.0 7 votes vote down vote up
def webhook():
    '''Receive a list of changed user IDs from Dropbox and process each.'''

    # Make sure this is a valid request from Dropbox
    signature = request.headers.get('X-Dropbox-Signature')
    key = bytes(APP_SECRET, encoding="ascii")
    computed_signature = hmac.new(key, request.data, sha256).hexdigest()
    if not hmac.compare_digest(signature, computed_signature):
        abort(403)

    for account in json.loads(request.data)['list_folder']['accounts']:
        # We need to respond quickly to the webhook request, so we do the
        # actual work in a separate thread. For more robustness, it's a
        # good idea to add the work to a reliable queue and process the queue
        # in a worker process.
        threading.Thread(target=process_user, args=(account,)).start()
    return '' 
Example #16
Source File: backup.py    From Python-for-Everyday-Life with MIT License 7 votes vote down vote up
def backup_with_overwriting(dropbox, local_dir_path_obj, target_dropbox_dir):

    print('Backing up contents of local folder: {} to Dropbox folder {} ...\n'.format(
        local_dir_path_obj, target_dropbox_dir))

    print('Data will be overwritten\n')

    # Walk the local folder
    for path_obj in tree(local_dir_path_obj):
        if path_obj.is_file():
            # target paths on Dropbox must start with a "/"
            destination_path = '/' + target_dropbox_dir + '/' + str(path_obj)
            try:
                with path_obj.open('rb') as f:
                    print('UPLOAD: {} --> {}'.format(path_obj, destination_path))
                    dbx.files_upload(f.read(),
                                     destination_path,
                                     mode=dropbox.files.WriteMode.overwrite,
                                     mute=True)
            except Exception as e:
                print('Failed to upload {}, reason: {}\n'.format(path_obj, e))
                continue
    print('\nDone') 
Example #17
Source File: dropbox.py    From django-storages with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def _get_file(self):
        if self._file is None:
            self._file = SpooledTemporaryFile()
            # As dropbox==9.3.0, the client returns a tuple
            # (dropbox.files.FileMetadata, requests.models.Response)
            file_metadata, response = \
                self._storage.client.files_download(self.name)
            if response.status_code == 200:
                with BytesIO(response.content) as file_content:
                    copyfileobj(file_content, self._file)
            else:
                # JIC the exception isn't catched by the dropbox client
                raise DropBoxStorageException(
                    "Dropbox server returned a {} response when accessing {}"
                    .format(response.status_code, self.name)
                )
            self._file.seek(0)
        return self._file 
Example #18
Source File: ff4d.py    From ff4d with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def release(self, path, fh):
    path = path.encode('utf-8')
    if debug == True: appLog('debug', 'Called: release() - Path: ' + path + ' FH: ' + str(fh))

    # Check to finish Dropbox upload.
    if type(self.openfh[fh]['f']) is dict and 'upload_id' in self.openfh[fh]['f'] and self.openfh[fh]['f']['upload_id'] != "":
      # Flush still existing data in buffer.
      if self.openfh[fh]['f']['buf'] != "":
        if debug == True: appLog('debug', 'Flushing write buffer to Dropbox')
        result = self.dbxChunkedUpload(self.openfh[fh]['f']['buf'], self.openfh[fh]['f']['upload_id'], self.openfh[fh]['f']['offset'])
      if debug == True: appLog('debug', 'Finishing upload to Dropbox')
      result = self.dbxCommitChunkedUpload(path, self.openfh[fh]['f']['upload_id'], self.openfh[fh]['f']['offset'])

    # Remove outdated data from cache if handle was opened for writing.
    if self.openfh[fh]['mode'] == 'w':
      self.removeFromCache(os.path.dirname(path))

    self.releaseFH(fh)
    if debug == True: appLog('debug', 'Released filehandle: ' + str(fh))

    return 0

  # Truncate a file to overwrite it. 
Example #19
Source File: dropbox.py    From platypush with MIT License 6 votes vote down vote up
def get_account(self, account_id=None):
        """
        Get the information about a linked Dropbox account

        :param account_id: account_id. If none is specified then it will retrieve the current user's account id
        :type account_id: str

        :return: dict with the following attributes:
            account_id, name, email, email_verified, disabled, profile_photo_url, team_member_id
        """

        dbx = self._get_instance()

        if not account_id:
            acc = dbx.users_get_current_account()
        else:
            acc = dbx.users_get_account(account_id)

        return {
            'account_id': acc.account_id,
            'name': acc.name.display_name,
            'email': acc.email,
            'email_verified': acc.email_verified,
            'disabled': acc.disabled,
            'profile_photo_url': acc.profile_photo_url,
            'team_member_id': acc.team_member_id,
        } 
Example #20
Source File: dropbox.py    From platypush with MIT License 6 votes vote down vote up
def download(self, path: str, download_path=None, zip=False):
        """
        Download a file or a zipped directory from a user's Dropbox.

        :param str path: Dropbox destination path
        :param str download_path: Destination path on the local machine (optional)
        :param bool zip: If set then the content will be downloaded in zip format (default: False)
        :rtype: dict
        :return: A dictionary with keys: ``('id', 'name', 'parent_shared_folder_id', 'path', 'size', 'encoding',
            'content_hash')``. If download_path is set 'file' is also returned. Otherwise 'content' will be returned.
            If it's a text file then 'content' will contain its string representation, otherwise its base64-encoded
            representation.
        """

        from dropbox.files import FolderMetadata

        if download_path:
            download_path = os.path.abspath(os.path.expanduser(download_path))

        dbx = self._get_instance()

        metadata = dbx.files_get_metadata(path)
        if isinstance(metadata, FolderMetadata):
            zip = True

        if zip:
            return self._file_download_zip(path, download_path)

        return self._file_download(path, download_path) 
Example #21
Source File: dropbox_files.py    From ir with Mozilla Public License 2.0 6 votes vote down vote up
def upload_dropbox_file(file_from, file_to):
    dbx = dropbox.Dropbox(os.environ['DROPBOX_API_KEY'])
    with open(file_from, 'rb') as f:
        dbx.files_upload(f.read(), file_to, mode=files.WriteMode.overwrite)
    try:
        dbx._session.close()
    except:
        pass 
Example #22
Source File: dropbox.py    From platypush with MIT License 6 votes vote down vote up
def search(self, query: str, path='', start=0, max_results=100, content=False):
        """
        Searches for files and folders. Note: Recent changes may not immediately
        be reflected in search results due to a short delay in indexing.

        :param str path: The path in the user's Dropbox to search. Should probably be a folder.
        :param str query: The string to search for. The search string is split
            on spaces into multiple tokens. For file name searching, the last
            token is used for prefix matching (i.e. "bat c" matches "bat cave"
            but not "batman car").
        :param long start: The starting index within the search results (used for paging).
        :param long max_results: The maximum number of search results to return.
        :param content: Search also in files content (default: False)
        :rtype dict:
        :return: Dictionary with the following fields: ``('matches', 'start')``.
        """

        from dropbox.files import SearchMode

        dbx = self._get_instance()
        response = dbx.files_search(query=query, path=path, start=start, max_results=max_results,
                                    mode=SearchMode.filename_and_content if content else SearchMode.filename)

        results = [self._parse_metadata(match.metadata) for match in response.matches]

        return {
            'results': results,
            'start': response.start,
        } 
Example #23
Source File: dropbox.py    From platypush with MIT License 6 votes vote down vote up
def _get_instance(self):
        """
        :rtype: :class:`dropbox.Dropbox`
        """
        # noinspection PyPackageRequirements
        import dropbox

        if not self._dbx:
            self._dbx = dropbox.Dropbox(self.access_token)

        return self._dbx 
Example #24
Source File: dropbox.py    From platypush with MIT License 6 votes vote down vote up
def copy(self, from_path: str, to_path: str, allow_shared_folder=True, autorename=False,
             allow_ownership_transfer=False):
        """
        Copy a file or folder to a different location in the user's Dropbox. If the source path is a folder all
        its contents will be copied.

        :param from_path: Source path
        :param to_path: Destination path
        :param bool allow_shared_folder: If true, :meth:`files_copy` will copy
            contents in shared folder, otherwise
            ``RelocationError.cant_copy_shared_folder`` will be returned if
            ``from_path`` contains shared folder. This field is always true for
            :meth:`files_move`.
        :param bool autorename: If there's a conflict, have the Dropbox server
            try to autorename the file to avoid the conflict.
        :param bool allow_ownership_transfer: Allow moves by owner even if it
            would result in an ownership transfer for the content being moved.
            This does not apply to copies.
        """

        dbx = self._get_instance()
        dbx.files_copy_v2(from_path, to_path, allow_shared_folder=allow_shared_folder,
                          autorename=autorename, allow_ownership_transfer=allow_ownership_transfer) 
Example #25
Source File: dropbox_files.py    From ir with Mozilla Public License 2.0 6 votes vote down vote up
def download_dropbox_file():
    dbx = dropbox.Dropbox(os.environ['DROPBOX_API_KEY'])
    dbx.files_download_to_file(OPERATIONS_FILEPATH, os.environ['DROPBOX_FILE_LOCATION'])
    try:
        dbx._session.close()
    except:
        pass 
Example #26
Source File: run.py    From Open-Browser with GNU General Public License v3.0 6 votes vote down vote up
def uploadFavorites(self):

        if os.path.exists('config.ini') is True:
            configb = configparser.ConfigParser()
            configb.read('config.ini')
            token = configb['DROPBOX']['access token']

            if token == '':
                pass
            else:
                dbx = dropbox.Dropbox(token)

                file_to = '/Favorites/bookmarks.json'

                with open('bookmarks.json', 'rb') as f:
                    dbx.files_upload(f, file_to, mode=dropbox.files.WriteMode.overwrite) 
Example #27
Source File: dropbox.py    From paper-to-git with Apache License 2.0 6 votes vote down vote up
def initialize():
    dbox = Dropbox()
    dbox.initialize()
    config.dbox = dbox 
Example #28
Source File: dropbox.py    From paper-to-git with Apache License 2.0 6 votes vote down vote up
def initialize(self):
        assert config.initialized
        self.dbx = dropbox.Dropbox(self.get_auth_token()) 
Example #29
Source File: dropbox_dropper.py    From SecPi with GNU General Public License v3.0 6 votes vote down vote up
def cleanup(self):
		logging.debug("Dropbox: No cleanup necessary at the moment") 
Example #30
Source File: dropbox.py    From platypush with MIT License 6 votes vote down vote up
def __init__(self, access_token, **kwargs):
        """
        :param access_token: Dropbox API access token. You can get yours by creating an app on
            https://dropbox.com/developers/apps
        :type access_token: str
        """

        super().__init__(**kwargs)
        self.access_token = access_token
        self._dbx = None