receipts.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  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.handlers._base import BaseHandler
  18. from synapse.types import ReadReceipt, get_domain_from_id
  19. from synapse.util.async_helpers import maybe_awaitable
  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. async 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. for room_id, room_values in content.items():
  38. for receipt_type, users in room_values.items():
  39. for user_id, user_values in users.items():
  40. if get_domain_from_id(user_id) != origin:
  41. logger.info(
  42. "Received receipt for user %r from server %s, ignoring",
  43. user_id,
  44. origin,
  45. )
  46. continue
  47. receipts.append(
  48. ReadReceipt(
  49. room_id=room_id,
  50. receipt_type=receipt_type,
  51. user_id=user_id,
  52. event_ids=user_values["event_ids"],
  53. data=user_values.get("data", {}),
  54. )
  55. )
  56. await self._handle_new_receipts(receipts)
  57. async def _handle_new_receipts(self, receipts):
  58. """Takes a list of receipts, stores them and informs the notifier.
  59. """
  60. min_batch_id = None
  61. max_batch_id = None
  62. for receipt in receipts:
  63. res = await self.store.insert_receipt(
  64. receipt.room_id,
  65. receipt.receipt_type,
  66. receipt.user_id,
  67. receipt.event_ids,
  68. receipt.data,
  69. )
  70. if not res:
  71. # res will be None if this read receipt is 'old'
  72. continue
  73. stream_id, max_persisted_id = res
  74. if min_batch_id is None or stream_id < min_batch_id:
  75. min_batch_id = stream_id
  76. if max_batch_id is None or max_persisted_id > max_batch_id:
  77. max_batch_id = max_persisted_id
  78. if min_batch_id is None:
  79. # no new receipts
  80. return False
  81. affected_room_ids = list({r.room_id for r in receipts})
  82. self.notifier.on_new_event("receipt_key", max_batch_id, rooms=affected_room_ids)
  83. # Note that the min here shouldn't be relied upon to be accurate.
  84. await maybe_awaitable(
  85. self.hs.get_pusherpool().on_new_receipts(
  86. min_batch_id, max_batch_id, affected_room_ids
  87. )
  88. )
  89. return True
  90. async def received_client_receipt(self, room_id, receipt_type, user_id, event_id):
  91. """Called when a client tells us a local user has read up to the given
  92. event_id in the room.
  93. """
  94. receipt = ReadReceipt(
  95. room_id=room_id,
  96. receipt_type=receipt_type,
  97. user_id=user_id,
  98. event_ids=[event_id],
  99. data={"ts": int(self.clock.time_msec())},
  100. )
  101. is_new = await self._handle_new_receipts([receipt])
  102. if not is_new:
  103. return
  104. await self.federation.send_read_receipt(receipt)
  105. class ReceiptEventSource(object):
  106. def __init__(self, hs):
  107. self.store = hs.get_datastore()
  108. @defer.inlineCallbacks
  109. def get_new_events(self, from_key, room_ids, **kwargs):
  110. from_key = int(from_key)
  111. to_key = yield self.get_current_key()
  112. if from_key == to_key:
  113. return [], to_key
  114. events = yield self.store.get_linearized_receipts_for_rooms(
  115. room_ids, from_key=from_key, to_key=to_key
  116. )
  117. return (events, to_key)
  118. def get_current_key(self, direction="f"):
  119. return self.store.get_max_receipt_stream_id()
  120. @defer.inlineCallbacks
  121. def get_pagination_rows(self, user, config, key):
  122. to_key = int(config.from_key)
  123. if config.to_key:
  124. from_key = int(config.to_key)
  125. else:
  126. from_key = None
  127. room_ids = yield self.store.get_rooms_for_user(user.to_string())
  128. events = yield self.store.get_linearized_receipts_for_rooms(
  129. room_ids, from_key=from_key, to_key=to_key
  130. )
  131. return (events, to_key)