maestral.main
This module defines the main API which is exposed to the CLI or GUI.
Module Contents
- class maestral.main.Maestral(config_name='maestral', log_to_stderr=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
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
andfatal_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 toFalse
.
- get_auth_url(self)[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
- link(self, token)[source]
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
- unlink(self)[source]
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(self, 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(self, section, name)[source]
Gets a configuration option.
- Parameters
- Returns
Config value. May be any type accepted by
ast.literal_eval
.- Return type
Any
- set_state(self, 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(self, section, name)[source]
Gets a state value.
- Parameters
- Returns
State value. May be any type accepted by
ast.literal_eval
.- Return type
Any
- property dropbox_path(self)[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()
ormove_dropbox_directory()
to set or change the Dropbox directory location instead.- Raises
NotLinkedError – if no Dropbox account is linked.
- Return type
- property excluded_items(self)[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()
andinclude_item()
to add or remove individual items from selective sync.
- property log_level(self)[source]
Log level for log files, stderr and the systemd journal.
- Return type
- property notification_snooze(self)[source]
Snooze time for desktop notifications in minutes. Defaults to 0 if notifications are not snoozed.
- Return type
- property notification_level(self)[source]
Level for desktop notifications. See
notify
for level definitions.- Return type
- status_change_longpoll(self, 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 (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
New in version 1.3.0.
- property pending_link(self)[source]
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.
- Return type
- property pending_dropbox_folder(self)[source]
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
maestral.exceptions.NoDropboxDirError
.- Return type
- property pending_first_download(self)[source]
Indicates if the initial download has already occurred (read only).
- Return type
- property paused(self)[source]
Indicates if syncing is paused by the user (read only). This is set by calling
pause()
.- Return type
- property running(self)[source]
Indicates if sync threads are running (read only). This will return
False
beforestart_sync()
is called, when shutting down, or because of an unhandled exception in a sync thread.- Return type
- property connected(self)[source]
Indicates if Dropbox servers can be reached (read only).
- Return type
- property status(self)[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
- property sync_errors(self)[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
- property fatal_errors(self)[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
- clear_fatal_errors(self)[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(self)[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
- get_file_status(self, 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” for a folder, even if some of the 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’ (for files outside the Dropbox directory). This will always be ‘unwatched’ if syncing is paused.
- Return type
- get_activity(self, 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 furthest up in the queue coming first.
- Raises
NotLinkedError – if no Dropbox account is linked.
- Return type
- get_history(self, 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 (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
- get_account_info(self)[source]
Returns the account information from Dropbox and returns it as a dictionary.
- Returns
Dropbox account information.
- Raises
DropboxAuthError – in case of an invalid access token.
DropboxServerError – for internal Dropbox errors.
ConnectionError – if the connection to Dropbox fails.
NotLinkedError – if no Dropbox account is linked.
- Return type
- get_space_usage(self)[source]
Gets the space usage from Dropbox and returns it as a dictionary.
- Returns
Dropbox space usage information.
- Raises
DropboxAuthError – in case of an invalid access token.
DropboxServerError – for internal Dropbox errors.
ConnectionError – if the connection to Dropbox fails.
NotLinkedError – if no Dropbox account is linked.
- Return type
- get_profile_pic(self)[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
DropboxAuthError – in case of an invalid access token.
DropboxServerError – for internal Dropbox errors.
ConnectionError – if the connection to Dropbox fails.
NotLinkedError – if no Dropbox account is linked.
- Return type
str | None
- get_metadata(self, 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
NotFoundError – if there is nothing at the given path.
DropboxAuthError – in case of an invalid access token.
DropboxServerError – for internal Dropbox errors.
ConnectionError – if the connection to Dropbox fails.
NotLinkedError – if no Dropbox account is linked.
- Return type
Metadata | None
- list_folder(self, 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 callclient.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
NotFoundError – if there is nothing at the given path.
NotAFolderError – if the given path refers to a file.
DropboxAuthError – in case of an invalid access token.
DropboxServerError – for internal Dropbox errors.
ConnectionError – if the connection to Dropbox fails.
NotLinkedError – if no Dropbox account is linked.
- Return type
- list_folder_iterator(self, 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 callclient.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
NotFoundError – if there is nothing at the given path.
NotAFolderError – if the given path refers to a file.
DropboxAuthError – in case of an invalid access token.
DropboxServerError – for internal Dropbox errors.
ConnectionError – if the connection to Dropbox fails.
NotLinkedError – if no Dropbox account is linked.
- Return type
Iterator[list[maestral.core.Metadata]]
- list_revisions(self, 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
- 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.
IsAFolderError – if the given path refers to a folder
DropboxAuthError – in case of an invalid access token.
DropboxServerError – for internal Dropbox errors.
ConnectionError – if the connection to Dropbox fails.
- Return type
- get_file_diff(self, 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
- Returns
Diff as a list of strings (lines).
- Raises
UnsupportedFileTypeForDiff – if file type is not supported.
UnsupportedFileTypeForDiff – if file content could not be decoded.
MaestralApiError – if file could not be read for any other reason.
- Return type
- restore(self, 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
DropboxAuthError – in case of an invalid access token.
DropboxServerError – for internal Dropbox errors.
ConnectionError – if the connection to Dropbox fails.
- Return type
- rebuild_index(self)[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
ormaestral_errors
.- Raises
NotLinkedError – if no Dropbox account is linked.
NoDropboxDirError – if local Dropbox folder is not set up.
- Return type
None
- start_sync(self)[source]
Creates syncing threads and starts syncing.
- Raises
NotLinkedError – if no Dropbox account is linked.
NoDropboxDirError – if local Dropbox folder is not set up.
- Return type
None
- stop_sync(self)[source]
Stops all syncing threads if running. Call
start_sync()
to restart syncing.- Return type
None
- reset_sync_state(self)[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_item(self, 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
NotFoundError – if there is nothing at the given path.
ConnectionError – if the connection to Dropbox fails.
DropboxAuthError – in case of an invalid access token.
DropboxServerError – for internal Dropbox errors.
ConnectionError – if the connection to Dropbox fails.
NotLinkedError – if no Dropbox account is linked.
NoDropboxDirError – if local Dropbox folder is not set up.
- Return type
None
- include_item(self, 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
ormaestral_errors
.- Parameters
dbx_path (str) – Dropbox path of item to include.
- Raises
NotFoundError – if there is nothing at the given path.
DropboxAuthError – in case of an invalid access token.
DropboxServerError – for internal Dropbox errors.
ConnectionError – if the connection to Dropbox fails.
NotLinkedError – if no Dropbox account is linked.
NoDropboxDirError – if local Dropbox folder is not set up.
- Return type
None
- excluded_status(self, 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
- move_dropbox_directory(self, 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
OSError – if moving the directory fails.
NotLinkedError – if no Dropbox account is linked.
NoDropboxDirError – if local Dropbox folder is not set up.
- Return type
None
- create_dropbox_directory(self, 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
OSError – if creation fails.
NotLinkedError – if no Dropbox account is linked.
- 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 | 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
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
DropboxAuthError – in case of an invalid access token.
DropboxServerError – for internal Dropbox errors.
ConnectionError – if the connection to Dropbox fails.
NotLinkedError – if no Dropbox account is linked.
- 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
DropboxAuthError – in case of an invalid access token.
DropboxServerError – for internal Dropbox errors.
ConnectionError – if the connection to Dropbox fails.
NotLinkedError – if no Dropbox account is linked.
- Return type
- to_local_path(self, 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
NotLinkedError – if no Dropbox account is linked.
NoDropboxDirError – if local Dropbox folder is not set up.
- Return type
- check_for_updates(self)[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