receipts.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 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. from twisted.internet import defer
  17. from synapse.types import get_domain_from_id
  18. from synapse.util import logcontext
  19. from synapse.util.logcontext import PreserveLoggingContext
  20. from ._base import BaseHandler
  21. logger = logging.getLogger(__name__)
  22. class ReceiptsHandler(BaseHandler):
  23. def __init__(self, hs):
  24. super(ReceiptsHandler, self).__init__(hs)
  25. self.server_name = hs.config.server_name
  26. self.store = hs.get_datastore()
  27. self.hs = hs
  28. self.federation = hs.get_federation_sender()
  29. hs.get_federation_registry().register_edu_handler(
  30. "m.receipt", self._received_remote_receipt
  31. )
  32. self.clock = self.hs.get_clock()
  33. self.state = hs.get_state_handler()
  34. @defer.inlineCallbacks
  35. def received_client_receipt(self, room_id, receipt_type, user_id,
  36. event_id):
  37. """Called when a client tells us a local user has read up to the given
  38. event_id in the room.
  39. """
  40. receipt = {
  41. "room_id": room_id,
  42. "receipt_type": receipt_type,
  43. "user_id": user_id,
  44. "event_ids": [event_id],
  45. "data": {
  46. "ts": int(self.clock.time_msec()),
  47. }
  48. }
  49. is_new = yield self._handle_new_receipts([receipt])
  50. if is_new:
  51. # fire off a process in the background to send the receipt to
  52. # remote servers
  53. self._push_remotes([receipt])
  54. @defer.inlineCallbacks
  55. def _received_remote_receipt(self, origin, content):
  56. """Called when we receive an EDU of type m.receipt from a remote HS.
  57. """
  58. receipts = [
  59. {
  60. "room_id": room_id,
  61. "receipt_type": receipt_type,
  62. "user_id": user_id,
  63. "event_ids": user_values["event_ids"],
  64. "data": user_values.get("data", {}),
  65. }
  66. for room_id, room_values in content.items()
  67. for receipt_type, users in room_values.items()
  68. for user_id, user_values in users.items()
  69. ]
  70. yield self._handle_new_receipts(receipts)
  71. @defer.inlineCallbacks
  72. def _handle_new_receipts(self, receipts):
  73. """Takes a list of receipts, stores them and informs the notifier.
  74. """
  75. min_batch_id = None
  76. max_batch_id = None
  77. for receipt in receipts:
  78. room_id = receipt["room_id"]
  79. receipt_type = receipt["receipt_type"]
  80. user_id = receipt["user_id"]
  81. event_ids = receipt["event_ids"]
  82. data = receipt["data"]
  83. res = yield self.store.insert_receipt(
  84. room_id, receipt_type, user_id, event_ids, data
  85. )
  86. if not res:
  87. # res will be None if this read receipt is 'old'
  88. continue
  89. stream_id, max_persisted_id = res
  90. if min_batch_id is None or stream_id < min_batch_id:
  91. min_batch_id = stream_id
  92. if max_batch_id is None or max_persisted_id > max_batch_id:
  93. max_batch_id = max_persisted_id
  94. if min_batch_id is None:
  95. # no new receipts
  96. defer.returnValue(False)
  97. affected_room_ids = list(set([r["room_id"] for r in receipts]))
  98. with PreserveLoggingContext():
  99. self.notifier.on_new_event(
  100. "receipt_key", max_batch_id, rooms=affected_room_ids
  101. )
  102. # Note that the min here shouldn't be relied upon to be accurate.
  103. self.hs.get_pusherpool().on_new_receipts(
  104. min_batch_id, max_batch_id, affected_room_ids
  105. )
  106. defer.returnValue(True)
  107. @logcontext.preserve_fn # caller should not yield on this
  108. @defer.inlineCallbacks
  109. def _push_remotes(self, receipts):
  110. """Given a list of receipts, works out which remote servers should be
  111. poked and pokes them.
  112. """
  113. try:
  114. # TODO: Some of this stuff should be coallesced.
  115. for receipt in receipts:
  116. room_id = receipt["room_id"]
  117. receipt_type = receipt["receipt_type"]
  118. user_id = receipt["user_id"]
  119. event_ids = receipt["event_ids"]
  120. data = receipt["data"]
  121. users = yield self.state.get_current_user_in_room(room_id)
  122. remotedomains = set(get_domain_from_id(u) for u in users)
  123. remotedomains = remotedomains.copy()
  124. remotedomains.discard(self.server_name)
  125. logger.debug("Sending receipt to: %r", remotedomains)
  126. for domain in remotedomains:
  127. self.federation.send_edu(
  128. destination=domain,
  129. edu_type="m.receipt",
  130. content={
  131. room_id: {
  132. receipt_type: {
  133. user_id: {
  134. "event_ids": event_ids,
  135. "data": data,
  136. }
  137. }
  138. },
  139. },
  140. key=(room_id, receipt_type, user_id),
  141. )
  142. except Exception:
  143. logger.exception("Error pushing receipts to remote servers")
  144. @defer.inlineCallbacks
  145. def get_receipts_for_room(self, room_id, to_key):
  146. """Gets all receipts for a room, upto the given key.
  147. """
  148. result = yield self.store.get_linearized_receipts_for_room(
  149. room_id,
  150. to_key=to_key,
  151. )
  152. if not result:
  153. defer.returnValue([])
  154. defer.returnValue(result)
  155. class ReceiptEventSource(object):
  156. def __init__(self, hs):
  157. self.store = hs.get_datastore()
  158. @defer.inlineCallbacks
  159. def get_new_events(self, from_key, room_ids, **kwargs):
  160. from_key = int(from_key)
  161. to_key = yield self.get_current_key()
  162. if from_key == to_key:
  163. defer.returnValue(([], to_key))
  164. events = yield self.store.get_linearized_receipts_for_rooms(
  165. room_ids,
  166. from_key=from_key,
  167. to_key=to_key,
  168. )
  169. defer.returnValue((events, to_key))
  170. def get_current_key(self, direction='f'):
  171. return self.store.get_max_receipt_stream_id()
  172. @defer.inlineCallbacks
  173. def get_pagination_rows(self, user, config, key):
  174. to_key = int(config.from_key)
  175. if config.to_key:
  176. from_key = int(config.to_key)
  177. else:
  178. from_key = None
  179. room_ids = yield self.store.get_rooms_for_user(user.to_string())
  180. events = yield self.store.get_linearized_receipts_for_rooms(
  181. room_ids,
  182. from_key=from_key,
  183. to_key=to_key,
  184. )
  185. defer.returnValue((events, to_key))