receipts.py 6.7 KB

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