events.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. import random
  17. from synapse.api.constants import EventTypes, Membership
  18. from synapse.api.errors import AuthError, SynapseError
  19. from synapse.events import EventBase
  20. from synapse.handlers.presence import format_user_presence_state
  21. from synapse.logging.utils import log_function
  22. from synapse.types import UserID
  23. from synapse.visibility import filter_events_for_client
  24. from ._base import BaseHandler
  25. logger = logging.getLogger(__name__)
  26. class EventStreamHandler(BaseHandler):
  27. def __init__(self, hs):
  28. super(EventStreamHandler, self).__init__(hs)
  29. # Count of active streams per user
  30. self._streams_per_user = {}
  31. # Grace timers per user to delay the "stopped" signal
  32. self._stop_timer_per_user = {}
  33. self.distributor = hs.get_distributor()
  34. self.distributor.declare("started_user_eventstream")
  35. self.distributor.declare("stopped_user_eventstream")
  36. self.clock = hs.get_clock()
  37. self.notifier = hs.get_notifier()
  38. self.state = hs.get_state_handler()
  39. self._server_notices_sender = hs.get_server_notices_sender()
  40. self._event_serializer = hs.get_event_client_serializer()
  41. @log_function
  42. async def get_stream(
  43. self,
  44. auth_user_id,
  45. pagin_config,
  46. timeout=0,
  47. as_client_event=True,
  48. affect_presence=True,
  49. only_keys=None,
  50. room_id=None,
  51. is_guest=False,
  52. ):
  53. """Fetches the events stream for a given user.
  54. If `only_keys` is not None, events from keys will be sent down.
  55. """
  56. if room_id:
  57. blocked = await self.store.is_room_blocked(room_id)
  58. if blocked:
  59. raise SynapseError(403, "This room has been blocked on this server")
  60. # send any outstanding server notices to the user.
  61. await self._server_notices_sender.on_user_syncing(auth_user_id)
  62. auth_user = UserID.from_string(auth_user_id)
  63. presence_handler = self.hs.get_presence_handler()
  64. context = await presence_handler.user_syncing(
  65. auth_user_id, affect_presence=affect_presence
  66. )
  67. with context:
  68. if timeout:
  69. # If they've set a timeout set a minimum limit.
  70. timeout = max(timeout, 500)
  71. # Add some randomness to this value to try and mitigate against
  72. # thundering herds on restart.
  73. timeout = random.randint(int(timeout * 0.9), int(timeout * 1.1))
  74. events, tokens = await self.notifier.get_events_for(
  75. auth_user,
  76. pagin_config,
  77. timeout,
  78. only_keys=only_keys,
  79. is_guest=is_guest,
  80. explicit_room_id=room_id,
  81. )
  82. time_now = self.clock.time_msec()
  83. # When the user joins a new room, or another user joins a currently
  84. # joined room, we need to send down presence for those users.
  85. to_add = []
  86. for event in events:
  87. if not isinstance(event, EventBase):
  88. continue
  89. if event.type == EventTypes.Member:
  90. if event.membership != Membership.JOIN:
  91. continue
  92. # Send down presence.
  93. if event.state_key == auth_user_id:
  94. # Send down presence for everyone in the room.
  95. users = await self.state.get_current_users_in_room(
  96. event.room_id
  97. )
  98. else:
  99. users = [event.state_key]
  100. states = await presence_handler.get_states(users)
  101. to_add.extend(
  102. {
  103. "type": EventTypes.Presence,
  104. "content": format_user_presence_state(state, time_now),
  105. }
  106. for state in states
  107. )
  108. events.extend(to_add)
  109. chunks = await self._event_serializer.serialize_events(
  110. events,
  111. time_now,
  112. as_client_event=as_client_event,
  113. # We don't bundle "live" events, as otherwise clients
  114. # will end up double counting annotations.
  115. bundle_aggregations=False,
  116. )
  117. chunk = {
  118. "chunk": chunks,
  119. "start": tokens[0].to_string(),
  120. "end": tokens[1].to_string(),
  121. }
  122. return chunk
  123. class EventHandler(BaseHandler):
  124. def __init__(self, hs):
  125. super(EventHandler, self).__init__(hs)
  126. self.storage = hs.get_storage()
  127. async def get_event(self, user, room_id, event_id):
  128. """Retrieve a single specified event.
  129. Args:
  130. user (synapse.types.UserID): The user requesting the event
  131. room_id (str|None): The expected room id. We'll return None if the
  132. event's room does not match.
  133. event_id (str): The event ID to obtain.
  134. Returns:
  135. dict: An event, or None if there is no event matching this ID.
  136. Raises:
  137. SynapseError if there was a problem retrieving this event, or
  138. AuthError if the user does not have the rights to inspect this
  139. event.
  140. """
  141. event = await self.store.get_event(event_id, check_room_id=room_id)
  142. if not event:
  143. return None
  144. users = await self.store.get_users_in_room(event.room_id)
  145. is_peeking = user.to_string() not in users
  146. filtered = await filter_events_for_client(
  147. self.storage, user.to_string(), [event], is_peeking=is_peeking
  148. )
  149. if not filtered:
  150. raise AuthError(403, "You don't have permission to access that event.")
  151. return event