desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Function to reterive a paginated list of users from users list. This will return a json object, which contains list of users and the total number of users in users table. Args: order (str): column name to order the select by this column start (int): start number to begin the query from limit (int): number of rows to r...
@defer.inlineCallbacks def get_users_paginate(self, order, start, limit):
ret = (yield self.store.get_users_paginate(order, start, limit)) defer.returnValue(ret)
'Function to search users list for one or more users with the matched term. Args: term (str): search term Returns: defer.Deferred: resolves to list[dict[str, Any]]'
@defer.inlineCallbacks def search_users(self, term):
ret = (yield self.store.search_users(term)) defer.returnValue(ret)
'Creates a new room. Args: requester (Requester): The user who requested the room creation. config (dict) : A dict of configuration options. Returns: The new room ID. Raises: SynapseError if the room ID couldn\'t be stored, or something went horribly wrong.'
@defer.inlineCallbacks def create_room(self, requester, config, ratelimit=True):
user_id = requester.user.to_string() if ratelimit: (yield self.ratelimit(requester)) if ('room_alias_name' in config): for wchar in string.whitespace: if (wchar in config['room_alias_name']): raise SynapseError(400, 'Invalid characters in room alias') ...
'Retrieves events, pagination tokens and state around a given event in a room. Args: user (UserID) room_id (str) event_id (str) limit (int): The maximum number of events to return in total (excluding state). Returns: dict, or None if the event isn\'t found'
@defer.inlineCallbacks def get_event_context(self, user, room_id, event_id, limit):
before_limit = math.floor((limit / 2.0)) after_limit = (limit - before_limit) now_token = (yield self.hs.get_event_sources().get_current_token()) users = (yield self.store.get_users_in_room(room_id)) is_peeking = (user.to_string() not in users) def filter_evts(events): return filter_even...
'Process a PDU received via a federation /send/ transaction, or via backfill of missing prev_events Args: origin (str): server which initiated the /send/ transaction. Will be used to fetch missing events or state. pdu (FrozenEvent): received PDU get_missing (bool): True if we should fetch missing prev_events Returns (D...
@defer.inlineCallbacks @log_function def on_receive_pdu(self, origin, pdu, get_missing=True):
existing = (yield self.get_persisted_pdu(origin, pdu.event_id, do_auth=False)) already_seen = (existing and ((not existing.internal_metadata.is_outlier()) or pdu.internal_metadata.is_outlier())) if already_seen: logger.debug('Already seen pdu %s', pdu.event_id) return if (pdu.ro...
'Args: origin (str): Origin of the pdu. Will be called to get the missing events pdu: received pdu prevs (set(str)): List of event ids which we are missing min_depth (int): Minimum depth of events to return.'
@defer.inlineCallbacks def _get_missing_events_for_pdu(self, origin, pdu, prevs, min_depth):
have_seen = (yield self.store.have_events(prevs)) seen = set(have_seen.keys()) if (not (prevs - seen)): return latest = (yield self.store.get_latest_event_ids_in_room(pdu.room_id)) latest = set(latest) latest |= seen logger.info('Missing %d events for room %r pdu ...
'Called when we have a new pdu. We need to do auth checks and put it through the StateHandler.'
@log_function @defer.inlineCallbacks def _process_received_pdu(self, origin, pdu, state, auth_chain):
event = pdu logger.debug('Processing event: %s', event) if (state and auth_chain and (not event.internal_metadata.is_outlier())): is_in_room = (yield self.auth.check_host_in_room(event.room_id, self.server_name)) else: is_in_room = True if (not is_in_room): logger.info(...
'Trigger a backfill request to `dest` for the given `room_id` This will attempt to get more events from the remote. This may return be successfull and still return no events if the other side has no new events to offer.'
@log_function @defer.inlineCallbacks def backfill(self, dest, room_id, limit, extremities):
if (dest == self.server_name): raise SynapseError(400, "Can't backfill from self.") events = (yield self.replication_layer.backfill(dest, room_id, limit=limit, extremities=extremities)) seen_events = (yield self.store.have_events_in_timeline(set((e.event_id for e in events)))) events = ...
'Checks the database to see if we should backfill before paginating, and if so do.'
@defer.inlineCallbacks def maybe_backfill(self, room_id, current_depth):
extremities = (yield self.store.get_oldest_events_with_depth_in_room(room_id)) if (not extremities): logger.debug('Not backfilling as no extremeties found.') return sorted_extremeties_tuple = sorted(extremities.items(), key=(lambda e: (- int(e[1])))) max_depth = sorted_ext...
'Sends the invite to the remote server for signing. Invites must be signed by the invitee\'s server before distribution.'
@defer.inlineCallbacks def send_invite(self, target_host, event):
pdu = (yield self.replication_layer.send_invite(destination=target_host, room_id=event.room_id, event_id=event.event_id, pdu=event)) defer.returnValue(pdu)
'Attempts to join the `joinee` to the room `room_id` via the server `target_host`. This first triggers a /make_join/ request that returns a partial event that we can fill out and sign. This is then sent to the remote server via /send_join/ which responds with the state at that event and the auth_chains. We suspend proc...
@log_function @defer.inlineCallbacks def do_invite_join(self, target_hosts, room_id, joinee, content):
logger.debug('Joining %s to %s', joinee, room_id) (origin, event) = (yield self._make_and_verify_event(target_hosts, room_id, joinee, 'join', content)) assert (room_id not in self.room_queues) self.room_queues[room_id] = [] (yield self.store.clean_room_for_join(room_id)) handled_events ...
'Process PDUs which got queued up while we were busy send_joining. Args: room_queue (list[FrozenEvent, str]): list of PDUs to be processed and the servers that sent them'
@defer.inlineCallbacks def _handle_queued_pdus(self, room_queue):
for (p, origin) in room_queue: try: logger.info('Processing queued PDU %s which was received while we were joining %s', p.event_id, p.room_id) (yield self.on_receive_pdu(origin, p)) except Exception as e: logger.warn('Error hand...
'We\'ve received a /make_join/ request, so we create a partial join event for the room and return that. We do *not* persist or process it until the other server has signed it and sent it back.'
@defer.inlineCallbacks @log_function def on_make_join_request(self, room_id, user_id):
event_content = {'membership': Membership.JOIN} builder = self.event_builder_factory.new({'type': EventTypes.Member, 'content': event_content, 'room_id': room_id, 'sender': user_id, 'state_key': user_id}) try: message_handler = self.hs.get_handlers().message_handler (event, context) = (yield...
'We have received a join event for a room. Fully process it and respond with the current state and auth chains.'
@defer.inlineCallbacks @log_function def on_send_join_request(self, origin, pdu):
event = pdu logger.debug('on_send_join_request: Got event: %s, signatures: %s', event.event_id, event.signatures) event.internal_metadata.outlier = False event.internal_metadata.send_on_behalf_of = origin (context, event_stream_id, max_stream_id) = (yield self._handle_new_event(origin...
'We\'ve got an invite event. Process and persist it. Sign it. Respond with the now signed event.'
@defer.inlineCallbacks def on_invite_request(self, origin, pdu):
event = pdu is_blocked = (yield self.store.is_room_blocked(event.room_id)) if is_blocked: raise SynapseError(403, 'This room has been blocked on this server') membership = event.content.get('membership') if ((event.type != EventTypes.Member) or (membership != Membership....
'We\'ve received a /make_leave/ request, so we create a partial join event for the room and return that. We do *not* persist or process it until the other server has signed it and sent it back.'
@defer.inlineCallbacks @log_function def on_make_leave_request(self, room_id, user_id):
builder = self.event_builder_factory.new({'type': EventTypes.Member, 'content': {'membership': Membership.LEAVE}, 'room_id': room_id, 'sender': user_id, 'state_key': user_id}) message_handler = self.hs.get_handlers().message_handler (event, context) = (yield message_handler._create_new_client_event(builder=...
'We have received a leave event for a room. Fully process it.'
@defer.inlineCallbacks @log_function def on_send_leave_request(self, origin, pdu):
event = pdu logger.debug('on_send_leave_request: Got event: %s, signatures: %s', event.event_id, event.signatures) event.internal_metadata.outlier = False (context, event_stream_id, max_stream_id) = (yield self._handle_new_event(origin, event)) logger.debug('on_send_leave_request: ...
'Returns the state at the event. i.e. not including said event.'
@defer.inlineCallbacks def get_state_for_pdu(self, room_id, event_id):
(yield run_on_reactor()) state_groups = (yield self.store.get_state_groups(room_id, [event_id])) if state_groups: (_, state) = state_groups.items().pop() results = {(e.type, e.state_key): e for e in state} event = (yield self.store.get_event(event_id)) if (event and event.is_...
'Returns the state at the event. i.e. not including said event.'
@defer.inlineCallbacks def get_state_ids_for_pdu(self, room_id, event_id):
(yield run_on_reactor()) state_groups = (yield self.store.get_state_groups_ids(room_id, [event_id])) if state_groups: (_, state) = state_groups.items().pop() results = state event = (yield self.store.get_event(event_id)) if (event and event.is_state()): if ('repla...
'Get a PDU from the database with given origin and id. Returns: Deferred: Results in a `Pdu`.'
@defer.inlineCallbacks @log_function def get_persisted_pdu(self, origin, event_id, do_auth=True):
event = (yield self.store.get_event(event_id, allow_none=True, allow_rejected=True)) if event: if self.is_mine_id(event.event_id): event.signatures.update(compute_event_signature(event, self.hs.hostname, self.hs.config.signing_key[0])) if do_auth: in_room = (yield self.au...
'Creates the appropriate contexts and persists events. The events should not depend on one another, e.g. this should be used to persist a bunch of outliers, but not a chunk of individual events that depend on each other for state calculations.'
@defer.inlineCallbacks def _handle_new_events(self, origin, event_infos, backfilled=False):
contexts = (yield preserve_context_over_deferred(defer.gatherResults([preserve_fn(self._prep_event)(origin, ev_info['event'], state=ev_info.get('state'), auth_events=ev_info.get('auth_events')) for ev_info in event_infos]))) (yield self.store.persist_events([(ev_info['event'], context) for (ev_info, context) in...
'Checks the auth chain is valid (and passes auth checks) for the state and event. Then persists the auth chain and state atomically. Persists the event seperately. Will attempt to fetch missing auth events. Args: origin (str): Where the events came from auth_events (list) state (list) event (Event) Returns: 2-tuple of ...
@defer.inlineCallbacks def _persist_auth_tree(self, origin, auth_events, state, event):
events_to_context = {} for e in itertools.chain(auth_events, state): e.internal_metadata.outlier = True ctx = (yield self.state_handler.compute_event_context(e)) events_to_context[e.event_id] = ctx event_map = {e.event_id: e for e in itertools.chain(auth_events, state, [event])} ...
'Args: origin: event: state: auth_events: Returns: Deferred, which resolves to synapse.events.snapshot.EventContext'
@defer.inlineCallbacks def _prep_event(self, origin, event, state=None, auth_events=None):
context = (yield self.state_handler.compute_event_context(event, old_state=state)) if (not auth_events): auth_events_ids = (yield self.auth.compute_auth_events(event, context.prev_state_ids, for_verification=True)) auth_events = (yield self.store.get_events(auth_events_ids)) auth_events ...
'Given a local and remote auth chain, find the differences. This assumes that we have already processed all events in remote_auth Params: local_auth (list) remote_auth (list) Returns: dict'
@defer.inlineCallbacks def construct_auth_difference(self, local_auth, remote_auth):
logger.debug('construct_auth_difference Start!') def sort_fun(ev): return (ev.depth, ev.event_id) logger.debug('construct_auth_difference after sort_fun!') remote_list = list(remote_auth) remote_list.sort(key=sort_fun) local_list = list(local_auth) local_list.sort(key=sort_f...
'Checks that the signature in the event is consistent with its invite. Args: event (Event): The m.room.member event to check context (EventContext): Raises: AuthError: if signature didn\'t match any keys, or key has been revoked, SynapseError: if a transient error meant a key couldn\'t be checked for revocation.'
@defer.inlineCallbacks def _check_signature(self, event, context):
signed = event.content['third_party_invite']['signed'] token = signed['token'] invite_event_id = context.prev_state_ids.get((EventTypes.ThirdPartyInvite, token)) invite_event = None if invite_event_id: invite_event = (yield self.store.get_event(invite_event_id, allow_none=True)) if (not ...
'Checks whether public_key has been revoked. Args: public_key (str): base-64 encoded public key. url (str): Key revocation URL. Raises: AuthError: if they key has been revoked. SynapseError: if a transient error meant a key couldn\'t be checked for revocation.'
@defer.inlineCallbacks def _check_key_revocation(self, public_key, url):
try: response = (yield self.hs.get_simple_http_client().get_json(url, {'public_key': public_key})) except Exception: raise SynapseError(502, 'Third party certificate could not be checked') if (('valid' not in response) or (not response['valid'])): raise AuthError(40...
'Get messages in a room. Args: requester (Requester): The user requesting messages. room_id (str): The room they want messages from. pagin_config (synapse.api.streams.PaginationConfig): The pagination config rules to apply, if any. as_client_event (bool): True to get events in client-server format. event_filter (Filter...
@defer.inlineCallbacks def get_messages(self, requester, room_id=None, pagin_config=None, as_client_event=True, event_filter=None):
user_id = requester.user.to_string() if pagin_config.from_token: room_token = pagin_config.from_token.room_key else: pagin_config.from_token = (yield self.hs.get_event_sources().get_current_token_for_room(room_id=room_id)) room_token = pagin_config.from_token.room_key room_token ...
'Given a dict from a client, create a new event. Creates an FrozenEvent object, filling out auth_events, prev_events, etc. Adds display names to Join membership events. Args: requester event_dict (dict): An entire event token_id (str) txn_id (str) prev_event_ids (list): The prev event ids to use when creating the event...
@defer.inlineCallbacks def create_event(self, requester, event_dict, token_id=None, txn_id=None, prev_event_ids=None):
builder = self.event_builder_factory.new(event_dict) with (yield self.limiter.queue(builder.room_id)): self.validator.validate_new(builder) if (builder.type == EventTypes.Member): membership = builder.content.get('membership', None) target = UserID.from_string(builder.sta...
'Persists and notifies local clients and federation of an event. Args: event (FrozenEvent) the event to send. context (Context) the context of the event. ratelimit (bool): Whether to rate limit this send. is_guest (bool): Whether the sender is a guest.'
@defer.inlineCallbacks def send_nonmember_event(self, requester, event, context, ratelimit=True):
if (event.type == EventTypes.Member): raise SynapseError(500, 'Tried to send member event through non-member codepath') (yield self.ratelimit(requester, update=False)) user = UserID.from_string(event.sender) assert self.hs.is_mine(user), ('User must be our own: ...
'Checks whether event is in the latest resolved state in context. If so, returns the version of the event in context. Otherwise, returns None.'
@defer.inlineCallbacks def deduplicate_state_event(self, event, context):
prev_event_id = context.prev_state_ids.get((event.type, event.state_key)) prev_event = (yield self.store.get_event(prev_event_id, allow_none=True)) if (not prev_event): return if (prev_event and (event.user_id == prev_event.user_id)): prev_content = encode_canonical_json(prev_event.conte...
'Creates an event, then sends it. See self.create_event and self.send_nonmember_event.'
@defer.inlineCallbacks def create_and_send_nonmember_event(self, requester, event_dict, ratelimit=True, txn_id=None):
(event, context) = (yield self.create_event(requester, event_dict, token_id=requester.access_token_id, txn_id=txn_id)) (yield self.send_nonmember_event(requester, event, context, ratelimit=ratelimit)) defer.returnValue(event)
'Get data from a room. Args: event : The room path event Returns: The path data content. Raises: SynapseError if something went wrong.'
@defer.inlineCallbacks def get_room_data(self, user_id=None, room_id=None, event_type=None, state_key='', is_guest=False):
(membership, membership_event_id) = (yield self._check_in_room_or_world_readable(room_id, user_id)) if (membership == Membership.JOIN): data = (yield self.state_handler.get_current_state(room_id, event_type, state_key)) elif (membership == Membership.LEAVE): key = (event_type, state_key) ...
'Retrieve all state events for a given room. If the user is joined to the room then return the current state. If the user has left the room return the state events from when they left. Args: user_id(str): The user requesting state events. room_id(str): The room ID to get all state events from. Returns: A list of dicts ...
@defer.inlineCallbacks def get_state_events(self, user_id, room_id, is_guest=False):
(membership, membership_event_id) = (yield self._check_in_room_or_world_readable(room_id, user_id)) if (membership == Membership.JOIN): room_state = (yield self.state_handler.get_current_state(room_id)) elif (membership == Membership.LEAVE): room_state = (yield self.store.get_state_for_event...
'Generate a local public room list. There are multiple different lists: the main one plus one per third party network. A client can ask for a specific list or to return all. Args: limit (int) since_token (str) search_filter (dict) network_tuple (ThirdPartyInstanceID): Which public list to use. This can be (None, None) ...
def get_local_public_room_list(self, limit=None, since_token=None, search_filter=None, network_tuple=EMTPY_THIRD_PARTY_ID):
logger.info('Getting public room list: limit=%r, since=%r, search=%r, network=%r', limit, since_token, bool(search_filter), network_tuple) if search_filter: return self._get_public_room_list(limit, since_token, search_filter, network_tuple=network_tuple) key = (limit, since_toke...
'Generate the entry for a room in the public room list and append it to the `chunk` if it matches the search filter'
@defer.inlineCallbacks def _append_room_entry_to_chunk(self, room_id, num_joined_users, chunk, limit, search_filter):
if (limit and (len(chunk) > (limit + 1))): return result = (yield self._generate_room_entry(room_id, num_joined_users)) if (result and _matches_room_entry(result, search_filter)): chunk.append(result)
'Returns the entry for a room'
@cachedInlineCallbacks(num_args=1, cache_context=True) def _generate_room_entry(self, room_id, num_joined_users, cache_context):
result = {'room_id': room_id, 'num_joined_members': num_joined_users} current_state_ids = (yield self.store.get_current_state_ids(room_id, on_invalidate=cache_context.invalidate)) event_map = (yield self.store.get_events([event_id for (key, event_id) in current_state_ids.iteritems() if (key[0] in (EventType...
'Updates the read marker for a given user in a given room if the event ID given is ahead in the stream relative to the current read marker. This uses a notifier to indicate that account data should be sent down /sync if the read marker has changed.'
@defer.inlineCallbacks def received_client_read_marker(self, room_id, user_id, event_id):
with (yield self.read_marker_linearizer.queue((room_id, user_id))): account_data = (yield self.store.get_account_data_for_room(user_id, room_id)) existing_read_marker = account_data.get('m.fully_read', None) should_update = True if existing_read_marker: should_update = (y...
'Notifies (pushes) all application services interested in this event. Pushing is done asynchronously, so this method won\'t block for any prolonged length of time. Args: current_id(int): The current maximum ID.'
@defer.inlineCallbacks def notify_interested_services(self, current_id):
services = self.store.get_app_services() if ((not services) or (not self.notify_appservices)): return self.current_max = max(self.current_max, current_id) if self.is_processing: return with Measure(self.clock, 'notify_interested_services'): self.is_processing = True t...
'Check if any application service knows this user_id exists. Args: user_id(str): The user to query if they exist on any AS. Returns: True if this user exists on at least one application service.'
@defer.inlineCallbacks def query_user_exists(self, user_id):
user_query_services = (yield self._get_services_for_user(user_id=user_id)) for user_service in user_query_services: is_known_user = (yield self.appservice_api.query_user(user_service, user_id)) if is_known_user: defer.returnValue(True) defer.returnValue(False)
'Check if an application service knows this room alias exists. Args: room_alias(RoomAlias): The room alias to query. Returns: namedtuple: with keys "room_id" and "servers" or None if no association can be found.'
@defer.inlineCallbacks def query_room_alias_exists(self, room_alias):
room_alias_str = room_alias.to_string() services = self.store.get_app_services() alias_query_services = [s for s in services if s.is_interested_in_alias(room_alias_str)] for alias_service in alias_query_services: is_known_alias = (yield self.appservice_api.query_alias(alias_service, room_alias_s...
'Retrieve a list of application services interested in this event. Args: event(Event): The event to check. Can be None if alias_list is not. Returns: list<ApplicationService>: A list of services interested in this event based on the service regex.'
@defer.inlineCallbacks def _get_services_for_event(self, event):
services = self.store.get_app_services() interested_list = [s for s in services if (yield s.is_interested(event, self.store))] defer.returnValue(interested_list)
'Gets called when shutting down. This lets us persist any updates that we haven\'t yet persisted, e.g. updates that only changes some internal timers. This allows changes to persist across startup without having to persist every single change. If this does not run it simply means that some of the timers will fire earli...
@defer.inlineCallbacks def _on_shutdown(self):
logger.info('Performing _on_shutdown. Persisting %d unpersisted changes', len(self.user_to_current_state)) if self.unpersisted_users_changes: (yield self.store.update_presence([self.user_to_current_state[user_id] for user_id in self.unpersisted_users_changes])) logger.info('Finished ...
'We periodically persist the unpersisted changes, as otherwise they may stack up and slow down shutdown times.'
@defer.inlineCallbacks def _persist_unpersisted_changes(self):
logger.info('Performing _persist_unpersisted_changes. Persisting %d unpersisted changes', len(self.unpersisted_users_changes)) unpersisted = self.unpersisted_users_changes self.unpersisted_users_changes = set() if unpersisted: (yield self.store.update_presence([self.user_to_curren...
'Updates presence of users. Sets the appropriate timeouts. Pokes the notifier and federation if and only if the changed presence state should be sent to clients/servers.'
@defer.inlineCallbacks def _update_states(self, new_states):
now = self.clock.time_msec() with Measure(self.clock, 'presence_update_states'): to_notify = {} to_federation_ping = {} new_states_dict = {} for new_state in new_states: new_states_dict[new_state.user_id] = new_state new_state = new_states_dict.values() ...
'Checks the presence of users that have timed out and updates as appropriate.'
def _handle_timeouts(self):
logger.info('Handling presence timeouts') now = self.clock.time_msec() try: with Measure(self.clock, 'presence_handle_timeouts'): users_to_check = set(self.wheel_timer.fetch(now)) expired_process_ids = [process_id for (process_id, last_update) in self.external_process_l...
'We\'ve seen the user do something that indicates they\'re interacting with the app.'
@defer.inlineCallbacks def bump_presence_active_time(self, user):
user_id = user.to_string() bump_active_time_counter.inc() prev_state = (yield self.current_state_for_user(user_id)) new_fields = {'last_active_ts': self.clock.time_msec()} if (prev_state.state == PresenceState.UNAVAILABLE): new_fields['state'] = PresenceState.ONLINE (yield self._update_s...
'Returns a context manager that should surround any stream requests from the user. This allows us to keep track of who is currently streaming and who isn\'t without having to have timers outside of this module to avoid flickering when users disconnect/reconnect. Args: user_id (str) affect_presence (bool): If false this...
@defer.inlineCallbacks def user_syncing(self, user_id, affect_presence=True):
if affect_presence: curr_sync = self.user_to_num_current_syncs.get(user_id, 0) self.user_to_num_current_syncs[user_id] = (curr_sync + 1) prev_state = (yield self.current_state_for_user(user_id)) if (prev_state.state == PresenceState.OFFLINE): (yield self._update_states([p...
'Get the set of user ids that are currently syncing on this HS. Returns: set(str): A set of user_id strings.'
def get_currently_syncing_users(self):
syncing_user_ids = {user_id for (user_id, count) in self.user_to_num_current_syncs.items() if count} for user_ids in self.external_process_to_current_syncs.values(): syncing_user_ids.update(user_ids) return syncing_user_ids
'Update the syncing users for an external process Args: process_id(str): An identifier for the process the users are syncing against. This allows synapse to process updates as user start and stop syncing against a given process. syncing_user_ids(set(str)): The set of user_ids that are currently syncing on that server.'...
@defer.inlineCallbacks def update_external_syncs(self, process_id, syncing_user_ids):
prev_syncing_user_ids = self.external_process_to_current_syncs.get(process_id, set()) prev_states = (yield self.current_state_for_users((syncing_user_ids | prev_syncing_user_ids))) updates = [] time_now_ms = self.clock.time_msec() for new_user_id in (syncing_user_ids - prev_syncing_user_ids): ...
'Update the syncing users for an external process as a delta. Args: process_id (str): An identifier for the process the users are syncing against. This allows synapse to process updates as user start and stop syncing against a given process. user_id (str): The user who has started or stopped syncing is_syncing (bool): ...
@defer.inlineCallbacks def update_external_syncs_row(self, process_id, user_id, is_syncing, sync_time_msec):
with (yield self.external_sync_linearizer.queue(process_id)): prev_state = (yield self.current_state_for_user(user_id)) process_presence = self.external_process_to_current_syncs.setdefault(process_id, set()) updates = [] if (is_syncing and (user_id not in process_presence)): ...
'Marks all users that had been marked as syncing by a given process as offline. Used when the process has stopped/disappeared.'
@defer.inlineCallbacks def update_external_syncs_clear(self, process_id):
with (yield self.external_sync_linearizer.queue(process_id)): process_presence = self.external_process_to_current_syncs.pop(process_id, set()) prev_states = (yield self.current_state_for_users(process_presence)) time_now_ms = self.clock.time_msec() (yield self._update_states([prev_st...
'Get the current presence state for a user.'
@defer.inlineCallbacks def current_state_for_user(self, user_id):
res = (yield self.current_state_for_users([user_id])) defer.returnValue(res[user_id])
'Get the current presence state for multiple users. Returns: dict: `user_id` -> `UserPresenceState`'
@defer.inlineCallbacks def current_state_for_users(self, user_ids):
states = {user_id: self.user_to_current_state.get(user_id, None) for user_id in user_ids} missing = [user_id for (user_id, state) in states.iteritems() if (not state)] if missing: res = (yield self.store.get_presence_for_users(missing)) states.update(res) missing = [user_id for (user...
'Persist states in the database, poke the notifier and send to interested remote servers'
@defer.inlineCallbacks def _persist_and_notify(self, states):
(stream_id, max_token) = (yield self.store.update_presence(states)) parties = (yield get_interested_parties(self.store, states)) (room_ids_to_states, users_to_states) = parties self.notifier.on_new_event('presence_key', stream_id, rooms=room_ids_to_states.keys(), users=[UserID.from_string(u) for u in us...
'Sends state updates to remote servers. Args: states (list(UserPresenceState))'
def _push_to_remotes(self, states):
self.federation.send_presence(states)
'Called when we receive a `m.presence` EDU from a remote server.'
@defer.inlineCallbacks def incoming_presence(self, origin, content):
now = self.clock.time_msec() updates = [] for push in content.get('push', []): user_id = push.get('user_id', None) if (not user_id): logger.info("Got presence update from %r with no 'user_id': %r", origin, push) continue if (get_domain_...
'Get the presence state for users. Args: target_user_ids (list) as_event (bool): Whether to format it as a client event or not. Returns: list'
@defer.inlineCallbacks def get_states(self, target_user_ids, as_event=False):
updates = (yield self.current_state_for_users(target_user_ids)) updates = updates.values() for user_id in (set(target_user_ids) - set((u.user_id for u in updates))): updates.append(UserPresenceState.default(user_id)) now = self.clock.time_msec() if as_event: defer.returnValue([{'type...
'Set the presence state of the user.'
@defer.inlineCallbacks def set_state(self, target_user, state, ignore_status_msg=False):
status_msg = state.get('status_msg', None) presence = state['presence'] valid_presence = (PresenceState.ONLINE, PresenceState.UNAVAILABLE, PresenceState.OFFLINE) if (presence not in valid_presence): raise SynapseError(400, 'Invalid presence state') user_id = target_user.to_string() ...
'Called (via the distributor) when a user joins a room. This funciton sends presence updates to servers, either: 1. the joining user is a local user and we send their presence to all servers in the room. 2. the joining user is a remote user and so we send presence for all local users in the room.'
@defer.inlineCallbacks def user_joined_room(self, user, room_id):
if self.is_mine(user): state = (yield self.current_state_for_user(user.to_string())) self._push_to_remotes([state]) else: user_ids = (yield self.store.get_users_in_room(room_id)) user_ids = filter(self.is_mine_id, user_ids) states = (yield self.current_state_for_users(use...
'Returns the presence for all users in their presence list.'
@defer.inlineCallbacks def get_presence_list(self, observer_user, accepted=None):
if (not self.is_mine(observer_user)): raise SynapseError(400, 'User is not hosted on this Home Server') presence_list = (yield self.store.get_presence_list(observer_user.localpart, accepted=accepted)) results = (yield self.get_states(target_user_ids=[row['observed_user_id'] for ...
'Sends a presence invite.'
@defer.inlineCallbacks def send_presence_invite(self, observer_user, observed_user):
(yield self.store.add_presence_list_pending(observer_user.localpart, observed_user.to_string())) if self.is_mine(observed_user): (yield self.invite_presence(observed_user, observer_user)) else: (yield self.federation.send_edu(destination=observed_user.domain, edu_type='m.presence_invite', co...
'Handles new presence invites.'
@defer.inlineCallbacks def invite_presence(self, observed_user, observer_user):
if (not self.is_mine(observed_user)): raise SynapseError(400, 'User is not hosted on this Home Server') if self.is_mine(observer_user): (yield self.accept_presence(observed_user, observer_user)) else: self.federation.send_edu(destination=observer_user.domain, edu...
'Handles a m.presence_accept EDU. Mark a presence invite from a local or remote user as accepted in a local user\'s presence list. Starts polling for presence updates from the local or remote user. Args: observed_user(UserID): The user to update in the presence list. observer_user(UserID): The owner of the presence lis...
@defer.inlineCallbacks def accept_presence(self, observed_user, observer_user):
(yield self.store.set_presence_list_accepted(observer_user.localpart, observed_user.to_string()))
'Handle a m.presence_deny EDU. Removes a local or remote user from a local user\'s presence list. Args: observed_user(UserID): The local or remote user to remove from the list. observer_user(UserID): The local owner of the presence list. Returns: A Deferred.'
@defer.inlineCallbacks def deny_presence(self, observed_user, observer_user):
(yield self.store.del_presence_list(observer_user.localpart, observed_user.to_string()))
'Remove a local or remote user from a local user\'s presence list and unsubscribe the local user from updates that user. Args: observed_user(UserId): The local or remote user to remove from the list. observer_user(UserId): The local owner of the presence list. Returns: A Deferred.'
@defer.inlineCallbacks def drop(self, observed_user, observer_user):
if (not self.is_mine(observer_user)): raise SynapseError(400, 'User is not hosted on this Home Server') (yield self.store.del_presence_list(observer_user.localpart, observed_user.to_string()))
'Returns whether a user can see another user\'s presence.'
@defer.inlineCallbacks def is_visible(self, observed_user, observer_user):
observer_room_ids = (yield self.store.get_rooms_for_user(observer_user.to_string())) observed_room_ids = (yield self.store.get_rooms_for_user(observed_user.to_string())) if (observer_room_ids & observed_room_ids): defer.returnValue(True) accepted_observers = (yield self.store.get_presence_list_o...
'Gets a list of presence update rows from between the given stream ids. Each row has: - stream_id(str) - user_id(str) - state(str) - last_active_ts(int) - last_federation_update_ts(int) - last_user_sync_ts(int) - status_msg(int) - currently_active(int)'
@defer.inlineCallbacks def get_all_presence_updates(self, last_id, current_id):
rows = (yield self.store.get_all_presence_updates(last_id, current_id)) defer.returnValue(rows)
'Returns the set of users that the given user should see presence updates for'
@cachedInlineCallbacks(num_args=2, cache_context=True) def _get_interested_in(self, user, explicit_room_id, cache_context):
user_id = user.to_string() plist = (yield self.store.get_presence_list_accepted(user.localpart, on_invalidate=cache_context.invalidate)) users_interested_in = set((row['observed_user_id'] for row in plist)) users_interested_in.add(user_id) users_who_share_room = (yield self.store.get_users_who_share...
'Change the membership status of a user in a room. Args: requester (Requester): The local user who requested the membership event. If None, certain checks, like whether this homeserver can act as the sender, will be skipped. event (SynapseEvent): The membership event. context: The context of the event. is_guest (bool):...
@defer.inlineCallbacks def send_membership_event(self, requester, event, context, remote_room_hosts=None, ratelimit=True):
remote_room_hosts = (remote_room_hosts or []) target_user = UserID.from_string(event.state_key) room_id = event.room_id if (requester is not None): sender = UserID.from_string(event.sender) assert (sender == requester.user), ('Sender (%s) must be same as requester (%...
'Returns whether a guest can join a room based on its current state.'
@defer.inlineCallbacks def _can_guest_join(self, current_state_ids):
guest_access_id = current_state_ids.get((EventTypes.GuestAccess, ''), None) if (not guest_access_id): defer.returnValue(False) guest_access = (yield self.store.get_event(guest_access_id)) defer.returnValue((guest_access and guest_access.content and ('guest_access' in guest_access.content) and (g...
'Get the room ID associated with a room alias. Args: room_alias (RoomAlias): The alias to look up. Returns: A tuple of: The room ID as a RoomID object. Hosts likely to be participating in the room ([str]). Raises: SynapseError if room alias could not be found.'
@defer.inlineCallbacks def lookup_room_alias(self, room_alias):
directory_handler = self.hs.get_handlers().directory_handler mapping = (yield directory_handler.get_association(room_alias)) if (not mapping): raise SynapseError(404, 'No such room alias') room_id = mapping['room_id'] servers = mapping['servers'] defer.returnValue((RoomID.from_s...
'Looks up a 3pid in the passed identity server. Args: id_server (str): The server name (including port, if required) of the identity server to use. medium (str): The type of the third party identifier (e.g. "email"). address (str): The third party identifier (e.g. "foo@example.com"). Returns: str: the matrix ID of the ...
@defer.inlineCallbacks def _lookup_3pid(self, id_server, medium, address):
try: data = (yield self.hs.get_simple_http_client().get_json(('%s%s/_matrix/identity/api/v1/lookup' % (id_server_scheme, id_server)), {'medium': medium, 'address': address})) if ('mxid' in data): if ('signatures' not in data): raise AuthError(401, 'No signatures on ...
'Asks an identity server for a third party invite. Args: id_server (str): hostname + optional port for the identity server. medium (str): The literal string "email". address (str): The third party address being invited. room_id (str): The ID of the room to which the user is invited. inviter_user_id (str): The user ID o...
@defer.inlineCallbacks def _ask_id_server_for_third_party_invite(self, id_server, medium, address, room_id, inviter_user_id, room_alias, room_avatar_url, room_join_rules, room_name, inviter_display_name, inviter_avatar_url):
is_url = ('%s%s/_matrix/identity/api/v1/store-invite' % (id_server_scheme, id_server)) invite_config = {'medium': medium, 'address': address, 'room_id': room_id, 'room_alias': room_alias, 'room_avatar_url': room_avatar_url, 'room_join_rules': room_join_rules, 'room_name': room_name, 'sender': inviter_user_id, '...
'Called when a client tells us a local user has read up to the given event_id in the room.'
@defer.inlineCallbacks def received_client_receipt(self, room_id, receipt_type, user_id, event_id):
receipt = {'room_id': room_id, 'receipt_type': receipt_type, 'user_id': user_id, 'event_ids': [event_id], 'data': {'ts': int(self.clock.time_msec())}} is_new = (yield self._handle_new_receipts([receipt])) if is_new: self._push_remotes([receipt])
'Called when we receive an EDU of type m.receipt from a remote HS.'
@defer.inlineCallbacks def _received_remote_receipt(self, origin, content):
receipts = [{'room_id': room_id, 'receipt_type': receipt_type, 'user_id': user_id, 'event_ids': user_values['event_ids'], 'data': user_values.get('data', {})} for (room_id, room_values) in content.items() for (receipt_type, users) in room_values.items() for (user_id, user_values) in users.items()] (yield self._...
'Takes a list of receipts, stores them and informs the notifier.'
@defer.inlineCallbacks def _handle_new_receipts(self, receipts):
min_batch_id = None max_batch_id = None for receipt in receipts: room_id = receipt['room_id'] receipt_type = receipt['receipt_type'] user_id = receipt['user_id'] event_ids = receipt['event_ids'] data = receipt['data'] res = (yield self.store.insert_receipt(roo...
'Given a list of receipts, works out which remote servers should be poked and pokes them.'
@defer.inlineCallbacks def _push_remotes(self, receipts):
for receipt in receipts: room_id = receipt['room_id'] receipt_type = receipt['receipt_type'] user_id = receipt['user_id'] event_ids = receipt['event_ids'] data = receipt['data'] users = (yield self.state.get_current_user_in_room(room_id)) remotedomains = set((...
'Gets all receipts for a room, upto the given key.'
@defer.inlineCallbacks def get_receipts_for_room(self, room_id, to_key):
result = (yield self.store.get_linearized_receipts_for_room(room_id, to_key=to_key)) if (not result): defer.returnValue([]) defer.returnValue(result)
'Retrieve a snapshot of all rooms the user is invited or has joined. This snapshot may include messages for all rooms where the user is joined, depending on the pagination config. Args: user_id (str): The ID of the user making the request. pagin_config (synapse.api.streams.PaginationConfig): The pagination config used ...
def snapshot_all_rooms(self, user_id=None, pagin_config=None, as_client_event=True, include_archived=False):
key = (user_id, pagin_config.from_token, pagin_config.to_token, pagin_config.direction, pagin_config.limit, as_client_event, include_archived) now_ms = self.clock.time_msec() result = self.snapshot_cache.get(now_ms, key) if (result is not None): return result return self.snapshot_cache.set(n...
'Capture the a snapshot of a room. If user is currently a member of the room this will be what is currently in the room. If the user left the room this will be what was in the room when they left. Args: requester(Requester): The user to get a snapshot for. room_id(str): The room to get a snapshot of. pagin_config(synap...
@defer.inlineCallbacks def room_initial_sync(self, requester, room_id, pagin_config=None):
user_id = requester.user.to_string() (membership, member_event_id) = (yield self._check_in_room_or_world_readable(room_id, user_id)) is_peeking = (member_event_id is None) if (membership == Membership.JOIN): result = (yield self._room_initial_sync_joined(user_id, room_id, pagin_config, membershi...
'A user has started syncing. Send a UserSync to the master, unless they had recently stopped syncing. Args: user_id (str)'
def mark_as_coming_online(self, user_id):
going_offline = self.users_going_offline.pop(user_id, None) if (not going_offline): self.send_user_sync(user_id, True, self.clock.time_msec())
'A user has stopped syncing. We wait before notifying the master as its likely they\'ll come back soon. This allows us to avoid sending a stopped syncing immediately followed by a started syncing notification to the master Args: user_id (str)'
def mark_as_going_offline(self, user_id):
self.users_going_offline[user_id] = self.clock.time_msec()
'Check if there are any users who have stopped syncing a while ago and haven\'t come back yet. If there are poke the master about them.'
def send_stop_syncing(self):
now = self.clock.time_msec() for (user_id, last_sync_ms) in self.users_going_offline.items(): if ((now - last_sync_ms) > (10 * 1000)): self.users_going_offline.pop(user_id, None) self.send_user_sync(user_id, False, last_sync_ms)
'This gets the rules for all users in the room at the time of the event, as well as the push rules for the invitee if the event is an invite. Returns: dict of user_id -> push_rules'
@defer.inlineCallbacks def _get_rules_for_event(self, event, context):
room_id = event.room_id rules_for_room = self._get_rules_for_room(room_id) rules_by_user = (yield rules_for_room.get_rules(event, context)) if ((event.type == 'm.room.member') and (event.content['membership'] == 'invite')): invited = event.state_key if (invited and self.hs.is_mine_id(inv...
'Get the current RulesForRoom object for the given room id Returns: RulesForRoom'
@cached() def _get_rules_for_room(self, room_id):
return RulesForRoom(self.hs, room_id, self._get_rules_for_room.cache)
'Given an event and context, evaluate the push rules and return the results Returns: dict of user_id -> action'
@defer.inlineCallbacks def action_for_event_by_user(self, event, context):
rules_by_user = (yield self._get_rules_for_event(event, context)) actions_by_user = {} user_tuples = [(u, False) for u in rules_by_user] filtered_by_user = (yield filter_events_for_clients_context(self.store, user_tuples, [event], {event.event_id: context})) room_members = (yield self.store.get_join...
'Args: hs (HomeServer) room_id (str) rules_for_room_cache(Cache): The cache object that caches these RoomsForUser objects.'
def __init__(self, hs, room_id, rules_for_room_cache):
self.room_id = room_id self.is_mine_id = hs.is_mine_id self.store = hs.get_datastore() self.linearizer = Linearizer(name='rules_for_room') self.member_map = {} self.rules_by_user = {} self.state_group = object() self.sequence = 0 self.uninteresting_user_set = set() self.invalidat...
'Given an event context return the rules for all users who are currently in the room.'
@defer.inlineCallbacks def get_rules(self, event, context):
state_group = context.state_group with (yield self.linearizer.queue(())): if (state_group and (self.state_group == state_group)): logger.debug('Using cached rules for %r', self.room_id) defer.returnValue(self.rules_by_user) ret_rules_by_user = {} missi...
'Update the partially filled rules_by_user dict by fetching rules for any newly joined users in the `member_event_ids` list. Args: ret_rules_by_user (dict): Partiallly filled dict of push rules. Gets updated with any new rules. member_event_ids (list): List of event ids for membership events that have happened since th...
@defer.inlineCallbacks def _update_rules_with_member_event_ids(self, ret_rules_by_user, member_event_ids, state_group, event):
sequence = self.sequence rows = (yield self.store._simple_select_many_batch(table='room_memberships', column='event_id', iterable=member_event_ids.values(), retcols=('user_id', 'membership', 'event_id'), keyvalues={}, batch_size=500, desc='_get_rules_for_member_event_ids')) members = {row['event_id']: (row[...
'Looks for unset notifications and dispatch them, in order Never call this directly: use _process which will only allow this to run once per pusher.'
@defer.inlineCallbacks def _unsafe_process(self):
fn = self.store.get_unread_push_actions_for_user_in_range_for_http unprocessed = (yield fn(self.user_id, self.last_stream_ordering, self.max_stream_ordering)) for push_action in unprocessed: processed = (yield self._process_one(push_action)) if processed: self.backoff_delay = Htt...
'Main logic of the push loop without the wrapper function that sets up logging, measures and guards against multiple instances of it being run.'
@defer.inlineCallbacks def _unsafe_process(self):
start = (0 if INCLUDE_ALL_UNREAD_NOTIFS else self.last_stream_ordering) fn = self.store.get_unread_push_actions_for_user_in_range_for_email unprocessed = (yield fn(self.user_id, start, self.max_stream_ordering)) soonest_due_at = None if (not unprocessed): (yield self.save_last_stream_orderin...
'Determines whether throttling should prevent us from sending an email for the given room Returns: The timestamp when we are next allowed to send an email notif for this room'
def room_ready_to_notify_at(self, room_id):
last_sent_ts = self.get_room_last_sent_ts(room_id) throttle_ms = self.get_room_throttle_ms(room_id) may_send_at = (last_sent_ts + throttle_ms) return may_send_at
'Args: hostname : The hostname for the server.'
def __init__(self, hostname, **kwargs):
self.hostname = hostname self._building = {} self.clock = Clock() self.distributor = Distributor() self.ratelimiter = Ratelimiter() for depname in kwargs: setattr(self, depname, kwargs[depname])
'Should this server be sending federation traffic directly?'
def should_send_federation(self):
return (self.config.send_federation and ((not self.config.worker_app) or (self.config.worker_app == 'synapse.app.federation_sender')))
'Bulk verfies signatures of json objects, bulk fetching keys as necessary. Args: server_and_json (list): List of pairs of (server_name, json_object) Returns: list of deferreds indicating success or failure to verify each json object\'s signature for the given server_name.'
def verify_json_objects_for_server(self, server_and_json):
verify_requests = [] for (server_name, json_object) in server_and_json: key_ids = signature_ids(json_object, server_name) if (not key_ids): logger.warn('Request from %s: no supported signature keys', server_name) deferred = defer.fail(SynapseError(400, '...
'Waits for any previous key lookups for the given servers to finish. Args: server_names (list): list of server_names we want to lookup server_to_deferred (dict): server_name to deferred which gets resolved once we\'ve finished looking up keys for that server'
@defer.inlineCallbacks def wait_for_previous_lookups(self, server_names, server_to_deferred):
while True: wait_on = [self.key_downloads[server_name] for server_name in server_names if (server_name in self.key_downloads)] if wait_on: with PreserveLoggingContext(): (yield defer.DeferredList(wait_on)) else: break for (server_name, deferred) in...
'Tries to find at least one key for each verify request For each verify_request, verify_request.deferred is called back with params (server_name, key_id, VerifyKey) if a key is found, or errbacked with a SynapseError if none of the keys are found. Args: verify_requests (list[VerifyKeyRequest]): list of verify requests'...
def get_server_verify_keys(self, verify_requests):
key_fetch_fns = (self.get_keys_from_store, self.get_keys_from_perspectives, self.get_keys_from_server) @defer.inlineCallbacks def do_iterations(): with Measure(self.clock, 'get_server_verify_keys'): merged_results = {} missing_keys = {} for verify_request in verif...
'Args: server_name_and_key_ids (list[(str, iterable[str])]): list of (server_name, iterable[key_id]) tuples to fetch keys for Returns: Deferred: resolves to dict[str, dict[str, VerifyKey]]: map from server_name -> key_id -> VerifyKey'
@defer.inlineCallbacks def get_keys_from_store(self, server_name_and_key_ids):
res = (yield preserve_context_over_deferred(defer.gatherResults([preserve_fn(self.store.get_server_verify_keys)(server_name, key_ids).addCallback((lambda ks, server: (server, ks)), server_name) for (server_name, key_ids) in server_name_and_key_ids], consumeErrors=True)).addErrback(unwrapFirstError)) defer.retur...
'Finds a verification key for the server with one of the key ids. Args: server_name (str): The name of the server to fetch a key for. keys_ids (list of str): The key_ids to check for.'
@defer.inlineCallbacks def get_server_verify_key_v1_direct(self, server_name, key_ids):
(response, tls_certificate) = (yield fetch_server_key(server_name, self.hs.tls_server_context_factory)) x509_certificate_bytes = crypto.dump_certificate(crypto.FILETYPE_ASN1, tls_certificate) if (('signatures' not in response) or (server_name not in response['signatures'])): raise KeyLookupError('Ke...
'Store a collection of verify keys for a given server Args: server_name(str): The name of the server the keys are for. from_server(str): The server the keys were downloaded from. verify_keys(dict): A mapping of key_id to VerifyKey. Returns: A deferred that completes when the keys are stored.'
@defer.inlineCallbacks def store_keys(self, server_name, from_server, verify_keys):
(yield preserve_context_over_deferred(defer.gatherResults([preserve_fn(self.store.store_server_verify_key)(server_name, server_name, key.time_added, key) for (key_id, key) in verify_keys.items()], consumeErrors=True)).addErrback(unwrapFirstError))