Synadm Package#

The synadm package contains the synadm.api module which is responsible for accessing the Synapse Admin API endpoints and the regular Matrix API endpoints. Also some helper methods, e.g to calculate time-related things are to be found in this module:

Synapse Admin API and regular Matrix API clients

Most API calls defined in this module respect the API’s defaults and only pass what’s necessary in the request body.

A fully qualified Matrix user ID looks like this: @user:server, where server often is a domain name only, e.g @user@example.org

See matrix-org/synapse for documentation of the Synapse Admin APIs and the Matrix spec at https://matrix.org/docs/spec/#matrix-apis.

class synadm.api.ApiRequest(log, user, token, base_url, path, timeout, debug, verify=None)#

Bases: object

Basic API request handling and helper utilities

This is subclassed by SynapseAdmin and Matrix

query(method, urlpart, params=None, data=None, token=None, base_url_override=None, verify=None, *args, **kwargs)#

Generic wrapper around requests methods.

Handles requests methods, logging and exceptions, and URL encoding.

Parameters:
  • urlpart (string) – The path to the API endpoint, excluding self.base_url and self.path (the part after proto://fqdn:port/path). It will be passed to Python’s str.format, so the string should not be already formatted (as f-strings or with str.format) as to sanitize the URL.

  • params (dict, optional) – URL parameters (?param1&paarm2). Defaults to None.

  • data (dict, optional) – Request body used in POST, PUT, DELETE requests. Defaults to None.

  • base_url_override (bool) – The default setting of self.base_url set on initialization can be overwritten using this argument.

  • verify (bool) – Mandatory SSL verification is turned on by default and can be turned off using this method.

  • *args – Arguments that will be URL encoded and passed to Python’s str.format.

  • **kwargs – Keyword arguments that will be URL encoded (only the values) and passed to Python’s str.format.

Returns:

Usually a JSON string containing

the response of the API; responses that are not 200(OK) (usally error messages returned by the API) will also be returned as JSON strings. On exceptions the error type and description are logged and None is returned.

Return type:

string or None

_timestamp_from_days_ago(days)#

Get a unix timestamp in ms from days ago

Parameters:

days (int) – number of days

Returns:

a unix timestamp in milliseconds (ms)

Return type:

int

_timestamp_from_days_ahead(days)#

Get a unix timestamp in ms for the given number of days ahead

Parameters:

days (int) – number of days

Returns:

a unix timestamp in milliseconds (ms)

Return type:

int

_timestamp_from_datetime(_datetime)#

Get a unix timestamp in ms from a datetime object

Parameters:

_datetime (datetime object) – an object built by datetime.datetime

Returns:

a unix timestamp in milliseconds (ms)

Return type:

int

_datetime_from_timestamp(timestamp, as_str=False)#

Get a datetime object from a unix timestamp in ms

Parameters:

timestamp (int) – a unix timestamp in milliseconds (ms)

Returns:

an object built by datetime.datetime.

If as_str is set, return a string formatted by self._format_datetime() instead.

Return type:

datetime object

_format_datetime(datetime_obj)#

Get a formatted date as a string.

Parameters:

datetime_obj (int) – A datetime object.

Returns:

A date in the format we use it throughout synadm. No sanity

checking.

Return type:

string

class synadm.api.MiscRequest(log, timeout, debug, verify=None)#

Bases: ApiRequest

Miscellaneous HTTP requests

Inheritance:
ApiRequest (object): parent class containing general properties and

methods for requesting REST API’s

federation_uri_well_known(base_url)#

Retrieve the URI to the Server-Server (Federation) API port via the .well-known resource of a Matrix server/domain.

Parameters:

base_url – proto://name or proto://fqdn

Returns:

https://fqdn:port of the delegated server for Server-Server

communication between Matrix homeservers or None on errors.

Return type:

string

class synadm.api.Matrix(log, user, token, base_url, matrix_path, timeout, debug, verify)#

Bases: ApiRequest

Matrix API client

Inheritance:
ApiRequest (object): parent class containing general properties and

methods for requesting REST API’s

user_login(user_id, password)#

Login as a Matrix user and retrieve an access token

Parameters:
  • user_id (string) – a fully qualified Matrix user ID

  • password (string) – the Matrix user’s password

Returns:

JSON string containing a token suitable to access the

Matrix API on the user’s behalf, a device_id and some more details on Matrix server and user.

Return type:

string

room_get_id(room_alias)#

Get the room ID for a given room alias

Parameters:

room_alias (string) – A Matrix room alias (#name:example.org)

Returns:

A dict containing the room ID for the alias.

If room_id is missing in the response we return the whole response as it might contain Synapse’s error message.

Return type:

string, dict or None

room_get_aliases(room_id)#

Get a list of room aliases for a given room ID

Parameters:

room_id (string) – A Matrix room ID (!abc123:example.org)

Returns:

A dict containing a list of room aliases, Synapse’s

error message or None on exceptions.

Return type:

dict or None

raw_request(endpoint, method, data, token=None)#
server_name_keys_api(server_server_uri)#

Retrieve the Matrix server’s own homeserver name via the Server-Server (Federation) API.

Parameters:

server_server_uri (string) – proto://name:port or proto://fqdn:port

Returns:

The Matrix server’s homeserver name or FQDN, usually something like matrix.DOMAIN or DOMAIN

Return type:

string

class synadm.api.SynapseAdmin(log, user, token, base_url, admin_path, timeout, debug, verify)#

Bases: ApiRequest

Synapse Admin API client

Inheritance:
ApiRequest (object): parent class containing general properties and

methods for requesting REST API’s

user_list(_from, _limit, _guests, _deactivated, _name, _user_id, _admin=None)#

List and search users

Parameters:
  • _from (int) – offsets user list by this number, used for pagination

  • _limit (int) – maximum number of users returned, used for pagination

  • _guests (bool) – enable/disable fetching of guest users

  • _deactivated (bool) – enable/disable fetching of deactivated users

  • _name (string) – user name localpart to search for, see Synapse Admin API docs for details

  • _user_id (string) – fully qualified Matrix user ID to search for

  • _admin (bool or None) – whether to filter for admins. a None does not filter.

Returns:

JSON string containing the found users

Return type:

string

user_list_paginate(_limit, _guests, _deactivated, _name, _user_id, _from='0', admin=None)#

Yields API responses for all of the pagination.

Parameters:
  • _limit (int) – Maximum number of users returned, used for pagination.

  • _guests (bool) – Enable/disable fetching of guest users.

  • _deactivated (bool) – Enable/disable fetching of deactivated users.

  • _name (string) – User name localpart to search for, see Synapse Admin API docs for details.

  • _user_id (string) – Fully qualified Matrix user ID to search for.

  • _from (string) – Offsets user list by this number, used for pagination.

Yields:

dict

The Admin API response for listing accounts.

https://element-hq.github.io/synapse/latest/admin_api/user_admin_api.html#list-accounts

user_membership(user_id, return_aliases, matrix_api)#

Get a list of rooms the given user is member of

Parameters:
  • user_id (string) – Fully qualified Matrix user ID

  • room_aliases (bool) – Return human readable room aliases instead of room ID’s if applicable.

  • matrix_api (object) – An initialized Matrix object needs to be passes as we need some Matrix API functionality here.

Returns:

JSON string containing the Admin API’s response or None if

an exception occured. See Synapse Admin API docs for details.

Return type:

string

user_deactivate(user_id, gdpr_erase)#

Delete a given user

Parameters:
  • user_id (string) – fully qualified Matrix user ID

  • gdpr_erase (bool) – enable/disable gdpr-erasing the user, see Synapse Admin API docs for details.

Returns:

JSON string containing the Admin API’s response or None if

an exception occured. See Synapse Admin API docs for details.

Return type:

string

user_password(user_id, password, no_logout)#

Set the user password, and log the user out if requested

Parameters:
  • user_id (string) – fully qualified Matrix user ID

  • password (string) – new password that should be set

  • no_logout (bool) – the API defaults to logging out the user after password reset via the Admin API, this option can be used to disable this behaviour.

Returns:

JSON string containing the Admin API’s response or None if an exception occured. See Synapse Admin API docs for details.

Return type:

string

user_details(user_id)#

Get information about a given user

Note that the Admin API docs describe this function as “Query User Account”.

Parameters:

user_id (string) – fully qualified Matrix user ID

Returns:

JSON string containing the Admin API’s response or None if

an exception occured. See Synapse Admin API docs for details.

Return type:

string

user_login(user_id, expire_days, expire, _expire_ts)#

Get an access token that can be used to authenticate as that user.

If one of the args expire_days, expire or _expire_ts is set, the valid_until_ms field will be sent to the API endpoint. If this is not the case the default of the API would be used. At the time of writing, this would be that tokens never expire.

Note: If this method is called by the CLI frontend code (synadm.cli.user.user_login_cmd), a default expiry date of 1 day (24h) is passed.

Parameters:
  • user_id (string) – fully qualified Matrix user ID

  • expire_days (int) – token should expire after this number of days

  • expire (datetime) – token should expire after this date/time - a datetime object (e.g. as generated by Click.DateTime())

  • _expire_ts (int) – token should expire after this date/time - a unix timestamp in ms.

Returns:

JSON string containing the Admin API’s response or None if an exception occured. See Synapse Admin API docs for details.

Return type:

string

user_modify(user_id, password, display_name, threepid, avatar_url, admin, deactivation, user_type, lock)#

Create or update information about a given user

The threepid argument must be passed as a tuple in a tuple (which is what we usually get from a Click multi-arg option)

user_whois(user_id)#

Return information about the active sessions for a specific user

user_devices(user_id)#

Return information about all devices for a specific user.

Parameters:

user_id (string) – Fully qualified Matrix user ID.

Returns:

JSON string containing the Admin API’s response or None if

an exception occured. See Synapse Admin API docs for details.

Return type:

string

user_devices_get_todelete(devices_data, min_days, min_surviving, device_id, readable_seen)#

Gather a list of devices that possibly could be deleted.

This method is used by the ‘user prune-devices’ command.

Parameters:
  • devices_data (list) – Containing dicts of all the user’s devices, as returned by the user_devices method (the user/devices API endpoint).

  • min_days (int) – At least this number of days need to have passed from the last time a device was seen for it to be deleted. A reasonable default should be sent by the CLI level method.

  • min_surviving – At least this amount of devices will be kept alive. A reasonable default should be sent by the CLI level method.

  • device_id – Only search devices with this ID.

  • datetime – When True, ‘last seen timestamp’ is replaced with a human readable format.

Returns:

Containing dicts of devices that possibly could be deleted.

If non apply, an empty list is returned.

Return type:

list

user_devices_delete(user_id, devices)#

Delete the specified devices for a specific user. Returns an empty JSON dict.

devices is a list of device IDs

Finds a user based on their ID (external id) in auth provider represented by auth provider id (provider).

Finds a user based on their Third Party ID by specifying what kind of 3PID it is as medium.

room_join(room_id_or_alias, user_id)#

Allow an administrator to join an user account with a given user_id to a room with a given room_id_or_alias

room_list(_from, limit, name, order_by, reverse)#

List and search rooms

room_list_paginate(limit, name, order_by, reverse, _from=0)#

Yields API responses for room listing.

Parameters:
  • limit (int) – Maximum number of rooms returned per pagination.

  • name (string or None) – Search for a room by name. Passed as search_term in the room list API. Use Python None to avoid searching.

  • order_by (string) – Synapse Room list API specific argument.

  • reverse (bool) – Whether the results should be

  • _from (int) – Initial offset in pagination.

Yields:

dict

The Admin API response for listing accounts.

https://element-hq.github.io/synapse/latest/admin_api/rooms.html#list-room-api

room_details(room_id)#

Get details about a room

room_members(room_id)#

Get a list of room members

room_state(room_id)#

Get a list of all state events in a room.

Parameters:

room_id (string) –

Returns:

JSON string containing the Admin API’s response or None if

an exception occured. See Synapse Admin API docs for details.

Return type:

string

room_power_levels(from_, limit, name, order_by, reverse, room_id=None, all_details=True, output_format='json')#

Get a list of configured power_levels in all rooms.

or a single room.

Parameters:

room_id (string) – If left out, all rooms are fetched.

Returns:

JSON string containing the Admin API’s response or None if

an exception occured. See Synapse Admin API docs for details.

Return type:

string

room_delete(room_id, new_room_user_id, room_name, message, block, no_purge, force_purge)#

Delete a room and purge it if requested

room_delete_v2(room_id, new_room_user_id, room_name, message, block, purge, force_purge)#

Delete a room asynchronously and purge it if requested

room_delete_v2_status_by_room_id(room_id)#
room_delete_v2_status_by_delete_id(delete_id)#
block_room(room_id, block)#

Block or unblock a room.

Parameters:
  • room_id (string) – Required.

  • block (boolean) – Whether to block or unblock a room.

Returns:

JSON string containing the Admin API’s response or None if

an exception occurred. See Synapse Admin API docs for details.

Return type:

string

room_block_status(room_id)#

Returns if the room is blocked or not, and who blocked it.

Parameters:

room_id (string) – Fully qualified Matrix room ID.

Returns:

JSON string containing the Admin API’s response or None if

an exception occured. See Synapse Admin API docs for details.

Return type:

string

room_make_admin(room_id, user_id)#

Grant a user room admin permission. If the user is not in the room, and it is not publicly joinable, then invite the user.

room_media_list(room_id)#

Get a list of known media in an (unencrypted) room.

media_quarantine(server_name, media_id)#

Quarantine a single piece of local or remote media

media_unquarantine(server_name, media_id)#

Removes a single piece of local or remote media from quarantine.

room_media_quarantine(room_id)#

Quarantine all local and remote media in a room

user_media_quarantine(user_id)#

Quarantine all local and remote media of a user

user_media(user_id, _from, limit, order_by, reverse, readable)#

Get a user’s uploaded media

media_delete(server_name, media_id)#

Delete a specific (local) media_id

media_delete_by_date_or_size(before_days, before, _before_ts, _size_gt, delete_profiles)#

Delete local media by date and/or size FIXME and/or?

media_protect(media_id)#

Protect a single piece of local or remote media

from being quarantined

purge_media_cache(before_days, before, _before_ts)#

Purge old cached remote media

version()#

Get the server version

group_delete(group_id)#

Delete a local group (community)

purge_history(room_id, before_event_id, before_days, before, _before_ts, delete_local)#

Purge room history

purge_history_status(purge_id)#

Get status of a recent history purge

The status will be one of active, complete, or failed.

regtok_list(valid, readable_expiry)#

List registration tokens

Parameters:
  • valid (bool) – List only valid (if True) or invalid (if False) tokens. Default is to list all tokens regardless of validity.

  • readable_expiry (bool) – If True, replace the expiry_time field with a human readable datetime. If False, expiry_time will be a unix timestamp.

Returns:

JSON string containing the Admin API’s response or None if

an exception occured. See Synapse Admin API docs for details.

Return type:

string

regtok_details(token, readable_expiry)#

Get details about the given registration token

Parameters:
  • token (string) – The registration token in question

  • readable_expiry (bool) – If True, replace the expiry_time field with a human readable datetime. If False, expiry_time will be a unix timestamp.

Returns:

JSON string containing the Admin API’s response or None if

an exception occured. See Synapse Admin API docs for details.

Return type:

string

regtok_new(token, length, uses_allowed, expiry_ts, expire_at)#

Create a new registration token

Parameters:
  • token (string) – Registration token to create. Default is randomly generated by the server.

  • length (int) – The length of the token to generate if the token is not provided.

  • uses_allowed (int) – The number of times the token can be used to complete a registration before it becomes invalid.

  • expiry_ts (int) – The latest time the registration token is valid. Given as the number of milliseconds since 1970-01-01 00:00:00 UTC.

  • expire_at (click.DateTime) – The latest time the registration token is valid.

Returns:

JSON string containing the Admin API’s response or None if

an exception occured. See Synapse Admin API docs for details.

Return type:

string

regtok_update(token, uses_allowed, expiry_ts, expire_at)#

Update a registration token

Parameters:
  • token (string) – Registration token to update.

  • uses_allowed (int) – The number of times the token can be used to complete a registration before it becomes invalid.

  • expiry_ts (int) – The latest time the registration token is valid. Given as the number of milliseconds since 1970-01-01 00:00:00 UTC. -1 indicates no expiry.

  • expire_at (click.DateTime) – The latest time the registration token is valid.

Returns:

JSON string containing the Admin API’s response or None if

an exception occured. See Synapse Admin API docs for details.

Return type:

string

regtok_delete(token)#

Delete a registration token

Parameters:

token (string) – The registration token to delete

Returns:

JSON string containing the Admin API’s response or None if

an exception occured. See Synapse Admin API docs for details.

Return type:

string

user_shadow_ban(user_id, unban)#

Shadow-ban or unban a user.

Parameters:
  • user_id (string) – The user to be banned/unbanned.

  • unban (boolean) – Unban the specified user.

notice_send(receivers, content_plain, content_html, paginate, regex)#

Send server notices.

Parameters:
  • receivers (string) – Target(s) of the notice. Either localpart or regular expression matching localparts.

  • content_plain (string) – Unformatted text of the notice.

  • content_html (string) – HTML-formatted text of the notice.

  • paginate (int) – Limits to how many users the notice is sent at once. Users are fetched with the user_list method and using its pagination capabilities.

  • to_regex (bool) – Selects whether receivers should be interpreted as a regular expression or a single recipient.

Returns:

A list of dictionaries, each containing the response of

what a single notice Admin API call returned. Usually that is an event ID or an error. See Synapse Admin API docs for details.

Return type:

list

raw_request(endpoint, method, data)#