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.
 
 
 
 
 
 

2210 lines
78 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2019 The Matrix.org Foundation C.I.C.
  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 abc import abstractmethod
  17. from enum import Enum
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. Awaitable,
  22. Collection,
  23. Dict,
  24. List,
  25. Mapping,
  26. Optional,
  27. Sequence,
  28. Tuple,
  29. Union,
  30. cast,
  31. )
  32. import attr
  33. from synapse.api.constants import (
  34. EventContentFields,
  35. EventTypes,
  36. JoinRules,
  37. PublicRoomsFilterFields,
  38. )
  39. from synapse.api.errors import StoreError
  40. from synapse.api.room_versions import RoomVersion, RoomVersions
  41. from synapse.config.homeserver import HomeServerConfig
  42. from synapse.events import EventBase
  43. from synapse.storage._base import SQLBaseStore, db_to_json, make_in_list_sql_clause
  44. from synapse.storage.database import (
  45. DatabasePool,
  46. LoggingDatabaseConnection,
  47. LoggingTransaction,
  48. )
  49. from synapse.storage.databases.main.cache import CacheInvalidationWorkerStore
  50. from synapse.storage.types import Cursor
  51. from synapse.storage.util.id_generators import IdGenerator
  52. from synapse.types import JsonDict, RetentionPolicy, ThirdPartyInstanceID
  53. from synapse.util import json_encoder
  54. from synapse.util.caches.descriptors import cached
  55. from synapse.util.stringutils import MXC_REGEX
  56. if TYPE_CHECKING:
  57. from synapse.server import HomeServer
  58. logger = logging.getLogger(__name__)
  59. @attr.s(slots=True, frozen=True, auto_attribs=True)
  60. class RatelimitOverride:
  61. messages_per_second: int
  62. burst_count: int
  63. class RoomSortOrder(Enum):
  64. """
  65. Enum to define the sorting method used when returning rooms with get_rooms_paginate
  66. NAME = sort rooms alphabetically by name
  67. JOINED_MEMBERS = sort rooms by membership size, highest to lowest
  68. """
  69. # ALPHABETICAL and SIZE are deprecated.
  70. # ALPHABETICAL is the same as NAME.
  71. ALPHABETICAL = "alphabetical"
  72. # SIZE is the same as JOINED_MEMBERS.
  73. SIZE = "size"
  74. NAME = "name"
  75. CANONICAL_ALIAS = "canonical_alias"
  76. JOINED_MEMBERS = "joined_members"
  77. JOINED_LOCAL_MEMBERS = "joined_local_members"
  78. VERSION = "version"
  79. CREATOR = "creator"
  80. ENCRYPTION = "encryption"
  81. FEDERATABLE = "federatable"
  82. PUBLIC = "public"
  83. JOIN_RULES = "join_rules"
  84. GUEST_ACCESS = "guest_access"
  85. HISTORY_VISIBILITY = "history_visibility"
  86. STATE_EVENTS = "state_events"
  87. class RoomWorkerStore(CacheInvalidationWorkerStore):
  88. def __init__(
  89. self,
  90. database: DatabasePool,
  91. db_conn: LoggingDatabaseConnection,
  92. hs: "HomeServer",
  93. ):
  94. super().__init__(database, db_conn, hs)
  95. self.config: HomeServerConfig = hs.config
  96. async def store_room(
  97. self,
  98. room_id: str,
  99. room_creator_user_id: str,
  100. is_public: bool,
  101. room_version: RoomVersion,
  102. ) -> None:
  103. """Stores a room.
  104. Args:
  105. room_id: The desired room ID, can be None.
  106. room_creator_user_id: The user ID of the room creator.
  107. is_public: True to indicate that this room should appear in
  108. public room lists.
  109. room_version: The version of the room
  110. Raises:
  111. StoreError if the room could not be stored.
  112. """
  113. try:
  114. await self.db_pool.simple_insert(
  115. "rooms",
  116. {
  117. "room_id": room_id,
  118. "creator": room_creator_user_id,
  119. "is_public": is_public,
  120. "room_version": room_version.identifier,
  121. "has_auth_chain_index": True,
  122. },
  123. desc="store_room",
  124. )
  125. except Exception as e:
  126. logger.error("store_room with room_id=%s failed: %s", room_id, e)
  127. raise StoreError(500, "Problem creating room.")
  128. async def get_room(self, room_id: str) -> Optional[Dict[str, Any]]:
  129. """Retrieve a room.
  130. Args:
  131. room_id: The ID of the room to retrieve.
  132. Returns:
  133. A dict containing the room information, or None if the room is unknown.
  134. """
  135. return await self.db_pool.simple_select_one(
  136. table="rooms",
  137. keyvalues={"room_id": room_id},
  138. retcols=("room_id", "is_public", "creator", "has_auth_chain_index"),
  139. desc="get_room",
  140. allow_none=True,
  141. )
  142. async def get_room_with_stats(self, room_id: str) -> Optional[Dict[str, Any]]:
  143. """Retrieve room with statistics.
  144. Args:
  145. room_id: The ID of the room to retrieve.
  146. Returns:
  147. A dict containing the room information, or None if the room is unknown.
  148. """
  149. def get_room_with_stats_txn(
  150. txn: LoggingTransaction, room_id: str
  151. ) -> Optional[Dict[str, Any]]:
  152. sql = """
  153. SELECT room_id, state.name, state.canonical_alias, curr.joined_members,
  154. curr.local_users_in_room AS joined_local_members, rooms.room_version AS version,
  155. rooms.creator, state.encryption, state.is_federatable AS federatable,
  156. rooms.is_public AS public, state.join_rules, state.guest_access,
  157. state.history_visibility, curr.current_state_events AS state_events,
  158. state.avatar, state.topic, state.room_type
  159. FROM rooms
  160. LEFT JOIN room_stats_state state USING (room_id)
  161. LEFT JOIN room_stats_current curr USING (room_id)
  162. WHERE room_id = ?
  163. """
  164. txn.execute(sql, [room_id])
  165. # Catch error if sql returns empty result to return "None" instead of an error
  166. try:
  167. res = self.db_pool.cursor_to_dict(txn)[0]
  168. except IndexError:
  169. return None
  170. res["federatable"] = bool(res["federatable"])
  171. res["public"] = bool(res["public"])
  172. return res
  173. return await self.db_pool.runInteraction(
  174. "get_room_with_stats", get_room_with_stats_txn, room_id
  175. )
  176. async def get_public_room_ids(self) -> List[str]:
  177. return await self.db_pool.simple_select_onecol(
  178. table="rooms",
  179. keyvalues={"is_public": True},
  180. retcol="room_id",
  181. desc="get_public_room_ids",
  182. )
  183. def _construct_room_type_where_clause(
  184. self, room_types: Union[List[Union[str, None]], None]
  185. ) -> Tuple[Union[str, None], List[str]]:
  186. if not room_types:
  187. return None, []
  188. else:
  189. # We use None when we want get rooms without a type
  190. is_null_clause = ""
  191. if None in room_types:
  192. is_null_clause = "OR room_type IS NULL"
  193. room_types = [value for value in room_types if value is not None]
  194. list_clause, args = make_in_list_sql_clause(
  195. self.database_engine, "room_type", room_types
  196. )
  197. return f"({list_clause} {is_null_clause})", args
  198. async def count_public_rooms(
  199. self,
  200. network_tuple: Optional[ThirdPartyInstanceID],
  201. ignore_non_federatable: bool,
  202. search_filter: Optional[dict],
  203. ) -> int:
  204. """Counts the number of public rooms as tracked in the room_stats_current
  205. and room_stats_state table.
  206. Args:
  207. network_tuple
  208. ignore_non_federatable: If true filters out non-federatable rooms
  209. search_filter
  210. """
  211. def _count_public_rooms_txn(txn: LoggingTransaction) -> int:
  212. query_args = []
  213. room_type_clause, args = self._construct_room_type_where_clause(
  214. search_filter.get(PublicRoomsFilterFields.ROOM_TYPES, None)
  215. if search_filter
  216. else None
  217. )
  218. room_type_clause = f" AND {room_type_clause}" if room_type_clause else ""
  219. query_args += args
  220. if network_tuple:
  221. if network_tuple.appservice_id:
  222. published_sql = """
  223. SELECT room_id from appservice_room_list
  224. WHERE appservice_id = ? AND network_id = ?
  225. """
  226. query_args.append(network_tuple.appservice_id)
  227. assert network_tuple.network_id is not None
  228. query_args.append(network_tuple.network_id)
  229. else:
  230. published_sql = """
  231. SELECT room_id FROM rooms WHERE is_public
  232. """
  233. else:
  234. published_sql = """
  235. SELECT room_id FROM rooms WHERE is_public
  236. UNION SELECT room_id from appservice_room_list
  237. """
  238. sql = f"""
  239. SELECT
  240. COUNT(*)
  241. FROM (
  242. {published_sql}
  243. ) published
  244. INNER JOIN room_stats_state USING (room_id)
  245. INNER JOIN room_stats_current USING (room_id)
  246. WHERE
  247. (
  248. join_rules = '{JoinRules.PUBLIC}'
  249. OR join_rules = '{JoinRules.KNOCK}'
  250. OR join_rules = '{JoinRules.KNOCK_RESTRICTED}'
  251. OR history_visibility = 'world_readable'
  252. )
  253. {room_type_clause}
  254. AND joined_members > 0
  255. """
  256. txn.execute(sql, query_args)
  257. return cast(Tuple[int], txn.fetchone())[0]
  258. return await self.db_pool.runInteraction(
  259. "count_public_rooms", _count_public_rooms_txn
  260. )
  261. async def get_room_count(self) -> int:
  262. """Retrieve the total number of rooms."""
  263. def f(txn: LoggingTransaction) -> int:
  264. sql = "SELECT count(*) FROM rooms"
  265. txn.execute(sql)
  266. row = cast(Tuple[int], txn.fetchone())
  267. return row[0]
  268. return await self.db_pool.runInteraction("get_rooms", f)
  269. async def get_largest_public_rooms(
  270. self,
  271. network_tuple: Optional[ThirdPartyInstanceID],
  272. search_filter: Optional[dict],
  273. limit: Optional[int],
  274. bounds: Optional[Tuple[int, str]],
  275. forwards: bool,
  276. ignore_non_federatable: bool = False,
  277. ) -> List[Dict[str, Any]]:
  278. """Gets the largest public rooms (where largest is in terms of joined
  279. members, as tracked in the statistics table).
  280. Args:
  281. network_tuple
  282. search_filter
  283. limit: Maxmimum number of rows to return, unlimited otherwise.
  284. bounds: An uppoer or lower bound to apply to result set if given,
  285. consists of a joined member count and room_id (these are
  286. excluded from result set).
  287. forwards: true iff going forwards, going backwards otherwise
  288. ignore_non_federatable: If true filters out non-federatable rooms.
  289. Returns:
  290. Rooms in order: biggest number of joined users first.
  291. We then arbitrarily use the room_id as a tie breaker.
  292. """
  293. where_clauses = []
  294. query_args: List[Union[str, int]] = []
  295. if network_tuple:
  296. if network_tuple.appservice_id:
  297. published_sql = """
  298. SELECT room_id from appservice_room_list
  299. WHERE appservice_id = ? AND network_id = ?
  300. """
  301. query_args.append(network_tuple.appservice_id)
  302. assert network_tuple.network_id is not None
  303. query_args.append(network_tuple.network_id)
  304. else:
  305. published_sql = """
  306. SELECT room_id FROM rooms WHERE is_public
  307. """
  308. else:
  309. published_sql = """
  310. SELECT room_id FROM rooms WHERE is_public
  311. UNION SELECT room_id from appservice_room_list
  312. """
  313. # Work out the bounds if we're given them, these bounds look slightly
  314. # odd, but are designed to help query planner use indices by pulling
  315. # out a common bound.
  316. if bounds:
  317. last_joined_members, last_room_id = bounds
  318. if forwards:
  319. where_clauses.append(
  320. """
  321. joined_members <= ? AND (
  322. joined_members < ? OR room_id < ?
  323. )
  324. """
  325. )
  326. else:
  327. where_clauses.append(
  328. """
  329. joined_members >= ? AND (
  330. joined_members > ? OR room_id > ?
  331. )
  332. """
  333. )
  334. query_args += [last_joined_members, last_joined_members, last_room_id]
  335. if ignore_non_federatable:
  336. where_clauses.append("is_federatable")
  337. if search_filter and search_filter.get(
  338. PublicRoomsFilterFields.GENERIC_SEARCH_TERM, None
  339. ):
  340. search_term = (
  341. "%" + search_filter[PublicRoomsFilterFields.GENERIC_SEARCH_TERM] + "%"
  342. )
  343. where_clauses.append(
  344. """
  345. (
  346. LOWER(name) LIKE ?
  347. OR LOWER(topic) LIKE ?
  348. OR LOWER(canonical_alias) LIKE ?
  349. )
  350. """
  351. )
  352. query_args += [
  353. search_term.lower(),
  354. search_term.lower(),
  355. search_term.lower(),
  356. ]
  357. room_type_clause, args = self._construct_room_type_where_clause(
  358. search_filter.get(PublicRoomsFilterFields.ROOM_TYPES, None)
  359. if search_filter
  360. else None
  361. )
  362. if room_type_clause:
  363. where_clauses.append(room_type_clause)
  364. query_args += args
  365. where_clause = ""
  366. if where_clauses:
  367. where_clause = " AND " + " AND ".join(where_clauses)
  368. dir = "DESC" if forwards else "ASC"
  369. sql = f"""
  370. SELECT
  371. room_id, name, topic, canonical_alias, joined_members,
  372. avatar, history_visibility, guest_access, join_rules, room_type
  373. FROM (
  374. {published_sql}
  375. ) published
  376. INNER JOIN room_stats_state USING (room_id)
  377. INNER JOIN room_stats_current USING (room_id)
  378. WHERE
  379. (
  380. join_rules = '{JoinRules.PUBLIC}'
  381. OR join_rules = '{JoinRules.KNOCK}'
  382. OR join_rules = '{JoinRules.KNOCK_RESTRICTED}'
  383. OR history_visibility = 'world_readable'
  384. )
  385. AND joined_members > 0
  386. {where_clause}
  387. ORDER BY
  388. joined_members {dir},
  389. room_id {dir}
  390. """
  391. if limit is not None:
  392. query_args.append(limit)
  393. sql += """
  394. LIMIT ?
  395. """
  396. def _get_largest_public_rooms_txn(
  397. txn: LoggingTransaction,
  398. ) -> List[Dict[str, Any]]:
  399. txn.execute(sql, query_args)
  400. results = self.db_pool.cursor_to_dict(txn)
  401. if not forwards:
  402. results.reverse()
  403. return results
  404. ret_val = await self.db_pool.runInteraction(
  405. "get_largest_public_rooms", _get_largest_public_rooms_txn
  406. )
  407. return ret_val
  408. @cached(max_entries=10000)
  409. async def is_room_blocked(self, room_id: str) -> Optional[bool]:
  410. return await self.db_pool.simple_select_one_onecol(
  411. table="blocked_rooms",
  412. keyvalues={"room_id": room_id},
  413. retcol="1",
  414. allow_none=True,
  415. desc="is_room_blocked",
  416. )
  417. async def room_is_blocked_by(self, room_id: str) -> Optional[str]:
  418. """
  419. Function to retrieve user who has blocked the room.
  420. user_id is non-nullable
  421. It returns None if the room is not blocked.
  422. """
  423. return await self.db_pool.simple_select_one_onecol(
  424. table="blocked_rooms",
  425. keyvalues={"room_id": room_id},
  426. retcol="user_id",
  427. allow_none=True,
  428. desc="room_is_blocked_by",
  429. )
  430. async def get_rooms_paginate(
  431. self,
  432. start: int,
  433. limit: int,
  434. order_by: str,
  435. reverse_order: bool,
  436. search_term: Optional[str],
  437. ) -> Tuple[List[Dict[str, Any]], int]:
  438. """Function to retrieve a paginated list of rooms as json.
  439. Args:
  440. start: offset in the list
  441. limit: maximum amount of rooms to retrieve
  442. order_by: the sort order of the returned list
  443. reverse_order: whether to reverse the room list
  444. search_term: a string to filter room names,
  445. canonical alias and room ids by.
  446. Room ID must match exactly. Canonical alias must match a substring of the local part.
  447. Returns:
  448. A list of room dicts and an integer representing the total number of
  449. rooms that exist given this query
  450. """
  451. # Filter room names by a string
  452. where_statement = ""
  453. search_pattern: List[object] = []
  454. if search_term:
  455. where_statement = """
  456. WHERE LOWER(state.name) LIKE ?
  457. OR LOWER(state.canonical_alias) LIKE ?
  458. OR state.room_id = ?
  459. """
  460. # Our postgres db driver converts ? -> %s in SQL strings as that's the
  461. # placeholder for postgres.
  462. # HOWEVER, if you put a % into your SQL then everything goes wibbly.
  463. # To get around this, we're going to surround search_term with %'s
  464. # before giving it to the database in python instead
  465. search_pattern = [
  466. "%" + search_term.lower() + "%",
  467. "#%" + search_term.lower() + "%:%",
  468. search_term,
  469. ]
  470. # Set ordering
  471. if RoomSortOrder(order_by) == RoomSortOrder.SIZE:
  472. # Deprecated in favour of RoomSortOrder.JOINED_MEMBERS
  473. order_by_column = "curr.joined_members"
  474. order_by_asc = False
  475. elif RoomSortOrder(order_by) == RoomSortOrder.ALPHABETICAL:
  476. # Deprecated in favour of RoomSortOrder.NAME
  477. order_by_column = "state.name"
  478. order_by_asc = True
  479. elif RoomSortOrder(order_by) == RoomSortOrder.NAME:
  480. order_by_column = "state.name"
  481. order_by_asc = True
  482. elif RoomSortOrder(order_by) == RoomSortOrder.CANONICAL_ALIAS:
  483. order_by_column = "state.canonical_alias"
  484. order_by_asc = True
  485. elif RoomSortOrder(order_by) == RoomSortOrder.JOINED_MEMBERS:
  486. order_by_column = "curr.joined_members"
  487. order_by_asc = False
  488. elif RoomSortOrder(order_by) == RoomSortOrder.JOINED_LOCAL_MEMBERS:
  489. order_by_column = "curr.local_users_in_room"
  490. order_by_asc = False
  491. elif RoomSortOrder(order_by) == RoomSortOrder.VERSION:
  492. order_by_column = "rooms.room_version"
  493. order_by_asc = False
  494. elif RoomSortOrder(order_by) == RoomSortOrder.CREATOR:
  495. order_by_column = "rooms.creator"
  496. order_by_asc = True
  497. elif RoomSortOrder(order_by) == RoomSortOrder.ENCRYPTION:
  498. order_by_column = "state.encryption"
  499. order_by_asc = True
  500. elif RoomSortOrder(order_by) == RoomSortOrder.FEDERATABLE:
  501. order_by_column = "state.is_federatable"
  502. order_by_asc = True
  503. elif RoomSortOrder(order_by) == RoomSortOrder.PUBLIC:
  504. order_by_column = "rooms.is_public"
  505. order_by_asc = True
  506. elif RoomSortOrder(order_by) == RoomSortOrder.JOIN_RULES:
  507. order_by_column = "state.join_rules"
  508. order_by_asc = True
  509. elif RoomSortOrder(order_by) == RoomSortOrder.GUEST_ACCESS:
  510. order_by_column = "state.guest_access"
  511. order_by_asc = True
  512. elif RoomSortOrder(order_by) == RoomSortOrder.HISTORY_VISIBILITY:
  513. order_by_column = "state.history_visibility"
  514. order_by_asc = True
  515. elif RoomSortOrder(order_by) == RoomSortOrder.STATE_EVENTS:
  516. order_by_column = "curr.current_state_events"
  517. order_by_asc = False
  518. else:
  519. raise StoreError(
  520. 500, "Incorrect value for order_by provided: %s" % order_by
  521. )
  522. # Whether to return the list in reverse order
  523. if reverse_order:
  524. # Flip the boolean
  525. order_by_asc = not order_by_asc
  526. # Create one query for getting the limited number of events that the user asked
  527. # for, and another query for getting the total number of events that could be
  528. # returned. Thus allowing us to see if there are more events to paginate through
  529. info_sql = """
  530. SELECT state.room_id, state.name, state.canonical_alias, curr.joined_members,
  531. curr.local_users_in_room, rooms.room_version, rooms.creator,
  532. state.encryption, state.is_federatable, rooms.is_public, state.join_rules,
  533. state.guest_access, state.history_visibility, curr.current_state_events,
  534. state.room_type
  535. FROM room_stats_state state
  536. INNER JOIN room_stats_current curr USING (room_id)
  537. INNER JOIN rooms USING (room_id)
  538. {where}
  539. ORDER BY {order_by} {direction}, state.room_id {direction}
  540. LIMIT ?
  541. OFFSET ?
  542. """.format(
  543. where=where_statement,
  544. order_by=order_by_column,
  545. direction="ASC" if order_by_asc else "DESC",
  546. )
  547. # Use a nested SELECT statement as SQL can't count(*) with an OFFSET
  548. count_sql = """
  549. SELECT count(*) FROM (
  550. SELECT room_id FROM room_stats_state state
  551. {where}
  552. ) AS get_room_ids
  553. """.format(
  554. where=where_statement,
  555. )
  556. def _get_rooms_paginate_txn(
  557. txn: LoggingTransaction,
  558. ) -> Tuple[List[Dict[str, Any]], int]:
  559. # Add the search term into the WHERE clause
  560. # and execute the data query
  561. txn.execute(info_sql, search_pattern + [limit, start])
  562. # Refactor room query data into a structured dictionary
  563. rooms = []
  564. for room in txn:
  565. rooms.append(
  566. {
  567. "room_id": room[0],
  568. "name": room[1],
  569. "canonical_alias": room[2],
  570. "joined_members": room[3],
  571. "joined_local_members": room[4],
  572. "version": room[5],
  573. "creator": room[6],
  574. "encryption": room[7],
  575. # room_stats_state.federatable is an integer on sqlite.
  576. "federatable": bool(room[8]),
  577. # rooms.is_public is an integer on sqlite.
  578. "public": bool(room[9]),
  579. "join_rules": room[10],
  580. "guest_access": room[11],
  581. "history_visibility": room[12],
  582. "state_events": room[13],
  583. "room_type": room[14],
  584. }
  585. )
  586. # Execute the count query
  587. # Add the search term into the WHERE clause if present
  588. txn.execute(count_sql, search_pattern)
  589. room_count = cast(Tuple[int], txn.fetchone())
  590. return rooms, room_count[0]
  591. return await self.db_pool.runInteraction(
  592. "get_rooms_paginate",
  593. _get_rooms_paginate_txn,
  594. )
  595. @cached(max_entries=10000)
  596. async def get_ratelimit_for_user(self, user_id: str) -> Optional[RatelimitOverride]:
  597. """Check if there are any overrides for ratelimiting for the given user
  598. Args:
  599. user_id: user ID of the user
  600. Returns:
  601. RatelimitOverride if there is an override, else None. If the contents
  602. of RatelimitOverride are None or 0 then ratelimitng has been
  603. disabled for that user entirely.
  604. """
  605. row = await self.db_pool.simple_select_one(
  606. table="ratelimit_override",
  607. keyvalues={"user_id": user_id},
  608. retcols=("messages_per_second", "burst_count"),
  609. allow_none=True,
  610. desc="get_ratelimit_for_user",
  611. )
  612. if row:
  613. return RatelimitOverride(
  614. messages_per_second=row["messages_per_second"],
  615. burst_count=row["burst_count"],
  616. )
  617. else:
  618. return None
  619. async def set_ratelimit_for_user(
  620. self, user_id: str, messages_per_second: int, burst_count: int
  621. ) -> None:
  622. """Sets whether a user is set an overridden ratelimit.
  623. Args:
  624. user_id: user ID of the user
  625. messages_per_second: The number of actions that can be performed in a second.
  626. burst_count: How many actions that can be performed before being limited.
  627. """
  628. def set_ratelimit_txn(txn: LoggingTransaction) -> None:
  629. self.db_pool.simple_upsert_txn(
  630. txn,
  631. table="ratelimit_override",
  632. keyvalues={"user_id": user_id},
  633. values={
  634. "messages_per_second": messages_per_second,
  635. "burst_count": burst_count,
  636. },
  637. )
  638. self._invalidate_cache_and_stream(
  639. txn, self.get_ratelimit_for_user, (user_id,)
  640. )
  641. await self.db_pool.runInteraction("set_ratelimit", set_ratelimit_txn)
  642. async def delete_ratelimit_for_user(self, user_id: str) -> None:
  643. """Delete an overridden ratelimit for a user.
  644. Args:
  645. user_id: user ID of the user
  646. """
  647. def delete_ratelimit_txn(txn: LoggingTransaction) -> None:
  648. row = self.db_pool.simple_select_one_txn(
  649. txn,
  650. table="ratelimit_override",
  651. keyvalues={"user_id": user_id},
  652. retcols=["user_id"],
  653. allow_none=True,
  654. )
  655. if not row:
  656. return
  657. # They are there, delete them.
  658. self.db_pool.simple_delete_one_txn(
  659. txn, "ratelimit_override", keyvalues={"user_id": user_id}
  660. )
  661. self._invalidate_cache_and_stream(
  662. txn, self.get_ratelimit_for_user, (user_id,)
  663. )
  664. await self.db_pool.runInteraction("delete_ratelimit", delete_ratelimit_txn)
  665. @cached()
  666. async def get_retention_policy_for_room(self, room_id: str) -> RetentionPolicy:
  667. """Get the retention policy for a given room.
  668. If no retention policy has been found for this room, returns a policy defined
  669. by the configured default policy (which has None as both the 'min_lifetime' and
  670. the 'max_lifetime' if no default policy has been defined in the server's
  671. configuration).
  672. If support for retention policies is disabled, a policy with a 'min_lifetime' and
  673. 'max_lifetime' of None is returned.
  674. Args:
  675. room_id: The ID of the room to get the retention policy of.
  676. Returns:
  677. A dict containing "min_lifetime" and "max_lifetime" for this room.
  678. """
  679. # If the room retention feature is disabled, return a policy with no minimum nor
  680. # maximum. This prevents incorrectly filtering out events when sending to
  681. # the client.
  682. if not self.config.retention.retention_enabled:
  683. return RetentionPolicy()
  684. def get_retention_policy_for_room_txn(
  685. txn: LoggingTransaction,
  686. ) -> List[Dict[str, Optional[int]]]:
  687. txn.execute(
  688. """
  689. SELECT min_lifetime, max_lifetime FROM room_retention
  690. INNER JOIN current_state_events USING (event_id, room_id)
  691. WHERE room_id = ?;
  692. """,
  693. (room_id,),
  694. )
  695. return self.db_pool.cursor_to_dict(txn)
  696. ret = await self.db_pool.runInteraction(
  697. "get_retention_policy_for_room",
  698. get_retention_policy_for_room_txn,
  699. )
  700. # If we don't know this room ID, ret will be None, in this case return the default
  701. # policy.
  702. if not ret:
  703. return RetentionPolicy(
  704. min_lifetime=self.config.retention.retention_default_min_lifetime,
  705. max_lifetime=self.config.retention.retention_default_max_lifetime,
  706. )
  707. min_lifetime = ret[0]["min_lifetime"]
  708. max_lifetime = ret[0]["max_lifetime"]
  709. # If one of the room's policy's attributes isn't defined, use the matching
  710. # attribute from the default policy.
  711. # The default values will be None if no default policy has been defined, or if one
  712. # of the attributes is missing from the default policy.
  713. if min_lifetime is None:
  714. min_lifetime = self.config.retention.retention_default_min_lifetime
  715. if max_lifetime is None:
  716. max_lifetime = self.config.retention.retention_default_max_lifetime
  717. return RetentionPolicy(
  718. min_lifetime=min_lifetime,
  719. max_lifetime=max_lifetime,
  720. )
  721. async def get_media_mxcs_in_room(self, room_id: str) -> Tuple[List[str], List[str]]:
  722. """Retrieves all the local and remote media MXC URIs in a given room
  723. Args:
  724. room_id
  725. Returns:
  726. The local and remote media as a lists of the media IDs.
  727. """
  728. def _get_media_mxcs_in_room_txn(
  729. txn: LoggingTransaction,
  730. ) -> Tuple[List[str], List[str]]:
  731. local_mxcs, remote_mxcs = self._get_media_mxcs_in_room_txn(txn, room_id)
  732. local_media_mxcs = []
  733. remote_media_mxcs = []
  734. # Convert the IDs to MXC URIs
  735. for media_id in local_mxcs:
  736. local_media_mxcs.append("mxc://%s/%s" % (self.hs.hostname, media_id))
  737. for hostname, media_id in remote_mxcs:
  738. remote_media_mxcs.append("mxc://%s/%s" % (hostname, media_id))
  739. return local_media_mxcs, remote_media_mxcs
  740. return await self.db_pool.runInteraction(
  741. "get_media_ids_in_room", _get_media_mxcs_in_room_txn
  742. )
  743. async def quarantine_media_ids_in_room(
  744. self, room_id: str, quarantined_by: str
  745. ) -> int:
  746. """For a room loops through all events with media and quarantines
  747. the associated media
  748. """
  749. logger.info("Quarantining media in room: %s", room_id)
  750. def _quarantine_media_in_room_txn(txn: LoggingTransaction) -> int:
  751. local_mxcs, remote_mxcs = self._get_media_mxcs_in_room_txn(txn, room_id)
  752. return self._quarantine_media_txn(
  753. txn, local_mxcs, remote_mxcs, quarantined_by
  754. )
  755. return await self.db_pool.runInteraction(
  756. "quarantine_media_in_room", _quarantine_media_in_room_txn
  757. )
  758. def _get_media_mxcs_in_room_txn(
  759. self, txn: LoggingTransaction, room_id: str
  760. ) -> Tuple[List[str], List[Tuple[str, str]]]:
  761. """Retrieves all the local and remote media MXC URIs in a given room
  762. Returns:
  763. The local and remote media as a lists of tuples where the key is
  764. the hostname and the value is the media ID.
  765. """
  766. sql = """
  767. SELECT stream_ordering, json FROM events
  768. JOIN event_json USING (room_id, event_id)
  769. WHERE room_id = ?
  770. %(where_clause)s
  771. AND contains_url = ? AND outlier = ?
  772. ORDER BY stream_ordering DESC
  773. LIMIT ?
  774. """
  775. txn.execute(sql % {"where_clause": ""}, (room_id, True, False, 100))
  776. local_media_mxcs = []
  777. remote_media_mxcs = []
  778. while True:
  779. next_token = None
  780. for stream_ordering, content_json in txn:
  781. next_token = stream_ordering
  782. event_json = db_to_json(content_json)
  783. content = event_json["content"]
  784. content_url = content.get("url")
  785. thumbnail_url = content.get("info", {}).get("thumbnail_url")
  786. for url in (content_url, thumbnail_url):
  787. if not url:
  788. continue
  789. matches = MXC_REGEX.match(url)
  790. if matches:
  791. hostname = matches.group(1)
  792. media_id = matches.group(2)
  793. if hostname == self.hs.hostname:
  794. local_media_mxcs.append(media_id)
  795. else:
  796. remote_media_mxcs.append((hostname, media_id))
  797. if next_token is None:
  798. # We've gone through the whole room, so we're finished.
  799. break
  800. txn.execute(
  801. sql % {"where_clause": "AND stream_ordering < ?"},
  802. (room_id, next_token, True, False, 100),
  803. )
  804. return local_media_mxcs, remote_media_mxcs
  805. async def quarantine_media_by_id(
  806. self,
  807. server_name: str,
  808. media_id: str,
  809. quarantined_by: Optional[str],
  810. ) -> int:
  811. """quarantines or unquarantines a single local or remote media id
  812. Args:
  813. server_name: The name of the server that holds this media
  814. media_id: The ID of the media to be quarantined
  815. quarantined_by: The user ID that initiated the quarantine request
  816. If it is `None` media will be removed from quarantine
  817. """
  818. logger.info("Quarantining media: %s/%s", server_name, media_id)
  819. is_local = server_name == self.config.server.server_name
  820. def _quarantine_media_by_id_txn(txn: LoggingTransaction) -> int:
  821. local_mxcs = [media_id] if is_local else []
  822. remote_mxcs = [(server_name, media_id)] if not is_local else []
  823. return self._quarantine_media_txn(
  824. txn, local_mxcs, remote_mxcs, quarantined_by
  825. )
  826. return await self.db_pool.runInteraction(
  827. "quarantine_media_by_user", _quarantine_media_by_id_txn
  828. )
  829. async def quarantine_media_ids_by_user(
  830. self, user_id: str, quarantined_by: str
  831. ) -> int:
  832. """quarantines all local media associated with a single user
  833. Args:
  834. user_id: The ID of the user to quarantine media of
  835. quarantined_by: The ID of the user who made the quarantine request
  836. """
  837. def _quarantine_media_by_user_txn(txn: LoggingTransaction) -> int:
  838. local_media_ids = self._get_media_ids_by_user_txn(txn, user_id)
  839. return self._quarantine_media_txn(txn, local_media_ids, [], quarantined_by)
  840. return await self.db_pool.runInteraction(
  841. "quarantine_media_by_user", _quarantine_media_by_user_txn
  842. )
  843. def _get_media_ids_by_user_txn(
  844. self, txn: LoggingTransaction, user_id: str, filter_quarantined: bool = True
  845. ) -> List[str]:
  846. """Retrieves local media IDs by a given user
  847. Args:
  848. txn (cursor)
  849. user_id: The ID of the user to retrieve media IDs of
  850. Returns:
  851. The local and remote media as a lists of tuples where the key is
  852. the hostname and the value is the media ID.
  853. """
  854. # Local media
  855. sql = """
  856. SELECT media_id
  857. FROM local_media_repository
  858. WHERE user_id = ?
  859. """
  860. if filter_quarantined:
  861. sql += "AND quarantined_by IS NULL"
  862. txn.execute(sql, (user_id,))
  863. local_media_ids = [row[0] for row in txn]
  864. # TODO: Figure out all remote media a user has referenced in a message
  865. return local_media_ids
  866. def _quarantine_media_txn(
  867. self,
  868. txn: LoggingTransaction,
  869. local_mxcs: List[str],
  870. remote_mxcs: List[Tuple[str, str]],
  871. quarantined_by: Optional[str],
  872. ) -> int:
  873. """Quarantine and unquarantine local and remote media items
  874. Args:
  875. txn (cursor)
  876. local_mxcs: A list of local mxc URLs
  877. remote_mxcs: A list of (remote server, media id) tuples representing
  878. remote mxc URLs
  879. quarantined_by: The ID of the user who initiated the quarantine request
  880. If it is `None` media will be removed from quarantine
  881. Returns:
  882. The total number of media items quarantined
  883. """
  884. # Update all the tables to set the quarantined_by flag
  885. sql = """
  886. UPDATE local_media_repository
  887. SET quarantined_by = ?
  888. WHERE media_id = ?
  889. """
  890. # set quarantine
  891. if quarantined_by is not None:
  892. sql += "AND safe_from_quarantine = ?"
  893. txn.executemany(
  894. sql, [(quarantined_by, media_id, False) for media_id in local_mxcs]
  895. )
  896. # remove from quarantine
  897. else:
  898. txn.executemany(
  899. sql, [(quarantined_by, media_id) for media_id in local_mxcs]
  900. )
  901. # Note that a rowcount of -1 can be used to indicate no rows were affected.
  902. total_media_quarantined = txn.rowcount if txn.rowcount > 0 else 0
  903. txn.executemany(
  904. """
  905. UPDATE remote_media_cache
  906. SET quarantined_by = ?
  907. WHERE media_origin = ? AND media_id = ?
  908. """,
  909. ((quarantined_by, origin, media_id) for origin, media_id in remote_mxcs),
  910. )
  911. total_media_quarantined += txn.rowcount if txn.rowcount > 0 else 0
  912. return total_media_quarantined
  913. async def get_rooms_for_retention_period_in_range(
  914. self, min_ms: Optional[int], max_ms: Optional[int], include_null: bool = False
  915. ) -> Dict[str, RetentionPolicy]:
  916. """Retrieves all of the rooms within the given retention range.
  917. Optionally includes the rooms which don't have a retention policy.
  918. Args:
  919. min_ms: Duration in milliseconds that define the lower limit of
  920. the range to handle (exclusive). If None, doesn't set a lower limit.
  921. max_ms: Duration in milliseconds that define the upper limit of
  922. the range to handle (inclusive). If None, doesn't set an upper limit.
  923. include_null: Whether to include rooms which retention policy is NULL
  924. in the returned set.
  925. Returns:
  926. The rooms within this range, along with their retention
  927. policy. The key is "room_id", and maps to a dict describing the retention
  928. policy associated with this room ID. The keys for this nested dict are
  929. "min_lifetime" (int|None), and "max_lifetime" (int|None).
  930. """
  931. def get_rooms_for_retention_period_in_range_txn(
  932. txn: LoggingTransaction,
  933. ) -> Dict[str, RetentionPolicy]:
  934. range_conditions = []
  935. args = []
  936. if min_ms is not None:
  937. range_conditions.append("max_lifetime > ?")
  938. args.append(min_ms)
  939. if max_ms is not None:
  940. range_conditions.append("max_lifetime <= ?")
  941. args.append(max_ms)
  942. # Do a first query which will retrieve the rooms that have a retention policy
  943. # in their current state.
  944. sql = """
  945. SELECT room_id, min_lifetime, max_lifetime FROM room_retention
  946. INNER JOIN current_state_events USING (event_id, room_id)
  947. """
  948. if len(range_conditions):
  949. sql += " WHERE (" + " AND ".join(range_conditions) + ")"
  950. if include_null:
  951. sql += " OR max_lifetime IS NULL"
  952. txn.execute(sql, args)
  953. rows = self.db_pool.cursor_to_dict(txn)
  954. rooms_dict = {}
  955. for row in rows:
  956. rooms_dict[row["room_id"]] = RetentionPolicy(
  957. min_lifetime=row["min_lifetime"],
  958. max_lifetime=row["max_lifetime"],
  959. )
  960. if include_null:
  961. # If required, do a second query that retrieves all of the rooms we know
  962. # of so we can handle rooms with no retention policy.
  963. sql = "SELECT DISTINCT room_id FROM current_state_events"
  964. txn.execute(sql)
  965. rows = self.db_pool.cursor_to_dict(txn)
  966. # If a room isn't already in the dict (i.e. it doesn't have a retention
  967. # policy in its state), add it with a null policy.
  968. for row in rows:
  969. if row["room_id"] not in rooms_dict:
  970. rooms_dict[row["room_id"]] = RetentionPolicy()
  971. return rooms_dict
  972. return await self.db_pool.runInteraction(
  973. "get_rooms_for_retention_period_in_range",
  974. get_rooms_for_retention_period_in_range_txn,
  975. )
  976. async def get_partial_state_servers_at_join(self, room_id: str) -> Sequence[str]:
  977. """Gets the list of servers in a partial state room at the time we joined it.
  978. Returns:
  979. The `servers_in_room` list from the `/send_join` response for partial state
  980. rooms. May not be accurate or complete, as it comes from a remote
  981. homeserver.
  982. An empty list for full state rooms.
  983. """
  984. return await self.db_pool.simple_select_onecol(
  985. "partial_state_rooms_servers",
  986. keyvalues={"room_id": room_id},
  987. retcol="server_name",
  988. desc="get_partial_state_servers_at_join",
  989. )
  990. async def get_partial_state_rooms_and_servers(
  991. self,
  992. ) -> Mapping[str, Collection[str]]:
  993. """Get all rooms containing events with partial state, and the servers known
  994. to be in the room.
  995. Returns:
  996. A dictionary of rooms with partial state, with room IDs as keys and
  997. lists of servers in rooms as values.
  998. """
  999. room_servers: Dict[str, List[str]] = {}
  1000. rows = await self.db_pool.simple_select_list(
  1001. "partial_state_rooms_servers",
  1002. keyvalues=None,
  1003. retcols=("room_id", "server_name"),
  1004. desc="get_partial_state_rooms",
  1005. )
  1006. for row in rows:
  1007. room_id = row["room_id"]
  1008. server_name = row["server_name"]
  1009. room_servers.setdefault(room_id, []).append(server_name)
  1010. return room_servers
  1011. async def clear_partial_state_room(self, room_id: str) -> bool:
  1012. """Clears the partial state flag for a room.
  1013. Args:
  1014. room_id: The room whose partial state flag is to be cleared.
  1015. Returns:
  1016. `True` if the partial state flag has been cleared successfully.
  1017. `False` if the partial state flag could not be cleared because the room
  1018. still contains events with partial state.
  1019. """
  1020. try:
  1021. await self.db_pool.runInteraction(
  1022. "clear_partial_state_room", self._clear_partial_state_room_txn, room_id
  1023. )
  1024. return True
  1025. except self.db_pool.engine.module.IntegrityError as e:
  1026. # Assume that any `IntegrityError`s are due to partial state events.
  1027. logger.info(
  1028. "Exception while clearing lazy partial-state-room %s, retrying: %s",
  1029. room_id,
  1030. e,
  1031. )
  1032. return False
  1033. def _clear_partial_state_room_txn(
  1034. self, txn: LoggingTransaction, room_id: str
  1035. ) -> None:
  1036. DatabasePool.simple_delete_txn(
  1037. txn,
  1038. table="partial_state_rooms_servers",
  1039. keyvalues={"room_id": room_id},
  1040. )
  1041. DatabasePool.simple_delete_one_txn(
  1042. txn,
  1043. table="partial_state_rooms",
  1044. keyvalues={"room_id": room_id},
  1045. )
  1046. self._invalidate_cache_and_stream(txn, self.is_partial_state_room, (room_id,))
  1047. # We now delete anything from `device_lists_remote_pending` with a
  1048. # stream ID less than the minimum
  1049. # `partial_state_rooms.device_lists_stream_id`, as we no longer need them.
  1050. device_lists_stream_id = DatabasePool.simple_select_one_onecol_txn(
  1051. txn,
  1052. table="partial_state_rooms",
  1053. keyvalues={},
  1054. retcol="MIN(device_lists_stream_id)",
  1055. allow_none=True,
  1056. )
  1057. if device_lists_stream_id is None:
  1058. # There are no rooms being currently partially joined, so we delete everything.
  1059. txn.execute("DELETE FROM device_lists_remote_pending")
  1060. else:
  1061. sql = """
  1062. DELETE FROM device_lists_remote_pending
  1063. WHERE stream_id <= ?
  1064. """
  1065. txn.execute(sql, (device_lists_stream_id,))
  1066. @cached()
  1067. async def is_partial_state_room(self, room_id: str) -> bool:
  1068. """Checks if this room has partial state.
  1069. Returns true if this is a "partial-state" room, which means that the state
  1070. at events in the room, and `current_state_events`, may not yet be
  1071. complete.
  1072. """
  1073. entry = await self.db_pool.simple_select_one_onecol(
  1074. table="partial_state_rooms",
  1075. keyvalues={"room_id": room_id},
  1076. retcol="room_id",
  1077. allow_none=True,
  1078. desc="is_partial_state_room",
  1079. )
  1080. return entry is not None
  1081. class _BackgroundUpdates:
  1082. REMOVE_TOMESTONED_ROOMS_BG_UPDATE = "remove_tombstoned_rooms_from_directory"
  1083. ADD_ROOMS_ROOM_VERSION_COLUMN = "add_rooms_room_version_column"
  1084. POPULATE_ROOM_DEPTH_MIN_DEPTH2 = "populate_room_depth_min_depth2"
  1085. REPLACE_ROOM_DEPTH_MIN_DEPTH = "replace_room_depth_min_depth"
  1086. POPULATE_ROOMS_CREATOR_COLUMN = "populate_rooms_creator_column"
  1087. ADD_ROOM_TYPE_COLUMN = "add_room_type_column"
  1088. _REPLACE_ROOM_DEPTH_SQL_COMMANDS = (
  1089. "DROP TRIGGER populate_min_depth2_trigger ON room_depth",
  1090. "DROP FUNCTION populate_min_depth2()",
  1091. "ALTER TABLE room_depth DROP COLUMN min_depth",
  1092. "ALTER TABLE room_depth RENAME COLUMN min_depth2 TO min_depth",
  1093. )
  1094. class RoomBackgroundUpdateStore(SQLBaseStore):
  1095. def __init__(
  1096. self,
  1097. database: DatabasePool,
  1098. db_conn: LoggingDatabaseConnection,
  1099. hs: "HomeServer",
  1100. ):
  1101. super().__init__(database, db_conn, hs)
  1102. self.db_pool.updates.register_background_update_handler(
  1103. "insert_room_retention",
  1104. self._background_insert_retention,
  1105. )
  1106. self.db_pool.updates.register_background_update_handler(
  1107. _BackgroundUpdates.REMOVE_TOMESTONED_ROOMS_BG_UPDATE,
  1108. self._remove_tombstoned_rooms_from_directory,
  1109. )
  1110. self.db_pool.updates.register_background_update_handler(
  1111. _BackgroundUpdates.ADD_ROOMS_ROOM_VERSION_COLUMN,
  1112. self._background_add_rooms_room_version_column,
  1113. )
  1114. self.db_pool.updates.register_background_update_handler(
  1115. _BackgroundUpdates.ADD_ROOM_TYPE_COLUMN,
  1116. self._background_add_room_type_column,
  1117. )
  1118. # BG updates to change the type of room_depth.min_depth
  1119. self.db_pool.updates.register_background_update_handler(
  1120. _BackgroundUpdates.POPULATE_ROOM_DEPTH_MIN_DEPTH2,
  1121. self._background_populate_room_depth_min_depth2,
  1122. )
  1123. self.db_pool.updates.register_background_update_handler(
  1124. _BackgroundUpdates.REPLACE_ROOM_DEPTH_MIN_DEPTH,
  1125. self._background_replace_room_depth_min_depth,
  1126. )
  1127. self.db_pool.updates.register_background_update_handler(
  1128. _BackgroundUpdates.POPULATE_ROOMS_CREATOR_COLUMN,
  1129. self._background_populate_rooms_creator_column,
  1130. )
  1131. async def _background_insert_retention(
  1132. self, progress: JsonDict, batch_size: int
  1133. ) -> int:
  1134. """Retrieves a list of all rooms within a range and inserts an entry for each of
  1135. them into the room_retention table.
  1136. NULLs the property's columns if missing from the retention event in the room's
  1137. state (or NULLs all of them if there's no retention event in the room's state),
  1138. so that we fall back to the server's retention policy.
  1139. """
  1140. last_room = progress.get("room_id", "")
  1141. def _background_insert_retention_txn(txn: LoggingTransaction) -> bool:
  1142. txn.execute(
  1143. """
  1144. SELECT state.room_id, state.event_id, events.json
  1145. FROM current_state_events as state
  1146. LEFT JOIN event_json AS events ON (state.event_id = events.event_id)
  1147. WHERE state.room_id > ? AND state.type = '%s'
  1148. ORDER BY state.room_id ASC
  1149. LIMIT ?;
  1150. """
  1151. % EventTypes.Retention,
  1152. (last_room, batch_size),
  1153. )
  1154. rows = self.db_pool.cursor_to_dict(txn)
  1155. if not rows:
  1156. return True
  1157. for row in rows:
  1158. if not row["json"]:
  1159. retention_policy = {}
  1160. else:
  1161. ev = db_to_json(row["json"])
  1162. retention_policy = ev["content"]
  1163. self.db_pool.simple_insert_txn(
  1164. txn=txn,
  1165. table="room_retention",
  1166. values={
  1167. "room_id": row["room_id"],
  1168. "event_id": row["event_id"],
  1169. "min_lifetime": retention_policy.get("min_lifetime"),
  1170. "max_lifetime": retention_policy.get("max_lifetime"),
  1171. },
  1172. )
  1173. logger.info("Inserted %d rows into room_retention", len(rows))
  1174. self.db_pool.updates._background_update_progress_txn(
  1175. txn, "insert_room_retention", {"room_id": rows[-1]["room_id"]}
  1176. )
  1177. if batch_size > len(rows):
  1178. return True
  1179. else:
  1180. return False
  1181. end = await self.db_pool.runInteraction(
  1182. "insert_room_retention",
  1183. _background_insert_retention_txn,
  1184. )
  1185. if end:
  1186. await self.db_pool.updates._end_background_update("insert_room_retention")
  1187. return batch_size
  1188. async def _background_add_rooms_room_version_column(
  1189. self, progress: JsonDict, batch_size: int
  1190. ) -> int:
  1191. """Background update to go and add room version information to `rooms`
  1192. table from `current_state_events` table.
  1193. """
  1194. last_room_id = progress.get("room_id", "")
  1195. def _background_add_rooms_room_version_column_txn(
  1196. txn: LoggingTransaction,
  1197. ) -> bool:
  1198. sql = """
  1199. SELECT room_id, json FROM current_state_events
  1200. INNER JOIN event_json USING (room_id, event_id)
  1201. WHERE room_id > ? AND type = 'm.room.create' AND state_key = ''
  1202. ORDER BY room_id
  1203. LIMIT ?
  1204. """
  1205. txn.execute(sql, (last_room_id, batch_size))
  1206. updates = []
  1207. for room_id, event_json in txn:
  1208. event_dict = db_to_json(event_json)
  1209. room_version_id = event_dict.get("content", {}).get(
  1210. "room_version", RoomVersions.V1.identifier
  1211. )
  1212. creator = event_dict.get("content").get("creator")
  1213. updates.append((room_id, creator, room_version_id))
  1214. if not updates:
  1215. return True
  1216. new_last_room_id = ""
  1217. for room_id, creator, room_version_id in updates:
  1218. # We upsert here just in case we don't already have a row,
  1219. # mainly for paranoia as much badness would happen if we don't
  1220. # insert the row and then try and get the room version for the
  1221. # room.
  1222. self.db_pool.simple_upsert_txn(
  1223. txn,
  1224. table="rooms",
  1225. keyvalues={"room_id": room_id},
  1226. values={"room_version": room_version_id},
  1227. insertion_values={"is_public": False, "creator": creator},
  1228. )
  1229. new_last_room_id = room_id
  1230. self.db_pool.updates._background_update_progress_txn(
  1231. txn,
  1232. _BackgroundUpdates.ADD_ROOMS_ROOM_VERSION_COLUMN,
  1233. {"room_id": new_last_room_id},
  1234. )
  1235. return False
  1236. end = await self.db_pool.runInteraction(
  1237. "_background_add_rooms_room_version_column",
  1238. _background_add_rooms_room_version_column_txn,
  1239. )
  1240. if end:
  1241. await self.db_pool.updates._end_background_update(
  1242. _BackgroundUpdates.ADD_ROOMS_ROOM_VERSION_COLUMN
  1243. )
  1244. return batch_size
  1245. async def _remove_tombstoned_rooms_from_directory(
  1246. self, progress: JsonDict, batch_size: int
  1247. ) -> int:
  1248. """Removes any rooms with tombstone events from the room directory
  1249. Nowadays this is handled by the room upgrade handler, but we may have some
  1250. that got left behind
  1251. """
  1252. last_room = progress.get("room_id", "")
  1253. def _get_rooms(txn: LoggingTransaction) -> List[str]:
  1254. txn.execute(
  1255. """
  1256. SELECT room_id
  1257. FROM rooms r
  1258. INNER JOIN current_state_events cse USING (room_id)
  1259. WHERE room_id > ? AND r.is_public
  1260. AND cse.type = '%s' AND cse.state_key = ''
  1261. ORDER BY room_id ASC
  1262. LIMIT ?;
  1263. """
  1264. % EventTypes.Tombstone,
  1265. (last_room, batch_size),
  1266. )
  1267. return [row[0] for row in txn]
  1268. rooms = await self.db_pool.runInteraction(
  1269. "get_tombstoned_directory_rooms", _get_rooms
  1270. )
  1271. if not rooms:
  1272. await self.db_pool.updates._end_background_update(
  1273. _BackgroundUpdates.REMOVE_TOMESTONED_ROOMS_BG_UPDATE
  1274. )
  1275. return 0
  1276. for room_id in rooms:
  1277. logger.info("Removing tombstoned room %s from the directory", room_id)
  1278. await self.set_room_is_public(room_id, False)
  1279. await self.db_pool.updates._background_update_progress(
  1280. _BackgroundUpdates.REMOVE_TOMESTONED_ROOMS_BG_UPDATE, {"room_id": rooms[-1]}
  1281. )
  1282. return len(rooms)
  1283. @abstractmethod
  1284. def set_room_is_public(self, room_id: str, is_public: bool) -> Awaitable[None]:
  1285. # this will need to be implemented if a background update is performed with
  1286. # existing (tombstoned, public) rooms in the database.
  1287. #
  1288. # It's overridden by RoomStore for the synapse master.
  1289. raise NotImplementedError()
  1290. async def has_auth_chain_index(self, room_id: str) -> bool:
  1291. """Check if the room has (or can have) a chain cover index.
  1292. Defaults to True if we don't have an entry in `rooms` table nor any
  1293. events for the room.
  1294. """
  1295. has_auth_chain_index = await self.db_pool.simple_select_one_onecol(
  1296. table="rooms",
  1297. keyvalues={"room_id": room_id},
  1298. retcol="has_auth_chain_index",
  1299. desc="has_auth_chain_index",
  1300. allow_none=True,
  1301. )
  1302. if has_auth_chain_index:
  1303. return True
  1304. # It's possible that we already have events for the room in our DB
  1305. # without a corresponding room entry. If we do then we don't want to
  1306. # mark the room as having an auth chain cover index.
  1307. max_ordering = await self.db_pool.simple_select_one_onecol(
  1308. table="events",
  1309. keyvalues={"room_id": room_id},
  1310. retcol="MAX(stream_ordering)",
  1311. allow_none=True,
  1312. desc="has_auth_chain_index_fallback",
  1313. )
  1314. return max_ordering is None
  1315. async def _background_populate_room_depth_min_depth2(
  1316. self, progress: JsonDict, batch_size: int
  1317. ) -> int:
  1318. """Populate room_depth.min_depth2
  1319. This is to deal with the fact that min_depth was initially created as a
  1320. 32-bit integer field.
  1321. """
  1322. def process(txn: LoggingTransaction) -> int:
  1323. last_room = progress.get("last_room", "")
  1324. txn.execute(
  1325. """
  1326. UPDATE room_depth SET min_depth2=min_depth
  1327. WHERE room_id IN (
  1328. SELECT room_id FROM room_depth WHERE room_id > ?
  1329. ORDER BY room_id LIMIT ?
  1330. )
  1331. RETURNING room_id;
  1332. """,
  1333. (last_room, batch_size),
  1334. )
  1335. row_count = txn.rowcount
  1336. if row_count == 0:
  1337. return 0
  1338. last_room = max(row[0] for row in txn)
  1339. logger.info("populated room_depth up to %s", last_room)
  1340. self.db_pool.updates._background_update_progress_txn(
  1341. txn,
  1342. _BackgroundUpdates.POPULATE_ROOM_DEPTH_MIN_DEPTH2,
  1343. {"last_room": last_room},
  1344. )
  1345. return row_count
  1346. result = await self.db_pool.runInteraction(
  1347. "_background_populate_min_depth2", process
  1348. )
  1349. if result != 0:
  1350. return result
  1351. await self.db_pool.updates._end_background_update(
  1352. _BackgroundUpdates.POPULATE_ROOM_DEPTH_MIN_DEPTH2
  1353. )
  1354. return 0
  1355. async def _background_replace_room_depth_min_depth(
  1356. self, progress: JsonDict, batch_size: int
  1357. ) -> int:
  1358. """Drop the old 'min_depth' column and rename 'min_depth2' into its place."""
  1359. def process(txn: Cursor) -> None:
  1360. for sql in _REPLACE_ROOM_DEPTH_SQL_COMMANDS:
  1361. logger.info("completing room_depth migration: %s", sql)
  1362. txn.execute(sql)
  1363. await self.db_pool.runInteraction("_background_replace_room_depth", process)
  1364. await self.db_pool.updates._end_background_update(
  1365. _BackgroundUpdates.REPLACE_ROOM_DEPTH_MIN_DEPTH,
  1366. )
  1367. return 0
  1368. async def _background_populate_rooms_creator_column(
  1369. self, progress: JsonDict, batch_size: int
  1370. ) -> int:
  1371. """Background update to go and add creator information to `rooms`
  1372. table from `current_state_events` table.
  1373. """
  1374. last_room_id = progress.get("room_id", "")
  1375. def _background_populate_rooms_creator_column_txn(
  1376. txn: LoggingTransaction,
  1377. ) -> bool:
  1378. sql = """
  1379. SELECT room_id, json FROM event_json
  1380. INNER JOIN rooms AS room USING (room_id)
  1381. INNER JOIN current_state_events AS state_event USING (room_id, event_id)
  1382. WHERE room_id > ? AND (room.creator IS NULL OR room.creator = '') AND state_event.type = 'm.room.create' AND state_event.state_key = ''
  1383. ORDER BY room_id
  1384. LIMIT ?
  1385. """
  1386. txn.execute(sql, (last_room_id, batch_size))
  1387. room_id_to_create_event_results = txn.fetchall()
  1388. new_last_room_id = ""
  1389. for room_id, event_json in room_id_to_create_event_results:
  1390. event_dict = db_to_json(event_json)
  1391. creator = event_dict.get("content").get(EventContentFields.ROOM_CREATOR)
  1392. self.db_pool.simple_update_txn(
  1393. txn,
  1394. table="rooms",
  1395. keyvalues={"room_id": room_id},
  1396. updatevalues={"creator": creator},
  1397. )
  1398. new_last_room_id = room_id
  1399. if new_last_room_id == "":
  1400. return True
  1401. self.db_pool.updates._background_update_progress_txn(
  1402. txn,
  1403. _BackgroundUpdates.POPULATE_ROOMS_CREATOR_COLUMN,
  1404. {"room_id": new_last_room_id},
  1405. )
  1406. return False
  1407. end = await self.db_pool.runInteraction(
  1408. "_background_populate_rooms_creator_column",
  1409. _background_populate_rooms_creator_column_txn,
  1410. )
  1411. if end:
  1412. await self.db_pool.updates._end_background_update(
  1413. _BackgroundUpdates.POPULATE_ROOMS_CREATOR_COLUMN
  1414. )
  1415. return batch_size
  1416. async def _background_add_room_type_column(
  1417. self, progress: JsonDict, batch_size: int
  1418. ) -> int:
  1419. """Background update to go and add room_type information to `room_stats_state`
  1420. table from `event_json` table.
  1421. """
  1422. last_room_id = progress.get("room_id", "")
  1423. def _background_add_room_type_column_txn(
  1424. txn: LoggingTransaction,
  1425. ) -> bool:
  1426. sql = """
  1427. SELECT state.room_id, json FROM event_json
  1428. INNER JOIN current_state_events AS state USING (event_id)
  1429. WHERE state.room_id > ? AND type = 'm.room.create'
  1430. ORDER BY state.room_id
  1431. LIMIT ?
  1432. """
  1433. txn.execute(sql, (last_room_id, batch_size))
  1434. room_id_to_create_event_results = txn.fetchall()
  1435. new_last_room_id = None
  1436. for room_id, event_json in room_id_to_create_event_results:
  1437. event_dict = db_to_json(event_json)
  1438. room_type = event_dict.get("content", {}).get(
  1439. EventContentFields.ROOM_TYPE, None
  1440. )
  1441. if isinstance(room_type, str):
  1442. self.db_pool.simple_update_txn(
  1443. txn,
  1444. table="room_stats_state",
  1445. keyvalues={"room_id": room_id},
  1446. updatevalues={"room_type": room_type},
  1447. )
  1448. new_last_room_id = room_id
  1449. if new_last_room_id is None:
  1450. return True
  1451. self.db_pool.updates._background_update_progress_txn(
  1452. txn,
  1453. _BackgroundUpdates.ADD_ROOM_TYPE_COLUMN,
  1454. {"room_id": new_last_room_id},
  1455. )
  1456. return False
  1457. end = await self.db_pool.runInteraction(
  1458. "_background_add_room_type_column",
  1459. _background_add_room_type_column_txn,
  1460. )
  1461. if end:
  1462. await self.db_pool.updates._end_background_update(
  1463. _BackgroundUpdates.ADD_ROOM_TYPE_COLUMN
  1464. )
  1465. return batch_size
  1466. class RoomStore(RoomBackgroundUpdateStore, RoomWorkerStore):
  1467. def __init__(
  1468. self,
  1469. database: DatabasePool,
  1470. db_conn: LoggingDatabaseConnection,
  1471. hs: "HomeServer",
  1472. ):
  1473. super().__init__(database, db_conn, hs)
  1474. self._event_reports_id_gen = IdGenerator(db_conn, "event_reports", "id")
  1475. async def upsert_room_on_join(
  1476. self, room_id: str, room_version: RoomVersion, state_events: List[EventBase]
  1477. ) -> None:
  1478. """Ensure that the room is stored in the table
  1479. Called when we join a room over federation, and overwrites any room version
  1480. currently in the table.
  1481. """
  1482. # It's possible that we already have events for the room in our DB
  1483. # without a corresponding room entry. If we do then we don't want to
  1484. # mark the room as having an auth chain cover index.
  1485. has_auth_chain_index = await self.has_auth_chain_index(room_id)
  1486. create_event = None
  1487. for e in state_events:
  1488. if (e.type, e.state_key) == (EventTypes.Create, ""):
  1489. create_event = e
  1490. break
  1491. if create_event is None:
  1492. # If the state doesn't have a create event then the room is
  1493. # invalid, and it would fail auth checks anyway.
  1494. raise StoreError(400, "No create event in state")
  1495. room_creator = create_event.content.get(EventContentFields.ROOM_CREATOR)
  1496. if not isinstance(room_creator, str):
  1497. # If the create event does not have a creator then the room is
  1498. # invalid, and it would fail auth checks anyway.
  1499. raise StoreError(400, "No creator defined on the create event")
  1500. await self.db_pool.simple_upsert(
  1501. desc="upsert_room_on_join",
  1502. table="rooms",
  1503. keyvalues={"room_id": room_id},
  1504. values={"room_version": room_version.identifier},
  1505. insertion_values={
  1506. "is_public": False,
  1507. "creator": room_creator,
  1508. "has_auth_chain_index": has_auth_chain_index,
  1509. },
  1510. # rooms has a unique constraint on room_id, so no need to lock when doing an
  1511. # emulated upsert.
  1512. lock=False,
  1513. )
  1514. async def store_partial_state_room(
  1515. self,
  1516. room_id: str,
  1517. servers: Collection[str],
  1518. device_lists_stream_id: int,
  1519. ) -> None:
  1520. """Mark the given room as containing events with partial state.
  1521. We also store additional data that describes _when_ we first partial-joined this
  1522. room, which helps us to keep other homeservers in sync when we finally fully
  1523. join this room.
  1524. We do not include a `join_event_id` here---we need to wait for the join event
  1525. to be persisted first.
  1526. Args:
  1527. room_id: the ID of the room
  1528. servers: other servers known to be in the room
  1529. device_lists_stream_id: the device_lists stream ID at the time when we first
  1530. joined the room.
  1531. """
  1532. await self.db_pool.runInteraction(
  1533. "store_partial_state_room",
  1534. self._store_partial_state_room_txn,
  1535. room_id,
  1536. servers,
  1537. device_lists_stream_id,
  1538. )
  1539. def _store_partial_state_room_txn(
  1540. self,
  1541. txn: LoggingTransaction,
  1542. room_id: str,
  1543. servers: Collection[str],
  1544. device_lists_stream_id: int,
  1545. ) -> None:
  1546. DatabasePool.simple_insert_txn(
  1547. txn,
  1548. table="partial_state_rooms",
  1549. values={
  1550. "room_id": room_id,
  1551. "device_lists_stream_id": device_lists_stream_id,
  1552. # To be updated later once the join event is persisted.
  1553. "join_event_id": None,
  1554. },
  1555. )
  1556. DatabasePool.simple_insert_many_txn(
  1557. txn,
  1558. table="partial_state_rooms_servers",
  1559. keys=("room_id", "server_name"),
  1560. values=((room_id, s) for s in servers),
  1561. )
  1562. self._invalidate_cache_and_stream(txn, self.is_partial_state_room, (room_id,))
  1563. async def write_partial_state_rooms_join_event_id(
  1564. self,
  1565. room_id: str,
  1566. join_event_id: str,
  1567. ) -> None:
  1568. """Record the join event which resulted from a partial join.
  1569. We do this separately to `store_partial_state_room` because we need to wait for
  1570. the join event to be persisted. Otherwise we violate a foreign key constraint.
  1571. """
  1572. await self.db_pool.runInteraction(
  1573. "write_partial_state_rooms_join_event_id",
  1574. self._write_partial_state_rooms_join_event_id,
  1575. room_id,
  1576. join_event_id,
  1577. )
  1578. def _write_partial_state_rooms_join_event_id(
  1579. self,
  1580. txn: LoggingTransaction,
  1581. room_id: str,
  1582. join_event_id: str,
  1583. ) -> None:
  1584. DatabasePool.simple_update_txn(
  1585. txn,
  1586. table="partial_state_rooms",
  1587. keyvalues={"room_id": room_id},
  1588. updatevalues={"join_event_id": join_event_id},
  1589. )
  1590. async def maybe_store_room_on_outlier_membership(
  1591. self, room_id: str, room_version: RoomVersion
  1592. ) -> None:
  1593. """
  1594. When we receive an invite or any other event over federation that may relate to a room
  1595. we are not in, store the version of the room if we don't already know the room version.
  1596. """
  1597. # It's possible that we already have events for the room in our DB
  1598. # without a corresponding room entry. If we do then we don't want to
  1599. # mark the room as having an auth chain cover index.
  1600. has_auth_chain_index = await self.has_auth_chain_index(room_id)
  1601. await self.db_pool.simple_upsert(
  1602. desc="maybe_store_room_on_outlier_membership",
  1603. table="rooms",
  1604. keyvalues={"room_id": room_id},
  1605. values={},
  1606. insertion_values={
  1607. "room_version": room_version.identifier,
  1608. "is_public": False,
  1609. # We don't worry about setting the `creator` here because
  1610. # we don't process any messages in a room while a user is
  1611. # invited (only after the join).
  1612. "creator": "",
  1613. "has_auth_chain_index": has_auth_chain_index,
  1614. },
  1615. # rooms has a unique constraint on room_id, so no need to lock when doing an
  1616. # emulated upsert.
  1617. lock=False,
  1618. )
  1619. async def set_room_is_public(self, room_id: str, is_public: bool) -> None:
  1620. await self.db_pool.simple_update_one(
  1621. table="rooms",
  1622. keyvalues={"room_id": room_id},
  1623. updatevalues={"is_public": is_public},
  1624. desc="set_room_is_public",
  1625. )
  1626. self.hs.get_notifier().on_new_replication_data()
  1627. async def set_room_is_public_appservice(
  1628. self, room_id: str, appservice_id: str, network_id: str, is_public: bool
  1629. ) -> None:
  1630. """Edit the appservice/network specific public room list.
  1631. Each appservice can have a number of published room lists associated
  1632. with them, keyed off of an appservice defined `network_id`, which
  1633. basically represents a single instance of a bridge to a third party
  1634. network.
  1635. Args:
  1636. room_id
  1637. appservice_id
  1638. network_id
  1639. is_public: Whether to publish or unpublish the room from the list.
  1640. """
  1641. if is_public:
  1642. await self.db_pool.simple_upsert(
  1643. table="appservice_room_list",
  1644. keyvalues={
  1645. "appservice_id": appservice_id,
  1646. "network_id": network_id,
  1647. "room_id": room_id,
  1648. },
  1649. values={},
  1650. insertion_values={
  1651. "appservice_id": appservice_id,
  1652. "network_id": network_id,
  1653. "room_id": room_id,
  1654. },
  1655. desc="set_room_is_public_appservice_true",
  1656. )
  1657. else:
  1658. await self.db_pool.simple_delete(
  1659. table="appservice_room_list",
  1660. keyvalues={
  1661. "appservice_id": appservice_id,
  1662. "network_id": network_id,
  1663. "room_id": room_id,
  1664. },
  1665. desc="set_room_is_public_appservice_false",
  1666. )
  1667. self.hs.get_notifier().on_new_replication_data()
  1668. async def add_event_report(
  1669. self,
  1670. room_id: str,
  1671. event_id: str,
  1672. user_id: str,
  1673. reason: Optional[str],
  1674. content: JsonDict,
  1675. received_ts: int,
  1676. ) -> None:
  1677. next_id = self._event_reports_id_gen.get_next()
  1678. await self.db_pool.simple_insert(
  1679. table="event_reports",
  1680. values={
  1681. "id": next_id,
  1682. "received_ts": received_ts,
  1683. "room_id": room_id,
  1684. "event_id": event_id,
  1685. "user_id": user_id,
  1686. "reason": reason,
  1687. "content": json_encoder.encode(content),
  1688. },
  1689. desc="add_event_report",
  1690. )
  1691. async def get_event_report(self, report_id: int) -> Optional[Dict[str, Any]]:
  1692. """Retrieve an event report
  1693. Args:
  1694. report_id: ID of reported event in database
  1695. Returns:
  1696. event_report: json list of information from event report
  1697. """
  1698. def _get_event_report_txn(
  1699. txn: LoggingTransaction, report_id: int
  1700. ) -> Optional[Dict[str, Any]]:
  1701. sql = """
  1702. SELECT
  1703. er.id,
  1704. er.received_ts,
  1705. er.room_id,
  1706. er.event_id,
  1707. er.user_id,
  1708. er.content,
  1709. events.sender,
  1710. room_stats_state.canonical_alias,
  1711. room_stats_state.name,
  1712. event_json.json AS event_json
  1713. FROM event_reports AS er
  1714. LEFT JOIN events
  1715. ON events.event_id = er.event_id
  1716. JOIN event_json
  1717. ON event_json.event_id = er.event_id
  1718. JOIN room_stats_state
  1719. ON room_stats_state.room_id = er.room_id
  1720. WHERE er.id = ?
  1721. """
  1722. txn.execute(sql, [report_id])
  1723. row = txn.fetchone()
  1724. if not row:
  1725. return None
  1726. event_report = {
  1727. "id": row[0],
  1728. "received_ts": row[1],
  1729. "room_id": row[2],
  1730. "event_id": row[3],
  1731. "user_id": row[4],
  1732. "score": db_to_json(row[5]).get("score"),
  1733. "reason": db_to_json(row[5]).get("reason"),
  1734. "sender": row[6],
  1735. "canonical_alias": row[7],
  1736. "name": row[8],
  1737. "event_json": db_to_json(row[9]),
  1738. }
  1739. return event_report
  1740. return await self.db_pool.runInteraction(
  1741. "get_event_report", _get_event_report_txn, report_id
  1742. )
  1743. async def get_event_reports_paginate(
  1744. self,
  1745. start: int,
  1746. limit: int,
  1747. direction: str = "b",
  1748. user_id: Optional[str] = None,
  1749. room_id: Optional[str] = None,
  1750. ) -> Tuple[List[Dict[str, Any]], int]:
  1751. """Retrieve a paginated list of event reports
  1752. Args:
  1753. start: event offset to begin the query from
  1754. limit: number of rows to retrieve
  1755. direction: Whether to fetch the most recent first (`"b"`) or the
  1756. oldest first (`"f"`)
  1757. user_id: search for user_id. Ignored if user_id is None
  1758. room_id: search for room_id. Ignored if room_id is None
  1759. Returns:
  1760. event_reports: json list of event reports
  1761. count: total number of event reports matching the filter criteria
  1762. """
  1763. def _get_event_reports_paginate_txn(
  1764. txn: LoggingTransaction,
  1765. ) -> Tuple[List[Dict[str, Any]], int]:
  1766. filters = []
  1767. args: List[object] = []
  1768. if user_id:
  1769. filters.append("er.user_id LIKE ?")
  1770. args.extend(["%" + user_id + "%"])
  1771. if room_id:
  1772. filters.append("er.room_id LIKE ?")
  1773. args.extend(["%" + room_id + "%"])
  1774. if direction == "b":
  1775. order = "DESC"
  1776. else:
  1777. order = "ASC"
  1778. where_clause = "WHERE " + " AND ".join(filters) if len(filters) > 0 else ""
  1779. # We join on room_stats_state despite not using any columns from it
  1780. # because the join can influence the number of rows returned;
  1781. # e.g. a room that doesn't have state, maybe because it was deleted.
  1782. # The query returning the total count should be consistent with
  1783. # the query returning the results.
  1784. sql = """
  1785. SELECT COUNT(*) as total_event_reports
  1786. FROM event_reports AS er
  1787. JOIN room_stats_state ON room_stats_state.room_id = er.room_id
  1788. {}
  1789. """.format(
  1790. where_clause
  1791. )
  1792. txn.execute(sql, args)
  1793. count = cast(Tuple[int], txn.fetchone())[0]
  1794. sql = """
  1795. SELECT
  1796. er.id,
  1797. er.received_ts,
  1798. er.room_id,
  1799. er.event_id,
  1800. er.user_id,
  1801. er.content,
  1802. events.sender,
  1803. room_stats_state.canonical_alias,
  1804. room_stats_state.name
  1805. FROM event_reports AS er
  1806. LEFT JOIN events
  1807. ON events.event_id = er.event_id
  1808. JOIN room_stats_state
  1809. ON room_stats_state.room_id = er.room_id
  1810. {where_clause}
  1811. ORDER BY er.received_ts {order}
  1812. LIMIT ?
  1813. OFFSET ?
  1814. """.format(
  1815. where_clause=where_clause,
  1816. order=order,
  1817. )
  1818. args += [limit, start]
  1819. txn.execute(sql, args)
  1820. event_reports = []
  1821. for row in txn:
  1822. try:
  1823. s = db_to_json(row[5]).get("score")
  1824. r = db_to_json(row[5]).get("reason")
  1825. except Exception:
  1826. logger.error("Unable to parse json from event_reports: %s", row[0])
  1827. continue
  1828. event_reports.append(
  1829. {
  1830. "id": row[0],
  1831. "received_ts": row[1],
  1832. "room_id": row[2],
  1833. "event_id": row[3],
  1834. "user_id": row[4],
  1835. "score": s,
  1836. "reason": r,
  1837. "sender": row[6],
  1838. "canonical_alias": row[7],
  1839. "name": row[8],
  1840. }
  1841. )
  1842. return event_reports, count
  1843. return await self.db_pool.runInteraction(
  1844. "get_event_reports_paginate", _get_event_reports_paginate_txn
  1845. )
  1846. async def block_room(self, room_id: str, user_id: str) -> None:
  1847. """Marks the room as blocked.
  1848. Can be called multiple times (though we'll only track the last user to
  1849. block this room).
  1850. Can be called on a room unknown to this homeserver.
  1851. Args:
  1852. room_id: Room to block
  1853. user_id: Who blocked it
  1854. """
  1855. await self.db_pool.simple_upsert(
  1856. table="blocked_rooms",
  1857. keyvalues={"room_id": room_id},
  1858. values={},
  1859. insertion_values={"user_id": user_id},
  1860. desc="block_room",
  1861. )
  1862. await self.db_pool.runInteraction(
  1863. "block_room_invalidation",
  1864. self._invalidate_cache_and_stream,
  1865. self.is_room_blocked,
  1866. (room_id,),
  1867. )
  1868. async def unblock_room(self, room_id: str) -> None:
  1869. """Remove the room from blocking list.
  1870. Args:
  1871. room_id: Room to unblock
  1872. """
  1873. await self.db_pool.simple_delete(
  1874. table="blocked_rooms",
  1875. keyvalues={"room_id": room_id},
  1876. desc="unblock_room",
  1877. )
  1878. await self.db_pool.runInteraction(
  1879. "block_room_invalidation",
  1880. self._invalidate_cache_and_stream,
  1881. self.is_room_blocked,
  1882. (room_id,),
  1883. )