relations.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2019 New Vector 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. import attr
  17. from synapse.api.constants import RelationTypes
  18. from synapse.storage._base import SQLBaseStore
  19. from synapse.storage.data_stores.main.stream import generate_pagination_where_clause
  20. from synapse.storage.relations import (
  21. AggregationPaginationToken,
  22. PaginationChunk,
  23. RelationPaginationToken,
  24. )
  25. from synapse.util.caches.descriptors import cached, cachedInlineCallbacks
  26. logger = logging.getLogger(__name__)
  27. class RelationsWorkerStore(SQLBaseStore):
  28. @cached(tree=True)
  29. def get_relations_for_event(
  30. self,
  31. event_id,
  32. relation_type=None,
  33. event_type=None,
  34. aggregation_key=None,
  35. limit=5,
  36. direction="b",
  37. from_token=None,
  38. to_token=None,
  39. ):
  40. """Get a list of relations for an event, ordered by topological ordering.
  41. Args:
  42. event_id (str): Fetch events that relate to this event ID.
  43. relation_type (str|None): Only fetch events with this relation
  44. type, if given.
  45. event_type (str|None): Only fetch events with this event type, if
  46. given.
  47. aggregation_key (str|None): Only fetch events with this aggregation
  48. key, if given.
  49. limit (int): Only fetch the most recent `limit` events.
  50. direction (str): Whether to fetch the most recent first (`"b"`) or
  51. the oldest first (`"f"`).
  52. from_token (RelationPaginationToken|None): Fetch rows from the given
  53. token, or from the start if None.
  54. to_token (RelationPaginationToken|None): Fetch rows up to the given
  55. token, or up to the end if None.
  56. Returns:
  57. Deferred[PaginationChunk]: List of event IDs that match relations
  58. requested. The rows are of the form `{"event_id": "..."}`.
  59. """
  60. where_clause = ["relates_to_id = ?"]
  61. where_args = [event_id]
  62. if relation_type is not None:
  63. where_clause.append("relation_type = ?")
  64. where_args.append(relation_type)
  65. if event_type is not None:
  66. where_clause.append("type = ?")
  67. where_args.append(event_type)
  68. if aggregation_key:
  69. where_clause.append("aggregation_key = ?")
  70. where_args.append(aggregation_key)
  71. pagination_clause = generate_pagination_where_clause(
  72. direction=direction,
  73. column_names=("topological_ordering", "stream_ordering"),
  74. from_token=attr.astuple(from_token) if from_token else None,
  75. to_token=attr.astuple(to_token) if to_token else None,
  76. engine=self.database_engine,
  77. )
  78. if pagination_clause:
  79. where_clause.append(pagination_clause)
  80. if direction == "b":
  81. order = "DESC"
  82. else:
  83. order = "ASC"
  84. sql = """
  85. SELECT event_id, topological_ordering, stream_ordering
  86. FROM event_relations
  87. INNER JOIN events USING (event_id)
  88. WHERE %s
  89. ORDER BY topological_ordering %s, stream_ordering %s
  90. LIMIT ?
  91. """ % (
  92. " AND ".join(where_clause),
  93. order,
  94. order,
  95. )
  96. def _get_recent_references_for_event_txn(txn):
  97. txn.execute(sql, where_args + [limit + 1])
  98. last_topo_id = None
  99. last_stream_id = None
  100. events = []
  101. for row in txn:
  102. events.append({"event_id": row[0]})
  103. last_topo_id = row[1]
  104. last_stream_id = row[2]
  105. next_batch = None
  106. if len(events) > limit and last_topo_id and last_stream_id:
  107. next_batch = RelationPaginationToken(last_topo_id, last_stream_id)
  108. return PaginationChunk(
  109. chunk=list(events[:limit]), next_batch=next_batch, prev_batch=from_token
  110. )
  111. return self.db.runInteraction(
  112. "get_recent_references_for_event", _get_recent_references_for_event_txn
  113. )
  114. @cached(tree=True)
  115. def get_aggregation_groups_for_event(
  116. self,
  117. event_id,
  118. event_type=None,
  119. limit=5,
  120. direction="b",
  121. from_token=None,
  122. to_token=None,
  123. ):
  124. """Get a list of annotations on the event, grouped by event type and
  125. aggregation key, sorted by count.
  126. This is used e.g. to get the what and how many reactions have happend
  127. on an event.
  128. Args:
  129. event_id (str): Fetch events that relate to this event ID.
  130. event_type (str|None): Only fetch events with this event type, if
  131. given.
  132. limit (int): Only fetch the `limit` groups.
  133. direction (str): Whether to fetch the highest count first (`"b"`) or
  134. the lowest count first (`"f"`).
  135. from_token (AggregationPaginationToken|None): Fetch rows from the
  136. given token, or from the start if None.
  137. to_token (AggregationPaginationToken|None): Fetch rows up to the
  138. given token, or up to the end if None.
  139. Returns:
  140. Deferred[PaginationChunk]: List of groups of annotations that
  141. match. Each row is a dict with `type`, `key` and `count` fields.
  142. """
  143. where_clause = ["relates_to_id = ?", "relation_type = ?"]
  144. where_args = [event_id, RelationTypes.ANNOTATION]
  145. if event_type:
  146. where_clause.append("type = ?")
  147. where_args.append(event_type)
  148. having_clause = generate_pagination_where_clause(
  149. direction=direction,
  150. column_names=("COUNT(*)", "MAX(stream_ordering)"),
  151. from_token=attr.astuple(from_token) if from_token else None,
  152. to_token=attr.astuple(to_token) if to_token else None,
  153. engine=self.database_engine,
  154. )
  155. if direction == "b":
  156. order = "DESC"
  157. else:
  158. order = "ASC"
  159. if having_clause:
  160. having_clause = "HAVING " + having_clause
  161. else:
  162. having_clause = ""
  163. sql = """
  164. SELECT type, aggregation_key, COUNT(DISTINCT sender), MAX(stream_ordering)
  165. FROM event_relations
  166. INNER JOIN events USING (event_id)
  167. WHERE {where_clause}
  168. GROUP BY relation_type, type, aggregation_key
  169. {having_clause}
  170. ORDER BY COUNT(*) {order}, MAX(stream_ordering) {order}
  171. LIMIT ?
  172. """.format(
  173. where_clause=" AND ".join(where_clause),
  174. order=order,
  175. having_clause=having_clause,
  176. )
  177. def _get_aggregation_groups_for_event_txn(txn):
  178. txn.execute(sql, where_args + [limit + 1])
  179. next_batch = None
  180. events = []
  181. for row in txn:
  182. events.append({"type": row[0], "key": row[1], "count": row[2]})
  183. next_batch = AggregationPaginationToken(row[2], row[3])
  184. if len(events) <= limit:
  185. next_batch = None
  186. return PaginationChunk(
  187. chunk=list(events[:limit]), next_batch=next_batch, prev_batch=from_token
  188. )
  189. return self.db.runInteraction(
  190. "get_aggregation_groups_for_event", _get_aggregation_groups_for_event_txn
  191. )
  192. @cachedInlineCallbacks()
  193. def get_applicable_edit(self, event_id):
  194. """Get the most recent edit (if any) that has happened for the given
  195. event.
  196. Correctly handles checking whether edits were allowed to happen.
  197. Args:
  198. event_id (str): The original event ID
  199. Returns:
  200. Deferred[EventBase|None]: Returns the most recent edit, if any.
  201. """
  202. # We only allow edits for `m.room.message` events that have the same sender
  203. # and event type. We can't assert these things during regular event auth so
  204. # we have to do the checks post hoc.
  205. # Fetches latest edit that has the same type and sender as the
  206. # original, and is an `m.room.message`.
  207. sql = """
  208. SELECT edit.event_id FROM events AS edit
  209. INNER JOIN event_relations USING (event_id)
  210. INNER JOIN events AS original ON
  211. original.event_id = relates_to_id
  212. AND edit.type = original.type
  213. AND edit.sender = original.sender
  214. WHERE
  215. relates_to_id = ?
  216. AND relation_type = ?
  217. AND edit.type = 'm.room.message'
  218. ORDER by edit.origin_server_ts DESC, edit.event_id DESC
  219. LIMIT 1
  220. """
  221. def _get_applicable_edit_txn(txn):
  222. txn.execute(sql, (event_id, RelationTypes.REPLACE))
  223. row = txn.fetchone()
  224. if row:
  225. return row[0]
  226. edit_id = yield self.db.runInteraction(
  227. "get_applicable_edit", _get_applicable_edit_txn
  228. )
  229. if not edit_id:
  230. return
  231. edit_event = yield self.get_event(edit_id, allow_none=True)
  232. return edit_event
  233. def has_user_annotated_event(self, parent_id, event_type, aggregation_key, sender):
  234. """Check if a user has already annotated an event with the same key
  235. (e.g. already liked an event).
  236. Args:
  237. parent_id (str): The event being annotated
  238. event_type (str): The event type of the annotation
  239. aggregation_key (str): The aggregation key of the annotation
  240. sender (str): The sender of the annotation
  241. Returns:
  242. Deferred[bool]
  243. """
  244. sql = """
  245. SELECT 1 FROM event_relations
  246. INNER JOIN events USING (event_id)
  247. WHERE
  248. relates_to_id = ?
  249. AND relation_type = ?
  250. AND type = ?
  251. AND sender = ?
  252. AND aggregation_key = ?
  253. LIMIT 1;
  254. """
  255. def _get_if_user_has_annotated_event(txn):
  256. txn.execute(
  257. sql,
  258. (
  259. parent_id,
  260. RelationTypes.ANNOTATION,
  261. event_type,
  262. sender,
  263. aggregation_key,
  264. ),
  265. )
  266. return bool(txn.fetchone())
  267. return self.db.runInteraction(
  268. "get_if_user_has_annotated_event", _get_if_user_has_annotated_event
  269. )
  270. class RelationsStore(RelationsWorkerStore):
  271. def _handle_event_relations(self, txn, event):
  272. """Handles inserting relation data during peristence of events
  273. Args:
  274. txn
  275. event (EventBase)
  276. """
  277. relation = event.content.get("m.relates_to")
  278. if not relation:
  279. # No relations
  280. return
  281. rel_type = relation.get("rel_type")
  282. if rel_type not in (
  283. RelationTypes.ANNOTATION,
  284. RelationTypes.REFERENCE,
  285. RelationTypes.REPLACE,
  286. ):
  287. # Unknown relation type
  288. return
  289. parent_id = relation.get("event_id")
  290. if not parent_id:
  291. # Invalid relation
  292. return
  293. aggregation_key = relation.get("key")
  294. self.db.simple_insert_txn(
  295. txn,
  296. table="event_relations",
  297. values={
  298. "event_id": event.event_id,
  299. "relates_to_id": parent_id,
  300. "relation_type": rel_type,
  301. "aggregation_key": aggregation_key,
  302. },
  303. )
  304. txn.call_after(self.get_relations_for_event.invalidate_many, (parent_id,))
  305. txn.call_after(
  306. self.get_aggregation_groups_for_event.invalidate_many, (parent_id,)
  307. )
  308. if rel_type == RelationTypes.REPLACE:
  309. txn.call_after(self.get_applicable_edit.invalidate, (parent_id,))
  310. def _handle_redaction(self, txn, redacted_event_id):
  311. """Handles receiving a redaction and checking whether we need to remove
  312. any redacted relations from the database.
  313. Args:
  314. txn
  315. redacted_event_id (str): The event that was redacted.
  316. """
  317. self.db.simple_delete_txn(
  318. txn, table="event_relations", keyvalues={"event_id": redacted_event_id}
  319. )