選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 
 

182 行
6.2 KiB

  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. room_id=None,
  50. is_guest=False,
  51. ):
  52. """Fetches the events stream for a given user.
  53. """
  54. if room_id:
  55. blocked = await self.store.is_room_blocked(room_id)
  56. if blocked:
  57. raise SynapseError(403, "This room has been blocked on this server")
  58. # send any outstanding server notices to the user.
  59. await self._server_notices_sender.on_user_syncing(auth_user_id)
  60. auth_user = UserID.from_string(auth_user_id)
  61. presence_handler = self.hs.get_presence_handler()
  62. context = await presence_handler.user_syncing(
  63. auth_user_id, affect_presence=affect_presence
  64. )
  65. with context:
  66. if timeout:
  67. # If they've set a timeout set a minimum limit.
  68. timeout = max(timeout, 500)
  69. # Add some randomness to this value to try and mitigate against
  70. # thundering herds on restart.
  71. timeout = random.randint(int(timeout * 0.9), int(timeout * 1.1))
  72. events, tokens = await self.notifier.get_events_for(
  73. auth_user,
  74. pagin_config,
  75. timeout,
  76. is_guest=is_guest,
  77. explicit_room_id=room_id,
  78. )
  79. time_now = self.clock.time_msec()
  80. # When the user joins a new room, or another user joins a currently
  81. # joined room, we need to send down presence for those users.
  82. to_add = []
  83. for event in events:
  84. if not isinstance(event, EventBase):
  85. continue
  86. if event.type == EventTypes.Member:
  87. if event.membership != Membership.JOIN:
  88. continue
  89. # Send down presence.
  90. if event.state_key == auth_user_id:
  91. # Send down presence for everyone in the room.
  92. users = await self.state.get_current_users_in_room(
  93. event.room_id
  94. )
  95. else:
  96. users = [event.state_key]
  97. states = await presence_handler.get_states(users)
  98. to_add.extend(
  99. {
  100. "type": EventTypes.Presence,
  101. "content": format_user_presence_state(state, time_now),
  102. }
  103. for state in states
  104. )
  105. events.extend(to_add)
  106. chunks = await self._event_serializer.serialize_events(
  107. events,
  108. time_now,
  109. as_client_event=as_client_event,
  110. # We don't bundle "live" events, as otherwise clients
  111. # will end up double counting annotations.
  112. bundle_aggregations=False,
  113. )
  114. chunk = {
  115. "chunk": chunks,
  116. "start": tokens[0].to_string(),
  117. "end": tokens[1].to_string(),
  118. }
  119. return chunk
  120. class EventHandler(BaseHandler):
  121. def __init__(self, hs):
  122. super(EventHandler, self).__init__(hs)
  123. self.storage = hs.get_storage()
  124. async def get_event(self, user, room_id, event_id):
  125. """Retrieve a single specified event.
  126. Args:
  127. user (synapse.types.UserID): The user requesting the event
  128. room_id (str|None): The expected room id. We'll return None if the
  129. event's room does not match.
  130. event_id (str): The event ID to obtain.
  131. Returns:
  132. dict: An event, or None if there is no event matching this ID.
  133. Raises:
  134. SynapseError if there was a problem retrieving this event, or
  135. AuthError if the user does not have the rights to inspect this
  136. event.
  137. """
  138. event = await self.store.get_event(event_id, check_room_id=room_id)
  139. if not event:
  140. return None
  141. users = await self.store.get_users_in_room(event.room_id)
  142. is_peeking = user.to_string() not in users
  143. filtered = await filter_events_for_client(
  144. self.storage, 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