desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Get the last stream_id we got for a user. May be None if we haven\'t got any information for them.'
@cached(max_entries=10000) def get_device_list_last_stream_id_for_remote(self, user_id):
return self._simple_select_one_onecol(table='device_lists_remote_extremeties', keyvalues={'user_id': user_id}, retcol='stream_id', desc='get_device_list_remote_extremity', allow_none=True)
'Mark that we no longer track device lists for remote user.'
@defer.inlineCallbacks def mark_remote_user_device_list_as_unsubscribed(self, user_id):
(yield self._simple_delete(table='device_lists_remote_extremeties', keyvalues={'user_id': user_id}, desc='mark_remote_user_device_list_as_unsubscribed')) self.get_device_list_last_stream_id_for_remote.invalidate((user_id,))
'Updates a single user\'s device in the cache.'
def update_remote_device_list_cache_entry(self, user_id, device_id, content, stream_id):
return self.runInteraction('update_remote_device_list_cache_entry', self._update_remote_device_list_cache_entry_txn, user_id, device_id, content, stream_id)
'Replace the cache of the remote user\'s devices.'
def update_remote_device_list_cache(self, user_id, devices, stream_id):
return self.runInteraction('update_remote_device_list_cache', self._update_remote_device_list_cache_txn, user_id, devices, stream_id)
'Get stream of updates to send to remote servers Returns: (int, list[dict]): current stream id and list of updates'
def get_devices_by_remote(self, destination, from_stream_id):
now_stream_id = self._device_list_id_gen.get_current_token() has_changed = self._device_list_federation_stream_cache.has_entity_changed(destination, int(from_stream_id)) if (not has_changed): return (now_stream_id, []) return self.runInteraction('get_devices_by_remote', self._get_devices_by_remo...
'Get the devices (and keys if any) for remote users from the cache. Args: query_list(list): List of (user_id, device_ids), if device_ids is falsey then return all device ids for that user. Returns: (user_ids_not_in_cache, results_map), where user_ids_not_in_cache is a set of user_ids and results_map is a mapping of use...
@defer.inlineCallbacks def get_user_devices_from_cache(self, query_list):
user_ids = set((user_id for (user_id, _) in query_list)) user_map = (yield self.get_device_list_last_stream_id_for_remotes(list(user_ids))) user_ids_in_cache = set((user_id for (user_id, stream_id) in user_map.items() if stream_id)) user_ids_not_in_cache = (user_ids - user_ids_in_cache) results = {}...
'Get all devices (with any device keys) for a user Returns: (stream_id, devices)'
def get_devices_with_keys_by_user(self, user_id):
return self.runInteraction('get_devices_with_keys_by_user', self._get_devices_with_keys_by_user_txn, user_id)
'Mark that updates have successfully been sent to the destination.'
def mark_as_sent_devices_by_remote(self, destination, stream_id):
return self.runInteraction('mark_as_sent_devices_by_remote', self._mark_as_sent_devices_by_remote_txn, destination, stream_id)
'Get set of users whose devices have changed since `from_key`.'
@defer.inlineCallbacks def get_user_whose_devices_changed(self, from_key):
from_key = int(from_key) changed = self._device_list_stream_cache.get_all_entities_changed(from_key) if (changed is not None): defer.returnValue(set(changed)) sql = '\n SELECT DISTINCT user_id FROM device_lists_stream WHERE stream_...
'Return a list of `(stream_id, user_id, destination)` which is the combined list of changes to devices, and which destinations need to be poked. `destination` may be None if no destinations need to be poked.'
def get_all_device_list_changes_for_remotes(self, from_key, to_key):
sql = '\n SELECT stream_id, user_id, destination FROM device_lists_stream\n LEFT JOIN device_lists_outbound_pokes USING (stream_id, user_id, device_id)\n ...
'Persist that a user\'s devices have been updated, and which hosts (if any) should be poked.'
@defer.inlineCallbacks def add_device_change_to_streams(self, user_id, device_ids, hosts):
with self._device_list_id_gen.get_next() as stream_id: (yield self.runInteraction('add_device_change_to_streams', self._add_device_change_txn, user_id, device_ids, hosts, stream_id)) defer.returnValue(stream_id)
'Delete old entries out of the device_lists_outbound_pokes to ensure that we don\'t fill up due to dead servers. We keep one entry per (destination, user_id) tuple to ensure that the prev_ids remain correct if the server does come back.'
def _prune_old_outbound_device_pokes(self):
yesterday = (self._clock.time_msec() - (((24 * 60) * 60) * 1000)) def _prune_txn(txn): select_sql = '\n SELECT destination, user_id, max(stream_id) as stream_id\n ...
'Specialised version of _simple_upsert_txn that picks a push_rule_id using the _push_rule_id_gen if it needs to insert the rule. It assumes that the "push_rules" table is locked'
def _upsert_push_rule_txn(self, txn, stream_id, event_stream_ordering, user_id, rule_id, priority_class, priority, conditions_json, actions_json, update_stream=True):
sql = 'UPDATE push_rules SET priority_class = ?, priority = ?, conditions = ?, actions = ? WHERE user_name = ? AND rule_id = ?' txn.execute(sql, (priority_class, priority, conditions_json, actions_json, user_id, rule_id)) if (txn.rowcount == ...
'Delete a push rule. Args specify the row to be deleted and can be any of the columns in the push_rule table, but below are the standard ones Args: user_id (str): The matrix ID of the push rule owner rule_id (str): The rule_id of the rule to be deleted'
@defer.inlineCallbacks def delete_push_rule(self, user_id, rule_id):
def delete_push_rule_txn(txn, stream_id, event_stream_ordering): self._simple_delete_one_txn(txn, 'push_rules', {'user_name': user_id, 'rule_id': rule_id}) self._insert_push_rules_update_txn(txn, stream_id, event_stream_ordering, user_id, rule_id, op='DELETE') with self._push_rules_stream_id_gen...
'Get all the push rules changes that have happend on the server'
def get_all_push_rule_updates(self, last_id, current_id, limit):
if (last_id == current_id): return defer.succeed([]) def get_all_push_rule_updates_txn(txn): sql = 'SELECT stream_id, event_stream_ordering, user_id, rule_id, op, priority_class, priority, conditions, actions FROM push_rules_stream WHERE ? < stream_id...
'Get the position of the push rules stream. Returns a pair of a stream id for the push_rules stream and the room stream ordering it corresponds to.'
def get_push_rules_stream_token(self):
return self._push_rules_stream_id_gen.get_current_token()
'Get the current state event ids for a room based on the current_state_events table. Args: room_id (str) Returns: deferred: dict of (type, state_key) -> event_id'
@cached(max_entries=100000, iterable=True) def get_current_state_ids(self, room_id):
def _get_current_state_ids_txn(txn): txn.execute('SELECT type, state_key, event_id FROM current_state_events\n WHERE room_id = ?\n ', (room_id,)) retu...
'Given a state group try to return a previous group and a delta between the old and the new. Returns: (prev_group, delta_ids), where both may be None.'
@cached(max_entries=10000, iterable=True) def get_state_group_delta(self, state_group):
def _get_state_group_delta_txn(txn): prev_group = self._simple_select_one_onecol_txn(txn, table='state_group_edges', keyvalues={'state_group': state_group}, retcol='prev_state_group', allow_none=True) if (not prev_group): return _GetStateGroupDelta(None, None) delta_ids = self._s...
'Get the state groups for the given list of event_ids The return value is a dict mapping group names to lists of events.'
@defer.inlineCallbacks def get_state_groups(self, room_id, event_ids):
if (not event_ids): defer.returnValue({}) group_to_ids = (yield self.get_state_groups_ids(room_id, event_ids)) state_event_map = (yield self.get_events([ev_id for group_ids in group_to_ids.itervalues() for ev_id in group_ids.itervalues()], get_prev_content=False)) defer.returnValue({group: [stat...
'Given a state group, count how many hops there are in the tree. This is used to ensure the delta chains don\'t get too long.'
def _count_state_group_hops_txn(self, txn, state_group):
if isinstance(self.database_engine, PostgresEngine): sql = '\n WITH RECURSIVE state(state_group) AS (\n VALUES(?::bigint)\n ...
'Returns dictionary state_group -> (dict of (type, state_key) -> event id)'
@defer.inlineCallbacks def _get_state_groups_from_groups(self, groups, types):
results = {} chunks = [groups[i:(i + 100)] for i in xrange(0, len(groups), 100)] for chunk in chunks: res = (yield self.runInteraction('_get_state_groups_from_groups', self._get_state_groups_from_groups_txn, chunk, types)) results.update(res) defer.returnValue(results)
'Given a list of event_ids and type tuples, return a list of state dicts for each event. The state dicts will only have the type/state_keys that are in the `types` list. Args: event_ids (list) types (list): List of (type, state_key) tuples which are used to filter the state fetched. `state_key` may be None, which match...
@defer.inlineCallbacks def get_state_for_events(self, event_ids, types):
event_to_groups = (yield self._get_state_group_for_events(event_ids)) groups = set(event_to_groups.itervalues()) group_to_state = (yield self._get_state_for_groups(groups, types)) state_event_map = (yield self.get_events([ev_id for sd in group_to_state.itervalues() for ev_id in sd.itervalues()], get_pre...
'Get the state dicts corresponding to a list of events Args: event_ids(list(str)): events whose state should be returned types(list[(str, str)]|None): List of (type, state_key) tuples which are used to filter the state fetched. May be None, which matches any key Returns: A deferred dict from event_id -> (type, state_ke...
@defer.inlineCallbacks def get_state_ids_for_events(self, event_ids, types=None):
event_to_groups = (yield self._get_state_group_for_events(event_ids)) groups = set(event_to_groups.itervalues()) group_to_state = (yield self._get_state_for_groups(groups, types)) event_to_state = {event_id: group_to_state[group] for (event_id, group) in event_to_groups.iteritems()} defer.returnValu...
'Get the state dict corresponding to a particular event Args: event_id(str): event whose state should be returned types(list[(str, str)]|None): List of (type, state_key) tuples which are used to filter the state fetched. May be None, which matches any key Returns: A deferred dict from (type, state_key) -> state_event'
@defer.inlineCallbacks def get_state_for_event(self, event_id, types=None):
state_map = (yield self.get_state_for_events([event_id], types)) defer.returnValue(state_map[event_id])
'Get the state dict corresponding to a particular event Args: event_id(str): event whose state should be returned types(list[(str, str)]|None): List of (type, state_key) tuples which are used to filter the state fetched. May be None, which matches any key Returns: A deferred dict from (type, state_key) -> state_event'
@defer.inlineCallbacks def get_state_ids_for_event(self, event_id, types=None):
state_map = (yield self.get_state_ids_for_events([event_id], types)) defer.returnValue(state_map[event_id])
'Returns mapping event_id -> state_group'
@cachedList(cached_method_name='_get_state_group_for_event', list_name='event_ids', num_args=1, inlineCallbacks=True) def _get_state_group_for_events(self, event_ids):
rows = (yield self._simple_select_many_batch(table='event_to_state_groups', column='event_id', iterable=event_ids, keyvalues={}, retcols=('event_id', 'state_group'), desc='_get_state_group_for_events')) defer.returnValue({row['event_id']: row['state_group'] for row in rows})
'Checks if group is in cache. See `_get_state_for_groups` Returns 3-tuple (`state_dict`, `missing_types`, `got_all`). `missing_types` is the list of types that aren\'t in the cache for that group. `got_all` is a bool indicating if we successfully retrieved all requests state from the cache, if False we need to query th...
def _get_some_state_from_cache(self, group, types):
(is_all, known_absent, state_dict_ids) = self._state_group_cache.get(group) type_to_key = {} missing_types = set() for (typ, state_key) in types: key = (typ, state_key) if (state_key is None): type_to_key[typ] = None missing_types.add(key) else: ...
'Checks if group is in cache. See `_get_state_for_groups` Returns 2-tuple (`state_dict`, `got_all`). `got_all` is a bool indicating if we successfully retrieved all requests state from the cache, if False we need to query the DB for the missing state. Args: group: The state group to lookup'
def _get_all_state_from_cache(self, group):
(is_all, _, state_dict_ids) = self._state_group_cache.get(group) return (state_dict_ids, is_all)
'Given list of groups returns dict of group -> list of state events with matching types. `types` is a list of `(type, state_key)`, where a `state_key` of None matches all state_keys. If `types` is None then all events are returned.'
@defer.inlineCallbacks def _get_state_for_groups(self, groups, types=None):
if types: types = frozenset(types) results = {} missing_groups = [] if (types is not None): for group in set(groups): (state_dict_ids, _, got_all) = self._get_some_state_from_cache(group, types) results[group] = state_dict_ids if (not got_all): ...
'This background update will slowly deduplicate state by reencoding them as deltas.'
@defer.inlineCallbacks def _background_deduplicate_state(self, progress, batch_size):
last_state_group = progress.get('last_state_group', 0) rows_inserted = progress.get('rows_inserted', 0) max_group = progress.get('max_group', None) BATCH_SIZE_SCALE_FACTOR = 100 batch_size = max(1, int((batch_size / BATCH_SIZE_SCALE_FACTOR))) if (max_group is None): rows = (yield self._e...
'Adds an access token for the given user. Args: user_id (str): The user ID. token (str): The new access token to add. device_id (str): ID of the device to associate with the access token Raises: StoreError if there was a problem adding this.'
@defer.inlineCallbacks def add_access_token_to_user(self, user_id, token, device_id=None):
next_id = self._access_tokens_id_gen.get_next() (yield self._simple_insert('access_tokens', {'id': next_id, 'user_id': user_id, 'token': token, 'device_id': device_id}, desc='add_access_token_to_user'))
'Attempts to register an account. Args: user_id (str): The desired user ID to register. token (str): The desired access token to use for this user. If this is not None, the given access token is associated with the user id. password_hash (str): Optional. The password hash for this user. was_guest (bool): Optional. Whet...
def register(self, user_id, token=None, password_hash=None, was_guest=False, make_guest=False, appservice_id=None, create_profile_with_localpart=None, admin=False):
return self.runInteraction('register', self._register, user_id, token, password_hash, was_guest, make_guest, appservice_id, create_profile_with_localpart, admin)
'Gets users that match user_id case insensitively. Returns a mapping of user_id -> password_hash.'
def get_users_by_id_case_insensitive(self, user_id):
def f(txn): sql = 'SELECT name, password_hash FROM users WHERE lower(name) = lower(?)' txn.execute(sql, (user_id,)) return dict(txn) return self.runInteraction('get_users_by_id_case_insensitive', f)
'NB. This does *not* evict any cache because the one use for this removes most of the entries subsequently anyway so it would be pointless. Use flush_user separately.'
def user_set_password_hash(self, user_id, password_hash):
def user_set_password_hash_txn(txn): self._simple_update_one_txn(txn, 'users', {'name': user_id}, {'password_hash': password_hash}) self._invalidate_cache_and_stream(txn, self.get_user_by_id, (user_id,)) return self.runInteraction('user_set_password_hash', user_set_password_hash_txn)
'Invalidate access/refresh tokens belonging to a user Args: user_id (str): ID of user the tokens belong to except_token_id (str): list of access_tokens IDs which should *not* be deleted device_id (str|None): ID of device the tokens are associated with. If None, tokens associated with any device (or no device) will be...
@defer.inlineCallbacks def user_delete_access_tokens(self, user_id, except_token_id=None, device_id=None, delete_refresh_tokens=False):
def f(txn): keyvalues = {'user_id': user_id} if (device_id is not None): keyvalues['device_id'] = device_id if delete_refresh_tokens: self._simple_delete_txn(txn, table='refresh_tokens', keyvalues=keyvalues) items = keyvalues.items() where_clause = ' ...
'Get a user from the given access token. Args: token (str): The access token of a user. Returns: defer.Deferred: None, if the token did not match, otherwise dict including the keys `name`, `is_guest`, `device_id`, `token_id`.'
@cached() def get_user_by_access_token(self, token):
return self.runInteraction('get_user_by_access_token', self._query_for_auth, token)
'Counts all users registered on the homeserver.'
@defer.inlineCallbacks def count_all_users(self):
def _count_users(txn): txn.execute('SELECT COUNT(*) AS users FROM users') rows = self.cursor_to_dict(txn) if rows: return rows[0]['users'] return 0 ret = (yield self.runInteraction('count_users', _count_users)) defer.returnValue(ret)
'Gets the localpart of the next generated user ID. Generated user IDs are integers, and we aim for them to be as small as we can. Unfortunately, it\'s possible some of them are already taken by existing users, and there may be gaps in the already taken range. This function returns the start of the first allocatable gap...
@defer.inlineCallbacks def find_next_generated_user_id_localpart(self):
def _find_next_generated_user_id(txn): txn.execute('SELECT name FROM users') rows = self.cursor_to_dict(txn) regex = re.compile('^@(\\d+):') found = set() for r in rows: user_id = r['name'] match = regex.search(user_id) if match: ...
'Gets the 3pid\'s guest access token if exists, else saves access_token. Args: medium (str): Medium of the 3pid. Must be "email". address (str): 3pid address. access_token (str): The access token to persist if none is already persisted. inviter_user_id (str): User ID of the inviter. Returns: deferred str: Whichever acc...
@defer.inlineCallbacks def save_or_get_3pid_guest_access_token(self, medium, address, access_token, inviter_user_id):
def insert(txn): txn.execute('INSERT INTO threepid_guest_access_tokens (medium, address, guest_access_token, first_inviter) VALUES (?, ?, ?, ?)', (medium, address, access_token, inviter_user_id)) try: (yield self.runInteraction('save_3pid_guest_access_token', ins...
'Stores a room. Args: room_id (str): The desired room ID, can be None. room_creator_user_id (str): The user ID of the room creator. is_public (bool): True to indicate that this room should appear in public room lists. Raises: StoreError if the room could not be stored.'
@defer.inlineCallbacks def store_room(self, room_id, room_creator_user_id, is_public):
try: def store_room_txn(txn, next_id): self._simple_insert_txn(txn, 'rooms', {'room_id': room_id, 'creator': room_creator_user_id, 'is_public': is_public}) if is_public: self._simple_insert_txn(txn, table='public_room_list_stream', values={'stream_id': next_id, 'room_...
'Retrieve a room. Args: room_id (str): The ID of the room to retrieve. Returns: A namedtuple containing the room information, or an empty list.'
def get_room(self, room_id):
return self._simple_select_one(table='rooms', keyvalues={'room_id': room_id}, retcols=('room_id', 'is_public', 'creator'), desc='get_room', allow_none=True)
'Edit the appservice/network specific public room list. Each appservice can have a number of published room lists associated with them, keyed off of an appservice defined `network_id`, which basically represents a single instance of a bridge to a third party network. Args: room_id (str) appservice_id (str) network_id (...
@defer.inlineCallbacks def set_room_is_public_appservice(self, room_id, appservice_id, network_id, is_public):
def set_room_is_public_appservice_txn(txn, next_id): if is_public: try: self._simple_insert_txn(txn, table='appservice_room_list', values={'appservice_id': appservice_id, 'network_id': network_id, 'room_id': room_id}) except self.database_engine.module.IntegrityError:...
'Retrieve a list of all rooms'
def get_room_count(self):
def f(txn): sql = 'SELECT count(*) FROM rooms' txn.execute(sql) row = txn.fetchone() return (row[0] or 0) return self.runInteraction('get_rooms', f)
'Get pulbic rooms for a particular list, or across all lists. Args: stream_id (int) network_tuple (ThirdPartyInstanceID): The list to use (None, None) means the main list, None means all lsits.'
@cached(num_args=2, max_entries=100) def get_public_room_ids_at_stream_id(self, stream_id, network_tuple):
return self.runInteraction('get_public_room_ids_at_stream_id', self.get_public_room_ids_at_stream_id_txn, stream_id, network_tuple=network_tuple)
'Check if there are any overrides for ratelimiting for the given user Args: user_id (str) Returns: RatelimitOverride if there is an override, else None. If the contents of RatelimitOverride are None or 0 then ratelimitng has been disabled for that user entirely.'
@cachedInlineCallbacks(max_entries=10000) def get_ratelimit_for_user(self, user_id):
row = (yield self._simple_select_one(table='ratelimit_override', keyvalues={'user_id': user_id}, retcols=('messages_per_second', 'burst_count'), allow_none=True, desc='get_ratelimit_for_user')) if row: defer.returnValue(RatelimitOverride(messages_per_second=row['messages_per_second'], burst_count=row['b...
'For a room loops through all events with media and quarantines the associated media'
def quarantine_media_ids_in_room(self, room_id, quarantined_by):
def _get_media_ids_in_room(txn): mxc_re = re.compile('^mxc://([^/]+)/([^/#?]+)') next_token = (self.get_current_events_token() + 1) total_media_quarantined = 0 while next_token: sql = '\n SELEC...
'Given a list of rooms and a token, return rooms where there may have been changes. Args: room_ids (list) from_key (str): The room_key portion of a StreamToken'
def get_rooms_that_changed(self, room_ids, from_key):
from_key = RoomStreamToken.parse_stream_token(from_key).stream return set((room_id for room_id in room_ids if self._events_stream_cache.has_entity_changed(room_id, from_key)))
'Returns the current token for rooms stream. By default, it returns the current global stream token. Specifying a `room_id` causes it to return the current room specific topological token.'
@defer.inlineCallbacks def get_room_events_max_id(self, room_id=None):
token = (yield self._stream_id_gen.get_current_token()) if (room_id is None): defer.returnValue(('s%d' % (token,))) else: topo = (yield self.runInteraction('_get_max_topological_txn', self._get_max_topological_txn, room_id)) defer.returnValue(('t%d-%d' % (topo, token)))
'The stream token for an event Args: event_id(str): The id of the event to look up a stream token for. Raises: StoreError if the event wasn\'t in the database. Returns: A deferred "s%d" stream token.'
def get_stream_token_for_event(self, event_id):
return self._simple_select_one_onecol(table='events', keyvalues={'event_id': event_id}, retcol='stream_ordering').addCallback((lambda row: ('s%d' % (row,))))
'The stream token for an event Args: event_id(str): The id of the event to look up a stream token for. Raises: StoreError if the event wasn\'t in the database. Returns: A deferred "t%d-%d" topological token.'
def get_topological_token_for_event(self, event_id):
return self._simple_select_one(table='events', keyvalues={'event_id': event_id}, retcols=('stream_ordering', 'topological_ordering'), desc='get_topological_token_for_event').addCallback((lambda row: ('t%d-%d' % (row['topological_ordering'], row['stream_ordering']))))
'Retrieve events and pagination tokens around a given event in a room. Args: room_id (str) event_id (str) before_limit (int) after_limit (int) Returns: dict'
@defer.inlineCallbacks def get_events_around(self, room_id, event_id, before_limit, after_limit):
results = (yield self.runInteraction('get_events_around', self._get_events_around_txn, room_id, event_id, before_limit, after_limit)) events_before = (yield self._get_events([e for e in results['before']['event_ids']], get_prev_content=True)) events_after = (yield self._get_events([e for e in results['after...
'Retrieves event_ids and pagination tokens around a given event in a room. Args: room_id (str) event_id (str) before_limit (int) after_limit (int) Returns: dict'
def _get_events_around_txn(self, txn, room_id, event_id, before_limit, after_limit):
results = self._simple_select_one_txn(txn, 'events', keyvalues={'event_id': event_id, 'room_id': room_id}, retcols=['stream_ordering', 'topological_ordering']) token = RoomStreamToken(results['topological_ordering'], results['stream_ordering']) if isinstance(self.database_engine, Sqlite3Engine): que...
'Get all new events'
@defer.inlineCallbacks def get_all_new_events_stream(self, from_id, current_id, limit):
def get_all_new_events_stream_txn(txn): sql = 'SELECT e.stream_ordering, e.event_id FROM events AS e WHERE ? < e.stream_ordering AND e.stream_ordering <= ? ORDER BY e.stream_ordering ASC LIMIT ?' txn.execute(sql, (from_id, current_id, limit...
'Store a room member in the database.'
def _store_room_members_txn(self, txn, events, backfilled):
self._simple_insert_many_txn(txn, table='room_memberships', values=[{'event_id': event.event_id, 'user_id': event.state_key, 'sender': event.user_id, 'room_id': event.room_id, 'membership': event.membership, 'display_name': event.content.get('displayname', None), 'avatar_url': event.content.get('avatar_url', None)}...
'Returns the set of all hosts currently in the room'
@cachedInlineCallbacks(max_entries=100000, iterable=True, cache_context=True) def get_hosts_in_room(self, room_id, cache_context):
user_ids = (yield self.get_users_in_room(room_id, on_invalidate=cache_context.invalidate)) hosts = frozenset((get_domain_from_id(user_id) for user_id in user_ids)) defer.returnValue(hosts)
'Get all the rooms the user is invited to Args: user_id (str): The user ID. Returns: A deferred list of RoomsForUser.'
@cached() def get_invited_rooms_for_user(self, user_id):
return self.get_rooms_for_user_where_membership_is(user_id, [Membership.INVITE])
'Gets the invite for the given user and room Args: user_id (str) room_id (str) Returns: Deferred: Resolves to either a RoomsForUser or None if no invite was found.'
@defer.inlineCallbacks def get_invite_for_user_in_room(self, user_id, room_id):
invites = (yield self.get_invited_rooms_for_user(user_id)) for invite in invites: if (invite.room_id == room_id): defer.returnValue(invite) defer.returnValue(None)
'Get all the rooms for this user where the membership for this user matches one in the membership list. Args: user_id (str): The user ID. membership_list (list): A list of synapse.api.constants.Membership values which the user must be in. Returns: A list of dictionary objects, with room_id, membership and sender define...
def get_rooms_for_user_where_membership_is(self, user_id, membership_list):
if (not membership_list): return defer.succeed(None) return self.runInteraction('get_rooms_for_user_where_membership_is', self._get_rooms_for_user_where_membership_is_txn, user_id, membership_list)
'Returns a set of room_ids the user is currently joined to'
@cachedInlineCallbacks(max_entries=500000, iterable=True) def get_rooms_for_user(self, user_id):
rooms = (yield self.get_rooms_for_user_where_membership_is(user_id, membership_list=[Membership.JOIN])) defer.returnValue(frozenset((r.room_id for r in rooms)))
'Returns the set of users who share a room with `user_id`'
@cachedInlineCallbacks(max_entries=500000, cache_context=True, iterable=True) def get_users_who_share_room_with_user(self, user_id, cache_context):
room_ids = (yield self.get_rooms_for_user(user_id, on_invalidate=cache_context.invalidate)) user_who_share_room = set() for room_id in room_ids: user_ids = (yield self.get_users_in_room(room_id, on_invalidate=cache_context.invalidate)) user_who_share_room.update(user_ids) defer.returnVal...
'Indicate that user_id wishes to discard history for room_id.'
def forget(self, user_id, room_id):
def f(txn): sql = 'UPDATE room_memberships SET forgotten = 1 WHERE user_id = ? AND room_id = ?' txn.execute(sql, (user_id, room_id)) txn.call_after(self.was_forgotten_at.invalidate_all) txn.call_after(self.did_forget.invalidate, ...
'Returns whether user_id has elected to discard history for room_id. Returns False if they have since re-joined.'
@cachedInlineCallbacks(num_args=2) def did_forget(self, user_id, room_id):
def f(txn): sql = 'SELECT COUNT(*) FROM room_memberships WHERE user_id = ? AND room_id = ? AND forgotten = 0' txn.execute(sql, (user_id, room_id)) rows = txn.fetchall() return rows[0][0] count = (yield self.runInter...
'Returns whether user_id has elected to discard history for room_id at event_id. event_id must be a membership event.'
@cachedInlineCallbacks(num_args=3) def was_forgotten_at(self, user_id, room_id, event_id):
def f(txn): sql = 'SELECT forgotten FROM room_memberships WHERE user_id = ? AND room_id = ? AND event_id = ?' txn.execute(sql, (user_id, room_id, event_id)) rows = txn.fetchall() return rows[0][0] forgot = (yield se...
'Get set of destinations for a state entry Args: state_entry(synapse.state._StateCacheEntry)'
@defer.inlineCallbacks def get_destinations(self, state_entry):
if (state_entry.state_group == self.state_group): defer.returnValue(frozenset(self.hosts_to_joined_users)) with (yield self.linearizer.queue(())): if (state_entry.state_group == self.state_group): pass elif (state_entry.prev_group == self.state_group): for ((typ, ...
'Check if the user is one associated with an app service (exclusively)'
def get_if_app_services_interested_in_user(self, user_id):
if self.exclusive_user_regex: return bool(self.exclusive_user_regex.match(user_id)) else: return False
'Retrieve an application service from their user ID. All application services have associated with them a particular user ID. There is no distinguishing feature on the user ID which indicates it represents an application service. This function allows you to map from a user ID to an application service. Args: user_id(st...
def get_app_service_by_user_id(self, user_id):
for service in self.services_cache: if (service.sender == user_id): return service return None
'Get the application service with the given appservice token. Args: token (str): The application service token. Returns: synapse.appservice.ApplicationService or None.'
def get_app_service_by_token(self, token):
for service in self.services_cache: if (service.token == token): return service return None
'Get a list of RoomsForUser for this application service. Application services may be "interested" in lots of rooms depending on the room ID, the room aliases, or the members in the room. This function takes all of these into account and returns a list of RoomsForUser which represent the entire list of room IDs that th...
def get_app_service_rooms(self, service):
return self.runInteraction('get_app_service_rooms', self._get_app_service_rooms_txn, service)
'Get a list of application services based on their state. Args: state(ApplicationServiceState): The state to filter on. Returns: A Deferred which resolves to a list of ApplicationServices, which may be empty.'
@defer.inlineCallbacks def get_appservices_by_state(self, state):
results = (yield self._simple_select_list('application_services_state', dict(state=state), ['as_id'])) as_list = self.get_app_services() services = [] for res in results: for service in as_list: if (service.id == res['as_id']): services.append(service) defer.retur...
'Get the application service state. Args: service(ApplicationService): The service whose state to set. Returns: A Deferred which resolves to ApplicationServiceState.'
@defer.inlineCallbacks def get_appservice_state(self, service):
result = (yield self._simple_select_one('application_services_state', dict(as_id=service.id), ['state'], allow_none=True, desc='get_appservice_state')) if result: defer.returnValue(result.get('state')) return defer.returnValue(None)
'Set the application service state. Args: service(ApplicationService): The service whose state to set. state(ApplicationServiceState): The connectivity state to apply. Returns: A Deferred which resolves when the state was set successfully.'
def set_appservice_state(self, service, state):
return self._simple_upsert('application_services_state', dict(as_id=service.id), dict(state=state))
'Atomically creates a new transaction for this application service with the given list of events. Args: service(ApplicationService): The service who the transaction is for. events(list<Event>): A list of events to put in the transaction. Returns: AppServiceTransaction: A new transaction.'
def create_appservice_txn(self, service, events):
def _create_appservice_txn(txn): last_txn_id = self._get_last_txn(txn, service.id) txn.execute('SELECT MAX(txn_id) FROM application_services_txns WHERE as_id=?', (service.id,)) highest_txn_id = txn.fetchone()[0] if (highest_txn_id is None): highest_txn_id =...
'Completes an application service transaction. Args: txn_id(str): The transaction ID being completed. service(ApplicationService): The application service which was sent this transaction. Returns: A Deferred which resolves if this transaction was stored successfully.'
def complete_appservice_txn(self, txn_id, service):
txn_id = int(txn_id) def _complete_appservice_txn(txn): last_txn_id = self._get_last_txn(txn, service.id) if ((last_txn_id + 1) != txn_id): logger.error("appservice: Completing a transaction which has an ID > 1 from the last ID sent to ...
'Get the oldest transaction which has not been sent for this service. Args: service(ApplicationService): The app service to get the oldest txn. Returns: A Deferred which resolves to an AppServiceTransaction or None.'
@defer.inlineCallbacks def get_oldest_unsent_txn(self, service):
def _get_oldest_unsent_txn(txn): txn.execute('SELECT * FROM application_services_txns WHERE as_id=? ORDER BY txn_id ASC LIMIT 1', (service.id,)) rows = self.cursor_to_dict(txn) if (not rows): return None entry = rows[0] return entr...
'Get all new evnets'
@defer.inlineCallbacks def get_new_events_for_appservice(self, current_id, limit):
def get_new_events_for_appservice_txn(txn): sql = 'SELECT e.stream_ordering, e.event_id FROM events AS e WHERE (SELECT stream_ordering FROM appservice_stream_position) < e.stream_ordering AND e.stream_ordering <= ? ORDER BY e.stream...
'Usage: with stream_id_gen.get_next() as stream_id: # ... persist event ...'
def get_next(self):
with self._lock: self._current += self._step next_id = self._current self._unfinished_ids.append(next_id) @contextlib.contextmanager def manager(): try: (yield next_id) finally: with self._lock: self._unfinished_ids.remove(next_...
'Usage: with stream_id_gen.get_next(n) as stream_ids: # ... persist events ...'
def get_next_mult(self, n):
with self._lock: next_ids = range((self._current + self._step), (self._current + (self._step * (n + 1))), self._step) self._current += (n * self._step) for next_id in next_ids: self._unfinished_ids.append(next_id) @contextlib.contextmanager def manager(): try: ...
'Returns the maximum stream id such that all stream ids less than or equal to it have been successfully persisted. Returns: int'
def get_current_token(self):
with self._lock: if self._unfinished_ids: return (self._unfinished_ids[0] - self._step) return self._current
'Usage: with stream_id_gen.get_next() as (stream_id, chained_id): # ... persist event ...'
def get_next(self):
with self._lock: self._current_max += 1 next_id = self._current_max chained_id = self.chained_generator.get_current_token() self._unfinished_ids.append((next_id, chained_id)) @contextlib.contextmanager def manager(): try: (yield (next_id, chained_id)) ...
'Returns the maximum stream id such that all stream ids less than or equal to it have been successfully persisted.'
def get_current_token(self):
with self._lock: if self._unfinished_ids: (stream_id, chained_id) = self._unfinished_ids[0] return ((stream_id - 1), chained_id) return (self._current_max, self.chained_generator.get_current_token())
'Get the current max stream id for the private user data stream Returns: A deferred int.'
def get_max_account_data_stream_id(self):
return self._account_data_id_gen.get_current_token()
'Get all the tags for a user. Args: user_id(str): The user to get the tags for. Returns: A deferred dict mapping from room_id strings to dicts mapping from tag strings to tag content.'
@cached() def get_tags_for_user(self, user_id):
deferred = self._simple_select_list('room_tags', {'user_id': user_id}, ['room_id', 'tag', 'content']) @deferred.addCallback def tags_by_room(rows): tags_by_room = {} for row in rows: room_tags = tags_by_room.setdefault(row['room_id'], {}) room_tags[row['tag']] = json....
'Get all the client tags that have changed on the server Args: last_id(int): The position to fetch from. current_id(int): The position to fetch up to. Returns: A deferred list of tuples of stream_id int, user_id string, room_id string, tag string and content string.'
@defer.inlineCallbacks def get_all_updated_tags(self, last_id, current_id, limit):
if (last_id == current_id): defer.returnValue([]) def get_all_updated_tags_txn(txn): sql = 'SELECT stream_id, user_id, room_id FROM room_tags_revisions as r WHERE ? < stream_id AND stream_id <= ? ORDER BY stream_id ASC LIMIT ?' ...
'Get all the tags for the rooms where the tags have changed since the given version Args: user_id(str): The user to get the tags for. stream_id(int): The earliest update to get for the user. Returns: A deferred dict mapping from room_id strings to lists of tag strings for all the rooms that changed since the stream_id ...
@defer.inlineCallbacks def get_updated_tags(self, user_id, stream_id):
def get_updated_tags_txn(txn): sql = 'SELECT room_id from room_tags_revisions WHERE user_id = ? AND stream_id > ?' txn.execute(sql, (user_id, stream_id)) room_ids = [row[0] for row in txn] return room_ids changed = self._account_data_stream_cache....
'Get all the tags for the given room Args: user_id(str): The user to get tags for room_id(str): The room to get tags for Returns: A deferred list of string tags.'
def get_tags_for_room(self, user_id, room_id):
return self._simple_select_list(table='room_tags', keyvalues={'user_id': user_id, 'room_id': room_id}, retcols=('tag', 'content'), desc='get_tags_for_room').addCallback((lambda rows: {row['tag']: json.loads(row['content']) for row in rows}))
'Add a tag to a room for a user. Args: user_id(str): The user to add a tag for. room_id(str): The room to add a tag for. tag(str): The tag name to add. content(dict): A json object to associate with the tag. Returns: A deferred that completes once the tag has been added.'
@defer.inlineCallbacks def add_tag_to_room(self, user_id, room_id, tag, content):
content_json = json.dumps(content) def add_tag_txn(txn, next_id): self._simple_upsert_txn(txn, table='room_tags', keyvalues={'user_id': user_id, 'room_id': room_id, 'tag': tag}, values={'content': content_json}) self._update_revision_txn(txn, user_id, room_id, next_id) with self._account_dat...
'Remove a tag from a room for a user. Returns: A deferred that completes once the tag has been removed'
@defer.inlineCallbacks def remove_tag_from_room(self, user_id, room_id, tag):
def remove_tag_txn(txn, next_id): sql = 'DELETE FROM room_tags WHERE user_id = ? AND room_id = ? AND tag = ?' txn.execute(sql, (user_id, room_id, tag)) self._update_revision_txn(txn, user_id, room_id, next_id) with self._account_data_id_gen.g...
'Update the latest revision of the tags for the given user and room. Args: txn: The database cursor user_id(str): The ID of the user. room_id(str): The ID of the room. next_id(int): The the revision to advance to.'
def _update_revision_txn(self, txn, user_id, room_id, next_id):
txn.call_after(self._account_data_stream_cache.entity_has_changed, user_id, next_id) update_max_id_sql = 'UPDATE account_data_max_stream_id SET stream_id = ? WHERE stream_id < ?' txn.execute(update_max_id_sql, (next_id, next_id)) update_sql = 'UPDATE room_tags_revisions ...
'For each device_id listed, give the user_ip it was last seen on Args: user_id (str) device_id (str): If None fetches all devices for the user Returns: defer.Deferred: resolves to a dict, where the keys are (user_id, device_id) tuples. The values are also dicts, with keys giving the column names'
@defer.inlineCallbacks def get_last_client_ip_by_device(self, user_id, device_id):
res = (yield self.runInteraction('get_last_client_ip_by_device', self._get_last_client_ip_by_device_txn, user_id, device_id, retcols=('user_id', 'access_token', 'ip', 'user_agent', 'device_id', 'last_seen'))) ret = {(d['user_id'], d['device_id']): d for d in res} for key in self._batch_row_update: (...
'Get auth events for given event_ids. The events *must* be state events. Args: event_ids (list): state events include_given (bool): include the given events in result Returns: list of events'
def get_auth_chain(self, event_ids, include_given=False):
return self.get_auth_chain_ids(event_ids, include_given=include_given).addCallback(self._get_events)
'Get auth events for given event_ids. The events *must* be state events. Args: event_ids (list): state events include_given (bool): include the given events in result Returns: list of event_ids'
def get_auth_chain_ids(self, event_ids, include_given=False):
return self.runInteraction('get_auth_chain_ids', self._get_auth_chain_ids_txn, event_ids, include_given)
'For hte given room, get the minimum depth we have seen for it.'
def get_min_depth(self, room_id):
return self.runInteraction('get_min_depth', self._get_min_depth_interaction, room_id)
'For the given event, update the event edges table and forward and backward extremities tables.'
def _handle_mult_prev_events(self, txn, events):
self._simple_insert_many_txn(txn, table='event_edges', values=[{'event_id': ev.event_id, 'prev_event_id': e_id, 'room_id': ev.room_id, 'is_state': False} for ev in events for (e_id, _) in ev.prev_events]) self._update_backward_extremeties(txn, events)
'Updates the event_backward_extremities tables based on the new/updated events being persisted. This is called for new events *and* for events that were outliers, but are now being persisted as non-outliers. Forward extremities are handled when we first start persisting the events.'
def _update_backward_extremeties(self, txn, events):
events_by_room = {} for ev in events: events_by_room.setdefault(ev.room_id, []).append(ev) query = 'INSERT INTO event_backward_extremities (event_id, room_id) SELECT ?, ? WHERE NOT EXISTS ( SELECT 1 FROM event_backward_extremities WHERE event_id ...
'For a given room_id and stream_ordering, return the forward extremeties of the room at that point in "time". Throws a StoreError if we have since purged the index for stream_orderings from that point. Args: room_id (str): stream_ordering (int): Returns: deferred, which resolves to a list of event_ids'
def get_forward_extremeties_for_room(self, room_id, stream_ordering):
last_change = self._events_stream_cache.get_max_pos_of_last_change(room_id) last_change = max(self._stream_order_on_start, last_change) if (last_change > self.stream_ordering_month_ago): stream_ordering = min(last_change, stream_ordering) return self._get_forward_extremeties_for_room(room_id, st...
'For a given room_id and stream_ordering, return the forward extremeties of the room at that point in "time". Throws a StoreError if we have since purged the index for stream_orderings from that point.'
@cached(max_entries=5000, num_args=2) def _get_forward_extremeties_for_room(self, room_id, stream_ordering):
if (stream_ordering <= self.stream_ordering_month_ago): raise StoreError(400, 'stream_ordering too old') sql = '\n SELECT event_id FROM stream_ordering_to_exterm\n ...
'Get a list of Events for a given topic that occurred before (and including) the events in event_list. Return a list of max size `limit` Args: txn room_id (str) event_list (list) limit (int)'
def get_backfill_events(self, room_id, event_list, limit):
return self.runInteraction('get_backfill_events', self._get_backfill_events, room_id, event_list, limit).addCallback(self._get_events).addCallback((lambda l: sorted(l, key=(lambda e: (- e.depth)))))
'Returns a default presence state.'
@classmethod def default(cls, user_id):
return cls(user_id=user_id, state=PresenceState.OFFLINE, last_active_ts=0, last_federation_update_ts=0, last_user_sync_ts=0, status_msg=None, currently_active=False)
'Get receipts for multiple rooms for sending to clients. Args: room_ids (list): List of room_ids. to_key (int): Max stream id to fetch receipts upto. from_key (int): Min stream id to fetch receipts from. None fetches from the start. Returns: list: A list of receipts.'
@defer.inlineCallbacks def get_linearized_receipts_for_rooms(self, room_ids, to_key, from_key=None):
room_ids = set(room_ids) if from_key: room_ids = (yield self._receipts_stream_cache.get_entities_changed(room_ids, from_key)) results = (yield self._get_linearized_receipts_for_rooms(room_ids, to_key, from_key=from_key)) defer.returnValue([ev for res in results.values() for ev in res])
'Get receipts for a single room for sending to clients. Args: room_ids (str): The room id. to_key (int): Max stream id to fetch receipts upto. from_key (int): Min stream id to fetch receipts from. None fetches from the start. Returns: list: A list of receipts.'
@cachedInlineCallbacks(num_args=3, tree=True) def get_linearized_receipts_for_room(self, room_id, to_key, from_key=None):
def f(txn): if from_key: sql = 'SELECT * FROM receipts_linearized WHERE room_id = ? AND stream_id > ? AND stream_id <= ?' txn.execute(sql, (room_id, from_key, to_key)) else: sql = 'SELECT * FROM receipts_linear...