receipts.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 typing import TYPE_CHECKING, List, Optional, Tuple
  17. from synapse.appservice import ApplicationService
  18. from synapse.handlers._base import BaseHandler
  19. from synapse.types import JsonDict, ReadReceipt, get_domain_from_id
  20. if TYPE_CHECKING:
  21. from synapse.app.homeserver import HomeServer
  22. logger = logging.getLogger(__name__)
  23. class ReceiptsHandler(BaseHandler):
  24. def __init__(self, hs: "HomeServer"):
  25. super().__init__(hs)
  26. self.server_name = hs.config.server_name
  27. self.store = hs.get_datastore()
  28. self.hs = hs
  29. self.federation = hs.get_federation_sender()
  30. hs.get_federation_registry().register_edu_handler(
  31. "m.receipt", self._received_remote_receipt
  32. )
  33. self.clock = self.hs.get_clock()
  34. self.state = hs.get_state_handler()
  35. async def _received_remote_receipt(self, origin: str, content: JsonDict) -> None:
  36. """Called when we receive an EDU of type m.receipt from a remote HS.
  37. """
  38. receipts = []
  39. for room_id, room_values in content.items():
  40. for receipt_type, users in room_values.items():
  41. for user_id, user_values in users.items():
  42. if get_domain_from_id(user_id) != origin:
  43. logger.info(
  44. "Received receipt for user %r from server %s, ignoring",
  45. user_id,
  46. origin,
  47. )
  48. continue
  49. receipts.append(
  50. ReadReceipt(
  51. room_id=room_id,
  52. receipt_type=receipt_type,
  53. user_id=user_id,
  54. event_ids=user_values["event_ids"],
  55. data=user_values.get("data", {}),
  56. )
  57. )
  58. await self._handle_new_receipts(receipts)
  59. async def _handle_new_receipts(self, receipts: List[ReadReceipt]) -> bool:
  60. """Takes a list of receipts, stores them and informs the notifier.
  61. """
  62. min_batch_id = None # type: Optional[int]
  63. max_batch_id = None # type: Optional[int]
  64. for receipt in receipts:
  65. res = await self.store.insert_receipt(
  66. receipt.room_id,
  67. receipt.receipt_type,
  68. receipt.user_id,
  69. receipt.event_ids,
  70. receipt.data,
  71. )
  72. if not res:
  73. # res will be None if this read receipt is 'old'
  74. continue
  75. stream_id, max_persisted_id = res
  76. if min_batch_id is None or stream_id < min_batch_id:
  77. min_batch_id = stream_id
  78. if max_batch_id is None or max_persisted_id > max_batch_id:
  79. max_batch_id = max_persisted_id
  80. # Either both of these should be None or neither.
  81. if min_batch_id is None or max_batch_id is None:
  82. # no new receipts
  83. return False
  84. affected_room_ids = list({r.room_id for r in receipts})
  85. self.notifier.on_new_event("receipt_key", max_batch_id, rooms=affected_room_ids)
  86. # Note that the min here shouldn't be relied upon to be accurate.
  87. await self.hs.get_pusherpool().on_new_receipts(
  88. min_batch_id, max_batch_id, affected_room_ids
  89. )
  90. return True
  91. async def received_client_receipt(
  92. self, room_id: str, receipt_type: str, user_id: str, event_id: str
  93. ) -> None:
  94. """Called when a client tells us a local user has read up to the given
  95. event_id in the room.
  96. """
  97. receipt = ReadReceipt(
  98. room_id=room_id,
  99. receipt_type=receipt_type,
  100. user_id=user_id,
  101. event_ids=[event_id],
  102. data={"ts": int(self.clock.time_msec())},
  103. )
  104. is_new = await self._handle_new_receipts([receipt])
  105. if not is_new:
  106. return
  107. await self.federation.send_read_receipt(receipt)
  108. class ReceiptEventSource:
  109. def __init__(self, hs: "HomeServer"):
  110. self.store = hs.get_datastore()
  111. async def get_new_events(
  112. self, from_key: int, room_ids: List[str], **kwargs
  113. ) -> Tuple[List[JsonDict], int]:
  114. from_key = int(from_key)
  115. to_key = self.get_current_key()
  116. if from_key == to_key:
  117. return [], to_key
  118. events = await self.store.get_linearized_receipts_for_rooms(
  119. room_ids, from_key=from_key, to_key=to_key
  120. )
  121. return (events, to_key)
  122. async def get_new_events_as(
  123. self, from_key: int, service: ApplicationService
  124. ) -> Tuple[List[JsonDict], int]:
  125. """Returns a set of new receipt events that an appservice
  126. may be interested in.
  127. Args:
  128. from_key: the stream position at which events should be fetched from
  129. service: The appservice which may be interested
  130. """
  131. from_key = int(from_key)
  132. to_key = self.get_current_key()
  133. if from_key == to_key:
  134. return [], to_key
  135. # Fetch all read receipts for all rooms, up to a limit of 100. This is ordered
  136. # by most recent.
  137. rooms_to_events = await self.store.get_linearized_receipts_for_all_rooms(
  138. from_key=from_key, to_key=to_key
  139. )
  140. # Then filter down to rooms that the AS can read
  141. events = []
  142. for room_id, event in rooms_to_events.items():
  143. if not await service.matches_user_in_member_list(room_id, self.store):
  144. continue
  145. events.append(event)
  146. return (events, to_key)
  147. def get_current_key(self, direction: str = "f") -> int:
  148. return self.store.get_max_receipt_stream_id()