maestral.main

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

Module Contents

class maestral.main.Maestral(config_name: str = 'maestral', log_to_stdout: bool = False)[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 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 – Name of maestral configuration to run. Must not contain any whitespace. If the given config file does exist, it will be created.

  • log_to_stdout – If True, Maestral will print log messages to stdout. When started as a systemd services, this can result in duplicate log messages. Defaults to False.

log_handler_sd :Optional[SdNotificationHandler][source]
log_handler_journal :Optional['journal.JournalHandler'][source]
property version(self)str[source]

Returns the current Maestral version.

get_auth_url(self)str[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.

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 – OAuth token for Dropbox access.

Returns

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

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.

property config_name(self)str[source]

The selected configuration.

set_conf(self, section: str, name: str, value: Any)None[source]

Sets a configuration option.

Parameters
  • section – Name of section in config file.

  • name – Name of config option.

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

get_conf(self, section: str, name: str)Any[source]

Gets a configuration option.

Parameters
  • section – Name of section in config file.

  • name – Name of config option.

Returns

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

set_state(self, section: str, name: str, value: Any)None[source]

Sets a state value.

Parameters
  • section – Name of section in state file.

  • name – Name of state variable.

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

get_state(self, section: str, name: str)Any[source]

Gets a state value.

Parameters
  • section – Name of section in state file.

  • name – Name of state variable.

Returns

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

property dropbox_path(self)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.

property excluded_items(self)List[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. 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(self)int[source]

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

property log_to_stdout(self)bool[source]

Enables or disables logging to stdout.

property notification_snooze(self)float[source]

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

property notification_level(self)int[source]

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

status_change_longpoll(self, timeout: Optional[float] = 60)bool[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 – 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.

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

Indicates if a local Dropbox directory has been created (read only).

property pending_first_download(self)bool[source]

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

property paused(self)bool[source]

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

property running(self)bool[source]

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

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

property status(self)str[source]

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(self)List[ErrorType][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.

property fatal_errors(self)List[ErrorType][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.

clear_fatal_errors(self)None[source]

Manually clears all fatal errors. This should be used after they have been resolved by the user through the GUI or CLI.

property account_profile_pic_path(self)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.

get_file_status(self, local_path: str)str[source]

Returns the sync status of an individual file.

Parameters

local_path – 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.

get_activity(self, limit: Optional[int] = 100)List[StoneType][source]

Returns the current upload / download activity.

Parameters

limit – 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.

get_history(self, limit: Optional[int] = 100)List[StoneType][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 – 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.

get_account_info(self)maestral.utils.serializer.StoneType[source]

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

Returns

Dropbox account information.

Raises
get_space_usage(self)maestral.utils.serializer.StoneType[source]

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

Returns

Dropbox space usage information.

Raises
get_profile_pic(self)Optional[str][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
get_metadata(self, dbx_path: str)Optional[StoneType][source]

Returns metadata for a file or folder on Dropbox.

Parameters

dbx_path – Path to file or folder on Dropbox.

Returns

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

Raises
list_folder(self, dbx_path: str, **kwargs)List[StoneType][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 – Path to folder on Dropbox.

Returns

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

Raises
list_folder_iterator(self, dbx_path: str, **kwargs)Iterator[List[StoneType]][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 – Path to folder on Dropbox.

Returns

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

Raises
list_revisions(self, dbx_path: str, limit: int = 10)List[StoneType][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 – Path to file on Dropbox.

  • limit – Maximum number of revisions to list.

Returns

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

: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(self, old_rev: str, new_rev: Optional[str] = None)List[str][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 – Identifier of old revision.

  • new_rev – Identifier of new revision.

Returns

Diff as a list of strings (lines).

Raises
restore(self, dbx_path: str, rev: str)maestral.utils.serializer.StoneType[source]

Restore an old revision of a file.

Parameters
  • dbx_path – The path to save the restored file.

  • rev – 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
rebuild_index(self)None[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
start_sync(self)None[source]

Creates syncing threads and starts syncing.

Raises
stop_sync(self)None[source]

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

reset_sync_state(self)None[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.

set_excluded_items(self, items: List[str])None[source]
exclude_item(self, dbx_path: str)None[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 – Dropbox path of item to exclude.

Raises
include_item(self, dbx_path: str)None[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 – Dropbox path of item to include.

Raises
excluded_status(self, dbx_path: str)str[source]

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

Parameters

dbx_path – Path to item on Dropbox.

Returns

Excluded status.

Raises

NotLinkedError – if no Dropbox account is linked.

move_dropbox_directory(self, new_path: str)None[source]

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

Parameters

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

Raises
create_dropbox_directory(self, path: str)None[source]

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

Parameters

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

Raises

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

  • visibility – 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 – An optional password required to access the link. Will be ignored if the visibility is not “password”.

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

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

Parameters

url – URL of shared link to revoke.

Raises

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

Returns

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

Raises
to_local_path(self, dbx_path: str)str[source]

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

Parameters

dbx_path – Path relative to Dropbox root.

Returns

Corresponding path on local hard drive.

Raises
check_for_updates(self)Dict[str, Union[str, bool, None]][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).

shutdown_daemon(self)None[source]

Stop the event loop. This will also shut down the pyro daemon if running.