def forward_extremities_delete(self, roomid: str) -> int: """Delete forward extremities in a room (Do not use this method when writing automated script) https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/rooms.md#deleting-forward-extremities Args: roomid (str): the room you want the forward extremities to be deleted # noqa: E501 Returns: int: number of forward extremities deleted """ roomid = self.validate_room(roomid) resp = self.connection.request( "DELETE", self.admin_patterns(f"/rooms/{roomid}/forward_extremities", 1)) data = resp.json() if resp.status_code == 200: return data["deleted"] else: # Synapse bug: Internal server error # raise if the room does not exist if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def event_context(self, roomid: str, event_id: str) -> dict: """Query the context of an event https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/rooms.md#event-context-api Args: roomid (str): the room where the event exist event_id (str): the event you want to query Returns: dict: a dict with event context """ roomid = self.validate_room(roomid) resp = self.connection.request( "GET", self.admin_patterns(f"/rooms/{roomid}/context/{event_id}", 1), ) data = resp.json() if resp.status_code == 200: return data else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def set_admin(self, roomid: str, userid: str = None) -> bool: """Set a member to be the admin in the room https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/rooms.md#make-room-admin-api Args: roomid (str): the room you want to grant admin privilege to the user # noqa: E501 userid (str, optional): the user you wanted them as an admin in the room. Defaults to None (self). Returns: bool: The modification is successful or not """ roomid = self.validate_room(roomid) if userid is not None: userid = self.validate_username(userid) body = {"user_id": userid} else: body = {} resp = self.connection.request("POST", self.admin_patterns( f"/rooms/{roomid}/make_room_admin", 1), json=body) data = resp.json() if resp.status_code == 200: return True else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def set_admin(self, userid: str, activate: bool = None) -> Tuple[bool, bool]: """Set or revoke server admin role for a user https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#change-whether-a-user-is-a-server-administrator-or-not Args: userid (str): the user you want to set or revoke activate (bool, optional): True to set as admin, False to revoke their admin, leave None to let the program decide. Defaults to None. # noqa: E501 Returns: Tuple[bool, bool]: success or not, is the user admin or not now """ if activate is None: activate = not self.is_admin(userid) elif not isinstance(activate, bool): raise TypeError("Argument 'activate' only accept " f"boolean but not {type(activate)}.") userid = self.validate_username(userid) resp = self.connection.request("PUT", self.admin_patterns( f"/users/{userid}/admin", 1), json={"admin": activate}) if resp.status_code == 200: # TBD: whether or not to return both action status and admin status return True, activate else: data = resp.json() if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def purge_remote_media( self, timestamp: int = Utility.get_current_time()) -> int: """Purge remote homeserver media https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/media_admin_api.md#purge-remote-media-api Args: timestamp (int, optional): timestamp in millisecond. Defaults to Utility.get_current_time(). # noqa: E501 Returns: list: number of deleted media """ if not isinstance(timestamp, int): raise TypeError("Argument 'timestamp' should be an " f"int but not {type(timestamp)}") resp = self.connection.request( "POST", self.admin_patterns("/purge_media_cache?" f"before_ts={timestamp}", 1), json={}, ) data = resp.json() if resp.status_code == 200: return data["deleted"] else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def delete_old(self, roomid: str, new_room_userid: str = None, new_room_name: str = None, message: str = None, block: bool = False, purge: bool = True): """Old room deletion method. Use the new one.""" roomid = self.validate_room(roomid) data = {"block": block, "purge": purge} if new_room_userid is not None: new_room_userid = self.validate_username(new_room_userid) data["new_room_user_id"] = new_room_userid if new_room_name is not None: data["room_name"] = new_room_name if message is not None: data["message"] = message resp = self.connection.request("POST", self.admin_patterns( f"/rooms/{roomid}/delete", 1), json=data) data = resp.json() if resp.status_code == 200: return data else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def _delete_multiple(self, userid: str, devices: list) -> bool: """Delete multiple active devices (You should use User.delete) https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#delete-multiple-devices Args: userid (str): the owner of the device(s) device (list): the device(s) you want to delete Returns: bool: success or not """ userid = self.validate_username(userid) resp = self.connection.request("POST", self.admin_patterns( f"/users/{userid}/delete_devices", 2), json={"devices": devices}) if resp.status_code == 200: return True else: data = resp.json() if self.suppress_exception: return False, data["errcode"], data["error"] else: raise SynapseException(data["errcode"], data["error"])
def reset_password(self, userid: str, password: str = None, logout: bool = True) -> bool: """Reset a user password https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#reset-password Args: userid (str): the account you want to reset their password password (str, optional): the new password. Defaults to None. logout (bool, optional): whether or not to logout all current devices. Defaults to True. # noqa: E501 Returns: bool: success or not """ userid = self.validate_username(userid) if password is None: password = Utility.get_password() resp = self.connection.request("POST", self.admin_patterns( f"/reset_password/{userid}", 1), json={ "new_password": password, "logout_devices": logout }) if resp.status_code == 200: return True else: data = resp.json() if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def update(self, token: str, uses_allowed: int = None, expiry_time: int = None) -> dict: """Update a registration token https://github.com/matrix-org/synapse/blob/develop/docs/usage/administration/admin_api/registration_tokens.md#update-token Args: token (str): equivalent to "token". uses_allowed (int, optional): equivalent to "uses_allowed". Defaults to None. # noqa: E501 expiry_time (int, optional): equivalent to "expiry_time". Defaults to None. # noqa: E501 Returns: dict: new details of the token """ body = {} if uses_allowed: body["uses_allowed"] = uses_allowed if expiry_time: body["expiry_time"] = expiry_time resp = self.connection.request("PUT", self.admin_patterns( f"registration_tokens/{token}", 1), json=body) data = resp.json() if resp.status_code == 200: return data else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def deactivate(self, userid: str, erase: bool = True) -> bool: """Deactivate a user https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#deactivate-account Args: userid (str): the account you want to deactivate erase (bool, optional): whether to erase all information related to the user. Defaults to True. # noqa: E501 Returns: bool: success or not """ userid = self.validate_username(userid) resp = self.connection.request("POST", self.admin_patterns( f"/deactivate/{userid}", 1), json={"erase": erase}) data = resp.json() if resp.status_code == 200: return data["id_server_unbind_result"] == "success" else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def background_updates_run(self, job_name: str): """Run a background update https://github.com/matrix-org/synapse/blob/develop/docs/usage/administration/admin_api/background_updates.md#run Args: job_name (str): job name of the background update. # noqa: E501 """ jobs = {"populate_stats_process_rooms", "regenerate_directory"} if job_name not in jobs: raise ValueError( "Value of job_name can only be either" "populate_stats_process_rooms or regenerate_directory") resp = self.connection.request("POST", self.admin_patterns( "/background_updates/start_job", 1), json={"job_name": job_name}) data = resp.json() if resp.status_code == 200: return data else: if self.suppress_exception: return False, data["errcode"], data["error"] else: raise SynapseException(data["errcode"], data["error"])
def delete_local_media(self, mediaid: str, server_name: str = None) -> bool: """Delete a local media https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/media_admin_api.md#delete-a-specific-local-media Args: mediaid (str): the media you want to delete server_name (str, optional): the source of the media. Defaults to your local server name (None). # noqa: E501 Returns: str: the deletion is success or not """ if server_name is None: server_name = self.server_addr mediaid = self.extract_media_id(mediaid) resp = self.connection.request( "DELETE", self.admin_patterns(f"/media/{server_name}/{mediaid}", 1), json={}, ) data = resp.json() if resp.status_code == 200: return data["deleted_media"][0] == mediaid else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def purge_history(self, roomid: str, event_id_ts: Union[str, int], include_local_event: bool = False) -> str: """Purge old events in a room from database https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/purge_history_api.md#purge-history-api Args: roomid (str): the room you want to perform the purging event_id_ts (Union[str, int]): purge up to an event id or timestamp include_local_event (bool, optional): whether to purge local events. Defaults to False. # noqa: E501 Returns: str: purge id """ roomid = self.validate_room(roomid) data = {"delete_local_events": include_local_event} if isinstance(event_id_ts, str): data["purge_up_to_event_id"] = event_id_ts elif isinstance(event_id_ts, int): data["purge_up_to_ts"] = event_id_ts resp = self.connection.request("POST", self.admin_patterns( f"/purge_history/{roomid}", 1), json=data) data = resp.json() if resp.status_code == 200: return data["purge_id"] else: if self.suppress_exception: return False, data["errcode"], data["error"] else: raise SynapseException(data["errcode"], data["error"])
def update(self, userid: str, device: str, display_name: str) -> bool: """Update the display name of a device https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#update-a-device Args: userid (str): the owner of the device device (str): the device you want to modify display_name (str): the new display name Returns: bool: success or not """ userid = self.validate_username(userid) resp = self.connection.request("PUT", self.admin_patterns( f"/users/{userid}/devices/{device}", 2), json={"display_name": display_name}) if resp.status_code == 200: return True else: data = resp.json() if self.suppress_exception: return False, data["errcode"], data["error"] else: raise SynapseException(data["errcode"], data["error"])
def join_room(self, userid: str, roomid: str) -> bool: """Force an user to join a room https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/room_membership.md#edit-room-membership-api Args: userid (str): the user you want to add to the room roomid (str): the room you want to add the user into Returns: bool: success or not """ userid = self.validate_username(userid) roomid = self.validate_room(roomid) resp = self.connection.request("POST", self.admin_patterns( f"/join/{roomid}", 1), json={"user_id": userid}) data = resp.json() if resp.status_code == 200: if "room_id" in data and data["room_id"] == roomid: return True else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def create_modify(self, userid: str, *, password: str = None, displayname: str = None, threepids: list = None, avatar_url: str = None, admin: bool = None, deactivated: bool = None, external_ids: list = None, user_type: Union[str, None] = "") -> bool: """Create or modify a user https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#create-or-modify-account Args: userid (str): The user id of the user password (str, optional): equivalent to "password". Defaults to None. # noqa: E501 displayname (str, optional): equivalent to "displayname". Defaults to None. threepids (list, optional): equivalent to "threepids". Defaults to None. avatar_url (str, optional): equivalent to "avatar_url". Defaults to None. admin (bool, optional): equivalent to "admin". Defaults to None. deactivated (bool, optional): equivalent to "deactivated". Defaults to None. external_ids (list, optional): equivalent to "external_ids". Defaults to None. user_type (Union[str, None], optional): equivalent to "user_type", empty str to leave this value unchange. Defaults to "". Returns: bool: The creation of user is successful or not """ body = {} if password: body["password"] = password if displayname: body["displayname"] = displayname if threepids: body["threepids"] = threepids if avatar_url: body["avatar_url"] = avatar_url if admin: body["admin"] = admin if deactivated: body["deactivated"] = deactivated if external_ids: body["external_ids"] = external_ids if user_type != "": body["user_type"] = user_type userid = self.validate_username(userid) resp = self.connection.request("PUT", self.admin_patterns( f"/users/{userid}", 2), json=body) if resp.status_code == 200 or resp.status_code == 201: return True else: data = resp.json() if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def username_available(self, userid: str) -> bool: """Check if provided username is available or not https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#check-username-availability Args: userid (str): the username you want to check Returns: bool: True: the username is available False: the username is used Please note that this method DOES NOT supress exception """ resp = self.connection.request( "GET", self.admin_patterns(f"/username_available?username={userid}", 1)) data = resp.json() if "available" in data: return data["available"] elif "errcode" in data and data["errcode"] == "M_USER_IN_USE": return False else: raise SynapseException(data["errcode"], data["error"])
def delete(self, userid: str, device: Union[str, list]) -> bool: """Delete active device(s) https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#delete-multiple-devices Args: userid (str): the owner of the device(s) device (Union[str, list]): the device(s) you want to delete Returns: bool: success or not """ if isinstance(device, list) and len(device) > 1: return self._delete_multiple(userid, device) elif isinstance(device, list) and len(device) == 1: device = device[0] userid = self.validate_username(userid) resp = self.connection.request( "DELETE", self.admin_patterns(f"/users/{userid}/devices/{device}", 2)) if resp.status_code == 200: return True else: data = resp.json() if self.suppress_exception: return False, data["errcode"], data["error"] else: raise SynapseException(data["errcode"], data["error"])
def get_ratelimit(self, userid: str) -> Tuple[int, int]: """Query the ratelimit applied to a user https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#get-status-of-ratelimit Args: userid (str): the user you want to query Returns: Tuple[int, int]: the current messages per second and burst count """ userid = self.validate_username(userid) resp = self.connection.request( "GET", self.admin_patterns(f"/users/{userid}/" "override_ratelimit", 1)) data = resp.json() if data == {}: return data if resp.status_code == 200: return data["messages_per_second"], data["burst_count"] else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def set_ratelimit(self, userid: str, mps: int, bc: int) -> Tuple[int, int]: """Set the ratelimit applied to a user https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#set-ratelimit Args: userid (str): the user you want to set mps (int): messages per second bc (int): burst count Returns: Tuple[int, int]: the current messages per second and burst count """ userid = self.validate_username(userid) data = {"messages_per_second": mps, "burst_count": bc} resp = self.connection.request("POST", self.admin_patterns( f"/users/{userid}/" "override_ratelimit", 1), json=data) data = resp.json() if resp.status_code == 200: return data["messages_per_second"], data["burst_count"] else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def login(self, userid: str, valid_until_ms: int = None) -> str: """Login as a user and get their access token https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#login-as-a-user Args: userid (str): the user you want to login valid_until_ms (int, optional): the validity period in millisecond. Defaults to None. # noqa: E501 Returns: str: access token of the user """ if isinstance(valid_until_ms, int): data = {"valid_until_ms": valid_until_ms} elif valid_until_ms is None: data = {} else: raise TypeError("Argument valid_until_ms must be int " f"but not {type(valid_until_ms)}.") userid = self.validate_username(userid) resp = self.connection.request("POST", self.admin_patterns( f"/users/{userid}/login", 1), json=data) data = resp.json() if resp.status_code == 200: return data["access_token"] else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def unprotect_media(self, mediaid: str) -> bool: """Remove quarantine protection for a media https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/media_admin_api.md#unprotecting-media-from-being-quarantined Args: mediaid (str): the media you want to unprotect from quarantine Returns: bool: the operation is successful or not """ mediaid = self.extract_media_id(mediaid) resp = self.connection.request( "POST", self.admin_patterns(f"/media/unprotect/{mediaid}", 1), json={}, ) data = resp.json() if data == {}: return True else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def block(self, roomid: str, blocked: bool = True) -> bool: """Block or unblock a room https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/rooms.md#block-or-unblock-a-room Args: roomid (str): the room to block or unblock blocked (bool, optional): whether the room should be blocked or unblocked, True to blocked, False to unblocked. Defaults to True. # noqa: E501 Returns: bool: whether the room is blocked or not """ roomid = self.validate_room(roomid) resp = self.connection.request("PUT", self.admin_patterns( f"/rooms/{roomid}/block", 1), json={"block": blocked}) data = resp.json() if resp.status_code == 200: return data["block"] else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def admin_login(protocol: str, host: str, port: str, username: str = None, password: str = None, suppress_exception: bool = False, no_admin: bool = False) -> str: """Login and get an access token Args: protocol (str): "http://" or "https://". Defaults to None. # noqa: E501 host (str): homeserver address. Defaults to None. port (int): homeserver listening port. Defaults to None. username (str, optional): just username. Defaults to None. password (str, optional): just password. Defaults to None. suppress_exception (bool, optional): suppress exception or not, if not return False and the error in dict. Defaults to False. # noqa: E501 Returns: str: access token """ if username is None: username = input("Enter a username: "******"identifier": { "type": "m.id.user", "user": username }, "type": "m.login.password", "password": password, "initial_device_display_name": "matrix-synapse-admin" } http = Client() base_url = f"{protocol}{host}:{port}" while True: resp = http.post(f"{base_url}{ClientAPI.BASE_PATH}/login", json=login_data) data = resp.json() if "errcode" in data and data["errcode"] == "M_LIMIT_EXCEEDED": time.sleep(data["retry_after_ms"] / 1000) continue if resp.status_code == 200: access_token = data["access_token"] if not no_admin: resp = User(host, port, access_token, protocol).query(username) if "errcode" not in resp: return data["access_token"] else: data = resp else: return access_token if suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def lists(self, _from: int = None, limit: int = None, orderby: str = None, recent_first: bool = True, search: str = None) -> Contents: """List all local rooms https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/rooms.md#list-room-api Args: _from (int, optional): equivalent to "from". Defaults to None. limit (int, optional): equivalent to "limit". Defaults to None. orderby (str, optional): equivalent to "order_by". Defaults to None. recent_first (bool, optional): equivalent to "dir", True to f False to b. Defaults to True. # noqa: E501 search (str, optional): equivalent to "search_term". Defaults to None. Returns: Contents: list of room """ if recent_first: optional_str = "dir=b" else: optional_str = "dir=f" if _from is not None: optional_str += f"&from={_from}" if limit is not None: optional_str += f"&limit={limit}" if orderby is not None: if not isinstance(orderby, str): raise TypeError("Argument 'orderby' should be a " f"str but not {type(orderby)}") elif orderby not in Room.order: raise ValueError( "Argument 'orderby' must be included in Room.order, " "for details please read documentation.") optional_str += f"&orderby={orderby}" if search: optional_str += f"&search_term={search}" resp = self.connection.request( "GET", self.admin_patterns(f"/rooms?{optional_str}", 1), ) data = resp.json() if resp.status_code == 200: return Contents(data["rooms"], data["total_rooms"], data.get("next_batch", None)) else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def lists(self, offset: int = 0, limit: int = 100, userid: str = None, name: str = None, guests: bool = True, deactivated: bool = False, order_by: str = None, _dir: str = "f") -> Contents: """List all local users https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#list-accounts Args: offset (int, optional): equivalent to "from". Defaults to 0. # noqa: E501 limit (int, optional): equivalent to "limit". Defaults to 100. userid (str, optional): equivalent to "user_id". Defaults to None. name (str, optional): equivalent to "name". Defaults to None. guests (bool, optional): equivalent to "guests". Defaults to True. deactivated (bool, optional): equivalent to "deactivated". Defaults to False. # noqa: E501 order_by (str, optional): equivalent to "order_by". Defaults to None. _dir (str, optional): equivalent to "dir". Defaults to "f". Returns: Contents: list of user """ optional_str = "" if userid is not None: userid = self.validate_username(userid) optional_str += f"&user_id={userid}" if name is not None: optional_str += f"&name={name}" if order_by is not None: if order_by not in User.ORDER: raise ValueError( "Argument 'order_by' must be included in User.ORDER, " "for details please read the documentation.") optional_str += f"&order_by={order_by}" resp = self.connection.request( "GET", self.admin_patterns( f"/users?from={offset}&limit={limit}&guests=" f"{Utility.get_bool(guests)}&deactivated=" f"{Utility.get_bool(deactivated)}&dir={_dir}{optional_str}", 2)) data = resp.json() if resp.status_code == 200: return Contents(data["users"], data["total"], data.get("next_token", None)) else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def delete_async(self, roomid: str, new_room_userid: str = None, room_name: str = None, message: str = None, block: bool = False, purge: bool = True, force_purge: bool = None) -> str: """Delete a room asynchronously https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/rooms.md#version-2-new-version Args: roomid (str): the room you want to delete new_room_userid (str, optional): equivalent to "new_room_user_id". Defaults to None. # noqa: E501 room_name (str, optional): equivalent to "room_name". Defaults to None. message (str, optional): equivalent to "message". Defaults to None. block (bool, optional): equivalent to "block". Defaults to False. purge (bool, optional): whether or not to purge all information of the rooom from the database. Defaults to True. force_purge (bool, optional): equivalent to "force_purge". Defaults to None. Returns: dict: a dict containing kicked_users, failed_tokick_users, local_aliases, new_room_id """ roomid = self.validate_room(roomid) data = {"block": block, "purge": purge} if new_room_userid is not None: new_room_userid = self.validate_username(new_room_userid) data["new_room_user_id"] = new_room_userid if room_name is not None: data["room_name"] = room_name if message is not None: data["message"] = message if force_purge is not None: data["force_purge"] = force_purge resp = self.connection.request( "DELETE", self.admin_patterns(f"/rooms/{roomid}", 2), json=data, ) data = resp.json() if resp.status_code == 200: return data["delete_id"] else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def background_updates_get(self) -> Tuple[bool, dict]: """Get the current status of background updates https://github.com/matrix-org/synapse/blob/develop/docs/usage/administration/admin_api/background_updates.md#status Returns: Tuple[bool, dict]: whether background updates is enabled, details of current updates # noqa: E501 """ resp = self.connection.request( "GET", self.admin_patterns("/background_updates/status", 1)) data = resp.json() if resp.status_code == 200: return data["enabled"], data["current_updates"] else: if self.suppress_exception: return False, data["errcode"], data["error"] else: raise SynapseException(data["errcode"], data["error"])
def register(self, username: str, shared_secret: Union[str, bytes], *, displayname: str, password: str = None, admin: bool = False) -> dict: """Register a new user https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/register_api.md#shared-secret-registration Args: username (str): the username shared_secret (Union[str, bytes]): the shared secret defined in homeserver.yaml # noqa: E501 displayname (str): the display name for the user password (str, optional): the password for the user. Defaults to None. admin (bool, optional): whether or not to set the user as server admin. Defaults to False. # noqa: E501 Returns: dict: a dict including access token and other information of the new account """ nonce = self._get_register_nonce() if password is None: password = Utility.get_password() data = { "nonce": nonce, "username": username, "display_name": displayname, "password": password, "admin": admin, "mac": self._generate_mac(nonce, username, password, shared_secret) } resp = self.connection.request("POST", self.admin_patterns("/register", 1), json=data) data = resp.json() if resp.status_code == 200: return data else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])
def list_media(self, userid: str, limit: int = 100, _from: int = 0, order_by: int = None, _dir: str = "f") -> Contents: """list all media sent by the user https://github.com/matrix-org/synapse/blob/develop/docs/admin_api/user_admin_api.md#list-media-of-a-user Args: userid (str): the user you want to query limit (int, optional): equivalent to "limit". Defaults to 100. _from (int, optional): equivalent to "from". Defaults to 0. order_by (int, optional): equivalent to "order_by". Defaults to None. # noqa: E501 _dir (str, optional): equivalent to "dir". Defaults to "f". Returns: Contents: list of media # noqa: E501 """ userid = self.validate_username(userid) optional_str = "" if order_by is not None: optional_str += f"&order_by={order_by}" resp = self.connection.request( "GET", self.admin_patterns( f"/users/{userid}/media?" f"limit={limit}&from={_from}" f"&dir={_dir}{optional_str}", 1)) data = resp.json() if resp.status_code == 200: if "next_token" not in data: next_token = 0 else: next_token = data["next_token"] return Contents(data["media"], data["total"], next_token) else: if self.suppress_exception: return False, data else: raise SynapseException(data["errcode"], data["error"])