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)[source]

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: 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) – 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) – 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 | 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[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.

property version: str[source]

Returns the current Maestral version.

Return type:

str

property config_name: str[source]

The selected configuration.

Return type:

str

property dropbox_path: str[source]

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 – if no Dropbox account is linked.

Return type:

str

property excluded_items: set[str][source]

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[str]

property log_level: int[source]

Log level for log files, stderr and the systemd journal.

Return type:

int

property notification_snooze: float[source]

Snooze time for desktop notifications in minutes. Defaults to 0 if notifications are not snoozed.

Return type:

float

property notification_level: int[source]

Level for desktop notifications. See notify for level definitions.

Return type:

int

property bandwidth_limit_down: float[source]

Maximum download bandwidth to use in bytes per second.

Return type:

float

property bandwidth_limit_up: float[source]

Maximum download bandwidth to use in bytes per second.

Return type:

float

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

property pending_dropbox_folder: bool[source]

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.

Return type:

bool

property pending_first_download: bool[source]

Whether the initial download has already started (read only).

Return type:

bool

property paused: bool[source]

Whether syncing is paused by the user (read only). Use start_sync() and stop_sync() to start and stop syncing, respectively.

Return type:

bool

property running: bool[source]

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

property connected: bool[source]

Whether Dropbox servers can be reached (read only).

Return type:

bool

property status: str[source]

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

property sync_errors: list[maestral.models.SyncErrorEntry][source]

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 – if no Dropbox account is linked.

Return type:

list[maestral.models.SyncErrorEntry]

property fatal_errors: list[maestral.exceptions.MaestralApiError][source]

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[maestral.exceptions.MaestralApiError]

property account_profile_pic_path: str[source]

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

get_auth_url()[source]

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

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 | None) – Authorization code.

  • refresh_token (str | None) – Optionally, instead of an authorization code, directly provide a refresh token.

  • access_token (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

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 – if no Dropbox account is linked.

Return type:

None

set_conf(section, name, value)[source]

Sets a configuration option.

Parameters:
  • section (str) – Name of section in config file.

  • name (str) – Name of config option.

  • value (Any) – Config value. May be any type accepted by ast.literal_eval.

Return type:

None

get_conf(section, name)[source]

Gets a configuration option.

Parameters:
  • section (str) – Name of section in config file.

  • name (str) – Name of config option.

Returns:

Config value. May be any type accepted by ast.literal_eval.

Return type:

Any

set_state(section, name, value)[source]

Sets a state value.

Parameters:
  • section (str) – Name of section in state file.

  • name (str) – Name of state variable.

  • value (Any) – State value. May be any type accepted by ast.literal_eval.

Return type:

None

get_state(section, name)[source]

Gets a state value.

Parameters:
  • section (str) – Name of section in state file.

  • name (str) – Name of state variable.

Returns:

State value. May be any type accepted by ast.literal_eval.

Return type:

Any

status_change_longpoll(timeout=60)[source]

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 | 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

Added in version 1.3.0.

clear_fatal_errors()[source]

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

get_file_status(local_path)[source]

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) – 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

get_activity(limit=100)[source]

Returns the current upload / download activity.

Parameters:

limit (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 – if no Dropbox account is linked.

Return type:

list[maestral.models.SyncEvent]

get_history(dbx_path=None, limit=100)[source]

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 | None) – If given, show sync history for the specified Dropbox path only.

  • limit (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 – if no Dropbox account is linked.

Return type:

list[maestral.models.SyncEvent]

get_account_info()[source]

Returns the account information from Dropbox and returns it as a dictionary.

Returns:

Dropbox account information.

Raises:
Return type:

maestral.core.FullAccount

get_space_usage()[source]

Gets the space usage from Dropbox and returns it as a dictionary.

Returns:

Dropbox space usage information.

Raises:
Return type:

maestral.core.PersonalSpaceUsage

get_profile_pic()[source]

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:
Return type:

str | None

get_metadata(dbx_path)[source]

Returns metadata for a file or folder on Dropbox.

Parameters:

dbx_path (str) – Path to file or folder on Dropbox.

Returns:

Dropbox item metadata as dict. See dropbox.files.Metadata for keys and values.

Raises:
Return type:

maestral.core.Metadata | None

list_folder(dbx_path, recursive=False, include_deleted=False, include_mounted_folders=True, include_non_downloadable_files=False)[source]

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) – Path to folder on Dropbox.

  • recursive (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) – If true, the results will include entries for files and folders that used to exist but were deleted.

  • include_mounted_folders (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) – If true, include files that are not downloadable, i.e. Google Docs.

Raises:
Return type:

list[maestral.core.Metadata]

list_folder_iterator(dbx_path, recursive=False, include_deleted=False, include_mounted_folders=True, limit=None, include_non_downloadable_files=False)[source]

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) – Path to folder on Dropbox.

  • recursive (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) – If true, the results will include entries for files and folders that used to exist but were deleted.

  • include_mounted_folders (bool) – If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder.

  • limit (Nullable[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) – 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 for keys and values.

Raises:
Return type:

Iterator[list[maestral.core.Metadata]]

list_revisions(dbx_path, limit=10)[source]

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) – Path to file on Dropbox.

  • limit (int) – Maximum number of revisions to list.

Returns:

List of Dropbox file metadata as dicts. See dropbox.files.Metadata for keys and values.

Raises:
Return type:

list[maestral.core.FileMetadata]

get_file_diff(old_rev, new_rev=None)[source]

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) – Identifier of old revision.

  • new_rev (str | None) – Identifier of new revision.

Returns:

Diff as a list of strings (lines).

Raises:
Return type:

list[str]

restore(dbx_path, rev)[source]

Restore an old revision of a file.

Parameters:
  • dbx_path (str) – The path to save the restored file.

  • rev (str) – The revision to restore. Old revisions can be listed with list_revisions().

Returns:

Metadata of the returned file. See dropbox.files.FileMetadata for keys and values.

Raises:
Return type:

maestral.core.FileMetadata

rebuild_index()[source]

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:
Return type:

None

start_sync()[source]

Creates syncing threads and starts syncing.

Raises:
Return type:

None

stop_sync()[source]

Stops all syncing threads if running. Call start_sync() to restart syncing.

Return type:

None

reset_sync_state()[source]

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 – if no Dropbox account is linked.

Return type:

None

exclude_items(*dbx_paths)[source]

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) – Dropbox paths of items to exclude.

Raises:
Return type:

None

include_items(*dbx_paths)[source]

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) – Dropbox paths of items to include.

Raises:
Return type:

None

excluded_status(dbx_path)[source]

Returns ‘excluded’, ‘partially excluded’ or ‘included’. This function will not check if the item actually exists on Dropbox.

Parameters:

dbx_path (str) – Path to item on Dropbox.

Returns:

Excluded status.

Raises:

NotLinkedError – if no Dropbox account is linked.

Return type:

str

move_dropbox_directory(new_path)[source]

Sets the local Dropbox directory. This moves all local files to the new location and resumes syncing afterwards.

Parameters:

new_path (str) – Full path to local Dropbox folder. “~” will be expanded to the user’s home directory.

Raises:
Return type:

None

create_dropbox_directory(path)[source]

Creates a new Dropbox directory. Only call this during setup.

Parameters:

path (str) – Full path to local Dropbox folder. “~” will be expanded to the user’s home directory.

Raises:
Return type:

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) – Dropbox path to file or folder to share.

  • visibility (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) – The level of access granted with the link. Can be viewer, editor, or max for maximum possible access level.

  • allow_download (bool | None) – Whether to allow download capabilities for the link.

  • password (str | None) – If given, enables password protection for the link.

  • expires (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

Revokes the given shared link. Note that any other links to the same file or folder will remain valid.

Parameters:

url (str) – URL of shared link to revoke.

Raises:
Return type:

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 | None) – Path to item on Dropbox.

Returns:

List of shared link information as dictionaries. See dropbox.sharing.SharedLinkMetadata for keys and values.

Raises:
Return type:

list[maestral.core.SharedLinkMetadata]

to_local_path(dbx_path)[source]

Converts a path relative to the Dropbox folder to a correctly cased local file system path.

Parameters:

dbx_path (str) – Path relative to Dropbox root.

Returns:

Corresponding path on local hard drive.

Raises:
Return type:

str

check_for_updates()[source]

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 – if checking for an update fails.

Return type:

maestral.core.UpdateCheckResult

shutdown_daemon()[source]

Stop syncing and notify anyone monitoring shutdown_future that we are done.

Return type:

None