You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

617 lines
23 KiB

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