maestral.main ============= .. py:module:: maestral.main .. autoapi-nested-parse:: This module defines the main API which is exposed to the CLI or GUI. Module Contents --------------- .. py:class:: 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 :exc:`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 :attr:`sync_errors` and :attr:`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 :meth:`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() :param config_name: Name of maestral configuration to run. Must not contain any whitespace. If the given config file does exist, it will be created. :param log_to_stderr: 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``. :param event_loop: 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. :param shutdown_future: 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``. .. py:attribute:: cred_storage .. py:attribute:: client .. py:attribute:: sync .. py:attribute:: manager .. py:attribute:: shutdown_future :value: None .. py:property:: version :type: str Returns the current Maestral version. .. py:method:: 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 :meth:`link` with the provided code. :returns: URL to retrieve an authorization code. .. py:method:: 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 :mod:`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. :param code: Authorization code. :param refresh_token: Optionally, instead of an authorization code, directly provide a refresh token. :param access_token: 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. .. py:method:: 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: if no Dropbox account is linked. .. py:property:: config_name :type: str The selected configuration. .. py:method:: set_conf(section, name, value) Sets a configuration option. :param section: Name of section in config file. :param name: Name of config option. :param value: Config value. May be any type accepted by :obj:`ast.literal_eval`. .. py:method:: get_conf(section, name) Gets a configuration option. :param section: Name of section in config file. :param name: Name of config option. :returns: Config value. May be any type accepted by :obj:`ast.literal_eval`. .. py:method:: set_state(section, name, value) Sets a state value. :param section: Name of section in state file. :param name: Name of state variable. :param value: State value. May be any type accepted by :obj:`ast.literal_eval`. .. py:method:: get_state(section, name) Gets a state value. :param section: Name of section in state file. :param name: Name of state variable. :returns: State value. May be any type accepted by :obj:`ast.literal_eval`. .. py:property:: dropbox_path :type: 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 :meth:`create_dropbox_directory` or :meth:`move_dropbox_directory` to set or change the Dropbox directory location instead. :raises NotLinkedError: if no Dropbox account is linked. .. py:property:: excluded_items :type: set[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 :meth:`exclude_item` and :meth:`include_item` to add or remove individual items from selective sync. .. py:property:: log_level :type: int Log level for log files, stderr and the systemd journal. .. py:property:: notification_snooze :type: float Snooze time for desktop notifications in minutes. Defaults to 0 if notifications are not snoozed. .. py:property:: notification_level :type: int Level for desktop notifications. See :mod:`notify` for level definitions. .. py:property:: bandwidth_limit_down :type: float Maximum download bandwidth to use in bytes per second. .. py:property:: bandwidth_limit_up :type: float Maximum download bandwidth to use in bytes per second. .. py:method:: 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. :param timeout: Maximum time to block before returning, even if there is no status change. :returns: Whether there was a status change within the timeout. .. versionadded:: 1.3.0 .. py:property:: pending_link :type: 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. .. py:property:: pending_dropbox_folder :type: 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 :exc:`maestral.exceptions.NoDropboxDirError`. .. py:property:: pending_first_download :type: bool Whether the initial download has already started (read only). .. py:property:: paused :type: bool Whether syncing is paused by the user (read only). Use :meth:`start_sync` and :meth:`stop_sync` to start and stop syncing, respectively. .. py:property:: running :type: bool Whether sync threads are running (read only). This is similar to :attr:`paused` but also returns False if syncing is paused because we cannot connect to Dropbox servers.. .. py:property:: connected :type: bool Whether Dropbox servers can be reached (read only). .. py:property:: status :type: str The last status message (read only). This can be displayed as information to the user but should not be relied on otherwise. .. py:property:: sync_errors :type: list[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: if no Dropbox account is linked. .. py:property:: fatal_errors :type: list[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. .. py:method:: 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. .. py:property:: account_profile_pic_path :type: 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. .. py:method:: 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. .. versionadded:: 1.4.4 Recursive behavior. Previous versions would return "up to date" for a folder, even if some contained files would be syncing. :param 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'. .. py:method:: get_activity(limit = 100) Returns the current upload / download activity. :param 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 the furthest up in the queue coming first. :raises NotLinkedError: if no Dropbox account is linked. .. py:method:: 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. :param dbx_path: If given, show sync history for the specified Dropbox path only. :param 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. .. py:method:: get_account_info() 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. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. :raises NotLinkedError: if no Dropbox account is linked. .. py:method:: get_space_usage() 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. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. :raises NotLinkedError: if no Dropbox account is linked. .. py:method:: 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 :attr:`account_profile_pic_path` for cached profile pics. :returns: Path to saved profile picture or ``None`` if no profile picture was downloaded. :raises DropboxAuthError: in case of an invalid access token. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. :raises NotLinkedError: if no Dropbox account is linked. .. py:method:: get_metadata(dbx_path) Returns metadata for a file or folder on Dropbox. :param dbx_path: Path to file or folder on Dropbox. :returns: Dropbox item metadata as dict. See :class:`dropbox.files.Metadata` for keys and values. :raises NotFoundError: if there is nothing at the given path. :raises DropboxAuthError: in case of an invalid access token. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. :raises NotLinkedError: if no Dropbox account is linked. .. py:method:: 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 :meth:`client.DropboxClient.list_folder`. :param dbx_path: Path to folder on Dropbox. :param recursive: If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders. :param include_deleted: If true, the results will include entries for files and folders that used to exist but were deleted. :param bool include_mounted_folders: If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder. :param bool include_non_downloadable_files: If true, include files that are not downloadable, i.e. Google Docs. :raises NotFoundError: if there is nothing at the given path. :raises NotAFolderError: if the given path refers to a file. :raises DropboxAuthError: in case of an invalid access token. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. :raises NotLinkedError: if no Dropbox account is linked. .. py:method:: 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 :meth:`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. :param dbx_path: Path to folder on Dropbox. :param recursive: If true, the list folder operation will be applied recursively to all subfolders and the response will contain contents of all subfolders. :param include_deleted: If true, the results will include entries for files and folders that used to exist but were deleted. :param bool include_mounted_folders: If true, the results will include entries under mounted folders which includes app folder, shared folder and team folder. :param Nullable[int] limit: 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. :param bool include_non_downloadable_files: If true, include files that are not downloadable, i.e. Google Docs. :returns: Iterator over list of Dropbox item metadata as dicts. See :class:`dropbox.files.Metadata` for keys and values. :raises NotFoundError: if there is nothing at the given path. :raises NotAFolderError: if the given path refers to a file. :raises DropboxAuthError: in case of an invalid access token. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. :raises NotLinkedError: if no Dropbox account is linked. .. py:method:: 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. :param dbx_path: Path to file on Dropbox. :param limit: Maximum number of revisions to list. :returns: List of Dropbox file metadata as dicts. See :class:`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. .. py:method:: 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. :param old_rev: Identifier of old revision. :param new_rev: Identifier of new revision. :returns: Diff as a list of strings (lines). :raises UnsupportedFileTypeForDiff: if file type is not supported. :raises UnsupportedFileTypeForDiff: if file content could not be decoded. :raises MaestralApiError: if file could not be read for any other reason. .. py:method:: restore(dbx_path, rev) Restore an old revision of a file. :param dbx_path: The path to save the restored file. :param rev: The revision to restore. Old revisions can be listed with :meth:`list_revisions`. :returns: Metadata of the returned file. See :class:`dropbox.files.FileMetadata` for keys and values. :raises DropboxAuthError: in case of an invalid access token. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. .. py:method:: 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 :attr:`sync_errors` or :attr:`maestral_errors`. :raises NotLinkedError: if no Dropbox account is linked. :raises NoDropboxDirError: if local Dropbox folder is not set up. .. py:method:: start_sync() Creates syncing threads and starts syncing. :raises NotLinkedError: if no Dropbox account is linked. :raises NoDropboxDirError: if local Dropbox folder is not set up. .. py:method:: stop_sync() Stops all syncing threads if running. Call :meth:`start_sync` to restart syncing. .. py:method:: 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: if no Dropbox account is linked. .. py:method:: 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. :param dbx_paths: Dropbox paths of items to exclude. :raises NotFoundError: if there is nothing at the given path. :raises ConnectionError: if the connection to Dropbox fails. :raises DropboxAuthError: in case of an invalid access token. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. :raises NotLinkedError: if no Dropbox account is linked. :raises NoDropboxDirError: if local Dropbox folder is not set up. .. py:method:: 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 :attr:`sync_errors` or :attr:`maestral_errors`. :param dbx_paths: Dropbox paths of items to include. :raises NotFoundError: if there is nothing at the given path. :raises DropboxAuthError: in case of an invalid access token. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. :raises NotLinkedError: if no Dropbox account is linked. :raises NoDropboxDirError: if local Dropbox folder is not set up. .. py:method:: excluded_status(dbx_path) Returns 'excluded', 'partially excluded' or 'included'. This function will not check if the item actually exists on Dropbox. :param dbx_path: Path to item on Dropbox. :returns: Excluded status. :raises NotLinkedError: if no Dropbox account is linked. .. py:method:: move_dropbox_directory(new_path) Sets the local Dropbox directory. This moves all local files to the new location and resumes syncing afterwards. :param new_path: Full path to local Dropbox folder. "~" will be expanded to the user's home directory. :raises OSError: if moving the directory fails. :raises NotLinkedError: if no Dropbox account is linked. :raises NoDropboxDirError: if local Dropbox folder is not set up. .. py:method:: create_dropbox_directory(path) Creates a new Dropbox directory. Only call this during setup. :param path: Full path to local Dropbox folder. "~" will be expanded to the user's home directory. :raises OSError: if creation fails. :raises NotLinkedError: if no Dropbox account is linked. .. py:method:: 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. :param dbx_path: Dropbox path to file or folder to share. :param visibility: 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. :param access_level: The level of access granted with the link. Can be viewer, editor, or max for maximum possible access level. :param allow_download: Whether to allow download capabilities for the link. :param password: If given, enables password protection for the link. :param expires: 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. .. py:method:: revoke_shared_link(url) Revokes the given shared link. Note that any other links to the same file or folder will remain valid. :param url: URL of shared link to revoke. :raises DropboxAuthError: in case of an invalid access token. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. :raises NotLinkedError: if no Dropbox account is linked. .. py:method:: 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. :param dbx_path: Path to item on Dropbox. :returns: List of shared link information as dictionaries. See :class:`dropbox.sharing.SharedLinkMetadata` for keys and values. :raises DropboxAuthError: in case of an invalid access token. :raises DropboxServerError: for internal Dropbox errors. :raises ConnectionError: if the connection to Dropbox fails. :raises NotLinkedError: if no Dropbox account is linked. .. py:method:: to_local_path(dbx_path) Converts a path relative to the Dropbox folder to a correctly cased local file system path. :param dbx_path: Path relative to Dropbox root. :returns: Corresponding path on local hard drive. :raises NotLinkedError: if no Dropbox account is linked. :raises NoDropboxDirError: if local Dropbox folder is not set up. .. py:method:: 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: if checking for an update fails. .. py:method:: shutdown_daemon() Stop syncing and notify anyone monitoring ``shutdown_future`` that we are done.