receipts.py 6.5 KB

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