MAESTRAL(1)

NAME
maestral - Maestral 1.9.5

This documentation provides an API reference for the maestral daemon. It is built from the current dev branch and is intended for developers. For a user manual and an overview of Maestral's functionality, please refer to maestral.app <https://maestral.app>.

SYNC LOGIC

The maestral.sync.SyncEngine <#maestral.sync.SyncEngine> class provides access to the current sync state through its properties and provides the methods which are necessary to complete an upload or a download sync cycle. This includes methods to wait for and return local and remote changes, to sort those changes and discard any excluded items and to apply local changes to the Dropbox server and vice versa.

The maestral.sync.SyncMonitor class coordinates the sync process with its threads for startup, download-sync, upload-sync and periodic maintenance.

  Processing of sync events

Remote events come in three types: dropbox.files.DeletedMetadata <https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html#dropbox.files.DeletedMetadata>, dropbox.files.FolderMetadata <https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html#dropbox.files.FolderMetadata> and dropbox.files.FileMetadata <https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html#dropbox.files.FileMetadata>. The Dropbox API does not differentiate between created, moved or modified events. Maestral processes remote events as follows:

1.  SyncEngine.wait_for_remote_changes() blocks until remote changes are available.

2.  SyncEngine.list_remote_changes() lists all remote changes since the last sync. Those events are processed at follows:

•   Events for entries which are excluded by selective sync and hard-coded file names which are always excluded (e.g., '.DS_Store') are filtered out at this stage.

•   Multiple events per file path are combined to one. This is rarely necessary, Dropbox typically already provides only a single event per path but this is not guaranteed and may change. One exception is sharing a folder: Dropbox does this by removing the folder from the user's root and re-mounting it as a shared folder. This produces at least one DeletedMetadata and one FolderMetadata event. If querying for changes during this process, multiple dropbox.files.DeletedMetadata <https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html#dropbox.files.DeletedMetadata> events may be returned.

•   If a file / folder event implies a type changes, e.g., replacing a folder with a file, we explicitly generate the necessary dropbox.files.DeletedMetadata <https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html#dropbox.files.DeletedMetadata> here to simplify conflict resolution.

3.  SyncEngine.apply_remote_changes(): Sorts all events hierarchically, with top-level events coming first. Deleted and folder events are processed in order, file events in parallel with up to 6 worker threads.

4.  SyncEngine.notify_user(): Shows a desktop notification for the remote changes.

    Local file events come in eight types: For both files and folders we collect created, moved, modified and deleted events. They are processed as follows:

1.  SyncEngine.wait_for_local_changes(): Blocks until local changes are registered by FSEventHandler.

2.  SyncEngine.list_local_changes(): Lists all local file events. Those are processed as follows:

•   Events ignored by a "mignore" pattern as well as hard-coded file names and changes in our cache path are filtered out at this stage.

•   Events are further cleaned up to return the minimum number of events necessary to reproduce the actual changes: Multiple events per path are combined into a single event which reproduces the file change. The only exception is when the entry type changes from file to folder or vice versa: in this case, both deleted and created events are kept. Further, when a whole folder is moved or deleted, we discard the moved or deleted events for its children.

2.  SyncEngine.apply_local_changes(): Sorts local changes hierarchically and applies events in the order of deleted, folders and files. Deleted, created and modified events will be applies to the remote Dropbox in parallel with up to 6 threads. Moves will be carried out synchronously.

    Before processing, we convert all Dropbox metadata and local file events to a unified format of maestral.database.SyncEvent instances which are also used to store the sync history data in our SQLite database.

  Detection and resolution of sync conflicts

Sync conflicts during a download are detected by comparing the file's "rev" with the locally saved revision identifier in Maestral's index. We assign folders a rev of 'folder' and deleted / non-existent items a rev of None.

1.  If both revs are equal, the local item is either the same as on Dropbox or newer and the local changes haven't been uploaded and committed to our index yet. No download sync occurs (including deletion of the local file).

2.  If revs are different, we compare content hashes. If those hashes are equal, no download occurs.

3.  If content hashes are different, we check if the local item has been modified since the last download sync. In case of a folder, we take the most recent change of any of its children. If the local entry has not been modified since the last sync, it will be replaced. Otherwise, we create a conflicting copy.

    Conflict resolution for uploads is handled as follows:

1.  For created and moved events, we check if the new path has been excluded by the user with selective sync but still exists on Dropbox. If yes, it will be renamed by appending "(selective sync conflict)".

2.  On case-sensitive file systems, we check if the new path differs only in casing from an existing path. If yes, it will be renamed by appending "(case conflict)".

3.  If a file has been replaced with a folder or vice versa, we check if any un-synced changes will be lost by replacing the remote item and create a conflicting copy if necessary.

4.  For created or modified files, check if the local content hash equals the remote content hash. If yes, we don't upload but update our rev number. If no, we upload the changes and specify the rev which we want to replace or delete. If the remote item is newer (different rev), Dropbox will handle conflict resolution for us.

5.  We finally confirm the successful upload and check if Dropbox has renamed the item to a conflicting copy. In the latter case, we apply those changes locally.

LOGGING

Maestral makes extensive use of Python's logging module to collect debug, status and error information from different parts of the program and distribute it to the appropriate channels.

Broadly speaking, the builtin log levels are used as follows:
Level | Typical messages
DEBUG | Individual sync progress, conflict resolution, daemon startup and environment info
INFO | Cumulative sync progress, sync errors that require user resolution (e.g., insufficient space)
WARNING | Failure to initialise non-critical functionality (e.g., desktop notifications, system keyring)
ERROR | Errors that prevent all syncing (revoked access token, deleted folder, etc)

Maestral defines a number of log handlers to process those messages, some of them for internal usage, others for external communication. For instance, cached logging handlers are used to populate the public APIs Maestral.status and Maestral.fatal_errors and therefore use fixed log levels. Logging to stderr, the systemd journal (if applicable) and to our log files uses the user defined log level from Maestral.log_level which defaults to INFO.
Target | Log level | Enabled
Log file | User defined (default: INFO) | Always
Stderr | User defined (default: INFO) | If verbose flag is passed
Systemd journal | User defined (default: INFO) | If started as systemd service
Systemd notify status | INFO | If started as systemd notify service
maestral.main.Maestral.status <#maestral.main.Maestral.status> | INFO | Always
Desktop notifications | WARNING | Always
maestral.main.Maestral.fatal_errors <#maestral.main.Maestral.fatal_errors> | ERROR | Always

All custom handlers are defined in the maestral.logging <#module-maestral.logging> module. Maestral also subclasses the default logging.LogRecord <https://docs.python.org/3/library/logging.html#logging.LogRecord> to guarantee that any surrogate escape characters in file paths are replaced before emitting a log and flushing to any streams. Otherwise, incorrectly encoded file paths could prevent logging from working properly in exactly those cases where it would be particularly useful.

CONFIG FILES

The config files are located at $XDG_CONFIG_HOME/maestral on Linux (typically ~/.config/maestral) and ~/Library/Application Support/maestral on macOS. Each configuration will get its own INI file with the settings documented below.

Config values for path and excluded_items should not be edited manually but rather through the corresponding CLI commands or GUI options. This is because changes of these settings require Maestral to perform accompanying actions, e.g., download items which have been removed from the excluded list or move the local Dropbox directory. Those will not be performed if the user edits the options manually.

This also holds for the account_id which will be written to the config file after successfully completing the OAuth flow with Dropbox servers.

Any changes will only take effect once Maestral is restarted. Any changes made to the config file may be overwritten without warning if made while the sync daemon is running.

    [main]
    # Config file version (not the Maestral version!)
    version = 15.0.0
    [auth]
    # Unique Dropbox account ID. The account's email
    # address may change and is therefore not stored here.
    account_id = dbid:AABP7CC5bpYd8ghjIColDFrMoc9SdhACA4
    # The keychain to use to store user credentials. If "automatic",
    # will be set automatically from available backends when
    # completing the OAuth flow. Mus be a fully qualified class name.
    keyring = keyring.backends.macOS.Keyring
    [app]
    # Level for desktop notifications:
    # 15 = FILECHANGE
    # 30 = SYNCISSUE
    # 40 = ERROR
    # 100 = NONE
    notification_level = 15
    # Level for log messages:
    # 10 = DEBUG
    # 20 = INFO
    # 30 = WARNING
    # 40 = ERR0R
    log_level = 20
    # Interval in sec to check for updates
    update_notification_interval = 604800
    [sync]
    # The current Dropbox directory
    path = /Users/UserName/Dropbox (Maestral)
    # List of excluded files and folders
    excluded_items = ['/test_folder', '/sub/folder']
    # Interval in sec to perform a full reindexing
    reindex_interval = 604800
    # Maximum CPU usage per core
    max_cpu_percent = 20.0
    # Sync history to keep in seconds
    keep_history = 604800
    # Enable upload syncing
    upload = True
    # Enable download syncing
    download = True

STATE FILES

Maestral saves its persistent state in two files: {config_name}.db for the file index and {config_name}.state for anything else. Both files are located at $XDG_DATA_DIR/maestral on Linux (typically ~/.local/share/maestral) and ~/Library/Application Support/maestral on macOS. Each configuration will get its own state file.

  Database

The index is stored in a SQLite database with contains the sync index, the sync event history of the last week and a cache of locally calculated content hashes. We use our own light-weight ORM layer, defined in maestral.utils.orm, to manage the mapping between Python objects and database rows. The actual table declarations are given by the definitions of maestral.database.IndexEntry, maestral.database.SyncEvent and maestral.database.HashCacheEntry.

  State file

The state file has the following sections:

    [main]
    # State file version (not the Maestral version!)
    version = 12.0.0
    [account]
    email = foo@bar.com
    display_name = Foo Bar
    abbreviated_name = FB
    type = business
    usage = 39.2% of 1312.8TB used
    usage_type = team
    # Information about the user's root namespace. This
    # may be a personal namespace or a Team Space for certain
    # Dropbox Business accounts.
    path_root_type = team
    path_root_nsid = 1287234
    home_path = /User Name
    [auth]
    # The type of OAuth access token used:
    # legacy: long-lived token
    # offline: short-lived token with long-lived refresh token
    token_access_type = offline
    [app]
    # Version for which update / migration scripts have
    # run. This is bumped to the currently installed
    # version after an update.
    updated_scripts_completed = 1.2.0
    # Time stamp of last update notification
    update_notification_last = 0.0
    # Latest available release
    latest_release = 1.2.0
    [sync]
    # Cursor reflecting last-synced remote state
    cursor = ...
    # Time stamp reflecting last-synced local state
    lastsync = 1589979736.623609
    # Time stamp of last full reindexing
    last_reindex = 1589577566.8533309
    # Lower case Dropbox paths of interrupted uploads
    pending_uploads = []
    # Lower case Dropbox paths of interrupted downloads
    pending_downloads = []

Notably, account info which can be changed by the user such as the email address is saved in the state file while only the fixed Dropbox ID is saved in the config file.

CONTRIBUTING

Thank you for your interest in contributing!

  Code

To start, install maestral with the dev extra to get all dependencies required for development:

    pip3 install maestral[dev]

This will install packages to check and enforce the code style, use pre-commit hooks and bump the current version.

Code is formatted with black <https://github.com/psf/black>. Coding style is checked with flake8 <http://flake8.pycqa.org>. Type hints, PEP484 <https://www.python.org/dev/peps/pep-0484/>, are checked with mypy <http://mypy-lang.org/>.

You can check the format, coding style, and type hints at the same time by running the provided pre-commit hook from the git directory:

    pre-commit run -a

You can also install the provided pre-commit hook to run checks on every commit. This will however significantly slow down commits. An introduction to pre-commit commit hooks is given at <https://pre-commit.com>.

  Documentation

The documentation is built using sphinx <https://www.sphinx-doc.org/en/master/> and a few of its extensions. It is built from the develop and master branches and hosted on Read The Docs <https://maestral.readthedocs.io/en/latest/>. If you want to build the documentation locally, install maestral with the docs extra to get all required dependencies:

    pip3 install maestral[docs]

The API documentation is mostly based on doc strings. Inline comments should be used whenever code may be difficult to understand for others.

  Tests

The test suite uses pytest <https://pytest-cov.readthedocs.io/en/latest/> to define and run all tests.

Test are grouped into those which require a linked Dropbox account ("linked") and those who can run by themselves ("offline"). The former tend to be integration test while the latter are mostly unit tests. The focus currently lies on integration tests, especially for the sync engine, as they are easier to maintain when the implementation and internal APIs change. Exceptions are made for performance tests, for instance for indexing and cleaning up sync events, and for particularly complex functions that are prone to regressions.

Important: The entire content of the Dropbox folder is deleted before and after running each test case. You should therefore use a dedicated account to run tests.

The current test suite uses a Dropbox access token provided by the environment variable DROPBOX_ACCESS_TOKEN or a refresh token provided by DROPBOX_REFRESH_TOKEN to connect to a real account. The GitHub action which is running the tests will set the DROPBOX_ACCESS_TOKEN environment variable for you with a temporary access token that expires after 4 hours. Tests are run on ubuntu-latest and macos-latest in parallel on different accounts.

When you create a new test case, you should acquire a "lock" on the account before running tests to prevent them from interfering which each other by creating a folder test.lock in the root of the Dropbox folder. This folder should have a client_modified time set in the future, to the expiry time of the lock. Fixtures to create and clean up a test config and to acquire a lock are provided in the tests/linked/conftest.py.

If you run the tests locally, you will need to provide a refresh or access token for your own Dropbox account. If your account is already linked with Maestral, it will have saved a long-lived "refresh token" in your system keyring. You can access it manually or through the Python API:

    from maestral.main import Maestral
    m = Maestral()
    print(m.cred_storage.token)

You can then store the retrieved refresh token in the environment variable DROPBOX_REFRESH_TOKEN to be automatically picked up by the tests.

MAESTRAL.AUTOSTART

This module handles starting the maestral daemon on user login and supports multiple platform specific backends such as launchd or systemd.

Note that launchd agents will not show as "login items" in macOS system preferences. As a result, the user does not have a convenient UI to remove Maestral autostart entries manually outside Maestral itself. Login items however only support app bundles and provide no option to pass command line arguments to the app. They would therefore neither support pip installed packages nor multiple configurations.

  Module Contents

class maestral.autostart.SupportedImplementations
    Bases: enum.Enum <https://docs.python.org/3/library/enum.html#enum.Enum>

    Enumeration of supported implementations

systemd = 'systemd'

launchd = 'launchd'

xdg_desktop = 'xdg_desktop'

class maestral.autostart.AutoStartBase
    Base class for autostart backends

abstractmethod enable()
    Enable autostart. Must be implemented in subclass.

Return type
    None

abstractmethod disable()
    Disable autostart. Must be implemented in subclass.

Return type
    None

property enabled: bool <https://docs.python.org/3/library/functions.html#bool>
    Returns the enabled status as bool. Must be implemented in subclass.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

class maestral.autostart.AutoStartSystemd(service_name, start_cmd, unit_dict=None, service_dict=None, install_dict=None)
    Bases: AutoStartBase

    Autostart backend for systemd

Parameters

•   service_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of systemd service.

•   start_cmd (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Absolute path to executable and optional program arguments.

•   unit_dict (dict <https://docs.python.org/3/library/stdtypes.html#dict>[str <https://docs.python.org/3/library/stdtypes.html#str>, str <https://docs.python.org/3/library/stdtypes.html#str>] | None) -- Dictionary of additional keys and values for the Unit section.

•   service_dict (dict <https://docs.python.org/3/library/stdtypes.html#dict>[str <https://docs.python.org/3/library/stdtypes.html#str>, str <https://docs.python.org/3/library/stdtypes.html#str>] | None) -- Dictionary of additional keys and values for the Service section.

•   install_dict (dict <https://docs.python.org/3/library/stdtypes.html#dict>[str <https://docs.python.org/3/library/stdtypes.html#str>, str <https://docs.python.org/3/library/stdtypes.html#str>] | None) -- Dictionary of additional keys and values for the "Install" section.

service_name

destination

service_config

enable()
    Enable autostart. Must be implemented in subclass.

Return type
    None

disable()
    Disable autostart. Must be implemented in subclass.

Return type
    None

property enabled: bool <https://docs.python.org/3/library/functions.html#bool>
    Checks if the systemd service is enabled.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

class maestral.autostart.AutoStartLaunchd(launchd_id, start_cmd, **kwargs)
    Bases: AutoStartBase

    Autostart backend for launchd

Parameters

•   launchd_id (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Identifier for the launchd job, e.g., "com.google.calendar".

•   start_cmd (list <https://docs.python.org/3/library/stdtypes.html#list>[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- Absolute path to executable and optional program arguments.

•   kwargs (Any) -- Additional key, value pairs to add to plist. Values may be strings, booleans, lists or dictionaries.

path

destination

plist_dict

enable()
    Enable autostart. Must be implemented in subclass.

Return type
    None

disable()
    Disable autostart. Must be implemented in subclass.

Return type
    None

property enabled: bool <https://docs.python.org/3/library/functions.html#bool>
    Checks if the launchd plist exists in ~/Library/LaunchAgents.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

class maestral.autostart.AutoStartXDGDesktop(app_name, start_cmd, filename, **kwargs)
    Bases: AutoStartBase

    Autostart backend for XDG desktop entries

    Used to start a GUI on user login for most Linux desktops. For a full specifications, please see:

    <https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html>

Parameters

•   app_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of application.

•   start_cmd (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Executable on $PATH or absolute path to executable and optional program arguments.

•   filename (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Name of desktop entry file. If not given, the application name will be used.

•   kwargs (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Additional key, value pairs to be used in the desktop entries. Values must be strings and may not contain "=", otherwise no additional validation will be performed.

config

destination

enable()
    Enable autostart. Must be implemented in subclass.

Return type
    None

disable()
    Disable autostart. Must be implemented in subclass.

Return type
    None

property enabled: bool <https://docs.python.org/3/library/functions.html#bool>
    Checks if the XDG desktop entry exists in ~/.config/autostart.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

maestral.autostart.get_available_implementation()
    Returns the supported implementation depending on the platform.

Return type
    SupportedImplementations <#maestral.autostart.SupportedImplementations> | None

maestral.autostart.get_command_path(dist, command)
    Returns the path to a command line script. Tries to check dist_files first, falls back to shutil.which() otherwise.

Parameters

•   dist (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The distribution which installed the command line script.

•   command (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The command.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

class maestral.autostart.AutoStart(config_name)
    Starts Maestral on user log-in

    Creates auto-start files in the appropriate system location to automatically start Maestral when the user logs in. Different backends are used depending on the platform.

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of Maestral config.

implementation

property enabled: bool <https://docs.python.org/3/library/functions.html#bool>
    True if autostart is enabled, False otherwise.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

toggle()
    Toggles autostart on or off.

Return type
    None

enable()
    Enable autostart.

Return type
    None

disable()
    Disable autostart.

Return type
    None

MAESTRAL.CLI

This module contains the command line interface of Maestral. Keep all heavy imports local to the command or method that requires them to ensure a responsive CLI.

  Submodules

  maestral.cli.cli_core

  Module Contents

maestral.cli.cli_core.OK = ''

maestral.cli.cli_core.FAILED = ''

maestral.cli.cli_core.KILLED = ''

maestral.cli.cli_core.stop_daemon_with_cli_feedback(config_name)
    Wrapper around daemon.stop_maestral_daemon_process() with command line feedback.

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_core.select_dbx_path_dialog(config_name, default_dir_name=None, allow_merge=False)
    A CLI dialog to ask for a local Dropbox folder location.

Parameters

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The configuration to use for the default folder name.

•   default_dir_name (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- The default directory name. Defaults to "Dropbox ({config_name})" if not given.

•   allow_merge (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, allows the selection of an existing folder without deleting it. Defaults to False.

Returns
    Path given by user.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.cli.cli_core.link_dialog(m)
    A CLI dialog for linking a Dropbox account.

Parameters
    m (maestral.daemon.MaestralProxy <#maestral.daemon.MaestralProxy> | maestral.main.Maestral <#maestral.main.Maestral>) -- Proxy to Maestral daemon.

Return type
    None

maestral.cli.cli_core.start(foreground, verbose, config_name)

Parameters

•   foreground (bool <https://docs.python.org/3/library/functions.html#bool>)

•   verbose (bool <https://docs.python.org/3/library/functions.html#bool>)

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_core.stop(config_name)

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_core.gui(config_name)

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_core.pause(m)

Parameters
    m (maestral.main.Maestral <#maestral.main.Maestral>)

Return type
    None

maestral.cli.cli_core.resume(m)

Parameters
    m (maestral.main.Maestral <#maestral.main.Maestral>)

Return type
    None

maestral.cli.cli_core.auth()

Return type
    None

maestral.cli.cli_core.auth_link(m, relink, refresh_token, access_token)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   relink (bool <https://docs.python.org/3/library/functions.html#bool>)

•   refresh_token (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   access_token (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

Return type
    None

maestral.cli.cli_core.auth_unlink(yes, config_name)

Parameters

•   yes (bool <https://docs.python.org/3/library/functions.html#bool>)

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_core.auth_status(config_name)

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_core.sharelink()

Return type
    None

maestral.cli.cli_core.sharelink_create(m, dropbox_path, password, expiry)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   dropbox_path (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   password (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   expiry (datetime.datetime <https://docs.python.org/3/library/datetime.html#datetime.datetime> | None)

Return type
    None

maestral.cli.cli_core.sharelink_revoke(m, url)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   url (list <https://docs.python.org/3/library/stdtypes.html#list>[str <https://docs.python.org/3/library/stdtypes.html#str>])

Return type
    None

maestral.cli.cli_core.sharelink_list(m, dropbox_path, long)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   dropbox_path (list <https://docs.python.org/3/library/stdtypes.html#list>[str <https://docs.python.org/3/library/stdtypes.html#str>])

•   long (bool <https://docs.python.org/3/library/functions.html#bool>)

Return type
    None

  maestral.cli.cli_info

  Module Contents

maestral.cli.cli_info.status(m)

Parameters
    m (maestral.main.Maestral <#maestral.main.Maestral>)

Return type
    None

maestral.cli.cli_info.filestatus(m, local_path)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_info.activity(m)

Parameters
    m (maestral.main.Maestral <#maestral.main.Maestral>)

Return type
    None

maestral.cli.cli_info.history(m, dropbox_path)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   dropbox_path (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_info.ls(m, long, dropbox_path, include_deleted)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   long (bool <https://docs.python.org/3/library/functions.html#bool>)

•   dropbox_path (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   include_deleted (bool <https://docs.python.org/3/library/functions.html#bool>)

Return type
    None

maestral.cli.cli_info.config_files(clean)

Parameters
    clean (bool <https://docs.python.org/3/library/functions.html#bool>)

Return type
    None

  maestral.cli.cli_main

  Module Contents

maestral.cli.cli_main.main()

Return type
    None

  maestral.cli.cli_maintenance

  Module Contents

maestral.cli.cli_maintenance.move_dir(m, new_path)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   new_path (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_maintenance.rebuild_index(m, yes)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   yes (bool <https://docs.python.org/3/library/functions.html#bool>)

Return type
    None

maestral.cli.cli_maintenance.revs(m, dropbox_path, limit)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   dropbox_path (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   limit (int <https://docs.python.org/3/library/functions.html#int>)

Return type
    None

maestral.cli.cli_maintenance.diff(m, dropbox_path, rev, no_color, no_pager, limit)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   dropbox_path (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   rev (list <https://docs.python.org/3/library/stdtypes.html#list>[str <https://docs.python.org/3/library/stdtypes.html#str>])

•   no_color (bool <https://docs.python.org/3/library/functions.html#bool>)

•   no_pager (bool <https://docs.python.org/3/library/functions.html#bool>)

•   limit (int <https://docs.python.org/3/library/functions.html#int>)

Return type
    None

maestral.cli.cli_maintenance.restore(m, dropbox_path, rev, limit)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   dropbox_path (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   rev (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   limit (int <https://docs.python.org/3/library/functions.html#int>)

Return type
    None

maestral.cli.cli_maintenance.log()

Return type
    None

maestral.cli.cli_maintenance.log_show(external, config_name)

Parameters

•   external (bool <https://docs.python.org/3/library/functions.html#bool>)

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_maintenance.log_clear(config_name)

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_maintenance.log_level(m, level_name)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   level_name (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_maintenance.config()

Return type
    None

maestral.cli.cli_maintenance.config_get(m, key)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   key (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_maintenance.config_set(m, key, value)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   key (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   value (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_maintenance.config_show(no_pager, config_name)

Parameters

•   no_pager (bool <https://docs.python.org/3/library/functions.html#bool>)

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_maintenance.completion(shell)

Parameters
    shell (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

  maestral.cli.cli_settings

  Module Contents

maestral.cli.cli_settings.autostart(yes, no, config_name)

Parameters

•   yes (bool <https://docs.python.org/3/library/functions.html#bool>)

•   no (bool <https://docs.python.org/3/library/functions.html#bool>)

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_settings.excluded()

Return type
    None

maestral.cli.cli_settings.excluded_list(m)

Parameters
    m (maestral.main.Maestral <#maestral.main.Maestral>)

Return type
    None

maestral.cli.cli_settings.excluded_add(m, dropbox_paths)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   dropbox_paths (list <https://docs.python.org/3/library/stdtypes.html#list>[str <https://docs.python.org/3/library/stdtypes.html#str>])

Return type
    None

maestral.cli.cli_settings.excluded_remove(m, dropbox_paths)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   dropbox_paths (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_settings.notify()

Return type
    None

maestral.cli.cli_settings.notify_level(m, level_name)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   level_name (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

maestral.cli.cli_settings.notify_snooze(m, minutes)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   minutes (int <https://docs.python.org/3/library/functions.html#int>)

Return type
    None

maestral.cli.cli_settings.bandwidth_limit()

Return type
    None

maestral.cli.cli_settings.bandwidth_limit_up(m, mb_per_second)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   mb_per_second (float <https://docs.python.org/3/library/functions.html#float> | None)

Return type
    None

maestral.cli.cli_settings.bandwidth_limit_down(m, mb_per_second)

Parameters

•   m (maestral.main.Maestral <#maestral.main.Maestral>)

•   mb_per_second (float <https://docs.python.org/3/library/functions.html#float> | None)

Return type
    None

  maestral.cli.common

  Module Contents

maestral.cli.common.P

maestral.cli.common.T

maestral.cli.common.convert_api_errors(func)
    Decorator that catches a MaestralApiError and prints a formatted error message to stdout before exiting. Calls sys.exit(1) after printing the error to stdout.

Parameters
    func (Callable[P, T])

Return type
    Callable[P, T]

maestral.cli.common.check_for_fatal_errors(m)
    Checks the given Maestral instance for fatal errors such as revoked Dropbox access, deleted Dropbox folder etc. Prints a nice representation to the command line.

Parameters
    m (maestral.daemon.MaestralProxy <#maestral.daemon.MaestralProxy> | maestral.main.Maestral <#maestral.main.Maestral>) -- Proxy to Maestral daemon or Maestral instance.

Returns
    True in case of fatal errors, False otherwise.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

maestral.cli.common.config_option

maestral.cli.common.existing_config_option

maestral.cli.common.inject_proxy(fallback, existing_config)

Parameters

•   fallback (bool <https://docs.python.org/3/library/functions.html#bool>)

•   existing_config (bool <https://docs.python.org/3/library/functions.html#bool>)

Return type
    Callable[[Callable[P, T]], Callable[P, Any]]

  maestral.cli.core

This module provides custom click command line parameters for Maestral such DropboxPath, ConfigKey and ConfigName, as well as an ordered command group class which prints its help output in sections.

  Module Contents

class maestral.cli.core.DropboxPath(file_okay=True, dir_okay=True)
    Bases: click.ParamType <https://click.palletsprojects.com/en/latest/api/#click.ParamType>

    A command line parameter representing a Dropbox path

    This parameter type provides custom shell completion for items inside the local Dropbox folder.

Parameters

•   file_okay (bool <https://docs.python.org/3/library/functions.html#bool>) -- Controls if a file is a possible value.

•   dir_okay (bool <https://docs.python.org/3/library/functions.html#bool>) -- Controls if a directory is a possible value.

name = 'Dropbox path'

envvar_list_splitter = ':'

file_okay = True

dir_okay = True

convert(value, param, ctx)
    Convert the value to the correct type. This is not called if the value is None (the missing value).

    This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

    The param and ctx arguments may be None in certain situations, such as when converting prompt input.

    If the value cannot be converted, call fail() with a descriptive message.

Parameters

•   value (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- The value to convert.

•   param (click.Parameter <https://click.palletsprojects.com/en/latest/api/#click.Parameter> | None) -- The parameter that is using this type to convert its value. May be None.

•   ctx (click.Context <https://click.palletsprojects.com/en/latest/api/#click.Context> | None) -- The current context that arrived at this value. May be None.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str> | None

shell_complete(ctx, param, incomplete)
    Return a list of CompletionItem <https://click.palletsprojects.com/en/latest/api/#click.shell_completion.CompletionItem> objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well.

Parameters

•   ctx (click.Context <https://click.palletsprojects.com/en/latest/api/#click.Context> | None) -- Invocation context for this command.

•   param (click.Parameter <https://click.palletsprojects.com/en/latest/api/#click.Parameter> | None) -- The parameter that is requesting completion.

•   incomplete (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Value being completed. May be empty.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[click.shell_completion.CompletionItem <https://click.palletsprojects.com/en/latest/api/#click.shell_completion.CompletionItem>]

    Added in version 8.0.

class maestral.cli.core.ConfigKey
    Bases: click.ParamType <https://click.palletsprojects.com/en/latest/api/#click.ParamType>

    A command line parameter representing a config key

    This parameter type provides custom shell completion for existing config keys.

name = 'key'

shell_complete(ctx, param, incomplete)
    Return a list of CompletionItem <https://click.palletsprojects.com/en/latest/api/#click.shell_completion.CompletionItem> objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well.

Parameters

•   ctx (click.Context <https://click.palletsprojects.com/en/latest/api/#click.Context> | None) -- Invocation context for this command.

•   param (click.Parameter <https://click.palletsprojects.com/en/latest/api/#click.Parameter> | None) -- The parameter that is requesting completion.

•   incomplete (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Value being completed. May be empty.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[click.shell_completion.CompletionItem <https://click.palletsprojects.com/en/latest/api/#click.shell_completion.CompletionItem>]

    Added in version 8.0.

class maestral.cli.core.ConfigName(existing=True)
    Bases: click.ParamType <https://click.palletsprojects.com/en/latest/api/#click.ParamType>

    A command line parameter representing a Dropbox path

    This parameter type provides custom shell completion for existing config names.

Parameters
    existing (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True require an existing config, otherwise create a new config on demand.

name = 'config'

existing = True

convert(value, param, ctx)
    Convert the value to the correct type. This is not called if the value is None (the missing value).

    This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

    The param and ctx arguments may be None in certain situations, such as when converting prompt input.

    If the value cannot be converted, call fail() with a descriptive message.

Parameters

•   value (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- The value to convert.

•   param (click.Parameter <https://click.palletsprojects.com/en/latest/api/#click.Parameter> | None) -- The parameter that is using this type to convert its value. May be None.

•   ctx (click.Context <https://click.palletsprojects.com/en/latest/api/#click.Context> | None) -- The current context that arrived at this value. May be None.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str> | None

shell_complete(ctx, param, incomplete)
    Return a list of CompletionItem <https://click.palletsprojects.com/en/latest/api/#click.shell_completion.CompletionItem> objects for the incomplete value. Most types do not provide completions, but some do, and this allows custom types to provide custom completions as well.

Parameters

•   ctx (click.Context <https://click.palletsprojects.com/en/latest/api/#click.Context> | None) -- Invocation context for this command.

•   param (click.Parameter <https://click.palletsprojects.com/en/latest/api/#click.Parameter> | None) -- The parameter that is requesting completion.

•   incomplete (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Value being completed. May be empty.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[click.shell_completion.CompletionItem <https://click.palletsprojects.com/en/latest/api/#click.shell_completion.CompletionItem>]

    Added in version 8.0.

class maestral.cli.core.OrderedGroup(name=None, commands=None, invoke_without_command=False, no_args_is_help=None, subcommand_metavar=None, chain=False, result_callback=None, **kwargs)
    Bases: click.Group <https://click.palletsprojects.com/en/latest/api/#click.Group>

    Click command group with customizable sections of help output.

Parameters

•   name (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   commands (collections.abc.MutableMapping <https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping>[str <https://docs.python.org/3/library/stdtypes.html#str>, Command] | collections.abc.Sequence <https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence>[Command] | None)

•   invoke_without_command (bool <https://docs.python.org/3/library/functions.html#bool>)

•   no_args_is_help (bool <https://docs.python.org/3/library/functions.html#bool> | None)

•   subcommand_metavar (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   chain (bool <https://docs.python.org/3/library/functions.html#bool>)

•   result_callback (Callable[Ellipsis, Any] | None)

•   kwargs (Any)

sections: dict <https://docs.python.org/3/library/stdtypes.html#dict>[str <https://docs.python.org/3/library/stdtypes.html#str>, list <https://docs.python.org/3/library/stdtypes.html#list>[tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, click.Command <https://click.palletsprojects.com/en/latest/api/#click.Command>]]]

add_command(cmd, name=None, section='')
    Registers another Command with this group. If the name is not provided, the name of the command is used.

Parameters

•   cmd (click.Command <https://click.palletsprojects.com/en/latest/api/#click.Command>)

•   name (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   section (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    None

format_commands(ctx, formatter)
    Extra format methods for multi methods that adds all the commands after the options.

Parameters

•   ctx (click.Context <https://click.palletsprojects.com/en/latest/api/#click.Context>)

•   formatter (click.HelpFormatter <https://click.palletsprojects.com/en/latest/api/#click.HelpFormatter>)

Return type
    None

exception maestral.cli.core.CliException(message)
    Bases: click.ClickException <https://click.palletsprojects.com/en/latest/api/#click.ClickException>

    Subclass of click.CliException exception with a nicely formatted error message.

Parameters
    message (str <https://docs.python.org/3/library/stdtypes.html#str>)

show(file=None)

Parameters
    file (Any)

Return type
    None

  maestral.cli.dialogs

This module provides interactive commandline dialogs which are based on the survey Python library.

  Module Contents

maestral.cli.dialogs.P

maestral.cli.dialogs.T

maestral.cli.dialogs.exit_on_keyboard_interrupt(func)

Parameters
    func (Callable[P, T])

Return type
    Callable[P, T]

maestral.cli.dialogs.prompt(message, validate=None)

Parameters

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   validate (Callable[[str <https://docs.python.org/3/library/stdtypes.html#str>], bool <https://docs.python.org/3/library/functions.html#bool>] | None)

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.cli.dialogs.confirm(message, default=True)

Parameters

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   default (bool <https://docs.python.org/3/library/functions.html#bool> | None)

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

maestral.cli.dialogs.select(message, options, hint='')

Parameters

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   options (Sequence[str <https://docs.python.org/3/library/stdtypes.html#str>])

•   hint (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

Return type
    int <https://docs.python.org/3/library/functions.html#int>

maestral.cli.dialogs.select_multiple(message, options, hint=None)

Parameters

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   options (Sequence[str <https://docs.python.org/3/library/stdtypes.html#str>])

•   hint (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[int <https://docs.python.org/3/library/functions.html#int>]

maestral.cli.dialogs.select_path(message, default=None, validate=lambda x: ..., exists=False, files_allowed=True, dirs_allowed=True)

Parameters

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   default (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   validate (Callable[[str <https://docs.python.org/3/library/stdtypes.html#str>], bool <https://docs.python.org/3/library/functions.html#bool>])

•   exists (bool <https://docs.python.org/3/library/functions.html#bool>)

•   files_allowed (bool <https://docs.python.org/3/library/functions.html#bool>)

•   dirs_allowed (bool <https://docs.python.org/3/library/functions.html#bool>)

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

  maestral.cli.output

This module provides classes and methods for beautifully formatted output to stdout. This includes printing tables and grids, formatting dates and eliding strings.

  Module Contents

maestral.cli.output.TABLE_STYLE

maestral.cli.output.rich_table(*headers)

Parameters
    headers (rich.table.Column | str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    rich.table.Table

class maestral.cli.output.RichDateField(dt, style='')
    A datetime renderable.

Parameters

•   dt (datetime.datetime <https://docs.python.org/3/library/datetime.html#datetime.datetime>)

•   style (str <https://docs.python.org/3/library/stdtypes.html#str> | rich.style.Style)

dt

style = ''

format(max_width)

Parameters
    max_width (int <https://docs.python.org/3/library/functions.html#int>)

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

class maestral.cli.output.Prefix
    Bases: enum.Enum <https://docs.python.org/3/library/enum.html#enum.Enum>

    Prefix for command line output

Info = 0

Ok = 1

Warn = 2

NONE = 3

maestral.cli.output.echo(message, nl=True, prefix=Prefix.NONE)
    Print a message to stdout.

Parameters

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The string to output.

•   nl (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to end with a new line.

•   prefix (Prefix <#maestral.cli.output.Prefix>) -- Any prefix to output before the message,

Return type
    None

maestral.cli.output.info(message, nl=True)
    Print an info message to stdout. Will be prefixed with a dash.

Parameters

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The string to output.

•   nl (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to end with a new line.

Return type
    None

maestral.cli.output.warn(message, nl=True)
    Print a warning to stdout. Will be prefixed with an exclamation mark.

Parameters

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The string to output.

•   nl (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to end with a new line.

Return type
    None

maestral.cli.output.ok(message, nl=True)
    Print a confirmation to stdout. Will be prefixed with a checkmark.

Parameters

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The string to output.

•   nl (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to end with a new line.

Return type
    None

maestral.cli.output.echo_via_pager(text_or_generator, color=None)

Parameters

•   text_or_generator (Iterable[str <https://docs.python.org/3/library/stdtypes.html#str>] | Callable[[], Iterable[str <https://docs.python.org/3/library/stdtypes.html#str>]] | str <https://docs.python.org/3/library/stdtypes.html#str>)

•   color (bool <https://docs.python.org/3/library/functions.html#bool> | None)

Return type
    None

  maestral.cli.utils

Module to print neatly formatted tables and grids to the terminal.

  Module Contents

maestral.cli.utils.get_term_size()
    Returns the terminal size. If it cannot be determined, for example because output is piped to a file, return sys.maxsize for width and height instead.

Returns
    (width, height).

Return type
    os.terminal_size <https://docs.python.org/3/library/os.html#os.terminal_size>

MAESTRAL.CLIENT

This module contains the Dropbox API client. It wraps calls to the Dropbox Python SDK and handles exceptions, chunked uploads or downloads, etc.

  Module Contents

class maestral.client.DropboxClient(config_name, cred_storage, timeout=100, session=None, bandwidth_limit_up=0, bandwidth_limit_down=0)
    Client for the Dropbox SDK

    This client defines basic methods to wrap Dropbox Python SDK calls, such as creating, moving, modifying and deleting files and folders on Dropbox and downloading files from Dropbox.

    All Dropbox SDK exceptions, OSErrors from the local file system API and connection errors will be caught and reraised as a subclass of maestral.exceptions.MaestralApiError <#maestral.exceptions.MaestralApiError>.

    This class can be used as a context manager to clean up any network resources from the API requests.

Example

        >>> from maestral.client import DropboxClient
        >>> with DropboxClient("maestral") as client:
        ...     res = client.list_folder("/")
        >>> print(res.entries)

Parameters

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of config file and state file to use.

•   timeout (float <https://docs.python.org/3/library/functions.html#float>) -- Timeout for individual requests. Defaults to 100 sec if not given.

•   session (requests.Session <https://docs.python-requests.org/en/latest/api/#requests.Session> | None) -- Optional requests session to use. If not given, a new session will be created with dropbox.dropbox_client.create_session() <https://dropbox-sdk-python.readthedocs.io/en/latest/api/dropbox.html#dropbox.dropbox_client.create_session>.

•   bandwidth_limit_up (float <https://docs.python.org/3/library/functions.html#float>) -- Maximum bandwidth to use for uploads in bytes/sec. Will be enforced over all concurrent uploads (0 = unlimited).

•   bandwidth_limit_down (float <https://docs.python.org/3/library/functions.html#float>) -- Maximum bandwidth to use for downloads in bytes/sec. Will be enforced over all concurrent downloads (0 = unlimited).

•   cred_storage (maestral.keyring.CredentialStorage <#maestral.keyring.CredentialStorage>)

SDK_VERSION: str <https://docs.python.org/3/library/stdtypes.html#str> = '2.0'

MAX_TRANSFER_RETRIES = 10

MAX_LIST_FOLDER_RETRIES = 3

UPLOAD_REQUEST_CHUNK_SIZE = 4194304

DATA_TRANSFER_MIN_SLEEP_TIME = 0.0001

config_name

bandwidth_limit_up = 0

bandwidth_limit_down = 0

download_chunk_size = 4096

upload_chunk_size = 4096

property dbx_base: _DropboxSDK
    The underlying Dropbox SDK instance without namespace headers.

Return type
    _DropboxSDK

property dbx: _DropboxSDK
    The underlying Dropbox SDK instance with namespace headers.

Return type
    _DropboxSDK

property linked: bool <https://docs.python.org/3/library/functions.html#bool>
    Indicates if the client is linked to a Dropbox account (read only). This will block until the user's keyring is unlocked to load the saved auth token.

Raises
    KeyringAccessError <#maestral.exceptions.KeyringAccessError> -- if keyring access fails.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

get_auth_url()
    Returns a URL to authorize access to a Dropbox account. To link a Dropbox account, retrieve an authorization code from the URL and link Maestral by calling link() with the provided code.

Returns
    URL to retrieve an authorization code.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

link(code=None, refresh_token=None, access_token=None)
    Links Maestral with a Dropbox account using the given authorization code. The code will be exchanged for an access token and a refresh token with Dropbox servers. The refresh token will be stored for future usage in the provided credential store.

Parameters

•   code (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Authorization code.

•   refresh_token (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Optionally, instead of an authorization code, directly provide a refresh token.

•   access_token (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Optionally, instead of an authorization code or a refresh token, directly provide an access token. Note that access tokens are short-lived.

Returns
    0 on success, 1 for an invalid token and 2 for connection errors.

Return type
    int <https://docs.python.org/3/library/functions.html#int>

unlink()
    Unlinks the Dropbox account. The password will be deleted from the provided credential storage.

Raises

•   KeyringAccessError <#maestral.exceptions.KeyringAccessError> -- if keyring access fails.

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- if we cannot authenticate with Dropbox.

Return type
    None

property account_info: maestral.core.FullAccount <#maestral.core.FullAccount>
    Returns cached account info. Use get_account_info() to get the latest account info from Dropbox servers.

Return type
    maestral.core.FullAccount <#maestral.core.FullAccount>

property namespace_id: str <https://docs.python.org/3/library/stdtypes.html#str>
    The namespace ID of the path root currently used by the DropboxClient. All file paths will be interpreted as relative to the root namespace. Use update_path_root() to update the root namespace after the user joins or leaves a team with a Team Space.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

property is_team_space: bool <https://docs.python.org/3/library/functions.html#bool>
    Whether the user's Dropbox uses a Team Space. Use update_path_root() to update the root namespace after the user joins or eaves a team with a Team Space.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

close()
    Cleans up all resources like the request session/network connection.

Return type
    None

update_path_root(root_info)
    Updates the root path for the Dropbox client. All files paths given as arguments to API calls such as list_folder() or get_metadata() will be interpreted as relative to the root path. All file paths returned by API calls, for instance in file metadata, will be relative to this root path.

    The root namespace will change when the user joins or leaves a Dropbox Team with Team Spaces. If this happens, API calls using the old root namespace will raise a maestral.exceptions.PathRootError <#maestral.exceptions.PathRootError>. Use this method to update to the new root namespace.

    See <https://developers.dropbox.com/dbx-team-files-guide> and <https://www.dropbox.com/developers/reference/path-root-header-modes> for more information on Dropbox Team namespaces and path root headers in API calls.

    Note: We don't automatically switch root namespaces because API users may want to take action when the path root has changed before making further API calls. Be prepared to handle maestral.exceptions.PathRootError <#maestral.exceptions.PathRootError> and act accordingly for all methods.

Parameters
    root_info (maestral.core.RootInfo <#maestral.core.RootInfo>) -- core.RootInfo describing the path root. Use get_account_info() to retrieve.

Return type
    None

get_account_info(dbid: None <https://docs.python.org/3/library/constants.html#None> = None) -> maestral.core.FullAccount <#maestral.core.FullAccount>

get_account_info(dbid: str <https://docs.python.org/3/library/stdtypes.html#str>) -> maestral.core.Account <#maestral.core.Account>
    Gets current account information.

Parameters
    dbid -- Dropbox ID of account. If not given, will get the info of the currently linked account.

Returns
    Account info.

get_space_usage()

Returns
    The space usage of the currently linked account.

Return type
    maestral.core.PersonalSpaceUsage <#maestral.core.PersonalSpaceUsage>

get_metadata(dbx_path, include_deleted=False)
    Gets metadata for an item on Dropbox or returns False if no metadata is available. Keyword arguments are passed on to Dropbox SDK files_get_metadata call.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path of folder on Dropbox.

•   include_deleted (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to return data for deleted items.

Returns
    Metadata of item at the given path or None if item cannot be found.

Return type
    maestral.core.Metadata <#maestral.core.Metadata> | None

list_revisions(dbx_path, mode='path', limit=10)
    Lists all file revisions for the given file.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to file on Dropbox.

•   mode (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Must be 'path' or 'id'. If 'id', specify the Dropbox file ID instead of the file path to get revisions across move and rename events.

•   limit (int <https://docs.python.org/3/library/functions.html#int>) -- Maximum number of revisions to list.

Returns
    File revision history.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.core.FileMetadata <#maestral.core.FileMetadata>]

restore(dbx_path, rev)
    Restore an old revision of a file.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The path to save the restored file.

•   rev (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The revision to restore. Old revisions can be listed with list_revisions().

Returns
    Metadata of restored file.

Return type
    maestral.core.FileMetadata <#maestral.core.FileMetadata>

download(dbx_path, local_path, sync_event=None)
    Downloads a file from Dropbox to given local path.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to file on Dropbox or rev number.

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to local download destination.

•   sync_event (maestral.models.SyncEvent <#maestral.models.SyncEvent> | None) -- If given, the sync event will be updated with the number of downloaded bytes.

Returns
    Metadata of downloaded item.

Raises
    DataCorruptionError <#maestral.exceptions.DataCorruptionError> -- if data is corrupted during download.

Return type
    maestral.core.FileMetadata <#maestral.core.FileMetadata>

upload(local_path, dbx_path, write_mode=WriteMode.Add, update_rev=None, autorename=False, sync_event=None)
    Uploads local file to Dropbox. If the file size is smaller than 4 MB, the file will be uploaded all at once. Otherwise, the file will be loaded into memory and uploaded in chunks of 4 MB. If the file is modified during this chunked upload, this will raise a DataChangedError.

Parameters

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path of local file to upload.

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to save file on Dropbox.

•   write_mode (maestral.core.WriteMode <#maestral.core.WriteMode>) --

    Your intent when writing a file to some path. This is used to determine what constitutes a conflict and what the autorename strategy is. This is used to determine what constitutes a conflict and what the autorename strategy is. In some situations, the conflict behavior is identical: (a) If the target path doesn't refer to anything, the file is always written; no conflict. (b) If the target path refers to a folder, it's always a conflict. (c) If the target path refers to a file with identical contents, nothing gets written; no conflict. The conflict checking differs in the case where there's a file at the target path with contents different from the contents you're trying to write. core.WriteMode.Add Do not overwrite an existing file if there is a conflict. The autorename strategy is to append a number to the file name. For example, "document.txt" might become "document (2).txt".

core.WriteMode.Overwrite Always overwrite the existing file. The
    autorename strategy is the same as it is for add.

core.WriteMode.Update Overwrite if the given "update_rev" matches
    the existing file's "rev". The supplied value should be the latest known "rev" of the file, for example, from core.FileMetadata, from when the file was last downloaded by the app. This will cause the file on the Dropbox servers to be overwritten if the given "rev" matches the existing file's current "rev" on the Dropbox servers. The autorename strategy is to append the string "conflicted copy" to the file name. For example, "document.txt" might become "document (conflicted copy).txt" or "document (Panda's conflicted copy).txt".

•   update_rev (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Rev to match for core.WriteMode.Update.

•   sync_event (maestral.models.SyncEvent <#maestral.models.SyncEvent> | None) -- If given, the sync event will be updated with the number of downloaded bytes.

•   autorename (bool <https://docs.python.org/3/library/functions.html#bool>) -- If there's a conflict, as determined by mode, have the Dropbox server try to autorename the file to avoid conflict. The default for this field is False.

Returns
    Metadata of uploaded file.

Raises

•   DataCorruptionError <#maestral.exceptions.DataCorruptionError> -- if data is corrupted during upload.

•   DataChangedError <#maestral.exceptions.DataChangedError> -- if the file is modified during a chunked upload.

Return type
    maestral.core.FileMetadata <#maestral.core.FileMetadata>

remove(dbx_path, parent_rev=None)
    Removes a file / folder from Dropbox.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to file on Dropbox.

•   parent_rev (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Perform delete if given "rev" matches the existing file's latest "rev". This field does not support deleting a folder.

Returns
    Metadata of deleted item.

Return type
    maestral.core.FileMetadata <#maestral.core.FileMetadata> | maestral.core.FolderMetadata <#maestral.core.FolderMetadata>

remove_batch(entries, batch_size=900)
    Deletes multiple items on Dropbox in a batch job.

Parameters

•   entries (Sequence[tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, str <https://docs.python.org/3/library/stdtypes.html#str> | None]]) -- List of Dropbox paths and "rev"s to delete. If a "rev" is not None, the file will only be deleted if it matches the rev on Dropbox. This is not supported when deleting a folder.

•   batch_size (int <https://docs.python.org/3/library/functions.html#int>) -- Number of items to delete in each batch. Dropbox allows batches of up to 1,000 items. Larger values will be capped automatically.

Returns
    List of Metadata for deleted items or SyncErrors for failures. Results will be in the same order as the original input.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.core.FileMetadata <#maestral.core.FileMetadata> | maestral.core.FolderMetadata <#maestral.core.FolderMetadata> | maestral.exceptions.MaestralApiError <#maestral.exceptions.MaestralApiError>]

move(dbx_path, new_path, autorename=False)
    Moves / renames files or folders on Dropbox.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to file/folder on Dropbox.

•   new_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- New path on Dropbox to move to.

•   autorename (bool <https://docs.python.org/3/library/functions.html#bool>) -- Have the Dropbox server try to rename the item in case of a conflict.

Returns
    Metadata of moved item.

Return type
    maestral.core.FileMetadata <#maestral.core.FileMetadata> | maestral.core.FolderMetadata <#maestral.core.FolderMetadata>

make_dir(dbx_path, autorename=False)
    Creates a folder on Dropbox.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path of Dropbox folder.

•   autorename (bool <https://docs.python.org/3/library/functions.html#bool>) -- Have the Dropbox server try to rename the item in case of a conflict.

Returns
    Metadata of created folder.

Return type
    maestral.core.FolderMetadata <#maestral.core.FolderMetadata>

make_dir_batch(dbx_paths, batch_size=900, autorename=False, force_async=False)
    Creates multiple folders on Dropbox in a batch job.

Parameters

•   dbx_paths (list <https://docs.python.org/3/library/stdtypes.html#list>[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- List of dropbox folder paths.

•   batch_size (int <https://docs.python.org/3/library/functions.html#int>) -- Number of folders to create in each batch. Dropbox allows batches of up to 1,000 folders. Larger values will be capped automatically.

•   autorename (bool <https://docs.python.org/3/library/functions.html#bool>) -- Have the Dropbox server try to rename the item in case of a conflict.

•   force_async (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to force asynchronous creation on Dropbox servers.

Returns
    List of Metadata for created folders or SyncError for failures. Entries will be in the same order as given paths.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.core.FolderMetadata <#maestral.core.FolderMetadata> | maestral.exceptions.MaestralApiError <#maestral.exceptions.MaestralApiError>]

share_dir(dbx_path, force_async=False)
    Converts a Dropbox folder to a shared folder. Creates the folder if it does not exist. May return None if the folder is immediately deleted after creation.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path of Dropbox folder.

•   force_async (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to force async creation of the Dropbox directory. This only changes implementation details and is currently used to reliably test the async route.

Returns
    Metadata of shared folder.

Return type
    maestral.core.FolderMetadata <#maestral.core.FolderMetadata> | None

get_latest_cursor(dbx_path, include_non_downloadable_files=False)
    Gets the latest cursor for the given folder and subfolders.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path of folder on Dropbox.

•   include_non_downloadable_files (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, files that cannot be downloaded (at the moment only G-suite files on Dropbox) will be included.

•   kwargs -- Additional keyword arguments for Dropbox API files/list_folder/get_latest_cursor endpoint.

Returns
    The latest cursor representing a state of a folder and its subfolders.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

list_folder(dbx_path, recursive=False, include_deleted=False, include_mounted_folders=True, include_non_downloadable_files=False)
    Lists the contents of a folder on Dropbox. Similar to list_folder_iterator() but returns all entries in a single core.ListFolderResult instance.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path of folder on Dropbox.

•   dbx_path -- Path of folder on Dropbox.

•   recursive (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders.

•   include_deleted (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, the results will include entries for files and folders that used to exist but were deleted.

•   include_mounted_folders (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder.

•   include_non_downloadable_files (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, include files that are not downloadable, i.e. Google Docs.

Returns
    Content of given folder.

Return type
    maestral.core.ListFolderResult <#maestral.core.ListFolderResult>

list_folder_iterator(dbx_path, recursive=False, include_deleted=False, include_mounted_folders=True, limit=None, include_non_downloadable_files=False)
    Lists the contents of a folder on Dropbox. Returns an iterator yielding core.ListFolderResult instances. The number of entries returned in each iteration corresponds to the number of entries returned by a single Dropbox API call and will be typically around 500.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path of folder on Dropbox.

•   recursive (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders.

•   include_deleted (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, the results will include entries for files and folders that used to exist but were deleted.

•   include_mounted_folders (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder.

•   limit (Nullable[int <https://docs.python.org/3/library/functions.html#int>]) -- The maximum number of results to return per request. Note: This is an approximate number and there can be slightly more entries returned in some cases.

•   include_non_downloadable_files (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, include files that are not downloadable, i.e. Google Docs.

Returns
    Iterator over content of given folder.

Return type
    Iterator[maestral.core.ListFolderResult <#maestral.core.ListFolderResult>]

wait_for_remote_changes(last_cursor, timeout=40)
    Waits for remote changes since last_cursor. Call this method after starting the Dropbox client and periodically to get the latest updates.

Parameters

•   last_cursor (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Last to cursor to compare for changes.

•   timeout (int <https://docs.python.org/3/library/functions.html#int>) -- Seconds to wait until timeout. Must be between 30 and 480. The Dropbox API will add a random jitter of up to 60 sec to this value.

Returns
    True if changes are available, False otherwise.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

list_remote_changes(last_cursor)
    Lists changes to remote Dropbox since last_cursor. Same as list_remote_changes_iterator() but fetches all changes first and returns a single core.ListFolderResult. This may be useful if you want to fetch all changes in advance before starting to process them.

Parameters
    last_cursor (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Last to cursor to compare for changes.

Returns
    Remote changes since given cursor.

Return type
    maestral.core.ListFolderResult <#maestral.core.ListFolderResult>

list_remote_changes_iterator(last_cursor)
    Lists changes to the remote Dropbox since last_cursor. Returns an iterator yielding core.ListFolderResult instances. The number of entries returned in each iteration corresponds to the number of entries returned by a single Dropbox API call and will be typically around 500.

    Call this after wait_for_remote_changes() returns True.

Parameters
    last_cursor (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Last to cursor to compare for changes.

Returns
    Iterator over remote changes since given cursor.

Return type
    Iterator[maestral.core.ListFolderResult <#maestral.core.ListFolderResult>]

create_shared_link(dbx_path, visibility=LinkAudience.Public, access_level=LinkAccessLevel.Viewer, allow_download=None, password=None, expires=None)
    Creates a shared link for the given path. Some options are only available for Professional and Business accounts. Note that the requested visibility and access level for the link may not be granted, depending on the Dropbox folder or team settings. Check the returned link metadata to verify the visibility and access level.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Dropbox path to file or folder to share.

•   visibility (maestral.core.LinkAudience <#maestral.core.LinkAudience>) -- The visibility of the shared link. Can be public, team-only, or no-one. In case of the latter, the link merely points the user to the content and does not grant additional rights to the user. Users of this link can only access the content with their pre-existing access rights.

•   access_level (maestral.core.LinkAccessLevel <#maestral.core.LinkAccessLevel>) -- The level of access granted with the link. Can be viewer, editor, or max for maximum possible access level.

•   allow_download (bool <https://docs.python.org/3/library/functions.html#bool> | None) -- Whether to allow download capabilities for the link.

•   password (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- If given, enables password protection for the link.

•   expires (datetime.datetime <https://docs.python.org/3/library/datetime.html#datetime.datetime> | None) -- Expiry time for shared link. If no timezone is given, assume UTC. May not be supported for all account types.

Returns
    Metadata for shared link.

Return type
    maestral.core.SharedLinkMetadata <#maestral.core.SharedLinkMetadata>

revoke_shared_link(url)
    Revokes a shared link.

Parameters
    url (str <https://docs.python.org/3/library/stdtypes.html#str>) -- URL to revoke.

Return type
    None

list_shared_links(dbx_path=None)
    Lists all shared links for a given Dropbox path (file or folder). If no path is given, list all shared links for the account, up to a maximum of 1,000 links.

Parameters
    dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Dropbox path to file or folder.

Returns
    Shared links for a path, including any shared links for parents through which this path is accessible.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.core.SharedLinkMetadata <#maestral.core.SharedLinkMetadata>]

static flatten_results(results)
    Flattens a sequence listing results from a pagination to a single result with the cursor of the last result in the list.

Parameters
    results (list <https://docs.python.org/3/library/stdtypes.html#list>[PRT]) -- List of results to flatten.

Returns
    Flattened result.

Return type
    PRT

MAESTRAL.CONFIG

  Submodules

  maestral.config.main

This module contains the default configuration and state values and functions to return existing config or state instances for a specified config_name.

  Module Contents

maestral.config.main.CONFIG_DIR_NAME = 'maestral'

maestral.config.main.DEFAULTS_CONFIG: maestral.config.user._DefaultsType

maestral.config.main.DEFAULTS_STATE: maestral.config.user._DefaultsType

maestral.config.main.KEY_SECTION_MAP

maestral.config.main.CONF_VERSION

maestral.config.main.MaestralConfig(config_name)
    Returns an existing config instance or creates a new one.

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of maestral configuration to run. A new config file will be created if none exists for the given config_name.

Returns
    Maestral config instance which saves any changes to the drive.

Return type
    maestral.config.user.UserConfig <#maestral.config.user.UserConfig>

maestral.config.main.MaestralState(config_name)
    Returns an existing state instance or creates a new one.

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of maestral configuration to run. A new state file will be created if none exists for the given config_name.

Returns
    Maestral state instance which saves any changes to the drive.

Return type
    maestral.config.user.UserConfig <#maestral.config.user.UserConfig>

  maestral.config.user

This module provides user configuration file management and is mostly copied from the config module of the Spyder IDE.

  Module Contents

maestral.config.user.logger

class maestral.config.user.NoDefault

class maestral.config.user.DefaultsConfig(path)
    Bases: configparser.ConfigParser <https://docs.python.org/3/library/configparser.html#configparser.ConfigParser>

    Class used to save defaults to a file and as base class for UserConfig.

Parameters
    path (str <https://docs.python.org/3/library/stdtypes.html#str>)

save()
    Save config into the associated file.

Return type
    None

property config_path: str <https://docs.python.org/3/library/stdtypes.html#str>
    The ini file where this configuration is stored.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

class maestral.config.user.UserConfig(path, defaults=None, load=True, version=Version('0.0.0'), backup=False, remove_obsolete=False)
    Bases: DefaultsConfig

    UserConfig class, based on ConfigParser. This class is safe to use from different threads but must not be used from different processes!

Parameters

•   path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Configuration file will be saved to this path.

•   defaults (_DefaultsType | None) -- Dictionary containing options.

•   version (packaging.version.Version) -- Version of the configuration file.

•   backup (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to create a backup on version changes and on initial setup.

•   remove_obsolete (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, values that were removed from the configuration on version change, are removed from the saved configuration file.

•   load (bool <https://docs.python.org/3/library/functions.html#bool>)

    Note: The get and set arguments number and type differ from the reimplemented methods.

DEFAULT_SECTION_NAME = 'main'

default_config

remove_deprecated_options(save=True)
    Remove options which are present in the file but not in defaults.

Parameters
    save (bool <https://docs.python.org/3/library/functions.html#bool>)

Return type
    None

backup_path_for_version(version)
    Get backup location based on version.

Parameters
    version (packaging.version.Version | None) -- The version of the backup, if any.

Returns
    The back for the backup file.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

apply_configuration_patches(old_version)
    Apply any patch to configuration values on version changes.

    To be reimplemented if patches to configuration values are needed.

Parameters
    old_version (packaging.version.Version) -- Old config version to patch.

Return type
    None

get_version()
    Get the current config version.

Returns
    Configuration (not application!) version.

Return type
    packaging.version.Version

set_version(version, save=True)
    Set configuration (not application!) version.

Parameters

•   version (packaging.version.Version) -- New version to set.

•   save (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to save changes to drive.

Return type
    None

reset_to_defaults(section=None, save=True)
    Reset config to default values.

Parameters

•   section (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- The section to reset. If not given, reset all sections.

•   save (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to save the changes to the drive.

Return type
    None

get_default(section, option)
    Get default value for a given section and option.

    This is useful for type checking in get method.

Parameters

•   section (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Section to search for option.

•   option (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Config option.

Returns
    Config value or None if section / option do not exist.

Return type
    Any

get(section, option, default=NoDefault)
    Get an option.

Parameters

•   section (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Config section to search in.

•   option (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Config option to get.

•   default (Any) -- Default value to fall back to if not present.

Returns
    Config value.

Raises

•   cp.NoSectionError -- if the section does not exist.

•   cp.NoOptionError -- if the option does not exist and no default is given.

Return type
    Any

set_default(section, option, default_value)
    Set Default value for a given section, option.

    If the section or option does not exist, it will be created.

Parameters

•   section (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   option (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   default_value (Any)

Return type
    None

set(section, option, value, save=True)
    Set an option` on a given ``section.

    If section is None, the option is added to the default section.

Parameters

•   section (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Config section to search in.

•   option (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Config option to set.

•   value (Any) -- Config value.

•   save (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to save the changes to the drive.

Return type
    None

remove_section(section, save=True)
    Remove section and all options within it.

Parameters

•   section (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Section to remove from the config file.

•   save (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to save the changes to the drive.

Returns
    Whether the section was removed successfully.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

remove_option(section, option, save=True)
    Remove option from section.

Parameters

•   section (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Section to look for the option.

•   option (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Option to remove from the config file.

•   save (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to save the changes to the drive.

Returns
    Whether the section was removed successfully.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

cleanup()
    Remove files associated with config and reset to defaults.

Return type
    None

class maestral.config.user.PersistentMutableSet(conf, section, option)
    Bases: MutableSet[_T]

    Wraps a list in our state file as a Mapping

Parameters

•   conf (UserConfig <#maestral.config.user.UserConfig>) -- UserConfig instance to store the set.

•   section (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Section name in state file.

•   option (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Option name in state file.

section

option

add(entry)
    Add an element.

Parameters
    entry (_T)

Return type
    None

discard(entry)
    Remove an element. Do not raise an exception if absent.

Parameters
    entry (_T)

Return type
    None

update(*others)

Parameters
    others (Iterable[_T])

Return type
    None

difference_update(*others)

Parameters
    others (Iterable[_T])

Return type
    None

clear()
    Clears all elements.

Return type
    None

  Package Contents

maestral.config.list_configs()
    Lists all maestral configs.

Returns
    A list of all currently existing config files.

Return type
    List[str <https://docs.python.org/3/library/stdtypes.html#str>]

maestral.config.remove_configuration(config_name)
    Removes all config and state files associated with the given configuration.

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The configuration to remove.

Return type
    None

maestral.config.validate_config_name(string)
    Validates that the config name does not contain any whitespace.

Parameters
    string (_C) -- String to validate.

Returns
    The input value.

Raises
    ValueError <https://docs.python.org/3/library/exceptions.html#ValueError> -- if the config name contains whitespace.

Return type
    _C

MAESTRAL.CONSTANTS

This module provides constants used throughout the maestral, the GUI and CLI. It should be kept free of memory heavy imports.

  Module Contents

maestral.constants.resource_path(package, resource)

Parameters

•   package (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   resource (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    ContextManager[pathlib.Path <https://docs.python.org/3/library/pathlib.html#pathlib.Path>]

maestral.constants.FROZEN = False

maestral.constants.FROZEN

maestral.constants.APP_NAME = 'Maestral'

maestral.constants.BUNDLE_ID = 'com.samschott.maestral'

maestral.constants.APP_ICON_PATH = None

maestral.constants.ENV

maestral.constants.DEFAULT_CONFIG_NAME = 'maestral'

maestral.constants.OLD_REV_FILE = '.maestral'

maestral.constants.MIGNORE_FILE = '.mignore'

maestral.constants.FILE_CACHE = '.maestral.cache'

maestral.constants.EXCLUDED_FILE_NAMES

maestral.constants.EXCLUDED_DIR_NAMES

maestral.constants.IDLE = 'Up to date'

maestral.constants.SYNCING = 'Syncing...'

maestral.constants.PAUSED = 'Paused'

maestral.constants.CONNECTED = 'Connected'

maestral.constants.DISCONNECTED = 'Connection lost'

maestral.constants.CONNECTING = 'Connecting...'

maestral.constants.SYNC_ERROR = 'Sync error'

maestral.constants.ERROR = 'Fatal error'

class maestral.constants.FileStatus
    Bases: enum.Enum <https://docs.python.org/3/library/enum.html#enum.Enum>

    Enumeration of sync status

Unwatched = 'unwatched'

Uploading = 'uploading'

Downloading = 'downloading'

Error = 'error'

Synced = 'up to date'

maestral.constants.IS_MACOS

maestral.constants.IS_LINUX

maestral.constants.DROPBOX_APP_KEY = '2jmbq42w7vof78h'

maestral.constants.GITHUB_RELEASES_API = 'https://api.github.com/repos/samschott/maestral/releases'

MAESTRAL.DAEMON

This module defines functions to start and stop the sync daemon and retrieve proxy objects for a running daemon.

  Module Contents

maestral.daemon.freeze_support()
    Call this as early as possible in the main entry point of a frozen executable. This call will start the sync daemon if a matching command line arguments are detected and do nothing otherwise.

Return type
    None

class maestral.daemon.Stop
    Bases: enum.Enum <https://docs.python.org/3/library/enum.html#enum.Enum>

    Enumeration of daemon exit results

Ok = 0

Killed = 1

NotRunning = 2

Failed = 3

class maestral.daemon.Start
    Bases: enum.Enum <https://docs.python.org/3/library/enum.html#enum.Enum>

    Enumeration of daemon start results

Ok = 0

AlreadyRunning = 1

Failed = 2

class maestral.daemon.Lock(path)
    An inter-process and inter-thread lock

    This internally uses fasteners.InterProcessLock but provides non-blocking acquire. It also guarantees thread-safety when using the singleton() class method to create / retrieve a lock instance.

Parameters
    path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path of the lock file to use / create.

classmethod singleton(path)
    Retrieve an existing lock object with a given 'name' or create a new one. Use this method for thread-safe locks.

Parameters
    path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path of the lock file to use / create.

Return type
    Lock <#maestral.daemon.Lock>

path

pid

acquire()
    Attempts to acquire the given lock.

Returns
    Whether the acquisition succeeded.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

release()
    Release the previously acquired lock.

Return type
    None

locked()
    Checks if the lock is currently held by any thread or process.

Returns
    Whether the lock is acquired.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

locking_pid()
    Returns the PID of the process which currently holds the lock or None. This should work on macOS, OpenBSD and Linux but may fail on some platforms. Always use locked() to check if the lock is held by any process.

Returns
    The PID of the process which currently holds the lock or None.

Return type
    int <https://docs.python.org/3/library/functions.html#int> | None

maestral.daemon.maestral_lock(config_name)
    Returns an inter-process and inter-thread lock for Maestral. This is a wrapper around Lock which fills out the appropriate lockfile path for the given config name.

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The name of the Maestral configuration.

Returns
    Lock instance for the config name

Return type
    Lock <#maestral.daemon.Lock>

maestral.daemon.sockpath_for_config(config_name)
    Returns the unix socket location to be used for the config. This should default to the apps runtime directory + 'CONFIG_NAME.sock'.

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The name of the Maestral configuration.

Returns
    Socket path.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.daemon.lockpath_for_config(config_name)
    Returns the lock file location to be used for the config. This will be the apps runtime directory + 'CONFIG_NAME.lock'.

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The name of the Maestral configuration.

Returns
    Path of lock file to use.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.daemon.get_maestral_pid(config_name)
    Returns the PID of the daemon if it is running, None otherwise.

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The name of the Maestral configuration.

Returns
    The daemon's PID.

Return type
    int <https://docs.python.org/3/library/functions.html#int> | None

maestral.daemon.is_running(config_name)
    Checks if a daemon is currently running.

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The name of the Maestral configuration.

Returns
    Whether the daemon is running.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

maestral.daemon.wait_for_startup(config_name, timeout=30)
    Waits until we can communicate with the maestral daemon for config_name.

Parameters

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Configuration to connect to.

•   timeout (float <https://docs.python.org/3/library/functions.html#float>) -- Timeout it seconds until we raise an error.

Raises
    CommunicationError -- if we cannot communicate with the daemon within the given timeout.

Return type
    None

maestral.daemon.start_maestral_daemon(config_name='maestral', log_to_stderr=False)
    Starts the Maestral daemon with event loop in the current thread.

    Startup is race free: there will never be more than one daemon running with the same config name. The daemon is a maestral.main.Maestral <#maestral.main.Maestral> instance which is exposed as Pyro daemon object and listens for requests on a unix domain socket. This call starts an asyncio event loop to process client requests and blocks until the event loop shuts down. On macOS, the event loop is integrated with Cocoa's CFRunLoop. This allows processing Cocoa events and callbacks, for instance for desktop notifications.

Parameters

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The name of the Maestral configuration to use.

•   log_to_stderr (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, write logs to stderr.

Raises
    RuntimeError <https://docs.python.org/3/library/exceptions.html#RuntimeError> -- if a daemon for the given config_name is already running.

Return type
    None

maestral.daemon.start_maestral_daemon_process(config_name='maestral', timeout=30)
    Starts the Maestral daemon in a new process by calling start_maestral_daemon().

    Startup is race free: there will never be more than one daemon running for the same config name. This function will use sys.executable <https://docs.python.org/3/library/sys.html#sys.executable> as a Python executable to start the daemon.

    Environment variables from the current process will be preserved and updated with the environment variables defined in constants.ENV.

Parameters

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The name of the Maestral configuration to use.

•   timeout (float <https://docs.python.org/3/library/functions.html#float>) -- Time in sec to wait for daemon to start.

Returns
    Start.Ok if successful, Start.AlreadyRunning if the daemon was already running or Start.Failed if startup failed. It is possible that Start.Ok may be returned instead of Start.AlreadyRunning in case of a race but the daemon is nevertheless started only once.

Return type
    Start <#maestral.daemon.Start>

maestral.daemon.stop_maestral_daemon_process(config_name='maestral', timeout=10)
    Stops a maestral daemon process by finding its PID and shutting it down.

    This function first tries to shut down Maestral gracefully. If this fails and we know its PID, it will send SIGTERM. If that fails as well, it will send SIGKILL to the process.

Parameters

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The name of the Maestral configuration to use.

•   timeout (float <https://docs.python.org/3/library/functions.html#float>) -- Number of sec to wait for daemon to shut down before killing it.

Returns
    Stop.Ok if successful, Stop.Killed if killed, Stop.NotRunning if the daemon was not running and Stop.Failed if killing the process failed because we could not retrieve its PID.

Return type
    Stop <#maestral.daemon.Stop>

class maestral.daemon.MaestralProxy(config_name='maestral', fallback=False)
    Bases: ContextManager[MaestralProxy]

    A Proxy to the Maestral daemon

    All methods and properties of Maestral's public API are accessible and calls / access will be forwarded to the corresponding Maestral instance. This class can be used as a context manager to close the connection to the daemon on exit.

Example
    Use MaestralProxy as a context manager:

        >>> import src.maestral.cli.cli_info
        >>> with MaestralProxy() as m:
        ...     print(src.maestral.cli.cli_info.status)

    Use MaestralProxy directly:

        >>> import src.maestral.cli.cli_info
        >>> m = MaestralProxy()
        >>> print(src.maestral.cli.cli_info.status)
        >>> m._disconnect()

Variables
    _is_fallback -- Whether we are using an actual Maestral instance as fallback instead of a Proxy.

Parameters

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The name of the Maestral configuration to use.

•   fallback (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, a new instance of Maestral will be created in the current process when the daemon is not running.

Raises
    CommunicationError -- if the daemon is running but cannot be reached or if the daemon is not running and fallback is False.

MAESTRAL.DATABASE

This module provides a light-weight ORM to map between Python objects and an SQLite database. It is currently limited in functionality by what Maestral requires.

  Submodules

  maestral.database.core

This model defines our core SQLite database interface.

  Module Contents

class maestral.database.core.Database(connection)
    Wrapper around sqlite3.Connection with atomic transactions.

Parameters
    connection (sqlite3.Connection <https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection>)

connection

close()
    Closes the SQL connection.

Return type
    None

execute(sql, *args)
    Creates a cursor and executes the given SQL statement.

Parameters

•   sql (str <https://docs.python.org/3/library/stdtypes.html#str>) -- SQL statement to execute.

•   args (Any) -- Parameters to substitute for placeholders in SQL statement.

Returns
    The created cursor.

Return type
    sqlite3.Cursor <https://docs.python.org/3/library/sqlite3.html#sqlite3.Cursor>

executescript(script)
    Creates a cursor and executes the given SQL script.

Parameters
    script (str <https://docs.python.org/3/library/stdtypes.html#str>) -- SQL script to execute.

Returns
    The created cursor.

Return type
    None

  maestral.database.orm

A basic object relational mapper for SQLite.

This is a very simple ORM implementation which contains only functionality needed by Maestral. Many operations will still require explicit SQL statements. This module is no alternative to fully featured ORMs such as sqlalchemy but may be useful when system memory is constrained.

  Module Contents

class maestral.database.orm.NoDefault
    Class to denote the absence of a default value.

    This is distinct from None which may be a valid default.

class maestral.database.orm.Column(sql_type, unique=False, primary_key=False, index=False, default=None)
    Bases: Generic[T, ST]

    Represents a column in a database table.

Parameters

•   sql_type (maestral.database.types.SqlType <#maestral.database.types.SqlType>[T, ST]) -- Column type in database table. Python types which don't have SQLite equivalents, such as enum.Enum <https://docs.python.org/3/library/enum.html#enum.Enum>, will be converted appropriately.

•   unique (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, sets a unique constraint on the column.

•   primary_key (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, marks this column as a primary key column. Currently, only a single primary key column is supported.

•   index (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, create an index on this column.

•   default (T | type <https://docs.python.org/3/library/functions.html#type>[NoDefault <#maestral.database.orm.NoDefault>] | None) -- Default value for the column. Set to NoDefault if no default value should be used. Note than None / NULL is a valid default for an SQLite column.

type

unique = False

primary_key = False

index = False

name = ''

default: T | type <https://docs.python.org/3/library/functions.html#type>[NoDefault <#maestral.database.orm.NoDefault>] | None <https://docs.python.org/3/library/constants.html#None> = None

render_constraints()
    Returns a string with constraints for the SQLite column definition.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

render_properties()
    Returns a string with properties for the SQLite column definition.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

render_column()
    Returns a string with the full SQLite column definition.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

py_to_sql(value)
    Converts a Python value to a value which can be stored in the database column.

Parameters
    value (T | None) -- Native Python value.

Returns
    Converted Python value to store in database. Will only return str, int, float or None.

Return type
    ST | None

sql_to_py(value)
    Converts a database column value to the original Python type.

Parameters
    value (ST | None) -- Value from database column. Only accepts str, int, float or None.

Returns
    Converted Python value.

Return type
    T | None

class maestral.database.orm.NonNullColumn(sql_type, unique=False, primary_key=False, index=False, default=NoDefault)
    Bases: Column[T, ST]

    Subclass of Column which is not nullable, i.e., does not accept or return None as a value.

Parameters

•   sql_type (maestral.database.types.SqlType <#maestral.database.types.SqlType>[T, ST])

•   unique (bool <https://docs.python.org/3/library/functions.html#bool>)

•   primary_key (bool <https://docs.python.org/3/library/functions.html#bool>)

•   index (bool <https://docs.python.org/3/library/functions.html#bool>)

•   default (T | type <https://docs.python.org/3/library/functions.html#type>[NoDefault <#maestral.database.orm.NoDefault>])

py_to_sql(value)
    Converts a Python value to a value which can be stored in the database column.

Parameters
    value (T | None) -- Native Python value.

Returns
    Converted Python value to store in database. Will only return str, int, float or None.

Return type
    ST

sql_to_py(value)
    Converts a database column value to the original Python type.

Parameters
    value (ST | None) -- Value from database column. Only accepts str, int, float or None.

Returns
    Converted Python value.

Return type
    T

render_constraints()
    Returns a string with constraints for the SQLite column definition.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

class maestral.database.orm.Manager(db, model)
    Bases: Generic[M]

    A data mapper interface for a table model.

    Creates the table as defined in the model if it doesn't already exist. Keeps a cache of weak references to all retrieved and created rows to speed up queries. The cache should be cleared manually changes where made to the table from outside this manager.

Parameters

•   db (maestral.database.core.Database <#maestral.database.core.Database>) -- Database to use.

•   model (type <https://docs.python.org/3/library/functions.html#type>[M]) -- Model for database table.

db

model

table_name

pk_column

create_table_if_not_exists()
    Creates the table as defined by the model.

Return type
    None

clear_cache()
    Clears our cache.

Return type
    None

delete(query)

Parameters
    query (maestral.database.query.Query <#maestral.database.query.Query>)

Return type
    None

select(query)

Parameters
    query (maestral.database.query.Query <#maestral.database.query.Query>)

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[M]

select_iter(query, size=1000)

Parameters

•   query (maestral.database.query.Query <#maestral.database.query.Query>)

•   size (int <https://docs.python.org/3/library/functions.html#int>)

Return type
    Generator[list <https://docs.python.org/3/library/stdtypes.html#list>[M], Any, None]

select_sql(sql, *args)
    Performs the given SQL query and converts any returned rows to model objects.

Parameters

•   sql (str <https://docs.python.org/3/library/stdtypes.html#str>) -- SQL statement to execute.

•   args (Any) -- Parameters to substitute for placeholders in SQL statement.

Returns
    List of model objects from the query.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[M]

delete_primary_key(primary_key)
    Delete a model object / row from database by primary key.

Parameters
    primary_key (Any) -- Primary key for row.

Return type
    None

get(primary_key)
    Gets a model object from database by its primary key. This will return a cached value if available and None if no row with the primary key exists.

Parameters
    primary_key (Any) -- Primary key for row.

Returns
    Model object representing the row.

Return type
    M | None

has(primary_key)
    Checks if a model object exists in database by its primary key

Parameters
    primary_key (Any) -- The primary key.

Returns
    Whether the corresponding row exists in the table.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

save(obj)
    Saves a model object to the database table. If the primary key is None, a new primary key will be generated by SQLite on inserting the row. This key will be retrieved and stored in the primary key property of the object.

Parameters
    obj (M) -- Model object to save.

Returns
    Saved model object.

Return type
    M

update(obj)
    Updates the database table from a model object.

Parameters
    obj (M) -- The object to update.

Return type
    None

count()
    Returns the number of rows in the table.

Return type
    int <https://docs.python.org/3/library/functions.html#int>

clear()
    Delete all rows from table.

Return type
    None

class maestral.database.orm.Model(**kwargs)
    Abstract object model to represent an SQL table.

    Instances of this class are model objects which correspond to rows in the database table.

    To define a table, subclass Model and define class properties as Column. Override the __tablename__ attribute with the SQLite table name to use. The __columns__ attribute will be populated automatically for you.

Parameters
    kwargs (Any)

  maestral.database.query

SQL query definitions that facilitate writing object-oriented code to generate SQL queries.

  Module Contents

class maestral.database.query.Query
    Base type for query

abstractmethod clause()
    Generate the corresponding SQL clause.

Returns
    SQL clause and arguments to substitute.

Return type
    tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, Sequence[Any]]

order_by(expr)

Parameters
    expr (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    OrderedQuery <#maestral.database.query.OrderedQuery>

class maestral.database.query.OrderedQuery(query, order_expr)
    Bases: Query

    Ordered query

Parameters

•   query (Query <#maestral.database.query.Query>)

•   order_expr (str <https://docs.python.org/3/library/stdtypes.html#str>)

base_query

order_expr

clause()
    Generate the corresponding SQL clause.

Returns
    SQL clause and arguments to substitute.

Return type
    tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, Sequence[Any]]

class maestral.database.query.PathTreeQuery(column, path)
    Bases: Query

    Query for an entire subtree at the given path.

Parameters

•   column (maestral.database.orm.Column <#maestral.database.orm.Column>[Any, Any]) -- Column to match.

•   path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Root path for the subtree.

column

file_blob

dir_blob

clause()
    Generate the corresponding SQL clause.

Returns
    SQL clause and arguments to substitute.

Return type
    tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, Sequence[Any]]

class maestral.database.query.MatchQuery(column, value)
    Bases: Query

    Query to match an exact value.

Parameters

•   column (maestral.database.orm.Column <#maestral.database.orm.Column>[Any, Any]) -- Column to match.

•   value (Any) -- Value to match.

column

value

clause()
    Generate the corresponding SQL clause.

Returns
    SQL clause and arguments to substitute.

Return type
    tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, Sequence[Any]]

class maestral.database.query.AllQuery
    Bases: Query

    Query to match everything.

clause()
    Generate the corresponding SQL clause.

Returns
    SQL clause and arguments to substitute.

Return type
    tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, Sequence[Any]]

class maestral.database.query.CollectionQuery(*subqueries)
    Bases: Query

    An abstract query class that aggregates other queries. Can be indexed like a list to access the sub-queries.

Parameters
    subqueries (Query <#maestral.database.query.Query>) -- Subqueries to aggregate.

subqueries = ()

clause_with_joiner(joiner)
    Return a clause created by joining together the clauses of all subqueries with the string joiner (padded by spaces).

Parameters
    joiner (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, Sequence[Any]]

abstractmethod clause()
    Generate the corresponding SQL clause.

Returns
    SQL clause and arguments to substitute.

Return type
    tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, Sequence[Any]]

class maestral.database.query.AndQuery(*subqueries)
    Bases: CollectionQuery

    A conjunction of a list of other queries.

Parameters
    subqueries (Query <#maestral.database.query.Query>)

clause()
    Generate the corresponding SQL clause.

Returns
    SQL clause and arguments to substitute.

Return type
    tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, Sequence[Any]]

class maestral.database.query.OrQuery(*subqueries)
    Bases: CollectionQuery

    A conjunction of a list of other queries.

Parameters
    subqueries (Query <#maestral.database.query.Query>)

clause()
    Generate the corresponding SQL clause.

Returns
    SQL clause and arguments to substitute.

Return type
    tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, Sequence[Any]]

class maestral.database.query.NotQuery(subquery)
    Bases: Query

    A query that matches the negation of its subquery, as a shortcut for performing not(subquery) without using regular expressions.

Parameters
    subquery (Query <#maestral.database.query.Query>) -- Query to negate.

subquery

clause()
    Generate the corresponding SQL clause.

Returns
    SQL clause and arguments to substitute.

Return type
    tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, Sequence[Any]]

  maestral.database.types

SQL column type definitions, including conversion rules from / to Python types.

  Module Contents

maestral.database.types.T

maestral.database.types.ST

maestral.database.types.ET

class maestral.database.types.SqlType
    Bases: Generic[T, ST]

    Base class to represent Python types in SQLite table

sql_type = 'TEXT'

sql_to_py(value)
    Converts the return value from sqlite3 to the target Python type.

Parameters
    value (ST)

Return type
    T

py_to_sql(value)
    Converts a Python value to a type accepted by sqlite3.

Parameters
    value (T)

Return type
    ST

class maestral.database.types.SqlString
    Bases: SqlType[str <https://docs.python.org/3/library/stdtypes.html#str>, str <https://docs.python.org/3/library/stdtypes.html#str>]

    Class to represent Python strings in SQLite table

sql_type = 'TEXT'

class maestral.database.types.SqlInt
    Bases: SqlType[int <https://docs.python.org/3/library/functions.html#int>, int <https://docs.python.org/3/library/functions.html#int>]

    Class to represent Python integers in SQLite table

    SQLite supports up to 64-bit signed integers (-2**63 < int < 2**63 - 1)

sql_type = 'INTEGER'

class maestral.database.types.SqlFloat
    Bases: SqlType[float <https://docs.python.org/3/library/functions.html#float>, float <https://docs.python.org/3/library/functions.html#float>]

    Class to represent Python floats in SQLite table

sql_type = 'REAL'

class maestral.database.types.SqlLargeInt
    Bases: SqlType[int <https://docs.python.org/3/library/functions.html#int>, str <https://docs.python.org/3/library/stdtypes.html#str>]

    Class to represent large integers > 64bit in SQLite table

    Integers are stored as text in the database and converted on read / write.

sql_type = 'TEXT'

sql_to_py(value)
    Converts the return value from sqlite3 to the target Python type.

Parameters
    value (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    int <https://docs.python.org/3/library/functions.html#int>

py_to_sql(value)
    Converts a Python value to a type accepted by sqlite3.

Parameters
    value (int <https://docs.python.org/3/library/functions.html#int>)

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

class maestral.database.types.SqlPath
    Bases: SqlType[str <https://docs.python.org/3/library/stdtypes.html#str>, bytes <https://docs.python.org/3/library/stdtypes.html#bytes>]

    Class to represent Python paths in SQLite table

    Paths are stored as bytes in the database to handle characters in the path which cannot be decoded in the reported file system encoding. On the Python side, paths will contain surrogate escapes in place of such characters.

sql_type = 'BLOB'

sql_to_py(value)
    Converts the return value from sqlite3 to the target Python type.

Parameters
    value (bytes <https://docs.python.org/3/library/stdtypes.html#bytes>)

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

py_to_sql(value)
    Converts a Python value to a type accepted by sqlite3.

Parameters
    value (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    bytes <https://docs.python.org/3/library/stdtypes.html#bytes>

class maestral.database.types.SqlEnum(enum)
    Bases: SqlType[ET, str <https://docs.python.org/3/library/stdtypes.html#str>]

    Class to represent Python enums in SQLite table

    Enums are stored as text (attribute name) in the database.

Parameters
    enum (Iterable[ET])

sql_type = 'TEXT'

enum_type

sql_to_py(value)
    Converts the return value from sqlite3 to the target Python type.

Parameters
    value (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    ET

py_to_sql(value)
    Converts a Python value to a type accepted by sqlite3.

Parameters
    value (ET)

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

MAESTRAL.ERRORHANDLING

This module contains methods and decorators to convert OSErrors and Dropbox SDK exceptions to instances of maestral.exceptions.MaestralApiError <#maestral.exceptions.MaestralApiError>.

  Module Contents

maestral.errorhandling.CONNECTION_ERRORS

maestral.errorhandling.convert_api_errors(dbx_path=None, local_path=None)
    A context manager that catches and re-raises instances of OSError <https://docs.python.org/3/library/exceptions.html#OSError> and dropbox.exceptions.DropboxException <https://dropbox-sdk-python.readthedocs.io/en/latest/api/exceptions.html#dropbox.exceptions.DropboxException> as maestral.exceptions.MaestralApiError <#maestral.exceptions.MaestralApiError> or ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError>.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Dropbox path associated with the error.

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Local path associated with the error.

Return type
    Iterator[None]

maestral.errorhandling.os_to_maestral_error(exc, dbx_path=None, local_path=None)
    Converts a OSError <https://docs.python.org/3/library/exceptions.html#OSError> to a maestral.exceptions.MaestralApiError <#maestral.exceptions.MaestralApiError> and tries to add a reasonably informative error title and message.

Parameters

•   exc (OSError <https://docs.python.org/3/library/exceptions.html#OSError>) -- Original OSError.

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Dropbox path associated with the error.

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Local path associated with the error.

Returns
    Converted exception.

Return type
    LocalError

maestral.errorhandling.dropbox_to_maestral_error(exc, dbx_path=None, local_path=None)
    Converts a Dropbox SDK exception to a maestral.exceptions.MaestralApiError <#maestral.exceptions.MaestralApiError> and tries to add a reasonably informative error title and message.

Parameters

•   exc (dropbox.exceptions.DropboxException <https://dropbox-sdk-python.readthedocs.io/en/latest/api/exceptions.html#dropbox.exceptions.DropboxException> | dropbox.stone_validators.ValidationError | requests.HTTPError <https://docs.python-requests.org/en/latest/api/#requests.HTTPError>) -- Dropbox SDK exception..

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Dropbox path associated with the error.

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Local path associated with the error.

Returns
    Converted exception.

Return type
    maestral.exceptions.MaestralApiError <#maestral.exceptions.MaestralApiError>

MAESTRAL.EXCEPTIONS

This module defines Maestral's error classes. It should be kept free of memory heavy imports.

All errors inherit from MaestralApiError which has title and message attributes to display the error to the user. Errors which are related to syncing a specific file or folder inherit from SyncError, a subclass of MaestralApiError.

  Module Contents

exception maestral.exceptions.MaestralApiError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: Exception <https://docs.python.org/3/library/exceptions.html#Exception>

    Base class for Maestral errors

    MaestralApiError provides attributes that can be used to generate human-readable error messages and metadata regarding affected file paths (if any).

    Errors originating from the Dropbox API or the 'local API' both inherit from MaestralApiError.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>) -- A short description of the error type. This can be used in a CLI or GUI to give a short error summary.

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>) -- A more verbose description which can include instructions on how to proceed to fix the error.

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Dropbox path of the item that caused the error.

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Dropbox origin path of the item that caused the error. This should be set for instance when error occurs when moving an item.

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Local path of the item that caused the error.

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Local origin path of the item that caused the error. This should be set for instance when error occurs when moving an item.

title

message = ''

dbx_path = None

dbx_path_from = None

local_path = None

local_path_from = None

exception maestral.exceptions.SyncError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Base class for recoverable sync issues.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.DataCorruptionError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when data is corrupted in transit during upload or download.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.DataChangedError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when file changes during upload.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.InsufficientPermissionsError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when accessing a file or folder fails due to insufficient permissions, both locally and on Dropbox servers.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.InsufficientSpaceError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when the Dropbox account or local drive has insufficient storage space.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.PathError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when there is an issue with the provided file or folder path such as invalid characters or a too long file name.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.NotFoundError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when a file or folder is requested but does not exist.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.ConflictError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when trying to create a file or folder which already exists.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.FileConflictError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: ConflictError

    Raised when trying to create a file which already exists.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.FolderConflictError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when trying to create or folder which already exists.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.IsAFolderError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when a file is required but a folder is provided.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.NotAFolderError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when a folder is required but a file is provided.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.DropboxServerError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised in case of internal Dropbox errors.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.RestrictedContentError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when trying to sync restricted content, for instance when adding a file with a DMCA takedown notice to a public folder.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.UnsupportedFileError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when this file type cannot be downloaded but only exported. This is the case for G-suite files.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.FileSizeError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when attempting to upload a file larger than 350 GB in an upload session or larger than 150 MB in a single upload. Also raised when attempting to download a file with a size that exceeds file system's limit.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.FileReadError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when reading a local file failed.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.SymlinkError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: SyncError

    Raised when we cannot sync a symlink.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.DropboxConnectionError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when the connection to Dropbox fails

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.CancelledError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when syncing is cancelled by the user.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.NotLinkedError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when no Dropbox account is linked.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.InvalidDbidError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when the given Dropbox ID does not correspond to an existing account.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.KeyringAccessError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when retrieving a saved auth token from the user keyring fails.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.NoDropboxDirError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when the local Dropbox folder cannot be found.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.CacheDirError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when creating the cache directory fails.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.InotifyError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when the local Dropbox folder is too large to monitor with inotify.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.OutOfMemoryError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when there is insufficient memory to complete an operation.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.DatabaseError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when reading or writing to the database fails.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.DropboxAuthError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when authentication fails.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.TokenExpiredError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: DropboxAuthError

    Raised when authentication fails because the user's token has expired.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.TokenRevokedError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: DropboxAuthError

    Raised when authentication fails because the user's token has been revoked.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.CursorResetError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when the cursor used for a longpoll or list-folder request has been invalidated. Dropbox will very rarely invalidate a cursor. If this happens, a new cursor for the respective folder has to be obtained through files_list_folder. This may require re-syncing the entire Dropbox.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.BadInputError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when an API request is made with bad input. This should not happen during syncing but only in case of manual API calls.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.BusyError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when trying to perform an action which is only possible in the idle state and we cannot block or queue the job.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.UnsupportedFileTypeForDiff(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when a diff for an unsupported file type was issued.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.SharedLinkError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when creating a shared link fails.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.PathRootError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when making an API call with an invalid path root header.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

exception maestral.exceptions.UpdateCheckError(title, message='', dbx_path=None, dbx_path_from=None, local_path=None, local_path_from=None)
    Bases: MaestralApiError

    Raised when checking for updates fails.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   dbx_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

•   local_path_from (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

MAESTRAL.FSEVENTS

This module provides a custom polling file system event emitter for the watchdog package that sorts file system events in an order which can be applied to reproduce the new state from the old state. This is only required for the polling emitter which uses period directory snapshots and compares them with a watchdog.utils.dirsnapshot.DirectorySnapshotDiff <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.utils.dirsnapshot.DirectorySnapshotDiff> to generate file system events.

  Submodules

  maestral.fsevents.polling

Looking at the source code for watchdog.utils.dirsnapshot.DirectorySnapshotDiff <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.utils.dirsnapshot.DirectorySnapshotDiff>, the event types are categorised as follows:

•   Created event: The inode is unique to the new snapshot. The path may be unique to the new snapshot or exist in both. In the second case, there will be a preceding Deleted event or a Moved event with the path as starting point (the old item was deleted or moved away).

•   Deleted event: The inode is unique to the old snapshot. The path may be unique to the old snapshot or exist in both. In the second case, there will be a subsequent Created event or a Moved event with the path as end point (something else was created at or moved to the location).

•   Moved event: The inode exists in both snapshots but with different paths.

•   Modified event: The inode exists in both snapshots and the mtime or file size are different. DirectorySnapshotDiff will always use the inode’s path from the old snapshot.

    From the above classification, there can be at most two created/deleted/moved events that share the same path in one snapshot diff:

•   Deleted(path1) + Created(path1)

•   Moved(path1, path2) + Created(path1)

•   Deleted(path1) + Moved(path0, path1)

    Any Modified event will come before a Moved event or stand alone. Modified events will never be combined by themselves with created or deleted events because they require the inode to be present in both snapshots.

    From the above, we can achieve correct ordering for unique path by always adding Deleted events to the queue first, Modified events second, Moved events third and Created events last: Deleted -> Modified -> Moved -> Created

    The ordering won’t be correct between unrelated paths and between files and folder. The first does not matter for syncing. We solve the second by assuming that when a directory is deleted, so are its children. And before a child is created, its parent directory must exist.

    MovedEvents which are not unique (their paths appear in other events) will be split into Deleted and Created events by Maestral.

  Module Contents

class maestral.fsevents.polling.OrderedPollingEmitter(event_queue, watch, *, timeout=DEFAULT_EMITTER_TIMEOUT, event_filter=None, stat=os.stat, listdir=os.scandir)
    Bases: watchdog.observers.polling.PollingEmitter

    Ordered polling file system event emitter

    Platform-independent emitter that polls a directory to detect file system changes. Events are emitted in an order which can be used to produce the new file system state from the old one.

Parameters

•   event_queue (watchdog.observers.api.EventQueue <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.observers.api.EventQueue>)

•   watch (watchdog.observers.api.ObservedWatch <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.observers.api.ObservedWatch>)

•   timeout (float <https://docs.python.org/3/library/functions.html#float>)

•   event_filter (list <https://docs.python.org/3/library/stdtypes.html#list>[type <https://docs.python.org/3/library/functions.html#type>[watchdog.events.FileSystemEvent <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.events.FileSystemEvent>]] | None)

•   stat (Callable[[str <https://docs.python.org/3/library/stdtypes.html#str>], os.stat_result <https://docs.python.org/3/library/os.html#os.stat_result>])

•   listdir (Callable[[str <https://docs.python.org/3/library/stdtypes.html#str> | None], collections.abc.Iterator <https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator>[os.DirEntry <https://docs.python.org/3/library/os.html#os.DirEntry>]])

queue_events(timeout)
    Override this method to populate the event queue with events per interval period.

Parameters
    timeout (float) -- Timeout (in seconds) between successive attempts at reading events.

Return type
    None

class maestral.fsevents.polling.OrderedPollingObserver(timeout=DEFAULT_OBSERVER_TIMEOUT)
    Bases: watchdog.observers.polling.PollingObserver <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.observers.polling.PollingObserver>

    Platform-independent observer that polls a directory to detect file system changes.

Parameters
    timeout (float <https://docs.python.org/3/library/functions.html#float>)

  Package Contents

maestral.fsevents.ObserverType

maestral.fsevents.Observer: Type[ObserverType]

MAESTRAL.LOGGING

This module defines custom logging records and handlers.

  Module Contents

maestral.logging.LOG_FMT_LONG

maestral.logging.LOG_FMT_SHORT

class maestral.logging.EncodingSafeLogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None, **kwargs)
    Bases: logging.LogRecord <https://docs.python.org/3/library/logging.html#logging.LogRecord>

    A log record which ensures that messages contain only unicode characters

    This is useful when log messages may contain file paths generates by OS APIs. In Python, such path strings may contain surrogate escapes and will therefore raise a UnicodeEncodeError <https://docs.python.org/3/library/exceptions.html#UnicodeEncodeError> under many circumstances (printing to stdout, etc.).

getMessage()
    Formats the log message and replaces all surrogate escapes with "�".

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

class maestral.logging.AwaitableHandler(level=logging.NOTSET, max_unblock_per_second=1)
    Bases: logging.Handler <https://docs.python.org/3/library/logging.html#logging.Handler>

    Handler with a blocking API to wait for emits

    The method wait_for_emit() can be used from another thread to block until a new record is emitted, for instance to react to state changes.

Parameters

•   level (int <https://docs.python.org/3/library/functions.html#int>) -- Initial log level. Defaults to NOTSET.

•   max_unblock_per_second (int <https://docs.python.org/3/library/functions.html#int> | None) -- Maximum number of times per second to unblock.

emit(record)
    Do whatever it takes to actually log the specified logging record.

    This version is intended to be implemented by subclasses and so raises a NotImplementedError.

Parameters
    record (logging.LogRecord <https://docs.python.org/3/library/logging.html#logging.LogRecord>)

Return type
    None

wait_for_emit(timeout)
    Blocks until a new record is emitted. This is effectively a longpoll API. Will unblock at max_unblock_per_second.

Parameters
    timeout (float <https://docs.python.org/3/library/functions.html#float> | None) -- Maximum time to block before returning.

Returns
    True if there was a status change, False in case of a timeout.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

class maestral.logging.CachedHandler(level=logging.NOTSET, maxlen=None)
    Bases: logging.Handler <https://docs.python.org/3/library/logging.html#logging.Handler>

    Handler which stores past records

    This is used to populate Maestral's status and error interfaces. The method wait_for_emit() can be used from another thread to block until a new record is emitted, for instance to react to state changes.

Parameters

•   level (int <https://docs.python.org/3/library/functions.html#int>) -- Initial log level. Defaults to NOTSET.

•   maxlen (int <https://docs.python.org/3/library/functions.html#int> | None) -- Maximum number of records to store. If None, all records will be stored. Defaults to None.

cached_records: collections.deque <https://docs.python.org/3/library/collections.html#collections.deque>[logging.LogRecord <https://docs.python.org/3/library/logging.html#logging.LogRecord>]

emit(record)
    Logs the specified log record and saves it to the cache.

Parameters
    record (logging.LogRecord <https://docs.python.org/3/library/logging.html#logging.LogRecord>) -- Log record.

Return type
    None

get_last_message()

Returns
    The log message of the last record or an empty string.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

get_all_messages()

Returns
    A list of all record messages.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[str <https://docs.python.org/3/library/stdtypes.html#str>]

clear()
    Clears all cached records.

Return type
    None

class maestral.logging.SdNotificationHandler(level=NOTSET)
    Bases: logging.Handler <https://docs.python.org/3/library/logging.html#logging.Handler>

    Handler which emits messages as systemd notifications

    This is useful when used from a systemd service and will do nothing when no NOTIFY_SOCKET is provided.

notifier

emit(record)
    Sends the record message to systemd as service status.

Parameters
    record (logging.LogRecord <https://docs.python.org/3/library/logging.html#logging.LogRecord>) -- Log record.

Return type
    None

maestral.logging.scoped_logger_name(module_name, config_name='maestral')
    Returns a logger name for the module module_name, scoped to the given config.

Parameters

•   module_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Module name.

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Config name.

Returns
    Scoped logger name.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.logging.scoped_logger(module_name, config_name='maestral')
    Returns a logger for the module module_name, scoped to the given config.

Parameters

•   module_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Module name.

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Config name.

Returns
    Logger instances scoped to the config.

Return type
    logging.Logger <https://docs.python.org/3/library/logging.html#logging.Logger>

maestral.logging.setup_logging(config_name, file=True, stderr=True, journal=True, status=True)
    Set up loging to external channels. Systemd-related logging will fail silently if the current process was not started by systemd.

Parameters

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Config name to determine log level and namespace for loggers. See scoped_logger_name() for how the logger name is determined.

•   file (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to log to files.

•   stderr (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to log to stderr.

•   journal (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to log to the systemd journal.

•   status (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to log to the systemd status notifier. Note that this will always be performed at level INFO.

Returns
    Log handlers.

Return type
    Sequence[logging.Handler <https://docs.python.org/3/library/logging.html#logging.Handler>]

MAESTRAL.MAIN

This module defines the main API which is exposed to the CLI or GUI.

  Module Contents

class maestral.main.Maestral(config_name=DEFAULT_CONFIG_NAME, log_to_stderr=False, event_loop=None, shutdown_future=None)
    The public API

    All methods and properties return objects or raise exceptions which can safely be serialized, i.e., pure Python types. The only exception are instances of maestral.exceptions.MaestralApiError <#maestral.exceptions.MaestralApiError>: they need to be registered explicitly with the serpent serializer which is used for communication to frontends.

    Sync errors and fatal errors which occur in the sync threads can be read with the properties sync_errors and fatal_errors, respectively.

Example
    First create an instance with a new config_name. In this example, we choose "private" to sync a private Dropbox account. Then link the created config to an existing Dropbox account and set up the local Dropbox folder. If successful, invoke start_sync() to start syncing.

        >>> from maestral.main import Maestral
        >>> m = Maestral(config_name='private')
        >>> url = m.get_auth_url()  # get token from Dropbox website
        >>> print(f'Please go to {url} to retrieve a Dropbox authorization token.')
        >>> token = input('Enter auth token: ')
        >>> res = m.link(token)
        >>> if res == 0:
        ...     m.create_dropbox_directory('~/Dropbox (Private)')
        ...     m.start_sync()

Parameters

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of maestral configuration to run. Must not contain any whitespace. If the given config file does exist, it will be created.

•   log_to_stderr (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, Maestral will print log messages to stderr. When started as a systemd services, this can result in duplicate log messages in the systemd journal. Defaults to False.

•   event_loop (asyncio.AbstractEventLoop <https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop> | None) -- Event loop to use for any features that require an asyncio event loop. If not given, those features will be disabled. This currently only affects desktop notifications.

•   shutdown_future (asyncio.Future <https://docs.python.org/3/library/asyncio-future.html#asyncio.Future>[bool <https://docs.python.org/3/library/functions.html#bool>] | None) -- Feature to set a result when shutdown is complete. Used to inform the caller if an API client calls
    :method:`shutdown_daemon`
    . The event loop associated with the Future must be the same as event_loop.

cred_storage

client

sync

manager

shutdown_future = None

property version: str <https://docs.python.org/3/library/stdtypes.html#str>
    Returns the current Maestral version.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

get_auth_url()
    Returns a URL to authorize access to a Dropbox account. To link a Dropbox account, retrieve an authorization code from the URL and link Maestral by calling link() with the provided code.

Returns
    URL to retrieve an authorization code.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

link(code=None, refresh_token=None, access_token=None)
    Links Maestral with a Dropbox account using the given authorization code. The code will be exchanged for an access token and a refresh token with Dropbox servers. The refresh token will be stored for future usage as documented in the oauth module. Supported keyring backends are, in order of preference:

•   macOS Keychain

•   Any keyring implementing the SecretService Dbus specification

•   KWallet

•   Gnome Keyring

•   Plain text storage

    For testing, it is also possible to directly provide a long-lived refresh token or a short-lived access token. Note that the tokens must be issued for Maestral, with the required scopes, and will be validated with Dropbox servers as part of this call.

Parameters

•   code (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Authorization code.

•   refresh_token (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Optionally, instead of an authorization code, directly provide a refresh token.

•   access_token (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Optionally, instead of an authorization code or a refresh token, directly provide an access token. Note that access tokens are short-lived.

Returns
    0 on success, 1 for an invalid token and 2 for connection errors.

Return type
    int <https://docs.python.org/3/library/functions.html#int>

unlink()
    Unlinks the configured Dropbox account but leaves all downloaded files in place. All syncing metadata will be removed as well. Connection and API errors will be handled silently but the Dropbox access key will always be removed from the user's PC.

Raises
    NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    None

property config_name: str <https://docs.python.org/3/library/stdtypes.html#str>
    The selected configuration.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

set_conf(section, name, value)
    Sets a configuration option.

Parameters

•   section (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of section in config file.

•   name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of config option.

•   value (Any) -- Config value. May be any type accepted by ast.literal_eval <https://docs.python.org/3/library/ast.html#ast.literal_eval>.

Return type
    None

get_conf(section, name)
    Gets a configuration option.

Parameters

•   section (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of section in config file.

•   name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of config option.

Returns
    Config value. May be any type accepted by ast.literal_eval <https://docs.python.org/3/library/ast.html#ast.literal_eval>.

Return type
    Any

set_state(section, name, value)
    Sets a state value.

Parameters

•   section (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of section in state file.

•   name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of state variable.

•   value (Any) -- State value. May be any type accepted by ast.literal_eval <https://docs.python.org/3/library/ast.html#ast.literal_eval>.

Return type
    None

get_state(section, name)
    Gets a state value.

Parameters

•   section (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of section in state file.

•   name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of state variable.

Returns
    State value. May be any type accepted by ast.literal_eval <https://docs.python.org/3/library/ast.html#ast.literal_eval>.

Return type
    Any

property dropbox_path: str <https://docs.python.org/3/library/stdtypes.html#str>
    Returns the path to the local Dropbox folder (read only). This will be an empty string if not Dropbox folder has been set up yet. Use create_dropbox_directory() or move_dropbox_directory() to set or change the Dropbox directory location instead.

Raises
    NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

property excluded_items: set <https://docs.python.org/3/library/stdtypes.html#set>[str <https://docs.python.org/3/library/stdtypes.html#str>]
    The list of files and folders excluded by selective sync.

    Any changes to this list will be applied immediately if we have already performed the initial sync. Paths which have been added to the list will be deleted from the local drive and paths which have been removed will be downloaded.

    If the initial was not yet performed, changes will only be saved for the initial sync.

    Use exclude_item() and include_item() to add or remove individual items from selective sync.

Return type
    set <https://docs.python.org/3/library/stdtypes.html#set>[str <https://docs.python.org/3/library/stdtypes.html#str>]

property log_level: int <https://docs.python.org/3/library/functions.html#int>
    Log level for log files, stderr and the systemd journal.

Return type
    int <https://docs.python.org/3/library/functions.html#int>

property notification_snooze: float <https://docs.python.org/3/library/functions.html#float>
    Snooze time for desktop notifications in minutes. Defaults to 0 if notifications are not snoozed.

Return type
    float <https://docs.python.org/3/library/functions.html#float>

property notification_level: int <https://docs.python.org/3/library/functions.html#int>
    Level for desktop notifications. See notify for level definitions.

Return type
    int <https://docs.python.org/3/library/functions.html#int>

property bandwidth_limit_down: float <https://docs.python.org/3/library/functions.html#float>
    Maximum download bandwidth to use in bytes per second.

Return type
    float <https://docs.python.org/3/library/functions.html#float>

property bandwidth_limit_up: float <https://docs.python.org/3/library/functions.html#float>
    Maximum download bandwidth to use in bytes per second.

Return type
    float <https://docs.python.org/3/library/functions.html#float>

status_change_longpoll(timeout=60)
    Blocks until there is a change in status or until a timeout occurs.

    This method can be used by frontends to wait for status changes without constant polling. Status changes are for example transitions from syncing to idle or vice-versa, new errors, or connection status changes.

    Will unblock at most once per second.

Parameters
    timeout (float <https://docs.python.org/3/library/functions.html#float> | None) -- Maximum time to block before returning, even if there is no status change.

Returns
    Whether there was a status change within the timeout.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

    Added in version 1.3.0.

property pending_link: bool <https://docs.python.org/3/library/functions.html#bool>
    Whether Maestral is linked to a Dropbox account (read only). This will block until the user's keyring is unlocked to load the saved auth token.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property pending_dropbox_folder: bool <https://docs.python.org/3/library/functions.html#bool>
    Whether a local Dropbox directory has been configured (read only). This will not check if the configured directory actually exists, starting the sync may still raise a maestral.exceptions.NoDropboxDirError <#maestral.exceptions.NoDropboxDirError>.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property pending_first_download: bool <https://docs.python.org/3/library/functions.html#bool>
    Whether the initial download has already started (read only).

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property paused: bool <https://docs.python.org/3/library/functions.html#bool>
    Whether syncing is paused by the user (read only). Use start_sync() and stop_sync() to start and stop syncing, respectively.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property running: bool <https://docs.python.org/3/library/functions.html#bool>
    Whether sync threads are running (read only). This is similar to paused but also returns False if syncing is paused because we cannot connect to Dropbox servers..

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property connected: bool <https://docs.python.org/3/library/functions.html#bool>
    Whether Dropbox servers can be reached (read only).

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property status: str <https://docs.python.org/3/library/stdtypes.html#str>
    The last status message (read only). This can be displayed as information to the user but should not be relied on otherwise.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

property sync_errors: list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncErrorEntry <#maestral.models.SyncErrorEntry>]
    A list of current sync errors as dicts (read only). This list is populated by the sync threads. The following keys will always be present but may contain empty values: "type", "inherits", "title", "traceback", "title", "message", "local_path", "dbx_path".

Raises
    NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncErrorEntry <#maestral.models.SyncErrorEntry>]

property fatal_errors: list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.exceptions.MaestralApiError <#maestral.exceptions.MaestralApiError>]
    Returns a list of fatal errors as dicts (read only). This does not include lost internet connections or file sync errors which only emit warnings and are tracked and cleared separately. Errors listed here must be acted upon for Maestral to continue syncing.

    The following keys will always be present but may contain empty values: "type", "inherits", "title", "traceback", "title", and "message".s

    This list is populated from all log messages with level ERROR or higher that have exc_info attached.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.exceptions.MaestralApiError <#maestral.exceptions.MaestralApiError>]

clear_fatal_errors()
    Manually clears all fatal errors. This should be used after they have been resolved by the user through the GUI or CLI.

Return type
    None

property account_profile_pic_path: str <https://docs.python.org/3/library/stdtypes.html#str>
    The path of the current account's profile picture (read only). There may not be an actual file at that path if the user did not set a profile picture or the picture has not yet been downloaded.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

get_file_status(local_path)
    Returns the sync status of a file or folder. The returned status is recursive for folders.

•   "uploading" if any file inside the folder is being uploaded.

•   "downloading" if any file inside the folder is being downloaded.

•   "error" if any item inside the folder failed to sync and none are currently being uploaded or downloaded.

•   "up to date" if all items are successfully synced.

•   "unwatched" if syncing is paused or for items outside the Dropbox directory.

    Added in version 1.4.4: Recursive behavior. Previous versions would return "up to date" for a folder, even if some contained files would be syncing.

Parameters
    local_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to file on the local drive. May be relative to the current working directory.

Returns
    String indicating the sync status. Can be 'uploading', 'downloading', 'up to date', 'error', or 'unwatched'.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

get_activity(limit=100)
    Returns the current upload / download activity.

Parameters
    limit (int <https://docs.python.org/3/library/functions.html#int> | None) -- Maximum number of items to return. If None, all entries will be returned.

Returns
    A lists of all sync events currently queued for or being uploaded or downloaded with the events the furthest up in the queue coming first.

Raises
    NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncEvent <#maestral.models.SyncEvent>]

get_history(dbx_path=None, limit=100)
    Returns the historic upload / download activity. Up to 1,000 sync events are kept in the database. Any events which occurred before the interval specified by the keep_history config value are discarded.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- If given, show sync history for the specified Dropbox path only.

•   limit (int <https://docs.python.org/3/library/functions.html#int> | None) -- Maximum number of items to return. If None, all entries will be returned.

Returns
    A lists of all sync events since keep_history sorted by time with the oldest event first.

Raises
    NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncEvent <#maestral.models.SyncEvent>]

get_account_info()
    Returns the account information from Dropbox and returns it as a dictionary.

Returns
    Dropbox account information.

Raises

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- in case of an invalid access token.

•   DropboxServerError <#maestral.exceptions.DropboxServerError> -- for internal Dropbox errors.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    maestral.core.FullAccount <#maestral.core.FullAccount>

get_space_usage()
    Gets the space usage from Dropbox and returns it as a dictionary.

Returns
    Dropbox space usage information.

Raises

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- in case of an invalid access token.

•   DropboxServerError <#maestral.exceptions.DropboxServerError> -- for internal Dropbox errors.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    maestral.core.PersonalSpaceUsage <#maestral.core.PersonalSpaceUsage>

get_profile_pic()
    Attempts to download the user's profile picture from Dropbox. The picture is saved in Maestral's cache directory for retrieval when there is no internet connection. Check account_profile_pic_path for cached profile pics.

Returns
    Path to saved profile picture or None if no profile picture was downloaded.

Raises

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- in case of an invalid access token.

•   DropboxServerError <#maestral.exceptions.DropboxServerError> -- for internal Dropbox errors.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str> | None

get_metadata(dbx_path)
    Returns metadata for a file or folder on Dropbox.

Parameters
    dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to file or folder on Dropbox.

Returns
    Dropbox item metadata as dict. See dropbox.files.Metadata <https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html#dropbox.files.Metadata> for keys and values.

Raises

•   NotFoundError <#maestral.exceptions.NotFoundError> -- if there is nothing at the given path.

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- in case of an invalid access token.

•   DropboxServerError <#maestral.exceptions.DropboxServerError> -- for internal Dropbox errors.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    maestral.core.Metadata <#maestral.core.Metadata> | None

list_folder(dbx_path, recursive=False, include_deleted=False, include_mounted_folders=True, include_non_downloadable_files=False)
    List all items inside the folder given by dbx_path. Keyword arguments are passed on the Dropbox API call client.DropboxClient.list_folder().

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to folder on Dropbox.

•   recursive (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders.

•   include_deleted (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, the results will include entries for files and folders that used to exist but were deleted.

•   include_mounted_folders (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder.

•   include_non_downloadable_files (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, include files that are not downloadable, i.e. Google Docs.

Raises

•   NotFoundError <#maestral.exceptions.NotFoundError> -- if there is nothing at the given path.

•   NotAFolderError <#maestral.exceptions.NotAFolderError> -- if the given path refers to a file.

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- in case of an invalid access token.

•   DropboxServerError <#maestral.exceptions.DropboxServerError> -- for internal Dropbox errors.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.core.Metadata <#maestral.core.Metadata>]

list_folder_iterator(dbx_path, recursive=False, include_deleted=False, include_mounted_folders=True, limit=None, include_non_downloadable_files=False)
    Returns an iterator over items inside the folder given by dbx_path. Keyword arguments are passed on the client call client.DropboxClient.list_folder_iterator(). Each iteration will yield a list of approximately 500 entries, depending on the number of entries returned by an individual API call.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to folder on Dropbox.

•   recursive (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders.

•   include_deleted (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, the results will include entries for files and folders that used to exist but were deleted.

•   include_mounted_folders (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder.

•   limit (Nullable[int <https://docs.python.org/3/library/functions.html#int>]) -- The maximum number of results to return per request. Note: This is an approximate number and there can be slightly more entries returned in some cases.

•   include_non_downloadable_files (bool <https://docs.python.org/3/library/functions.html#bool>) -- If true, include files that are not downloadable, i.e. Google Docs.

Returns
    Iterator over list of Dropbox item metadata as dicts. See dropbox.files.Metadata <https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html#dropbox.files.Metadata> for keys and values.

Raises

•   NotFoundError <#maestral.exceptions.NotFoundError> -- if there is nothing at the given path.

•   NotAFolderError <#maestral.exceptions.NotAFolderError> -- if the given path refers to a file.

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- in case of an invalid access token.

•   DropboxServerError <#maestral.exceptions.DropboxServerError> -- for internal Dropbox errors.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    Iterator[list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.core.Metadata <#maestral.core.Metadata>]]

list_revisions(dbx_path, limit=10)
    List revisions of old files at the given path dbx_path. This will also return revisions if the file has already been deleted.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to file on Dropbox.

•   limit (int <https://docs.python.org/3/library/functions.html#int>) -- Maximum number of revisions to list.

Returns
    List of Dropbox file metadata as dicts. See dropbox.files.Metadata <https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html#dropbox.files.Metadata> for keys and values.

Raises

•   NotFoundError <#maestral.exceptions.NotFoundError> -- if there never was a file at the given path.

•   IsAFolderError <#maestral.exceptions.IsAFolderError> -- if the given path refers to a folder

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- in case of an invalid access token.

•   DropboxServerError <#maestral.exceptions.DropboxServerError> -- for internal Dropbox errors.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.core.FileMetadata <#maestral.core.FileMetadata>]

get_file_diff(old_rev, new_rev=None)
    Compare to revisions of a text file using Python's difflib. The versions will be downloaded to temporary files. If new_rev is None, the old revision will be compared to the corresponding local file, if any.

Parameters

•   old_rev (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Identifier of old revision.

•   new_rev (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Identifier of new revision.

Returns
    Diff as a list of strings (lines).

Raises

•   UnsupportedFileTypeForDiff <#maestral.exceptions.UnsupportedFileTypeForDiff> -- if file type is not supported.

•   UnsupportedFileTypeForDiff <#maestral.exceptions.UnsupportedFileTypeForDiff> -- if file content could not be decoded.

•   MaestralApiError <#maestral.exceptions.MaestralApiError> -- if file could not be read for any other reason.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[str <https://docs.python.org/3/library/stdtypes.html#str>]

restore(dbx_path, rev)
    Restore an old revision of a file.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The path to save the restored file.

•   rev (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The revision to restore. Old revisions can be listed with list_revisions().

Returns
    Metadata of the returned file. See dropbox.files.FileMetadata <https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html#dropbox.files.FileMetadata> for keys and values.

Raises

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- in case of an invalid access token.

•   DropboxServerError <#maestral.exceptions.DropboxServerError> -- for internal Dropbox errors.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

Return type
    maestral.core.FileMetadata <#maestral.core.FileMetadata>

rebuild_index()
    Rebuilds the rev file by comparing remote with local files and updating rev numbers from the Dropbox server. Files are compared by their content hashes and conflicting copies are created if the contents differ. File changes during the rebuild process will be queued and uploaded once rebuilding has completed.

    Rebuilding will be performed asynchronously and errors can be accessed through sync_errors or maestral_errors.

Raises

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

•   NoDropboxDirError <#maestral.exceptions.NoDropboxDirError> -- if local Dropbox folder is not set up.

Return type
    None

start_sync()
    Creates syncing threads and starts syncing.

Raises

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

•   NoDropboxDirError <#maestral.exceptions.NoDropboxDirError> -- if local Dropbox folder is not set up.

Return type
    None

stop_sync()
    Stops all syncing threads if running. Call start_sync() to restart syncing.

Return type
    None

reset_sync_state()
    Resets the sync index and state. Only call this to clean up leftover state information if a Dropbox was improperly unlinked (e.g., auth token has been manually deleted). Otherwise, leave state management to Maestral.

Raises
    NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    None

exclude_items(*dbx_paths)
    Excludes files or folders from sync and deletes it locally. It is safe to call this method with items which have already been excluded.

Parameters
    dbx_paths (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Dropbox paths of items to exclude.

Raises

•   NotFoundError <#maestral.exceptions.NotFoundError> -- if there is nothing at the given path.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- in case of an invalid access token.

•   DropboxServerError <#maestral.exceptions.DropboxServerError> -- for internal Dropbox errors.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

•   NoDropboxDirError <#maestral.exceptions.NoDropboxDirError> -- if local Dropbox folder is not set up.

Return type
    None

include_items(*dbx_paths)
    Includes files or folders in sync and downloads it in the background. It is safe to call this method with items which have already been included, they will not be downloaded again.

    If the path lies inside an excluded folder, all its immediate parents will be included. Other children of the excluded folder will remain excluded.

    If any children of dbx_path were excluded, they will now be included.

    Any downloads will be carried out by the sync threads. Errors during the download can be accessed through sync_errors or maestral_errors.

Parameters
    dbx_paths (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Dropbox paths of items to include.

Raises

•   NotFoundError <#maestral.exceptions.NotFoundError> -- if there is nothing at the given path.

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- in case of an invalid access token.

•   DropboxServerError <#maestral.exceptions.DropboxServerError> -- for internal Dropbox errors.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

•   NoDropboxDirError <#maestral.exceptions.NoDropboxDirError> -- if local Dropbox folder is not set up.

Return type
    None

excluded_status(dbx_path)
    Returns 'excluded', 'partially excluded' or 'included'. This function will not check if the item actually exists on Dropbox.

Parameters
    dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to item on Dropbox.

Returns
    Excluded status.

Raises
    NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

move_dropbox_directory(new_path)
    Sets the local Dropbox directory. This moves all local files to the new location and resumes syncing afterwards.

Parameters
    new_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Full path to local Dropbox folder. "~" will be expanded to the user's home directory.

Raises

•   OSError <https://docs.python.org/3/library/exceptions.html#OSError> -- if moving the directory fails.

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

•   NoDropboxDirError <#maestral.exceptions.NoDropboxDirError> -- if local Dropbox folder is not set up.

Return type
    None

create_dropbox_directory(path)
    Creates a new Dropbox directory. Only call this during setup.

Parameters
    path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Full path to local Dropbox folder. "~" will be expanded to the user's home directory.

Raises

•   OSError <https://docs.python.org/3/library/exceptions.html#OSError> -- if creation fails.

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    None

create_shared_link(dbx_path, visibility=LinkAudience.Public, access_level=LinkAccessLevel.Viewer, allow_download=None, password=None, expires=None)
    Creates a shared link for the given dbx_path. Returns a dictionary with information regarding the link, including the URL, access permissions, expiry time, etc. The shared link will grant read / download access only. Note that basic accounts do not support password protection or expiry times.

Parameters

•   dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Dropbox path to file or folder to share.

•   visibility (maestral.core.LinkAudience <#maestral.core.LinkAudience>) -- The visibility of the shared link. Can be public, team-only, or no-one. In case of the latter, the link merely points the user to the content and does not grant additional rights to the user. Users of this link can only access the content with their pre-existing access rights.

•   access_level (maestral.core.LinkAccessLevel <#maestral.core.LinkAccessLevel>) -- The level of access granted with the link. Can be viewer, editor, or max for maximum possible access level.

•   allow_download (bool <https://docs.python.org/3/library/functions.html#bool> | None) -- Whether to allow download capabilities for the link.

•   password (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- If given, enables password protection for the link.

•   expires (datetime.datetime <https://docs.python.org/3/library/datetime.html#datetime.datetime> | None) -- Expiry time for shared link. If no timezone is given, assume UTC. May not be supported for all account types.

Returns
    Metadata for shared link.

Return type
    maestral.core.SharedLinkMetadata <#maestral.core.SharedLinkMetadata>

revoke_shared_link(url)
    Revokes the given shared link. Note that any other links to the same file or folder will remain valid.

Parameters
    url (str <https://docs.python.org/3/library/stdtypes.html#str>) -- URL of shared link to revoke.

Raises

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- in case of an invalid access token.

•   DropboxServerError <#maestral.exceptions.DropboxServerError> -- for internal Dropbox errors.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    None

list_shared_links(dbx_path=None)
    Returns a list of all shared links for the given Dropbox path. If no path is given, return all shared links for the account, up to a maximum of 1,000 links.

Parameters
    dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None) -- Path to item on Dropbox.

Returns
    List of shared link information as dictionaries. See dropbox.sharing.SharedLinkMetadata <https://dropbox-sdk-python.readthedocs.io/en/latest/api/sharing.html#dropbox.sharing.SharedLinkMetadata> for keys and values.

Raises

•   DropboxAuthError <#maestral.exceptions.DropboxAuthError> -- in case of an invalid access token.

•   DropboxServerError <#maestral.exceptions.DropboxServerError> -- for internal Dropbox errors.

•   ConnectionError <https://docs.python.org/3/library/exceptions.html#ConnectionError> -- if the connection to Dropbox fails.

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.core.SharedLinkMetadata <#maestral.core.SharedLinkMetadata>]

to_local_path(dbx_path)
    Converts a path relative to the Dropbox folder to a correctly cased local file system path.

Parameters
    dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path relative to Dropbox root.

Returns
    Corresponding path on local hard drive.

Raises

•   NotLinkedError <#maestral.exceptions.NotLinkedError> -- if no Dropbox account is linked.

•   NoDropboxDirError <#maestral.exceptions.NoDropboxDirError> -- if local Dropbox folder is not set up.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

check_for_updates()
    Checks if an update is available.

Returns
    A dictionary with information about the latest release with the fields 'update_available' (bool), 'latest_release' (str), 'release_notes' (str) and 'error' (str or None).

Raises
    UpdateCheckError <#maestral.exceptions.UpdateCheckError> -- if checking for an update fails.

Return type
    maestral.core.UpdateCheckResult <#maestral.core.UpdateCheckResult>

shutdown_daemon()
    Stop syncing and notify anyone monitoring shutdown_future that we are done.

Return type
    None

MAESTRAL.MANAGER

This module contains the classes to coordinate sync threads.

  Module Contents

class maestral.manager.SyncManager(sync, desktop_notifier=None)
    Class to manage sync threads

Parameters

•   sync (maestral.sync.SyncEngine <#maestral.sync.SyncEngine>) -- The SyncEngine.

•   desktop_notifier (maestral.notify.MaestralDesktopNotifier <#maestral.notify.MaestralDesktopNotifier> | None) -- Used to send desktop notifications for management-level events such as joining or leaving a team or fatal errors.

download_queue: PersistentQueue[str <https://docs.python.org/3/library/stdtypes.html#str>]
    Queue of remote paths which have been newly included in syncing.

sync

desktop_notifier = None

running

startup_completed

autostart

connection_check_interval = 10

connected = False

connection_helper

local_observer_thread: maestral.fsevents.ObserverType | None <https://docs.python.org/3/library/constants.html#None> = None

property idle_time: float <https://docs.python.org/3/library/functions.html#float>
    Returns the idle time in seconds since the last file change or since startup if there haven't been any changes in our current session.

Return type
    float <https://docs.python.org/3/library/functions.html#float>

start()
    Creates observer threads and starts syncing.

Return type
    None

stop()
    Stops syncing and destroys worker threads.

Return type
    None

reset_sync_state()
    Resets all saved sync state. Settings are not affected.

Return type
    None

rebuild_index()
    Rebuilds the rev file by comparing remote with local files and updating rev numbers from the Dropbox server. Files are compared by their content hashes and conflicting copies are created if the contents differ. File changes during the rebuild process will be queued and uploaded once rebuilding has completed.

    Rebuilding will be performed asynchronously.

Return type
    None

check_and_update_path_root()
    Checks if the user's root namespace corresponds to the currently configured path root. Updates the root namespace if required and migrates the local folder structure. Syncing will be paused during the migration.

Returns
    Whether the path root was updated.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

connection_monitor()
    Monitors the connection to Dropbox servers. Pauses syncing when the connection is lost and resumes syncing when reconnected and syncing has not been paused by the user.

Return type
    None

download_worker(running, startup_completed, autostart)
    Worker to sync changes of remote Dropbox with local folder.

Parameters

•   running (threading.Event <https://docs.python.org/3/library/threading.html#threading.Event>) -- Event to shut down local file event handler and worker threads.

•   startup_completed (threading.Event <https://docs.python.org/3/library/threading.html#threading.Event>) -- Set when startup sync is completed.

•   autostart (threading.Event <https://docs.python.org/3/library/threading.html#threading.Event>) -- Set when syncing should automatically resume on connection.

Return type
    None

download_worker_added_item(running, startup_completed, autostart)
    Worker to download items which have been newly included in sync.

Parameters

•   running (threading.Event <https://docs.python.org/3/library/threading.html#threading.Event>) -- Event to shut down local file event handler and worker threads.

•   startup_completed (threading.Event <https://docs.python.org/3/library/threading.html#threading.Event>) -- Set when startup sync is completed.

•   autostart (threading.Event <https://docs.python.org/3/library/threading.html#threading.Event>) -- Set when syncing should automatically resume on connection.

Return type
    None

upload_worker(running, startup_completed, autostart)
    Worker to sync local changes to remote Dropbox.

Parameters

•   running (threading.Event <https://docs.python.org/3/library/threading.html#threading.Event>) -- Event to shut down local file event handler and worker threads.

•   startup_completed (threading.Event <https://docs.python.org/3/library/threading.html#threading.Event>) -- Set when startup sync is completed.

•   autostart (threading.Event <https://docs.python.org/3/library/threading.html#threading.Event>) -- Set when syncing should automatically resume on connection.

Return type
    None

startup_worker(running, startup_completed, autostart)
    Worker to sync local changes to remote Dropbox.

Parameters

•   running (threading.Event <https://docs.python.org/3/library/threading.html#threading.Event>) -- Event to shut down local file event handler and worker threads.

•   startup_completed (threading.Event <https://docs.python.org/3/library/threading.html#threading.Event>) -- Set when startup sync is completed.

•   autostart (threading.Event <https://docs.python.org/3/library/threading.html#threading.Event>) -- Set when syncing should automatically resume on connection.

Return type
    None

MAESTRAL.MODELS

This module contains the definitions of our database tables which store the index, sync history and cache of content hashes. Each table is defined by a subclass of maestral.database.orm.Model <#maestral.database.orm.Model> with properties representing database columns. Class instances then represent table rows.

  Module Contents

class maestral.models.SyncDirection
    Bases: enum.Enum <https://docs.python.org/3/library/enum.html#enum.Enum>

    Enumeration of sync directions

Up = 'up'

Down = 'down'

class maestral.models.SyncStatus
    Bases: enum.Enum <https://docs.python.org/3/library/enum.html#enum.Enum>

    Enumeration of sync status

Queued = 'queued'

Syncing = 'syncing'

Done = 'done'

Failed = 'failed'

Skipped = 'skipped'

Aborted = 'aborted'

Conflict = 'conflict'

class maestral.models.ItemType
    Bases: enum.Enum <https://docs.python.org/3/library/enum.html#enum.Enum>

    Enumeration of SyncEvent types

File = 'file'

Folder = 'folder'

Unknown = 'unknown'

class maestral.models.ChangeType
    Bases: enum.Enum <https://docs.python.org/3/library/enum.html#enum.Enum>

    Enumeration of SyncEvent change types

Added = 'added'

Removed = 'removed'

Moved = 'moved'

Modified = 'modified'

class maestral.models.SyncEvent(**kwargs)
    Bases: maestral.database.orm.Model <#maestral.database.orm.Model>

    Represents a file or folder change in the sync queue

    This class is used to represent both local and remote file system changes and track their sync progress. Some instance attributes will depend on the state of the sync session, e.g., local_path will depend on the current path of the local Dropbox folder. They may therefore become invalid between sync sessions.

    The class methods from_dbx_metadata() and from_file_system_event() should be used to properly construct a SyncEvent from a dropbox.files.Metadata <https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html#dropbox.files.Metadata> instance or a watchdog.events.FileSystemEvent <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.events.FileSystemEvent> instance, respectively.

Parameters
    kwargs (Any)

id  A unique identifier of the SyncEvent.

direction
    The SyncDirection.

item_type
    The ItemType. May be undetermined for remote deletions.

sync_time
    Timestamp in Unix epoch seconds the SyncEvent was registered.

dbx_id
    A unique dropbox ID for the file or folder. Will only be set for download events which are not deletions.

dbx_path
    Correctly cased Dropbox path of the item to sync. If the sync represents a move operation, this will be the destination path. Follows the casing from the path_display attribute of Dropbox metadata.

dbx_path_lower
    Dropbox path of the item to sync. If the sync represents a move operation, this will be the destination path. This is normalised as the path_lower attribute of Dropbox metadata.

local_path
    Local path of the item to sync. If the sync represents a move operation, this will be the destination path. This will be correctly cased.

dbx_path_from
    Dropbox path that this item was moved from. Will only be set if change_type is ChangeType.Moved. Follows the casing from the path_display attribute of Dropbox metadata.

dbx_path_from_lower
    Dropbox path that this item was moved from. Will only be set if change_type is ChangeType.Moved. This is normalised as the path_lower attribute of Dropbox metadata.

local_path_from
    Local path that this item was moved from. Will only be set if change_type is ChangeType.Moved. This will be correctly cased.

rev The file revision. Will only be set for remote changes. Will be 'folder' for folders and None for deletions.

content_hash
    A hash representing the file content. Will be 'folder' for folders and None for deletions. Set for both local and remote changes.

symlink_target
    If the file is a symlink, its target path. This should only be set for files.

change_type
    The ChangeType. Remote SyncEvents currently do not generate moved events but are reported as deleted and added at the new location.

change_time
    Timestamp in Unix epoch seconds when the file was last modified.

    Local ctime or remote client_modified time for files. None for folders or for remote deletions. Note that client_modified may not be reliable as it is set by other clients and not verified.

change_dbid
    The Dropbox ID of the account which performed the changes. This may not be set for added folders or deletions on the server.

change_user_name
    The user name corresponding to change_dbid, if the account still exists. This field may not be set for performance reasons.

status
    The SyncStatus.

size
    Size of the item in bytes. Always zero for folders.

completed
    File size in bytes which has already been uploaded or downloaded. Always zero for folders.

property change_time_or_sync_time: float <https://docs.python.org/3/library/functions.html#float>
    Change time when available, otherwise sync time. This can be used for sorting or user information purposes.

Return type
    float <https://docs.python.org/3/library/functions.html#float>

property is_file: bool <https://docs.python.org/3/library/functions.html#bool>
    Returns True for file changes

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property is_directory: bool <https://docs.python.org/3/library/functions.html#bool>
    Returns True for folder changes

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property is_added: bool <https://docs.python.org/3/library/functions.html#bool>
    Returns True for added items

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property is_moved: bool <https://docs.python.org/3/library/functions.html#bool>
    Returns True for moved items

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property is_changed: bool <https://docs.python.org/3/library/functions.html#bool>
    Returns True for changed file contents

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property is_deleted: bool <https://docs.python.org/3/library/functions.html#bool>
    Returns True for deleted items

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property is_upload: bool <https://docs.python.org/3/library/functions.html#bool>
    Returns True for changes to upload

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property is_download: bool <https://docs.python.org/3/library/functions.html#bool>
    Returns True for changes to download

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

classmethod from_metadata(md, sync_engine)
    Initializes a SyncEvent from the given Dropbox metadata.

Parameters

•   md (maestral.core.Metadata <#maestral.core.Metadata>) -- Dropbox Metadata.

•   sync_engine (maestral.sync.SyncEngine <#maestral.sync.SyncEngine>) -- SyncEngine instance.

Returns
    An instance of this class with attributes populated from the given Dropbox Metadata.

Return type
    SyncEvent <#maestral.models.SyncEvent>

classmethod from_file_system_event(event, sync_engine)
    Initializes a SyncEvent from the given local file system event.

Parameters

•   event (watchdog.events.FileSystemEvent <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.events.FileSystemEvent>) -- Local file system event.

•   sync_engine (maestral.sync.SyncEngine <#maestral.sync.SyncEngine>) -- SyncEngine instance.

Returns
    An instance of this class with attributes populated from the given SyncEvent.

Return type
    SyncEvent <#maestral.models.SyncEvent>

class maestral.models.IndexEntry(**kwargs)
    Bases: maestral.database.orm.Model <#maestral.database.orm.Model>

    Represents an entry in our local sync index

Parameters
    kwargs (Any)

dbx_path_lower
    Dropbox path of the item in lower case. This acts as a primary key for the SQLites database since there can only be one entry per case-insensitive Dropbox path. Corresponds to the path_lower field of Dropbox metadata.

dbx_path_cased
    Dropbox path of the item, correctly cased. Corresponds to the path_display field of Dropbox metadata.

dbx_id
    The unique dropbox ID for the item.

item_type
    The ItemType.

last_sync
    The last time a local change was uploaded. Should be the ctime of the local item.

rev The file revision. Will be 'folder' for folders.

content_hash
    A hash representing the file content. Will be 'folder' for folders. May be None if not yet calculated.

symlink_target
    If the file is a symlink, its target path. This should only be set for files.

property is_file: bool <https://docs.python.org/3/library/functions.html#bool>
    Returns True for files

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property is_directory: bool <https://docs.python.org/3/library/functions.html#bool>
    Returns True for folders

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property is_symlink: bool <https://docs.python.org/3/library/functions.html#bool>
    Returns True for symlinks

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

class maestral.models.HashCacheEntry(**kwargs)
    Bases: maestral.database.orm.Model <#maestral.database.orm.Model>

    Represents an entry in our cache of content hashes

Parameters
    kwargs (Any)

inode
    The inode of the item.

local_path
    The local path of the item.

hash_str
    The content hash of the item.

mtime
    The mtime of the item just before the hash was computed. When the current mtime is newer, the hash will need to be recalculated.

class maestral.models.SyncErrorEntry(**kwargs)
    Bases: maestral.database.orm.Model <#maestral.database.orm.Model>

    Table of sync errors

Parameters
    kwargs (Any)

dbx_path

dbx_path_lower

dbx_path_from

dbx_path_from_lower

local_path

local_path_from

direction

title

message

type

MAESTRAL.NOTIFY

This module handles desktop notifications It uses the desktop-notifier <https://desktop-notifier.readthedocs.io/en/latest/> package as a backend for cross-platform desktop notifications.

  Module Contents

maestral.notify.NONE = 100
    No desktop notifications

maestral.notify.ERROR = 40
    Notify only on fatal errors

maestral.notify.SYNCISSUE = 30
    Notify for sync issues and higher

maestral.notify.FILECHANGE = 15
    Notify for all remote file changes

maestral.notify.level_number_to_name(number)
    Converts a Maestral notification level number to name.

Parameters
    number (int <https://docs.python.org/3/library/functions.html#int>) -- Level number.

Returns
    Level name.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.notify.level_name_to_number(name)
    Converts a Maestral notification level name to number.

Parameters
    name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Level name.

Returns
    Level number.

Return type
    int <https://docs.python.org/3/library/functions.html#int>

class maestral.notify.MaestralDesktopNotifier(config_name, event_loop)
    Desktop notification emitter for Maestral

    Desktop notifier with snooze functionality and variable notification levels. Must be instantiated in the main thread.

Parameters

•   config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Config name. This is used to access notification settings for the daemon.

•   event_loop (asyncio.AbstractEventLoop <https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop>) -- Event loop to use to send notifications and receive callbacks.

property notify_level: int <https://docs.python.org/3/library/functions.html#int>
    Custom notification level. Notifications with a lower level will be discarded.

Return type
    int <https://docs.python.org/3/library/functions.html#int>

property snoozed: float <https://docs.python.org/3/library/functions.html#float>
    Time in minutes to snooze notifications. Applied to FILECHANGE level only.

Return type
    float <https://docs.python.org/3/library/functions.html#float>

notify(title, message, level=FILECHANGE, on_click=None, actions=None)
    Sends a desktop notification. This will schedule a notification task in the asyncio loop of the thread where DesktopNotifier was instantiated.

Parameters

•   title (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Notification title.

•   message (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Notification message.

•   level (int <https://docs.python.org/3/library/functions.html#int>) -- Notification level of the message.

•   on_click (Callable[[], Any] | None) -- A callback to execute when the notification is clicked. The provided callable must not take any arguments.

•   actions (dict <https://docs.python.org/3/library/stdtypes.html#dict>[str <https://docs.python.org/3/library/stdtypes.html#str>, Callable[[], Any]] | None) -- A dictionary with button names and callbacks for the notification.

Return type
    None

MAESTRAL.KEYRING

This module is responsible for authorization and token store in the system keyring.

  Module Contents

class maestral.keyring.CredentialStorage(config_name)
    Provides a threadsafe interface to store credentials in a system keyring

    CredentialStorage provides token store in the preferred system keyring. Supported keyring backends are, in order of preference:

•   macOS Keychain

•   Any keyring implementing the SecretService Dbus specification

•   KWallet

•   Plain text storage

    Note: Once the token has been stored with a keyring backend, that backend will be saved in the config file and remembered until deleting the credentials.

    Warning: Unlike macOS Keychain, Gnome Keyring and KWallet do not support app-specific access to passwords. If the user unlocks those keyrings, we and any other application in the same user session get access to all saved passwords.

Parameters
    config_name (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Name of maestral config.

property keyring: keyring.backend.KeyringBackend <https://keyring.readthedocs.io/en/latest/index.html#keyring.backend.KeyringBackend> | None <https://docs.python.org/3/library/constants.html#None>
    The keyring backend currently being used to store auth tokens. Will be None if we are not linked.

Return type
    keyring.backend.KeyringBackend <https://keyring.readthedocs.io/en/latest/index.html#keyring.backend.KeyringBackend> | None

set_keyring_backend(ring)
    Enforce usage of a particular keyring backend. If not called, the best backend will be selected depending on the platform. Do not change backends after saving credentials.

Parameters
    ring (keyring.backend.KeyringBackend <https://keyring.readthedocs.io/en/latest/index.html#keyring.backend.KeyringBackend> | None) -- Keyring backend to use.

Return type
    None

property loaded: bool <https://docs.python.org/3/library/functions.html#bool>
    Whether we have already loaded the credentials. This will be true after calling load_creds() or accessing the any of the auth credentials through instance properties.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property token: str <https://docs.python.org/3/library/stdtypes.html#str> | None <https://docs.python.org/3/library/constants.html#None>
    The saved token (read only). This call will block until the keyring is unlocked.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str> | None

property account_id: str <https://docs.python.org/3/library/stdtypes.html#str> | None <https://docs.python.org/3/library/constants.html#None>
    The saved account id (read only).

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str> | None

load_creds()
    Loads auth token from system keyring. This will be called automatically when accessing the token property. This call will block until the keyring is unlocked or unlocking is declined by the user.

Raises
    KeyringAccessError <#maestral.exceptions.KeyringAccessError> -- if the system keyring is locked or otherwise cannot be accessed (for example if the app bundle signature has been invalidated).

Return type
    None

save_creds(account_id, token)
    Saves the auth token to system keyring. Falls back to plain text storage if the user denies access to keyring.

Parameters

•   account_id (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The account ID.

•   token (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The access token.

Return type
    None

delete_creds()
    Deletes auth token from system keyring.

Raises
    KeyringAccessError <#maestral.exceptions.KeyringAccessError> -- if the system keyring is locked or otherwise cannot be accessed (for example if the app bundle signature has been invalidated).

Return type
    None

MAESTRAL.SYNC

This module contains the main syncing functionality.

  Module Contents

class maestral.sync.Conflict
    Bases: enum.Enum <https://docs.python.org/3/library/enum.html#enum.Enum>

    Enumeration of sync conflict types

RemoteNewer = 'remote newer'

Conflict = 'conflict'

Identical = 'identical'

LocalNewerOrIdentical = 'local newer or identical'

class maestral.sync.FSEventHandler(file_event_types=(EVENT_TYPE_CREATED, EVENT_TYPE_DELETED, EVENT_TYPE_MODIFIED, EVENT_TYPE_MOVED), dir_event_types=(EVENT_TYPE_CREATED, EVENT_TYPE_DELETED, EVENT_TYPE_MOVED))
    Bases: watchdog.events.FileSystemEventHandler <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.events.FileSystemEventHandler>

    A local file event handler

    Handles captured file events and adds them to SyncEngine's file event queue to be uploaded by upload_worker(). This acts as a translation layer between watchdog.Observer and SyncEngine.

    White lists of event types to handle are supplied as file_event_types and dir_event_types. This is for forward compatibility as additional event types may be added to watchdog in the future.

Parameters

•   file_event_types (tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, Ellipsis]) -- Types of file events to handle. Acts as an allow list.

•   dir_event_types (tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[str <https://docs.python.org/3/library/stdtypes.html#str>, Ellipsis]) -- Types of folder events to handle. Acts as an allow list.

Variables
    ignore_timeout (float <https://docs.python.org/3/library/functions.html#float>) -- Timeout in seconds after which filters for ignored events will expire.

local_file_event_queue: queue.Queue <https://docs.python.org/3/library/queue.html#queue.Queue>[watchdog.events.FileSystemEvent <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.events.FileSystemEvent>]

has_events

file_event_types

dir_event_types

ignore_timeout = 2.0

property enabled: bool <https://docs.python.org/3/library/functions.html#bool>
    Whether queuing of events is enabled.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

enable()
    Turn on queueing of events.

Return type
    None

disable()
    Turn off queueing of new events and remove all events from queue.

Return type
    None

ignore(*events, recursive=True)
    A context manager to ignore local file events

    Once a matching event has been registered, further matching events will no longer be ignored unless recursive is True. If no matching event has occurred before leaving the context, the event will be ignored for ignore_timeout sec after leaving then context and then discarded. This accounts for possible delays in the emission of local file system events.

    This context manager is used to filter out file system events caused by maestral itself, for instance during a download or when moving a conflict.

Example
    Prevent triggereing a sync event when creating a local file:

        >>> from watchdog.events import FileCreatedEvent
        >>> from maestral.main import Maestral
        >>> m = Maestral()
        >>> with m.sync.fs_events.ignore(FileCreatedEvent('path')):
        ...     open('path').close()

Parameters

•   events (watchdog.events.FileSystemEvent <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.events.FileSystemEvent>) -- Local events to ignore.

•   recursive (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, all child events of a directory event will be ignored as well. This parameter will be ignored for file events.

Return type
    Iterator[None]

expire_ignored_events()
    Removes all expired ignore entries.

Return type
    None

on_any_event(event)
    Checks if the system file event should be ignored. If not, adds it to the queue for events to upload. If syncing is paused or stopped, all events will be ignored.

Parameters
    event (watchdog.events.FileSystemEvent <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.events.FileSystemEvent>) -- Watchdog file event.

Return type
    None

queue_event(event)
    Queues an individual file system event. Notifies / wakes up all threads that are waiting with wait_for_event().

Parameters
    event (watchdog.events.FileSystemEvent <https://python-watchdog.readthedocs.io/en/latest/api.html#watchdog.events.FileSystemEvent>) -- File system event to queue.

Return type
    None

wait_for_event(timeout=40)
    Blocks until an event is available in the queue or a timeout occurs, whichever comes first. You can use with method to wait for file system events in another thread.

    Note: If there are multiple threads waiting for events, all of them will be notified. If one of those threads starts getting events from local_file_event_queue, other threads may find that the queue is empty despite being woken. You should therefore be prepared to handle an empty queue even if this method returns True.

Parameters
    timeout (float <https://docs.python.org/3/library/functions.html#float>) -- Maximum time to block in seconds.

Returns
    True if an event is available, False if the call returns due to a timeout.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

class maestral.sync.ActivityNode(name, sync_events=(), parent=None)
    A node in a sparse tree to represent syncing activity.

    Each node represents an item in the local Dropbox folder. Apart from the root node, items will only be present if they or any of their children have any sync activity.

Attr children
    All children with sync activity. Leaf nodes must represent items that are being uploaded, downloaded, or have a sync error.

Attr sync_events
    All SyncEvents of this node and its children.

Parameters

•   name (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   sync_events (Iterable[maestral.models.SyncEvent <#maestral.models.SyncEvent>])

•   parent (ActivityNode <#maestral.sync.ActivityNode> | None)

name

parent = None

children: dict <https://docs.python.org/3/library/stdtypes.html#dict>[str <https://docs.python.org/3/library/stdtypes.html#str>, ActivityNode <#maestral.sync.ActivityNode>]

sync_events

class maestral.sync.ActivityTree
    Bases: ActivityNode

    The root node in a sync activity tree. Represents Dropbox root.

add(event)

Parameters
    event (maestral.models.SyncEvent <#maestral.models.SyncEvent>)

Return type
    None

remove(event)

Parameters
    event (maestral.models.SyncEvent <#maestral.models.SyncEvent>)

Return type
    None

discard(event)

Parameters
    event (maestral.models.SyncEvent <#maestral.models.SyncEvent>)

Return type
    None

has_path(dbx_path)

Parameters
    dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

get_node(dbx_path)

Parameters
    dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    ActivityNode <#maestral.sync.ActivityNode> | None

class maestral.sync.SyncEngine(client, desktop_notifier=None)
    Class that handles syncing with Dropbox

    Provides methods to wait for local or remote changes and sync them, including conflict resolution and updates to our index.

Parameters

•   client (maestral.client.DropboxClient <#maestral.client.DropboxClient>) -- Dropbox API client instance.

•   desktop_notifier (maestral.notify.MaestralDesktopNotifier <#maestral.notify.MaestralDesktopNotifier> | None) -- Desktop notifier instance to use for user notifications.

client

config_name

fs_events

desktop_notifier = None

sync_lock

activity

reload_cached_config()
    Reloads all config and state values that are otherwise cached by this class for faster access. Call this method if config or state values where modified directly instead of using SyncEngine APIs.

Return type
    None

property dropbox_path: str <https://docs.python.org/3/library/stdtypes.html#str>
    Path to local Dropbox folder, as loaded from the config file. Before changing dropbox_path, make sure that syncing is paused. Move the dropbox folder to the new location before resuming the sync. Changes are saved to the config file.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

property is_fs_case_sensitive: bool <https://docs.python.org/3/library/functions.html#bool>
    Whether the local Dropbox directory lies on a case-sensitive file system.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

property database_path: str <https://docs.python.org/3/library/stdtypes.html#str>
    Path SQLite database.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

property file_cache_path: str <https://docs.python.org/3/library/stdtypes.html#str>
    Path to cache folder for temporary files (read only). The cache folder '.maestral.cache' is located inside the local Dropbox folder to prevent file transfer between different partitions or drives during sync.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

property excluded_items: set <https://docs.python.org/3/library/stdtypes.html#set>[str <https://docs.python.org/3/library/stdtypes.html#str>]
    Set of all files and folders excluded from sync. Changes are saved to the config file. If a parent folder is excluded, its children will automatically be removed from the list. If only children are given but not the parent folder, any new items added to the parent will be synced. Change this property before downloading newly included items or deleting excluded items.

Return type
    set <https://docs.python.org/3/library/stdtypes.html#set>[str <https://docs.python.org/3/library/stdtypes.html#str>]

static clean_excluded_items_list(dbx_paths)
    Removes all duplicates and children of excluded items from the excluded items list. Normalises all paths to lower case.

Parameters
    dbx_paths (Collection[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- Dropbox paths to exclude.

Returns
    Cleaned up items.

Return type
    set <https://docs.python.org/3/library/stdtypes.html#set>[str <https://docs.python.org/3/library/stdtypes.html#str>]

property max_cpu_percent: float <https://docs.python.org/3/library/functions.html#float>
    Maximum CPU usage for parallel downloads or uploads in percent of the total available CPU time per core. Individual workers in a thread pool will pause until the usage drops below this value. Tasks in the main thread such as indexing file changes may still use more CPU time. Setting this to 200% means that two full logical CPU core can be used.

Return type
    float <https://docs.python.org/3/library/functions.html#float>

property remote_cursor: str <https://docs.python.org/3/library/stdtypes.html#str>
    Cursor from last sync with remote Dropbox. The value is updated and saved to the config file on every successful download of remote changes.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

property local_cursor: float <https://docs.python.org/3/library/functions.html#float>
    Time stamp from last sync with remote Dropbox. The value is updated and saved to the config file on every successful upload of local changes.

Return type
    float <https://docs.python.org/3/library/functions.html#float>

property last_change: float <https://docs.python.org/3/library/functions.html#float>
    The time stamp of the last file change or 0.0 if there are no file changes in our history.

Return type
    float <https://docs.python.org/3/library/functions.html#float>

property last_reindex: float <https://docs.python.org/3/library/functions.html#float>
    Time stamp of last full indexing. This is used to determine when the next full indexing should take place.

Return type
    float <https://docs.python.org/3/library/functions.html#float>

get_history(dbx_path=None)
    A list of the last SyncEvents in our history. History will be kept for the interval specified by the config value keep_history (defaults to two weeks) but at most 1,000 events will be kept.

Parameters
    dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str> | None)

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncEvent <#maestral.models.SyncEvent>]

reset_sync_state()
    Resets all saved sync state. Settings are not affected.

Return type
    None

property sync_errors: list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncErrorEntry <#maestral.models.SyncErrorEntry>]
    Returns a list of all sync errors.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncErrorEntry <#maestral.models.SyncErrorEntry>]

property upload_errors: list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncErrorEntry <#maestral.models.SyncErrorEntry>]
    Returns a list of all upload errors.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncErrorEntry <#maestral.models.SyncErrorEntry>]

property download_errors: list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncErrorEntry <#maestral.models.SyncErrorEntry>]
    Returns a list of all download errors.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncErrorEntry <#maestral.models.SyncErrorEntry>]

has_sync_errors()
    Returns True in case of sync errors, False otherwise.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

sync_errors_for_path(dbx_path_lower, direction=None)
    Returns a list of all sync errors for the given path and its children.

Parameters

•   dbx_path_lower (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Normalised Dropbox path.

•   direction (maestral.models.SyncDirection <#maestral.models.SyncDirection> | None) -- Direction to filter sync errors. If not given, both upload and download errors will be returned.

Returns
    List of sync errors.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncErrorEntry <#maestral.models.SyncErrorEntry>]

clear_sync_errors_for_path(dbx_path_lower, recursive=False)
    Clear all sync errors for a path after a successful sync event.

Parameters

•   dbx_path_lower (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Normalised Dropbox path to clear.

•   recursive (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to clear sync errors for children of the given path.

Return type
    None

clear_sync_errors_from_event(event)
    Clears sync errors corresponding to a sync event.

Parameters
    event (maestral.models.SyncEvent <#maestral.models.SyncEvent>)

Return type
    None

get_index()
    Returns a copy of the local index of synced files and folders.

Returns
    List of index entries.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.IndexEntry <#maestral.models.IndexEntry>]

get_index_entry(dbx_path_lower)
    Gets the index entry for the given Dropbox path.

Parameters
    dbx_path_lower (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Normalized lower case Dropbox path.

Returns
    Index entry or None if no entry exists for the given path.

Return type
    maestral.models.IndexEntry <#maestral.models.IndexEntry> | None

get_index_entry_for_local_path(local_path)
    Gets the index entry for the given local path. Ensures that the index entry has the correct casing but ignore unicode normalisation differences. Dropbox always normalizes to composed (NFC) on upload, even in the display_path, so we cannot distinguish.

Parameters
    local_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Local path as returned by file system APIs.

Returns
    Index entry or None if no entry exists for the given path.

Return type
    maestral.models.IndexEntry <#maestral.models.IndexEntry> | None

iter_index()
    Returns an iterator over the local index of synced files and folders.

Returns
    Iterator over index entries.

Return type
    Iterator[maestral.models.IndexEntry <#maestral.models.IndexEntry>]

index_count()
    Returns the number of items in our index without loading any items.

Returns
    Number of index entries.

Return type
    int <https://docs.python.org/3/library/functions.html#int>

get_local_rev(dbx_path_lower)
    Gets revision number of local file.

Parameters
    dbx_path_lower (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Normalized lower case Dropbox path.

Returns
    Revision number as str or None if no local revision number has been saved.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str> | None

get_last_sync(dbx_path_lower)
    Returns the timestamp of last sync for an individual path.

Parameters
    dbx_path_lower (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Normalized lower case Dropbox path.

Returns
    Time of last sync.

Return type
    float <https://docs.python.org/3/library/functions.html#float>

update_index_from_sync_event(event)
    Updates the local index from a SyncEvent.

Parameters
    event (maestral.models.SyncEvent <#maestral.models.SyncEvent>) -- SyncEvent from download.

Return type
    None

update_index_from_dbx_metadata(md)
    Updates the local index from Dropbox metadata.

Parameters
    md (maestral.core.Metadata <#maestral.core.Metadata>) -- Dropbox metadata.

Return type
    None

remove_node_from_index(dbx_path_lower)
    Removes any local index entries for the given path and all its children.

Parameters
    dbx_path_lower (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Normalized lower case Dropbox path.

Return type
    None

get_local_hash(local_path)
    Computes content hash of a local file.

Parameters
    local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | bytes <https://docs.python.org/3/library/stdtypes.html#bytes>) -- Absolute path on local drive.

Returns
    Content hash to compare with Dropbox's content hash, or 'folder' if the path points to a directory. None if there is nothing at the path.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str> | None

property mignore_path: str <https://docs.python.org/3/library/stdtypes.html#str>
    Path to mignore file on local drive (read only).

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

property mignore_rules: pathspec.PathSpec
    List of mignore rules following git wildmatch syntax (read only).

Return type
    pathspec.PathSpec

load_mignore_file()
    Loads rules from mignore file. No rules are loaded if the file does not exist or cannot be read.

Returns
    PathSpec instance with ignore patterns.

Return type
    None

ensure_dropbox_folder_present()
    Checks if the Dropbox folder still exists where we expect it to be.

Raises
    NoDropboxDirError <#maestral.exceptions.NoDropboxDirError> -- When local Dropbox directory does not exist.

Return type
    None

ensure_cache_dir_present()
    Checks for or creates a directory at file_cache_path.

Raises
    CacheDirError <#maestral.exceptions.CacheDirError> -- When local cache directory cannot be created.

Return type
    None

clean_cache_dir(raise_error=True)
    Removes all items in the cache directory.

Parameters
    raise_error (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether errors should be raised or only logged.

Return type
    None

correct_case(dbx_path_basename_cased)
    Converts a Dropbox path with correctly cased basename to a fully cased path.

    This is useful because the Dropbox API guarantees the correct casing for the basename only. In practice, casing of parent directories is often incorrect. This method retrieves the correct casing of all ancestors in the path, either from our cache, our database, or from Dropbox servers.

    Performance may vary significantly with the number of parent folders and the method used to resolve the casing of all parent directory names:

1.  If the parent directory is already in our cache, performance is O(1).

2.  If the parent directory is already in our sync index, performance is slower because it requires a sqlite query but still O(1).

3.  If the parent directory is unknown to us, its metadata (including the correct casing of the directory's basename) is queried from Dropbox. This is used to construct a correctly cased path by calling correct_case() again. At best, performance will be of O(2) if the parent directory is known to us, at worst it will be of order O(N) involving queries to Dropbox servers for each of the N parent directories.

    When calling correct_case() repeatedly for paths from the same tree, it is therefore best to do so in top-down traversal.

Parameters
    dbx_path_basename_cased (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Dropbox path with correctly cased basename, as provided by dropbox.files.Metadata.path_display <https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html#dropbox.files.Metadata.path_display> or dropbox.files.Metadata.name <https://dropbox-sdk-python.readthedocs.io/en/latest/api/files.html#dropbox.files.Metadata.name>.

Returns
    Correctly cased Dropbox path.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

to_dbx_path(local_path)
    Converts a local path to a path relative to the Dropbox folder. Casing of the given local_path will be preserved.

Parameters
    local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | bytes <https://docs.python.org/3/library/stdtypes.html#bytes>) -- Absolute path on local drive.

Returns
    Relative path with respect to Dropbox folder.

Raises
    ValueError <https://docs.python.org/3/library/exceptions.html#ValueError> -- When the path lies outside the local Dropbox folder.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

to_dbx_path_lower(local_path)
    Converts a local path to a path relative to the Dropbox folder. The path will be normalized as on Dropbox servers (lower case and some additional normalisations).

Parameters
    local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | bytes <https://docs.python.org/3/library/stdtypes.html#bytes>) -- Absolute path on local drive.

Returns
    Relative path with respect to Dropbox folder.

Raises
    ValueError <https://docs.python.org/3/library/exceptions.html#ValueError> -- When the path lies outside the local Dropbox folder.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

to_local_path_from_cased(dbx_path_cased)
    Converts a correctly cased Dropbox path to the corresponding local path. This is more efficient than to_local_path() which accepts uncased paths.

Parameters
    dbx_path_cased (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path relative to Dropbox folder, correctly cased.

Returns
    Corresponding local path on drive.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

to_local_path(dbx_path)
    Converts a Dropbox path to the corresponding local path. Only the basename must be correctly cased, as guaranteed by the Dropbox API for the display_path attribute of file or folder metadata.

    This method slower than to_local_path_from_cased().

Parameters
    dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path relative to Dropbox folder, must be correctly cased in its basename.

Returns
    Corresponding local path on drive.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

is_excluded(path)
    Checks if a file is excluded from sync. Certain file names are always excluded from syncing, following the Dropbox support article:

    <https://help.dropbox.com/installs-integrations/sync-uploads/files-not-syncing>

    This includes file system files such as 'desktop.ini' and '.DS_Store' and some temporary files as well as caches used by Dropbox or Maestral. is_excluded accepts both local and Dropbox paths.

Parameters
    path (str <https://docs.python.org/3/library/stdtypes.html#str> | bytes <https://docs.python.org/3/library/stdtypes.html#bytes>) -- Can be an absolute path, a path relative to the Dropbox folder or just a file name. Does not need to be normalized.

Returns
    Whether the path is excluded from syncing.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

is_excluded_by_user(dbx_path_lower)
    Check if file has been excluded through "selective sync" by the user.

Parameters
    dbx_path_lower (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Normalised lower case Dropbox path.

Returns
    Whether the path is excluded from download syncing by the user.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

is_mignore(event)
    Check if local file change has been excluded by a mignore pattern.

Parameters
    event (maestral.models.SyncEvent <#maestral.models.SyncEvent>) -- SyncEvent for local file event.

Returns
    Whether the path is excluded from upload syncing by the user.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

cancel_sync()
    Raises a maestral.exceptions.CancelledError <#maestral.exceptions.CancelledError> in all sync threads and waits for them to shut down.

Return type
    None

busy()
    Checks if we are currently syncing.

Returns
    True if sync_lock cannot be acquired, False otherwise.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

upload_local_changes_while_inactive()
    Collects changes while sync has not been running and uploads them to Dropbox. Call this method when resuming sync.

Return type
    None

wait_for_local_changes(timeout=40)
    Blocks until local changes are available.

Parameters
    timeout (float <https://docs.python.org/3/library/functions.html#float>) -- Maximum time in seconds to wait.

Returns
    True if changes are available, False otherwise.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

upload_sync_cycle()
    Performs a full upload sync cycle by calling in order:

1.  list_local_changes()

2.  apply_local_changes()

    Handles updating the local cursor for you. If monitoring for local file events was interrupted, call upload_local_changes_while_inactive() instead.

Return type
    None

list_local_changes(delay=1)
    Returns a list of local changes with at most one entry per path.

Parameters
    delay (float <https://docs.python.org/3/library/functions.html#float>) -- Delay in sec to wait for subsequent changes before returning.

Returns
    (list of sync times events, time_stamp)

Return type
    tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncEvent <#maestral.models.SyncEvent>], float <https://docs.python.org/3/library/functions.html#float>]

apply_local_changes(sync_events)
    Applies locally detected changes to the remote Dropbox. Changes which should be ignored (mignore or always ignored files) are skipped.

Parameters
    sync_events (Collection[maestral.models.SyncEvent <#maestral.models.SyncEvent>]) -- List of local file system events.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncEvent <#maestral.models.SyncEvent>]

get_remote_item(dbx_path)
    Downloads a remote file or folder and updates its local rev. If the remote item does not exist, any corresponding local items will be deleted. If dbx_path refers to a folder, the download will be handled by _get_remote_folder(). If it refers to a single file, the download will be performed by _create_local_entry().

    This method can be used to fetch individual items outside the regular sync cycle, for instance when including a previously excluded file or folder.

Parameters
    dbx_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path relative to Dropbox folder.

Returns
    Whether download was successful.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

wait_for_remote_changes(last_cursor, timeout=40)
    Blocks until changes to the remote Dropbox are available.

Parameters

•   last_cursor (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Cursor form last sync.

•   timeout (int <https://docs.python.org/3/library/functions.html#int>) -- Timeout in seconds before returning even if there are no changes. Dropbox adds random jitter of up to 90 sec to this value.

Returns
    True if changes are available, False otherwise.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

download_sync_cycle()
    Performs a full download sync cycle by calling in order:

1.  list_remote_changes_iterator()

2.  apply_remote_changes()

    Handles updating the remote cursor and resuming interrupted syncs for you. Calling this method will perform a full indexing if this is the first download.

Return type
    None

list_remote_changes_iterator(last_cursor)
    Get remote changes since the last download sync, as specified by last_cursor. If the last_cursor is from paginating through a previous set of changes, continue where we left off. If last_cursor is an empty string, perform a full indexing of the Dropbox folder.

Parameters
    last_cursor (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Cursor from last download sync.

Returns
    Iterator yielding tuples with remote changes and corresponding cursor.

Return type
    Iterator[tuple <https://docs.python.org/3/library/stdtypes.html#tuple>[list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncEvent <#maestral.models.SyncEvent>], str <https://docs.python.org/3/library/stdtypes.html#str>]]

apply_remote_changes(sync_events)
    Applies remote changes to local folder. Call this on the result of list_remote_changes(). The saved cursor is updated after a set of changes has been successfully applied. Entries in the local index are created after successful completion.

Parameters
    sync_events (Collection[maestral.models.SyncEvent <#maestral.models.SyncEvent>]) -- List of remote changes.

Returns
    List of changes that were made to local files and bool indicating if all download syncs were successful.

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[maestral.models.SyncEvent <#maestral.models.SyncEvent>]

notify_user(sync_events)
    Shows a desktop notification for the given file changes.

Parameters
    sync_events (Sequence[maestral.models.SyncEvent <#maestral.models.SyncEvent>]) -- List of SyncEvents from download sync.

Return type
    None

rescan(local_path)
    Forces a rescan of a local path: schedules created events for every folder, modified events for every file and deleted events for every deleted item (compared to our index).

Parameters
    local_path (str <https://docs.python.org/3/library/stdtypes.html#str> | bytes <https://docs.python.org/3/library/stdtypes.html#bytes>) -- Path to rescan.

Return type
    None

class maestral.sync.pf_repr(obj)
    Class that wraps an object and creates a pretty formatted representation for it. This can be used to get pretty formatting in log messages while deferring the actual formatting until the message is created.

Parameters
    obj (Any) -- Object to wrap.

obj

MAESTRAL.UTILS

Utility modules and functions

  Submodules

  maestral.utils.appdirs

This module contains functions to retrieve platform dependent locations to store app data. It supports macOS and Linux.

  Module Contents

maestral.utils.appdirs.get_home_dir()
    Returns user home directory. This will be determined from the first valid result out of (osp.expanduser("~"), $HOME, $USERPROFILE, $TMP).

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.appdirs.get_conf_path(subfolder=None, filename=None, create=True)
    Returns the default config path for the platform. This will be:

•   macOS: "~/Library/Application Support/<subfolder>/<filename>."

•   Linux: "XDG_CONFIG_HOME/<subfolder>/<filename>"

•   other: "~/.config/<subfolder>/<filename>"

Parameters

•   subfolder (Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- The subfolder for the app.

•   filename (Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- The filename to append for the app.

•   create (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, the folder subfolder will be created on-demand.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.appdirs.get_data_path(subfolder=None, filename=None, create=True)
    Returns the default path to save application data for the platform. This will be:

•   macOS: "~/Library/Application Support/SUBFOLDER/FILENAME"

•   Linux: "$XDG_DATA_DIR/SUBFOLDER/FILENAME"

•   fallback: "$HOME/.local/share/SUBFOLDER/FILENAME"

    Note: We do not use "~/Library/Saved Application State" on macOS since this folder is reserved for user interface state and can be cleared by the user / system.

Parameters

•   subfolder (Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- The subfolder for the app.

•   filename (Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- The filename to append for the app.

•   create (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, the folder subfolder will be created on-demand.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.appdirs.get_cache_path(subfolder=None, filename=None, create=True)
    Returns the default cache path for the platform. This will be:

•   macOS: "~/Library/Caches/SUBFOLDER/FILENAME"

•   Linux: "$XDG_CACHE_HOME/SUBFOLDER/FILENAME"

•   fallback: "$HOME/.cache/SUBFOLDER/FILENAME"

Parameters

•   subfolder (Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- The subfolder for the app.

•   filename (Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- The filename to append for the app.

•   create (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, the folder subfolder will be created on-demand.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.appdirs.get_log_path(subfolder=None, filename=None, create=True)
    Returns the default log path for the platform. This will be:

•   macOS: "~/Library/Logs/SUBFOLDER/FILENAME"

•   Linux: "$XDG_CACHE_HOME/SUBFOLDER/FILENAME"

•   fallback: "$HOME/.cache/SUBFOLDER/FILENAME"

Parameters

•   subfolder (Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- The subfolder for the app.

•   filename (Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- The filename to append for the app.

•   create (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, the folder subfolder will be created on-demand.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.appdirs.get_autostart_path(filename=None, create=True)
    Returns the default path for login items for the platform. This will be:

•   macOS: "~/Library/LaunchAgents/FILENAME"

•   Linux: "$XDG_CONFIG_HOME/autostart/FILENAME"

•   fallback: "$HOME/.config/autostart/FILENAME"

Parameters

•   filename (Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- The filename to append for the app.

•   create (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, the folder subfolder will be created on-demand.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.appdirs.get_runtime_path(subfolder=None, filename=None, create=True)
    Returns the default runtime path for the platform. This will be:

•   macOS: "~/Library/Application Support/SUBFOLDER/FILENAME"

•   Linux: "$XDG_RUNTIME_DIR/SUBFOLDER/FILENAME"

•   fallback: "$HOME/.cache/SUBFOLDER/FILENAME"

Parameters

•   subfolder (Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- The subfolder for the app.

•   filename (Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- The filename to append for the app.

•   create (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, the folder subfolder will be created on-demand.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

  maestral.utils.caches

Module containing cache implementations.

  Module Contents

class maestral.utils.caches.LRUCache(capacity)
    A simple LRU cache implementation

Parameters
    capacity (int <https://docs.python.org/3/library/functions.html#int>) -- Maximum number of entries to keep.

capacity

get(key)
    Get the cached value for a key. Mark as most recently used.

Parameters
    key (Hashable) -- Key to query.

Returns
    Cached value or None.

Return type
    Any

put(key, value)
    Set the cached value for a key. Mark as most recently used.

Parameters

•   key (Hashable) -- Key to use. Must be hashable.

•   value (Any) -- Value to cache.

Return type
    None

clear()
    Clears the cache.

Return type
    None

  maestral.utils.hashing

Module for content hashing file contents.

  Module Contents

class maestral.utils.hashing.DropboxContentHasher
    Computes a hash using the same algorithm that the Dropbox API uses for the "content_hash" metadata field.

    The digest() method returns a raw binary representation of the hash. The hexdigest() convenience method returns a hexadecimal-encoded version, which is what the "content_hash" metadata field uses.

    This class has the same interface as the hashers in the standard 'hashlib' package.

Example
    Read a file in chunks of 1024 bytes and compute its content hash:

        >>> hasher = DropboxContentHasher()
        >>> with open('some-file', 'rb') as f:
        ...     while True:
        ...         chunk = f.read(1024)
        ...         if len(chunk) == 0:
        ...             break
        ...         hasher.update(chunk)
        ... print(hasher.hexdigest())

BLOCK_SIZE = 4194304

digest_size = 1

update(new_data)

Parameters
    new_data (bytes <https://docs.python.org/3/library/stdtypes.html#bytes> | bytearray <https://docs.python.org/3/library/stdtypes.html#bytearray>)

Return type
    None

digest()

Return type
    bytes <https://docs.python.org/3/library/stdtypes.html#bytes>

hexdigest()

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

copy()

Return type
    DropboxContentHasher <#maestral.utils.hashing.DropboxContentHasher>

class maestral.utils.hashing.StreamHasher(f, hasher)
    A wrapper around a file-like object (either for reading or writing) that hashes everything that passes through it. Can be used with DropboxContentHasher or any 'hashlib' hasher.

Example

        >>> hasher = DropboxContentHasher()
        >>> with open('some-file', 'rb') as f:
        ...     wrapped_f = StreamHasher(f, hasher)
        ...     response = some_api_client.upload(wrapped_f)
        >>> locally_computed = hasher.hexdigest()
        >>> assert response.content_hash == locally_computed

Parameters

•   f (BinaryIO) -- File-like object.

•   hasher (DropboxContentHasher <#maestral.utils.hashing.DropboxContentHasher>) -- Hasher to use. Must implement an update method.

close()

Return type
    None

flush()

Return type
    None

fileno()

Return type
    int <https://docs.python.org/3/library/functions.html#int>

tell()

Return type
    int <https://docs.python.org/3/library/functions.html#int>

read(size=-1)

Parameters
    size (int <https://docs.python.org/3/library/functions.html#int>)

Return type
    bytes <https://docs.python.org/3/library/stdtypes.html#bytes>

write(b)

Parameters
    b (_WritableBuffer)

Return type
    int <https://docs.python.org/3/library/functions.html#int>

readline(size=-1)

Parameters
    size (int <https://docs.python.org/3/library/functions.html#int>)

Return type
    bytes <https://docs.python.org/3/library/stdtypes.html#bytes>

readlines(hint=-1)

Parameters
    hint (int <https://docs.python.org/3/library/functions.html#int>)

Return type
    list <https://docs.python.org/3/library/stdtypes.html#list>[bytes <https://docs.python.org/3/library/stdtypes.html#bytes>]

  maestral.utils.integration

This module provides functions for platform integration. Most of the functionality here could also be achieved with psutils, but we want to avoid the large dependency.

  Module Contents

maestral.utils.integration.CPU_CORE_COUNT

maestral.utils.integration.cat(*paths)
    Attempts to read the content of multiple files which may not exist. Returns the content of the first file which can be read. If none of them can be read return None. Returns an integer if the content is a digit.

Parameters
    paths (os.PathLike <https://docs.python.org/3/library/os.html#os.PathLike>[str <https://docs.python.org/3/library/stdtypes.html#str>])

Return type
    Union[bytes <https://docs.python.org/3/library/stdtypes.html#bytes>, None]

maestral.utils.integration.get_inotify_limits()
    Returns the current inotify limit settings as tuple.

Returns
    (max_user_watches, max_user_instances, max_queued_events)

Raises
    OSError <https://docs.python.org/3/library/exceptions.html#OSError> -- if the settings cannot be read from /proc/sys/fs/inotify. This may happen if /proc/sys is left out of the kernel image or simply not mounted.

Return type
    Tuple[int <https://docs.python.org/3/library/functions.html#int>, int <https://docs.python.org/3/library/functions.html#int>, int <https://docs.python.org/3/library/functions.html#int>]

maestral.utils.integration.cpu_usage_percent(interval=0.1)
    Returns a float representing the CPU utilization of the current process as a percentage. This duplicates the similar method from psutil to avoid the psutil dependency.

    Compares process times to system CPU times elapsed before and after the interval (blocking). It is recommended for accuracy that this function be called with an interval of at least 0.1 sec.

    A value > 100.0 can be returned in case of processes running multiple threads on different CPU cores. The returned value is explicitly NOT split evenly between all available logical CPUs. This means that a busy loop process running on a system with 2 logical CPUs will be reported as having 100% CPU utilization instead of 50%.

Parameters
    interval (float <https://docs.python.org/3/library/functions.html#float>) -- Interval in sec between comparisons of CPU times.

Returns
    CPU usage during interval in percent.

Return type
    float <https://docs.python.org/3/library/functions.html#float>

maestral.utils.integration.check_connection(hostname, timeout=2, logger=None)
    A low latency check for an internet connection.

Parameters

•   hostname (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Hostname to use for connection check.

•   timeout (int <https://docs.python.org/3/library/functions.html#int>) -- Timeout in seconds for connection check.

•   logger (Optional[logging.Logger <https://docs.python.org/3/library/logging.html#logging.Logger>]) -- If provided, log output for connection failures will be logged to this logger with the level DEBUG.

Returns
    Connection availability.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

class maestral.utils.integration.SystemdNotifier
    An interface to notify the systemd the service manager about status changes.

    Sends a status message to the systemd the service manager on the socket address provided by the NOTIFY_SOCKET environment variable. Does nothing NOTIFY_SOCKET is not set.

    See <https://www.freedesktop.org/software/systemd/man/sd_notify.html> for a documentation of message formats expected by systemd.

notify(status)
    Send a status update to the service manager.

Parameters
    status (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The status update to send.

Return type
    None

  maestral.utils.path

This module contains functions for common path operations.

  Module Contents

maestral.utils.path.F_GETPATH = 50

maestral.utils.path.is_child(path, parent, case_sensitive=True)
    Checks if path semantically is inside parent. Neither path needs to refer to an actual item on the drive. This function is case-sensitive.

Parameters

•   path (str <https://docs.python.org/3/library/stdtypes.html#str> | bytes <https://docs.python.org/3/library/stdtypes.html#bytes>) -- Item path.

•   parent (str <https://docs.python.org/3/library/stdtypes.html#str> | bytes <https://docs.python.org/3/library/stdtypes.html#bytes>) -- Parent path.

•   case_sensitive (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to do case-sensitive checks.

Returns
    Whether path semantically lies inside parent.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

maestral.utils.path.is_equal_or_child(path, parent, case_sensitive=True)
    Checks if path semantically is inside parent or equals parent. Neither path needs to refer to an actual item on the drive. This function is case-sensitive.

Parameters

•   path (str <https://docs.python.org/3/library/stdtypes.html#str> | bytes <https://docs.python.org/3/library/stdtypes.html#bytes>) -- Item path.

•   parent (str <https://docs.python.org/3/library/stdtypes.html#str> | bytes <https://docs.python.org/3/library/stdtypes.html#bytes>) -- Parent path.

•   case_sensitive (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to do case-sensitive checks.

Returns
    True if path semantically lies inside parent or path == parent.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

maestral.utils.path.normalize_case(string)
    Converts a string to lower case. Todo: Follow Python 2.5 / Dropbox conventions.

Parameters
    string (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Original string.

Returns
    Lowercase string.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.path.normalize_unicode(string)
    Normalizes a string to replace all decomposed unicode characters with their single character equivalents.

Parameters
    string (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Original string.

Returns
    Normalized string.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.path.normalize(path)
    Replicates the path normalization performed by Dropbox servers. This typically only involves converting the path to lower case, with a few (undocumented) exceptions:

•   Unicode normalization: decomposed characters are converted to composed characters.

•   Lower casing of non-ascii characters: Dropbox uses the Python 2.5 behavior for conversion to lower case. This means that some cyrillic characters are incorrectly lower-cased. For example: "Ꙋ".lower() -> "Ꙋ" instead of "ꙋ" "ΣΣΣ".lower() -> "σσσ" instead of "σσς"

•   Trailing spaces are stripped from folder names. We do not perform this normalization here because the Dropbox API will raise sync errors for such names anyways.

    Note that calling normalize() on an already normalized path will return the unmodified input.

    Todo: Follow Python 2.5 / Dropbox conventions instead of Python 3 conventions.

Parameters
    path (str <https://docs.python.org/3/library/stdtypes.html#str> | bytes <https://docs.python.org/3/library/stdtypes.html#bytes>) -- Original path.

Returns
    Normalized path.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.path.is_fs_case_sensitive(path)
    Checks if path lies on a partition with a case-sensitive file system.

Parameters
    path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to check.

Returns
    Whether path lies on a partition with a case-sensitive file system.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

maestral.utils.path.get_existing_equivalent_paths(path, root=osp.sep, norm_func=normalize)
    Given a "normalized" path using an injective (one-directional) normalization function, this method returns a list of matching un-normalized local paths. If no such local paths exist, list will be empty.

Example
    Assume the normalization function is str.lower(). If a root directory contains two folders "/parent/subfolder/child" and "/parent/Subfolder/child", two matches will be returned for "path = /parent/subfolder/child/file.txt".

Parameters

•   path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Normalized path relative to root.

•   root (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Parent directory to search in. There are significant performance improvements if a root directory with a small tree is given.

•   norm_func (Callable[[str <https://docs.python.org/3/library/stdtypes.html#str>], str <https://docs.python.org/3/library/stdtypes.html#str>]) -- Normalization function to use. Defaults to normalize().

Returns
    List of existing paths for which normalized(local_path) == normalized(path).

Return type
    List[str <https://docs.python.org/3/library/stdtypes.html#str>]

maestral.utils.path.to_existing_unnormalized_path(path, root=osp.sep, norm_func=normalize)
    Returns a cased version of the given path if corresponding nodes (with arbitrary casing) exist in the given root directory. If multiple matches are found, only one is returned.

    This is similar to get_existing_equivalent_paths() but returns only the first candidate or raises a FileNotFoundError <https://docs.python.org/3/library/exceptions.html#FileNotFoundError> if no candidates can be found.

    If the file system is not case-sensitive but case-preserving, this function effectively returns the "displayed" version of a path, as used for example in file managers.

    On macOS, we use fcntl F_GETPATH for a more efficient implementation.

Parameters

•   path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Original path relative to root.

•   root (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Parent directory to search in. There are significant performance improvements if a root directory with a small tree is given.

•   norm_func (Callable[[str <https://docs.python.org/3/library/stdtypes.html#str>], str <https://docs.python.org/3/library/stdtypes.html#str>]) -- Normalization function to use. Defaults to normalize().

Returns
    Absolute and cased version of given path.

Raises
    FileNotFoundError <https://docs.python.org/3/library/exceptions.html#FileNotFoundError> -- if path does not exist in root root or root itself does not exist.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.path.normalized_path_exists(path, root=osp.sep)
    Checks if a path exists in given root directory, similar to os.path.exists but case-insensitive. Normalisation is performed as by Dropbox servers (lower case and unicode normalisation).

Parameters

•   path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path relative to root.

•   root (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Directory where we will look for path. There are significant performance improvements if a root directory with a small tree is given.

Returns
    Whether an arbitrarily cased version of path exists.

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

maestral.utils.path.generate_cc_name(path, suffix)
    Generates a path for a conflicting copy of path. The file name is created by inserting the given suffix between the filename and the extension. For example, for suffix = "conflicting copy": "my_file.txt" -> "my_file (conflicting copy).txt"

    If a file with the resulting path already exists (case-insensitive!), we additionally append an integer number, for instance: "my_file.txt" -> "my_file (conflicting copy 1).txt"

Parameters

•   path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Original path name.

•   suffix (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Suffix to use.

Returns
    New path.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.path.delete(path, force_case_sensitive=False, raise_error=False)
    Deletes a file or folder at path. Symlinks will not be followed.

Parameters

•   path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path of item to delete.

•   force_case_sensitive (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to perform the deletion only if the item appears with the same casing as provided in path. This can be used on case-insensitive but preserving file systems to ensure that the intended item is deleted.

•   raise_error (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to raise errors or return them.

Returns
    Any caught exception during the deletion.

Return type
    Optional[OSError <https://docs.python.org/3/library/exceptions.html#OSError>]

maestral.utils.path.move(src_path, dest_path, raise_error=False, keep_target_permissions=False, keep_target_xattrs=False)
    Moves a file or folder from src_path to dest_path. If either the source or the destination path no longer exist, this function does nothing. Any other exceptions are either raised or returned if raise_error is False.

    Uses os.rename internally.

Parameters

•   src_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path of item to move.

•   dest_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Destination path. Any existing file at this path will be replaced by the move. Any existing empty folder will be replaced if the source is also a folder.

•   raise_error (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to raise errors or return them.

•   keep_target_permissions (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to preserve the permissions of a file at the destination, if any.

•   keep_target_xattrs (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to preserve the extended attributes of a file at the destination, if any.

Returns
    Any caught exception during the move.

Return type
    Optional[OSError <https://docs.python.org/3/library/exceptions.html#OSError>]

maestral.utils.path.walk(root, listdir=os.scandir)
    Iterates recursively over the content of a folder.

Parameters

•   root (str <https://docs.python.org/3/library/stdtypes.html#str> | bytes <https://docs.python.org/3/library/stdtypes.html#bytes>) -- Root folder to walk.

•   listdir (Callable[[str <https://docs.python.org/3/library/stdtypes.html#str>], Iterable[os.DirEntry <https://docs.python.org/3/library/os.html#os.DirEntry>[str <https://docs.python.org/3/library/stdtypes.html#str>]]]) -- Function to call to get the folder content.

Returns
    Iterator over (path, stat) results.

Return type
    Iterator[Tuple[str <https://docs.python.org/3/library/stdtypes.html#str>, os.stat_result <https://docs.python.org/3/library/os.html#os.stat_result>]]

maestral.utils.path.content_hash(local_path, chunk_size=65536)
    Computes content hash of a local file.

Parameters

•   local_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Absolute path on local drive.

•   chunk_size (int <https://docs.python.org/3/library/functions.html#int>) -- Size of chunks to hash in bytes.

Returns
    Content hash to compare with Dropbox's content hash and mtime just before the hash was computed.

Return type
    Tuple[Optional[str <https://docs.python.org/3/library/stdtypes.html#str>], Optional[float <https://docs.python.org/3/library/functions.html#float>]]

maestral.utils.path.fs_max_lengths_for_path(path='/')
    Return the maximum length of file names and paths allowed on a file system.

Parameters
    path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Path to check. This can be specified because different paths may be residing on different file systems. If the given path does not exist, the first existing parent directory in the tree be taken.

Returns
    Tuple giving the maximum file name and total path lengths.

Return type
    Tuple[int <https://docs.python.org/3/library/functions.html#int>, int <https://docs.python.org/3/library/functions.html#int>]

maestral.utils.path.opener_no_symlink(path, flags)
    Opener that does not follow symlinks. Uses os.open() under the hood.

Parameters

•   path (_AnyPath) -- Path to open.

•   flags (int <https://docs.python.org/3/library/functions.html#int>) -- Flags passed to os.open(). O_NOFOLLOW will be added.

Returns
    Open file descriptor.

Return type
    int <https://docs.python.org/3/library/functions.html#int>

maestral.utils.path.exists(path)
    Returns whether an item exists at the path. Returns True for symlinks.

Parameters
    path (_AnyPath)

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

maestral.utils.path.isfile(path)
    Returns whether a file exists at the path. Returns True for symlinks.

Parameters
    path (_AnyPath)

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

maestral.utils.path.isdir(path)
    Returns whether a folder exists at the path. Returns False for symlinks.

Parameters
    path (_AnyPath)

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

maestral.utils.path.getsize(path)
    Returns the size. Returns False for symlinks.

Parameters
    path (_AnyPath)

Return type
    int <https://docs.python.org/3/library/functions.html#int>

maestral.utils.path.equal_but_for_unicode_norm(s0, s1)

Parameters

•   s0 (str <https://docs.python.org/3/library/stdtypes.html#str>)

•   s1 (str <https://docs.python.org/3/library/stdtypes.html#str>)

Return type
    bool <https://docs.python.org/3/library/functions.html#bool>

maestral.utils.path.get_symlink_target(local_path)
    Returns the symlink target of a file.

Parameters
    local_path (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Absolute path on local drive.

Returns
    Symlink target of local file. None if the local path does not refer to a symlink or does not exist.

Return type
    Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]

  Package Contents

maestral.utils.natural_size(num, unit='B', sep=True)
    Convert number to a human-readable string with decimal prefix.

Parameters

•   num (float <https://docs.python.org/3/library/functions.html#float>) -- Value in given unit.

•   unit (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Unit suffix.

•   sep (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to separate unit and value with a space.

Returns
    Human-readable string with decimal prefixes.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.chunks(lst, n, consume=False)
    Partitions a list into chunks of length n.

Parameters

•   lst (list <https://docs.python.org/3/library/stdtypes.html#list>[_T]) -- Iterable to partition.

•   n (int <https://docs.python.org/3/library/functions.html#int>) -- Chunk size.

•   consume (bool <https://docs.python.org/3/library/functions.html#bool>) -- If True, the list will be consumed (emptied) during the iteration.

Returns
    Iterator over chunks.

Return type
    Iterator[list <https://docs.python.org/3/library/stdtypes.html#list>[_T]]

maestral.utils.clamp(n, minn, maxn)
    Clamps a number between a minimum and maximum value.

Parameters

•   n (_N) -- Original value.

•   minn (_N) -- Minimum allowed value.

•   maxn (_N) -- Maximum allowed value.

Returns
    Clamped value.

Return type
    _N

maestral.utils.get_newer_version(version, releases)
    Checks a given release version against a version list of releases to see if an update is available. Only offers newer versions if they are not a prerelease.

Parameters

•   version (str <https://docs.python.org/3/library/stdtypes.html#str>) -- The current version.

•   releases (Iterable[str <https://docs.python.org/3/library/stdtypes.html#str>]) -- A list of valid cleaned releases.

Returns
    The version string of the latest release if a newer release is available.

Return type
    Optional[str <https://docs.python.org/3/library/stdtypes.html#str>]

maestral.utils.removeprefix(string, prefix, case_sensitive=True)
    Removes the given prefix from a string. Only the first instance of the prefix is removed. The original string is returned if it does not start with the given prefix.

    This follows the Python 3.9 implementation of str.removeprefix.

Parameters

•   string (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Original string.

•   prefix (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Prefix to remove.

•   case_sensitive (bool <https://docs.python.org/3/library/functions.html#bool>) -- Whether to do case-sensitive prefix removal.

Returns
    String without prefix.

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.sanitize_string(string)
    Converts a string provided by file system APIs, which may contain surrogate escapes for bytes with unknown encoding, to a string which can always be displayed or printed. This is done by replacing invalid characters with "�".

Parameters
    string (str <https://docs.python.org/3/library/stdtypes.html#str>) -- Original string.

Returns
    Sanitised path where all surrogate escapes have been replaced with "�".

Return type
    str <https://docs.python.org/3/library/stdtypes.html#str>

maestral.utils.exc_info_tuple(exc)
    Creates an exc-info tuple from an exception.

Parameters
    exc (BaseException <https://docs.python.org/3/library/exceptions.html#BaseException>)

Return type
    _ExecInfoType

GETTING STARTED

To use the Maestral API in a Python interpreter, import the main module first and initialize a Maestral instance with a configuration name. For this example, we use a new configuration "private" which is not yet linked to a Dropbox account:

    >>> from maestral.main import Maestral
    >>> m = Maestral(config_name="private")

Config files will be created on-demand for the new configuration, as described in Config files <> and State files <>.

We now link the instance to an existing Dropbox account. This is done by generating a Dropbox URL for the user to visit and authorize Maestral. Using the link() method, the resulting auth code is exchanged for an access token to make Dropbox API calls. See Dropbox's oauth-guide <https://www.dropbox.com/lp/developers/reference/oauth-guide> for details on the OAuth2 PKCE flow which we use. When the auth flow is successfully completed, the credentials will be saved in the system keyring (e.g., macOS Keychain or Gnome Keyring).

    >>> url = m.get_auth_url()  # get token from Dropbox website
    >>> print(f"Please go to {url} to retrieve a Dropbox authorization token.")
    >>> token = input("Enter auth token: ")
    >>> res = m.link(token)

The call to link() will return 0 on success, 1 for an invalid code and 2 for connection errors. We verify that linking succeeded and proceed to create a local Dropbox folder and start syncing:

    >>> if res == 0:
    ...     m.create_dropbox_directory("~/Dropbox (Private)")
    ...     m.start_sync()

Author
Sam Schott

Copyright
2026, Sam Schott