events.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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.events import EventBase
  20. from synapse.events.utils import serialize_event
  21. from synapse.types import UserID
  22. from synapse.util.logutils import log_function
  23. from ._base import BaseHandler
  24. logger = logging.getLogger(__name__)
  25. class EventStreamHandler(BaseHandler):
  26. def __init__(self, hs):
  27. super(EventStreamHandler, self).__init__(hs)
  28. # Count of active streams per user
  29. self._streams_per_user = {}
  30. # Grace timers per user to delay the "stopped" signal
  31. self._stop_timer_per_user = {}
  32. self.distributor = hs.get_distributor()
  33. self.distributor.declare("started_user_eventstream")
  34. self.distributor.declare("stopped_user_eventstream")
  35. self.clock = hs.get_clock()
  36. self.notifier = hs.get_notifier()
  37. self.state = hs.get_state_handler()
  38. self._server_notices_sender = hs.get_server_notices_sender()
  39. @defer.inlineCallbacks
  40. @log_function
  41. def get_stream(self, auth_user_id, pagin_config, timeout=0,
  42. as_client_event=True, affect_presence=True,
  43. only_keys=None, room_id=None, is_guest=False):
  44. """Fetches the events stream for a given user.
  45. If `only_keys` is not None, events from keys will be sent down.
  46. """
  47. # send any outstanding server notices to the user.
  48. yield self._server_notices_sender.on_user_syncing(auth_user_id)
  49. auth_user = UserID.from_string(auth_user_id)
  50. presence_handler = self.hs.get_presence_handler()
  51. context = yield presence_handler.user_syncing(
  52. auth_user_id, affect_presence=affect_presence,
  53. )
  54. with context:
  55. if timeout:
  56. # If they've set a timeout set a minimum limit.
  57. timeout = max(timeout, 500)
  58. # Add some randomness to this value to try and mitigate against
  59. # thundering herds on restart.
  60. timeout = random.randint(int(timeout * 0.9), int(timeout * 1.1))
  61. events, tokens = yield self.notifier.get_events_for(
  62. auth_user, pagin_config, timeout,
  63. only_keys=only_keys,
  64. is_guest=is_guest, explicit_room_id=room_id
  65. )
  66. # When the user joins a new room, or another user joins a currently
  67. # joined room, we need to send down presence for those users.
  68. to_add = []
  69. for event in events:
  70. if not isinstance(event, EventBase):
  71. continue
  72. if event.type == EventTypes.Member:
  73. if event.membership != Membership.JOIN:
  74. continue
  75. # Send down presence.
  76. if event.state_key == auth_user_id:
  77. # Send down presence for everyone in the room.
  78. users = yield self.state.get_current_user_in_room(event.room_id)
  79. states = yield presence_handler.get_states(
  80. users,
  81. as_event=True,
  82. )
  83. to_add.extend(states)
  84. else:
  85. ev = yield presence_handler.get_state(
  86. UserID.from_string(event.state_key),
  87. as_event=True,
  88. )
  89. to_add.append(ev)
  90. events.extend(to_add)
  91. time_now = self.clock.time_msec()
  92. chunks = [
  93. serialize_event(e, time_now, as_client_event) for e in events
  94. ]
  95. chunk = {
  96. "chunk": chunks,
  97. "start": tokens[0].to_string(),
  98. "end": tokens[1].to_string(),
  99. }
  100. defer.returnValue(chunk)
  101. class EventHandler(BaseHandler):
  102. @defer.inlineCallbacks
  103. def get_event(self, user, event_id):
  104. """Retrieve a single specified event.
  105. Args:
  106. user (synapse.types.UserID): The user requesting the event
  107. event_id (str): The event ID to obtain.
  108. Returns:
  109. dict: An event, or None if there is no event matching this ID.
  110. Raises:
  111. SynapseError if there was a problem retrieving this event, or
  112. AuthError if the user does not have the rights to inspect this
  113. event.
  114. """
  115. event = yield self.store.get_event(event_id)
  116. if not event:
  117. defer.returnValue(None)
  118. return
  119. if hasattr(event, "room_id"):
  120. yield self.auth.check_joined_room(event.room_id, user.to_string())
  121. defer.returnValue(event)