relations.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import enum
  15. import logging
  16. from typing import TYPE_CHECKING, Collection, Dict, FrozenSet, Iterable, List, Optional
  17. import attr
  18. from synapse.api.constants import EventTypes, RelationTypes
  19. from synapse.api.errors import SynapseError
  20. from synapse.events import EventBase, relation_from_event
  21. from synapse.logging.context import make_deferred_yieldable, run_in_background
  22. from synapse.logging.opentracing import trace
  23. from synapse.storage.databases.main.relations import ThreadsNextBatch, _RelatedEvent
  24. from synapse.streams.config import PaginationConfig
  25. from synapse.types import JsonDict, Requester, UserID
  26. from synapse.util.async_helpers import gather_results
  27. from synapse.visibility import filter_events_for_client
  28. if TYPE_CHECKING:
  29. from synapse.server import HomeServer
  30. logger = logging.getLogger(__name__)
  31. class ThreadsListInclude(str, enum.Enum):
  32. """Valid values for the 'include' flag of /threads."""
  33. all = "all"
  34. participated = "participated"
  35. @attr.s(slots=True, frozen=True, auto_attribs=True)
  36. class _ThreadAggregation:
  37. # The latest event in the thread.
  38. latest_event: EventBase
  39. # The total number of events in the thread.
  40. count: int
  41. # True if the current user has sent an event to the thread.
  42. current_user_participated: bool
  43. @attr.s(slots=True, auto_attribs=True)
  44. class BundledAggregations:
  45. """
  46. The bundled aggregations for an event.
  47. Some values require additional processing during serialization.
  48. """
  49. annotations: Optional[JsonDict] = None
  50. references: Optional[JsonDict] = None
  51. replace: Optional[EventBase] = None
  52. thread: Optional[_ThreadAggregation] = None
  53. def __bool__(self) -> bool:
  54. return bool(self.annotations or self.references or self.replace or self.thread)
  55. class RelationsHandler:
  56. def __init__(self, hs: "HomeServer"):
  57. self._main_store = hs.get_datastores().main
  58. self._storage_controllers = hs.get_storage_controllers()
  59. self._auth = hs.get_auth()
  60. self._clock = hs.get_clock()
  61. self._event_handler = hs.get_event_handler()
  62. self._event_serializer = hs.get_event_client_serializer()
  63. self._event_creation_handler = hs.get_event_creation_handler()
  64. async def get_relations(
  65. self,
  66. requester: Requester,
  67. event_id: str,
  68. room_id: str,
  69. pagin_config: PaginationConfig,
  70. include_original_event: bool,
  71. relation_type: Optional[str] = None,
  72. event_type: Optional[str] = None,
  73. ) -> JsonDict:
  74. """Get related events of a event, ordered by topological ordering.
  75. TODO Accept a PaginationConfig instead of individual pagination parameters.
  76. Args:
  77. requester: The user requesting the relations.
  78. event_id: Fetch events that relate to this event ID.
  79. room_id: The room the event belongs to.
  80. pagin_config: The pagination config rules to apply, if any.
  81. include_original_event: Whether to include the parent event.
  82. relation_type: Only fetch events with this relation type, if given.
  83. event_type: Only fetch events with this event type, if given.
  84. Returns:
  85. The pagination chunk.
  86. """
  87. user_id = requester.user.to_string()
  88. # TODO Properly handle a user leaving a room.
  89. (_, member_event_id) = await self._auth.check_user_in_room_or_world_readable(
  90. room_id, requester, allow_departed_users=True
  91. )
  92. # This gets the original event and checks that a) the event exists and
  93. # b) the user is allowed to view it.
  94. event = await self._event_handler.get_event(requester.user, room_id, event_id)
  95. if event is None:
  96. raise SynapseError(404, "Unknown parent event.")
  97. # Note that ignored users are not passed into get_relations_for_event
  98. # below. Ignored users are handled in filter_events_for_client (and by
  99. # not passing them in here we should get a better cache hit rate).
  100. related_events, next_token = await self._main_store.get_relations_for_event(
  101. event_id=event_id,
  102. event=event,
  103. room_id=room_id,
  104. relation_type=relation_type,
  105. event_type=event_type,
  106. limit=pagin_config.limit,
  107. direction=pagin_config.direction,
  108. from_token=pagin_config.from_token,
  109. to_token=pagin_config.to_token,
  110. )
  111. events = await self._main_store.get_events_as_list(
  112. [e.event_id for e in related_events]
  113. )
  114. events = await filter_events_for_client(
  115. self._storage_controllers,
  116. user_id,
  117. events,
  118. is_peeking=(member_event_id is None),
  119. )
  120. # The relations returned for the requested event do include their
  121. # bundled aggregations.
  122. aggregations = await self.get_bundled_aggregations(
  123. events, requester.user.to_string()
  124. )
  125. now = self._clock.time_msec()
  126. return_value: JsonDict = {
  127. "chunk": self._event_serializer.serialize_events(
  128. events, now, bundle_aggregations=aggregations
  129. ),
  130. }
  131. if include_original_event:
  132. # Do not bundle aggregations when retrieving the original event because
  133. # we want the content before relations are applied to it.
  134. return_value["original_event"] = self._event_serializer.serialize_event(
  135. event, now, bundle_aggregations=None
  136. )
  137. if next_token:
  138. return_value["next_batch"] = await next_token.to_string(self._main_store)
  139. if pagin_config.from_token:
  140. return_value["prev_batch"] = await pagin_config.from_token.to_string(
  141. self._main_store
  142. )
  143. return return_value
  144. async def redact_events_related_to(
  145. self,
  146. requester: Requester,
  147. event_id: str,
  148. initial_redaction_event: EventBase,
  149. relation_types: List[str],
  150. ) -> None:
  151. """Redacts all events related to the given event ID with one of the given
  152. relation types.
  153. This method is expected to be called when redacting the event referred to by
  154. the given event ID.
  155. If an event cannot be redacted (e.g. because of insufficient permissions), log
  156. the error and try to redact the next one.
  157. Args:
  158. requester: The requester to redact events on behalf of.
  159. event_id: The event IDs to look and redact relations of.
  160. initial_redaction_event: The redaction for the event referred to by
  161. event_id.
  162. relation_types: The types of relations to look for.
  163. Raises:
  164. ShadowBanError if the requester is shadow-banned
  165. """
  166. related_event_ids = (
  167. await self._main_store.get_all_relations_for_event_with_types(
  168. event_id, relation_types
  169. )
  170. )
  171. for related_event_id in related_event_ids:
  172. try:
  173. await self._event_creation_handler.create_and_send_nonmember_event(
  174. requester,
  175. {
  176. "type": EventTypes.Redaction,
  177. "content": initial_redaction_event.content,
  178. "room_id": initial_redaction_event.room_id,
  179. "sender": requester.user.to_string(),
  180. "redacts": related_event_id,
  181. },
  182. ratelimit=False,
  183. )
  184. except SynapseError as e:
  185. logger.warning(
  186. "Failed to redact event %s (related to event %s): %s",
  187. related_event_id,
  188. event_id,
  189. e.msg,
  190. )
  191. async def get_annotations_for_events(
  192. self, event_ids: Collection[str], ignored_users: FrozenSet[str] = frozenset()
  193. ) -> Dict[str, List[JsonDict]]:
  194. """Get a list of annotations to the given events, grouped by event type and
  195. aggregation key, sorted by count.
  196. This is used e.g. to get the what and how many reactions have happened
  197. on an event.
  198. Args:
  199. event_ids: Fetch events that relate to these event IDs.
  200. ignored_users: The users ignored by the requesting user.
  201. Returns:
  202. A map of event IDs to a list of groups of annotations that match.
  203. Each entry is a dict with `type`, `key` and `count` fields.
  204. """
  205. # Get the base results for all users.
  206. full_results = await self._main_store.get_aggregation_groups_for_events(
  207. event_ids
  208. )
  209. # Avoid additional logic if there are no ignored users.
  210. if not ignored_users:
  211. return {
  212. event_id: results
  213. for event_id, results in full_results.items()
  214. if results
  215. }
  216. # Then subtract off the results for any ignored users.
  217. ignored_results = await self._main_store.get_aggregation_groups_for_users(
  218. [event_id for event_id, results in full_results.items() if results],
  219. ignored_users,
  220. )
  221. filtered_results = {}
  222. for event_id, results in full_results.items():
  223. # If no annotations, skip.
  224. if not results:
  225. continue
  226. # If there are not ignored results for this event, copy verbatim.
  227. if event_id not in ignored_results:
  228. filtered_results[event_id] = results
  229. continue
  230. # Otherwise, subtract out the ignored results.
  231. event_ignored_results = ignored_results[event_id]
  232. for result in results:
  233. key = (result["type"], result["key"])
  234. if key in event_ignored_results:
  235. # Ensure to not modify the cache.
  236. result = result.copy()
  237. result["count"] -= event_ignored_results[key]
  238. if result["count"] <= 0:
  239. continue
  240. filtered_results.setdefault(event_id, []).append(result)
  241. return filtered_results
  242. async def get_references_for_events(
  243. self, event_ids: Collection[str], ignored_users: FrozenSet[str] = frozenset()
  244. ) -> Dict[str, List[_RelatedEvent]]:
  245. """Get a list of references to the given events.
  246. Args:
  247. event_ids: Fetch events that relate to this event ID.
  248. ignored_users: The users ignored by the requesting user.
  249. Returns:
  250. A map of event IDs to a list related events.
  251. """
  252. related_events = await self._main_store.get_references_for_events(event_ids)
  253. # Avoid additional logic if there are no ignored users.
  254. if not ignored_users:
  255. return {
  256. event_id: results
  257. for event_id, results in related_events.items()
  258. if results
  259. }
  260. # Filter out ignored users.
  261. results = {}
  262. for event_id, events in related_events.items():
  263. # If no references, skip.
  264. if not events:
  265. continue
  266. # Filter ignored users out.
  267. events = [event for event in events if event.sender not in ignored_users]
  268. # If there are no events left, skip this event.
  269. if not events:
  270. continue
  271. results[event_id] = events
  272. return results
  273. async def _get_threads_for_events(
  274. self,
  275. events_by_id: Dict[str, EventBase],
  276. relations_by_id: Dict[str, str],
  277. user_id: str,
  278. ignored_users: FrozenSet[str],
  279. ) -> Dict[str, _ThreadAggregation]:
  280. """Get the bundled aggregations for threads for the requested events.
  281. Args:
  282. events_by_id: A map of event_id to events to get aggregations for threads.
  283. relations_by_id: A map of event_id to the relation type, if one exists
  284. for that event.
  285. user_id: The user requesting the bundled aggregations.
  286. ignored_users: The users ignored by the requesting user.
  287. Returns:
  288. A dictionary mapping event ID to the thread information.
  289. May not contain a value for all requested event IDs.
  290. """
  291. user = UserID.from_string(user_id)
  292. # It is not valid to start a thread on an event which itself relates to another event.
  293. event_ids = [eid for eid in events_by_id.keys() if eid not in relations_by_id]
  294. # Fetch thread summaries.
  295. summaries = await self._main_store.get_thread_summaries(event_ids)
  296. # Limit fetching whether the requester has participated in a thread to
  297. # events which are thread roots.
  298. thread_event_ids = [
  299. event_id for event_id, summary in summaries.items() if summary
  300. ]
  301. # Pre-seed thread participation with whether the requester sent the event.
  302. participated = {
  303. event_id: events_by_id[event_id].sender == user_id
  304. for event_id in thread_event_ids
  305. }
  306. # For events the requester did not send, check the database for whether
  307. # the requester sent a threaded reply.
  308. participated.update(
  309. await self._main_store.get_threads_participated(
  310. [
  311. event_id
  312. for event_id in thread_event_ids
  313. if not participated[event_id]
  314. ],
  315. user_id,
  316. )
  317. )
  318. # Then subtract off the results for any ignored users.
  319. ignored_results = await self._main_store.get_threaded_messages_per_user(
  320. thread_event_ids, ignored_users
  321. )
  322. # A map of event ID to the thread aggregation.
  323. results = {}
  324. for event_id, summary in summaries.items():
  325. # If no thread, skip.
  326. if not summary:
  327. continue
  328. thread_count, latest_thread_event = summary
  329. # Subtract off the count of any ignored users.
  330. for ignored_user in ignored_users:
  331. thread_count -= ignored_results.get((event_id, ignored_user), 0)
  332. # This is gnarly, but if the latest event is from an ignored user,
  333. # attempt to find one that isn't from an ignored user.
  334. if latest_thread_event.sender in ignored_users:
  335. room_id = latest_thread_event.room_id
  336. # If the root event is not found, something went wrong, do
  337. # not include a summary of the thread.
  338. event = await self._event_handler.get_event(user, room_id, event_id)
  339. if event is None:
  340. continue
  341. # Attempt to find another event to use as the latest event.
  342. potential_events, _ = await self._main_store.get_relations_for_event(
  343. event_id, event, room_id, RelationTypes.THREAD, direction="f"
  344. )
  345. # Filter out ignored users.
  346. potential_events = [
  347. event
  348. for event in potential_events
  349. if event.sender not in ignored_users
  350. ]
  351. # If all found events are from ignored users, do not include
  352. # a summary of the thread.
  353. if not potential_events:
  354. continue
  355. # The *last* event returned is the one that is cared about.
  356. event = await self._event_handler.get_event(
  357. user, room_id, potential_events[-1].event_id
  358. )
  359. # It is unexpected that the event will not exist.
  360. if event is None:
  361. logger.warning(
  362. "Unable to fetch latest event in a thread with event ID: %s",
  363. potential_events[-1].event_id,
  364. )
  365. continue
  366. latest_thread_event = event
  367. results[event_id] = _ThreadAggregation(
  368. latest_event=latest_thread_event,
  369. count=thread_count,
  370. # If there's a thread summary it must also exist in the
  371. # participated dictionary.
  372. current_user_participated=events_by_id[event_id].sender == user_id
  373. or participated[event_id],
  374. )
  375. return results
  376. @trace
  377. async def get_bundled_aggregations(
  378. self, events: Iterable[EventBase], user_id: str
  379. ) -> Dict[str, BundledAggregations]:
  380. """Generate bundled aggregations for events.
  381. Args:
  382. events: The iterable of events to calculate bundled aggregations for.
  383. user_id: The user requesting the bundled aggregations.
  384. Returns:
  385. A map of event ID to the bundled aggregations for the event.
  386. Not all requested events may exist in the results (if they don't have
  387. bundled aggregations).
  388. The results may include additional events which are related to the
  389. requested events.
  390. """
  391. # De-duplicated events by ID to handle the same event requested multiple times.
  392. events_by_id = {}
  393. # A map of event ID to the relation in that event, if there is one.
  394. relations_by_id: Dict[str, str] = {}
  395. for event in events:
  396. # State events do not get bundled aggregations.
  397. if event.is_state():
  398. continue
  399. relates_to = relation_from_event(event)
  400. if relates_to:
  401. # An event which is a replacement (ie edit) or annotation (ie,
  402. # reaction) may not have any other event related to it.
  403. if relates_to.rel_type in (
  404. RelationTypes.ANNOTATION,
  405. RelationTypes.REPLACE,
  406. ):
  407. continue
  408. # Track the event's relation information for later.
  409. relations_by_id[event.event_id] = relates_to.rel_type
  410. # The event should get bundled aggregations.
  411. events_by_id[event.event_id] = event
  412. # event ID -> bundled aggregation in non-serialized form.
  413. results: Dict[str, BundledAggregations] = {}
  414. # Fetch any ignored users of the requesting user.
  415. ignored_users = await self._main_store.ignored_users(user_id)
  416. # Threads are special as the latest event of a thread might cause additional
  417. # events to be fetched. Thus, we check those first!
  418. # Fetch thread summaries (but only for the directly requested events).
  419. threads = await self._get_threads_for_events(
  420. events_by_id,
  421. relations_by_id,
  422. user_id,
  423. ignored_users,
  424. )
  425. for event_id, thread in threads.items():
  426. results.setdefault(event_id, BundledAggregations()).thread = thread
  427. # If the latest event in a thread is not already being fetched,
  428. # add it. This ensures that the bundled aggregations for the
  429. # latest thread event is correct.
  430. latest_thread_event = thread.latest_event
  431. if latest_thread_event and latest_thread_event.event_id not in events_by_id:
  432. events_by_id[latest_thread_event.event_id] = latest_thread_event
  433. # Keep relations_by_id in sync with events_by_id:
  434. #
  435. # We know that the latest event in a thread has a thread relation
  436. # (as that is what makes it part of the thread).
  437. relations_by_id[latest_thread_event.event_id] = RelationTypes.THREAD
  438. async def _fetch_annotations() -> None:
  439. """Fetch any annotations (ie, reactions) to bundle with this event."""
  440. annotations_by_event_id = await self.get_annotations_for_events(
  441. events_by_id.keys(), ignored_users=ignored_users
  442. )
  443. for event_id, annotations in annotations_by_event_id.items():
  444. if annotations:
  445. results.setdefault(event_id, BundledAggregations()).annotations = {
  446. "chunk": annotations
  447. }
  448. async def _fetch_references() -> None:
  449. """Fetch any references to bundle with this event."""
  450. references_by_event_id = await self.get_references_for_events(
  451. events_by_id.keys(), ignored_users=ignored_users
  452. )
  453. for event_id, references in references_by_event_id.items():
  454. if references:
  455. results.setdefault(event_id, BundledAggregations()).references = {
  456. "chunk": [{"event_id": ev.event_id} for ev in references]
  457. }
  458. async def _fetch_edits() -> None:
  459. """
  460. Fetch any edits (but not for redacted events).
  461. Note that there is no use in limiting edits by ignored users since the
  462. parent event should be ignored in the first place if the user is ignored.
  463. """
  464. edits = await self._main_store.get_applicable_edits(
  465. [
  466. event_id
  467. for event_id, event in events_by_id.items()
  468. if not event.internal_metadata.is_redacted()
  469. ]
  470. )
  471. for event_id, edit in edits.items():
  472. results.setdefault(event_id, BundledAggregations()).replace = edit
  473. # Parallelize the calls for annotations, references, and edits since they
  474. # are unrelated.
  475. await make_deferred_yieldable(
  476. gather_results(
  477. (
  478. run_in_background(_fetch_annotations),
  479. run_in_background(_fetch_references),
  480. run_in_background(_fetch_edits),
  481. )
  482. )
  483. )
  484. return results
  485. async def get_threads(
  486. self,
  487. requester: Requester,
  488. room_id: str,
  489. include: ThreadsListInclude,
  490. limit: int = 5,
  491. from_token: Optional[ThreadsNextBatch] = None,
  492. ) -> JsonDict:
  493. """Get related events of a event, ordered by topological ordering.
  494. Args:
  495. requester: The user requesting the relations.
  496. room_id: The room the event belongs to.
  497. include: One of "all" or "participated" to indicate which threads should
  498. be returned.
  499. limit: Only fetch the most recent `limit` events.
  500. from_token: Fetch rows from the given token, or from the start if None.
  501. Returns:
  502. The pagination chunk.
  503. """
  504. user_id = requester.user.to_string()
  505. # TODO Properly handle a user leaving a room.
  506. (_, member_event_id) = await self._auth.check_user_in_room_or_world_readable(
  507. room_id, requester, allow_departed_users=True
  508. )
  509. # Note that ignored users are not passed into get_threads
  510. # below. Ignored users are handled in filter_events_for_client (and by
  511. # not passing them in here we should get a better cache hit rate).
  512. thread_roots, next_batch = await self._main_store.get_threads(
  513. room_id=room_id, limit=limit, from_token=from_token
  514. )
  515. events = await self._main_store.get_events_as_list(thread_roots)
  516. if include == ThreadsListInclude.participated:
  517. # Pre-seed thread participation with whether the requester sent the event.
  518. participated = {event.event_id: event.sender == user_id for event in events}
  519. # For events the requester did not send, check the database for whether
  520. # the requester sent a threaded reply.
  521. participated.update(
  522. await self._main_store.get_threads_participated(
  523. [eid for eid, p in participated.items() if not p],
  524. user_id,
  525. )
  526. )
  527. # Limit the returned threads to those the user has participated in.
  528. events = [event for event in events if participated[event.event_id]]
  529. events = await filter_events_for_client(
  530. self._storage_controllers,
  531. user_id,
  532. events,
  533. is_peeking=(member_event_id is None),
  534. )
  535. aggregations = await self.get_bundled_aggregations(
  536. events, requester.user.to_string()
  537. )
  538. now = self._clock.time_msec()
  539. serialized_events = self._event_serializer.serialize_events(
  540. events, now, bundle_aggregations=aggregations
  541. )
  542. return_value: JsonDict = {"chunk": serialized_events}
  543. if next_batch:
  544. return_value["next_batch"] = str(next_batch)
  545. return return_value