maestral.main

This module defines the main API which is exposed to the CLI or GUI.

class maestral.main.Maestral(config_name='maestral', log_to_stderr=False)[source]

Bases: object

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

Return type

None

property version: str

Returns the current Maestral version.

get_auth_url()[source]

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

Returns

URL to retrieve an OAuth token.

Return type

str

Links Maestral with a Dropbox account using the given access token. The 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

Parameters

token (str) – OAuth token for Dropbox access.

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

property config_name: str

The selected configuration.

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

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

property excluded_items: List[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. I.e., paths which have been added to the list will be deleted from the local drive and paths which have been removed will be downloaded.

Use exclude_item() and include_item() to add or remove individual items from selective sync.

property log_level: int

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

property notification_snooze: float

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

property notification_level: int

Level for desktop notifications. See utils.notify for level definitions.

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.

Parameters

timeout (Optional[float]) – Maximum time to block before returning, even if there is no status change.

Returns

True``if there was a status change, ``False in case of a timeout.

Return type

bool

New in version 1.3.0.

Indicates if 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.

property pending_dropbox_folder: bool

Indicates if 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 NoDropboxDirError.

property pending_first_download: bool

Indicates if the initial download has already occurred (read only).

property paused: bool

Indicates if syncing is paused by the user (read only). This is set by calling pause().

property running: bool

Indicates if sync threads are running (read only). They will be stopped before start_sync() is called, when shutting down or because of an exception.

property connected: bool

Indicates if Dropbox servers can be reached (read only).

property status: str

The last status message (read only). This can be displayed as information to the user but should not be relied on otherwise.

property sync_errors: List[Dict[str, Optional[Union[str, Sequence[str]]]]]

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.

property fatal_errors: List[Dict[str, Optional[Union[str, Sequence[str]]]]]

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.

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

property account_profile_pic_path: 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.

get_file_status(local_path)[source]

Returns the sync status of a file or folder. The returned status is recursive for folders, e.g., the file status will be “uploading” for a a folder if any file inside that folder is being uploaded.

New in version 1.4.4: Recursive behavior. Previous versions would return “up to date” even if in case of syncing children.

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’ (for files outside of the Dropbox directory). This will always be ‘unwatched’ if syncing is paused.

Return type

str

get_activity(limit=100)[source]

Returns the current upload / download activity.

Parameters

limit (Optional[int]) – 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 furthest up in the queue coming first.

Raises

NotLinkedError – if no Dropbox account is linked.

Return type

List[Dict[str, Optional[Union[str, float, bool]]]]

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

limit (Optional[int]) – 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[Dict[str, Optional[Union[str, float, bool]]]]

get_account_info()[source]

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

Returns

Dropbox account information.

Raises
Return type

Dict[str, Optional[Union[str, float, bool]]]

get_space_usage()[source]

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

Returns

Dropbox space usage information.

Raises
Return type

Dict[str, Optional[Union[str, float, bool]]]

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.

Returns

Path to saved profile picture or None if no profile picture was downloaded.

Raises
Return type

Optional[str]

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

Optional[Dict[str, Optional[Union[str, float, bool]]]]

list_folder(dbx_path, **kwargs)[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.

Returns

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

Raises
Return type

List[Dict[str, Optional[Union[str, float, bool]]]]

list_folder_iterator(dbx_path, **kwargs)[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.

Returns

Iterator over list of Dropbox item metadata as dicts. See dropbox.files.Metadata for keys and values.

Raises
Return type

Iterator[List[Dict[str, Optional[Union[str, float, bool]]]]]

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.

Return type

List[Dict[str, Optional[Union[str, float, bool]]]]

:raises NotFoundError:if there never was a file at the given path. :raises IsAFolderError: if the given path refers to a folder :raises DropboxAuthError: in case of an invalid access token. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails.

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 (Optional[str]) – 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

Dict[str, Optional[Union[str, float, bool]]]

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

set_excluded_items(items)[source]
Parameters

items (List[str]) –

Return type

None

exclude_item(dbx_path)[source]

Excludes file or folder from sync and deletes it locally. It is safe to call this method with items which have already been excluded.

Parameters

dbx_path (str) – Dropbox path of item to exclude.

Raises
Return type

None

include_item(dbx_path)[source]

Includes a file or folder 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_path (str) – Dropbox path of item 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) – Path to item on Dropbox.

  • visibility (str) – Requested visibility of the shared link. Must be “public”, “team_only” or “password”. The actual visibility may be different, depending on the team and folder settings. Inspect the “link_permissions” entry of the returned dictionary.

  • password (Optional[str]) – An optional password required to access the link. Will be ignored if the visibility is not “password”.

  • expires (Optional[float]) – An optional expiry time for the link as POSIX timestamp.

Returns

Shared link information as dict. See dropbox.sharing.SharedLinkMetadata for keys and values.

Raises
Return type

Dict[str, Optional[Union[str, float, bool]]]

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 (Optional[str]) – 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[Dict[str, Optional[Union[str, float, bool]]]]

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

Return type

Dict[str, Optional[Union[str, bool]]]

shutdown_daemon()[source]

Stop syncing and clean up our asyncio tasks. Set a result for the shutdown_complete future.

Return type

None