events.py 5.0 KB

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