events.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 twisted.internet import defer
  18. from synapse.api.constants import EventTypes, Membership
  19. from synapse.api.errors import AuthError, SynapseError
  20. from synapse.events import EventBase
  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. @defer.inlineCallbacks
  42. @log_function
  43. def get_stream(
  44. self,
  45. auth_user_id,
  46. pagin_config,
  47. timeout=0,
  48. as_client_event=True,
  49. affect_presence=True,
  50. only_keys=None,
  51. room_id=None,
  52. is_guest=False,
  53. ):
  54. """Fetches the events stream for a given user.
  55. If `only_keys` is not None, events from keys will be sent down.
  56. """
  57. if room_id:
  58. blocked = yield self.store.is_room_blocked(room_id)
  59. if blocked:
  60. raise SynapseError(403, "This room has been blocked on this server")
  61. # send any outstanding server notices to the user.
  62. yield self._server_notices_sender.on_user_syncing(auth_user_id)
  63. auth_user = UserID.from_string(auth_user_id)
  64. presence_handler = self.hs.get_presence_handler()
  65. context = yield presence_handler.user_syncing(
  66. auth_user_id, affect_presence=affect_presence
  67. )
  68. with context:
  69. if timeout:
  70. # If they've set a timeout set a minimum limit.
  71. timeout = max(timeout, 500)
  72. # Add some randomness to this value to try and mitigate against
  73. # thundering herds on restart.
  74. timeout = random.randint(int(timeout * 0.9), int(timeout * 1.1))
  75. events, tokens = yield self.notifier.get_events_for(
  76. auth_user,
  77. pagin_config,
  78. timeout,
  79. only_keys=only_keys,
  80. is_guest=is_guest,
  81. explicit_room_id=room_id,
  82. )
  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 = yield self.state.get_current_users_in_room(
  96. event.room_id
  97. )
  98. states = yield presence_handler.get_states(users, as_event=True)
  99. to_add.extend(states)
  100. else:
  101. ev = yield presence_handler.get_state(
  102. UserID.from_string(event.state_key), as_event=True
  103. )
  104. to_add.append(ev)
  105. events.extend(to_add)
  106. time_now = self.clock.time_msec()
  107. chunks = yield self._event_serializer.serialize_events(
  108. events,
  109. time_now,
  110. as_client_event=as_client_event,
  111. # We don't bundle "live" events, as otherwise clients
  112. # will end up double counting annotations.
  113. bundle_aggregations=False,
  114. )
  115. chunk = {
  116. "chunk": chunks,
  117. "start": tokens[0].to_string(),
  118. "end": tokens[1].to_string(),
  119. }
  120. return chunk
  121. class EventHandler(BaseHandler):
  122. @defer.inlineCallbacks
  123. def get_event(self, user, room_id, event_id):
  124. """Retrieve a single specified event.
  125. Args:
  126. user (synapse.types.UserID): The user requesting the event
  127. room_id (str|None): The expected room id. We'll return None if the
  128. event's room does not match.
  129. event_id (str): The event ID to obtain.
  130. Returns:
  131. dict: An event, or None if there is no event matching this ID.
  132. Raises:
  133. SynapseError if there was a problem retrieving this event, or
  134. AuthError if the user does not have the rights to inspect this
  135. event.
  136. """
  137. event = yield self.store.get_event(event_id, check_room_id=room_id)
  138. if not event:
  139. return None
  140. return
  141. users = yield self.store.get_users_in_room(event.room_id)
  142. is_peeking = user.to_string() not in users
  143. filtered = yield filter_events_for_client(
  144. self.store, user.to_string(), [event], is_peeking=is_peeking
  145. )
  146. if not filtered:
  147. raise AuthError(403, "You don't have permission to access that event.")
  148. return event