receipts.py 7.3 KB

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