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.
 
 
 
 
 
 

1525 lines
54 KiB

  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2018 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. from typing import (
  17. TYPE_CHECKING,
  18. AbstractSet,
  19. Collection,
  20. Dict,
  21. FrozenSet,
  22. Iterable,
  23. List,
  24. Mapping,
  25. Optional,
  26. Sequence,
  27. Set,
  28. Tuple,
  29. Union,
  30. )
  31. import attr
  32. from synapse.api.constants import EventTypes, Membership
  33. from synapse.metrics import LaterGauge
  34. from synapse.metrics.background_process_metrics import wrap_as_background_process
  35. from synapse.storage._base import SQLBaseStore, db_to_json, make_in_list_sql_clause
  36. from synapse.storage.database import (
  37. DatabasePool,
  38. LoggingDatabaseConnection,
  39. LoggingTransaction,
  40. )
  41. from synapse.storage.databases.main.cache import CacheInvalidationWorkerStore
  42. from synapse.storage.databases.main.events_worker import EventsWorkerStore
  43. from synapse.storage.engines import Sqlite3Engine
  44. from synapse.storage.roommember import (
  45. GetRoomsForUserWithStreamOrdering,
  46. MemberSummary,
  47. ProfileInfo,
  48. RoomsForUser,
  49. )
  50. from synapse.types import (
  51. JsonDict,
  52. PersistedEventPosition,
  53. StateMap,
  54. StrCollection,
  55. get_domain_from_id,
  56. )
  57. from synapse.util.caches.descriptors import _CacheContext, cached, cachedList
  58. from synapse.util.iterutils import batch_iter
  59. from synapse.util.metrics import Measure
  60. if TYPE_CHECKING:
  61. from synapse.server import HomeServer
  62. logger = logging.getLogger(__name__)
  63. _MEMBERSHIP_PROFILE_UPDATE_NAME = "room_membership_profile_update"
  64. _CURRENT_STATE_MEMBERSHIP_UPDATE_NAME = "current_state_events_membership"
  65. @attr.s(frozen=True, slots=True, auto_attribs=True)
  66. class EventIdMembership:
  67. """Returned by `get_membership_from_event_ids`"""
  68. user_id: str
  69. membership: str
  70. class RoomMemberWorkerStore(EventsWorkerStore, CacheInvalidationWorkerStore):
  71. def __init__(
  72. self,
  73. database: DatabasePool,
  74. db_conn: LoggingDatabaseConnection,
  75. hs: "HomeServer",
  76. ):
  77. super().__init__(database, db_conn, hs)
  78. self._server_notices_mxid = hs.config.servernotices.server_notices_mxid
  79. if (
  80. self.hs.config.worker.run_background_tasks
  81. and self.hs.config.metrics.metrics_flags.known_servers
  82. ):
  83. self._known_servers_count = 1
  84. self.hs.get_clock().looping_call(
  85. self._count_known_servers,
  86. 60 * 1000,
  87. )
  88. self.hs.get_clock().call_later(
  89. 1,
  90. self._count_known_servers,
  91. )
  92. LaterGauge(
  93. "synapse_federation_known_servers",
  94. "",
  95. [],
  96. lambda: self._known_servers_count,
  97. )
  98. @wrap_as_background_process("_count_known_servers")
  99. async def _count_known_servers(self) -> int:
  100. """
  101. Count the servers that this server knows about.
  102. The statistic is stored on the class for the
  103. `synapse_federation_known_servers` LaterGauge to collect.
  104. """
  105. def _transact(txn: LoggingTransaction) -> int:
  106. if isinstance(self.database_engine, Sqlite3Engine):
  107. query = """
  108. SELECT COUNT(DISTINCT substr(out.user_id, pos+1))
  109. FROM (
  110. SELECT rm.user_id as user_id, instr(rm.user_id, ':')
  111. AS pos FROM room_memberships as rm
  112. INNER JOIN current_state_events as c ON rm.event_id = c.event_id
  113. WHERE c.type = 'm.room.member'
  114. ) as out
  115. """
  116. else:
  117. query = """
  118. SELECT COUNT(DISTINCT split_part(state_key, ':', 2))
  119. FROM current_state_events
  120. WHERE type = 'm.room.member' AND membership = 'join';
  121. """
  122. txn.execute(query)
  123. return list(txn)[0][0]
  124. count = await self.db_pool.runInteraction("get_known_servers", _transact)
  125. # We always know about ourselves, even if we have nothing in
  126. # room_memberships (for example, the server is new).
  127. self._known_servers_count = max([count, 1])
  128. return self._known_servers_count
  129. @cached(max_entries=100000, iterable=True)
  130. async def get_users_in_room(self, room_id: str) -> Sequence[str]:
  131. """Returns a list of users in the room.
  132. Will return inaccurate results for rooms with partial state, since the state for
  133. the forward extremities of those rooms will exclude most members. We may also
  134. calculate room state incorrectly for such rooms and believe that a member is or
  135. is not in the room when the opposite is true.
  136. Note: If you only care about users in the room local to the homeserver, use
  137. `get_local_users_in_room(...)` instead which will be more performant.
  138. """
  139. return await self.db_pool.simple_select_onecol(
  140. table="current_state_events",
  141. keyvalues={
  142. "type": EventTypes.Member,
  143. "room_id": room_id,
  144. "membership": Membership.JOIN,
  145. },
  146. retcol="state_key",
  147. desc="get_users_in_room",
  148. )
  149. def get_users_in_room_txn(self, txn: LoggingTransaction, room_id: str) -> List[str]:
  150. """Returns a list of users in the room."""
  151. return self.db_pool.simple_select_onecol_txn(
  152. txn,
  153. table="current_state_events",
  154. keyvalues={
  155. "type": EventTypes.Member,
  156. "room_id": room_id,
  157. "membership": Membership.JOIN,
  158. },
  159. retcol="state_key",
  160. )
  161. @cached()
  162. def get_user_in_room_with_profile(self, room_id: str, user_id: str) -> ProfileInfo:
  163. raise NotImplementedError()
  164. @cachedList(
  165. cached_method_name="get_user_in_room_with_profile", list_name="user_ids"
  166. )
  167. async def get_subset_users_in_room_with_profiles(
  168. self, room_id: str, user_ids: Collection[str]
  169. ) -> Mapping[str, ProfileInfo]:
  170. """Get a mapping from user ID to profile information for a list of users
  171. in a given room.
  172. The profile information comes directly from this room's `m.room.member`
  173. events, and so may be specific to this room rather than part of a user's
  174. global profile. To avoid privacy leaks, the profile data should only be
  175. revealed to users who are already in this room.
  176. Args:
  177. room_id: The ID of the room to retrieve the users of.
  178. user_ids: a list of users in the room to run the query for
  179. Returns:
  180. A mapping from user ID to ProfileInfo.
  181. """
  182. def _get_subset_users_in_room_with_profiles(
  183. txn: LoggingTransaction,
  184. ) -> Dict[str, ProfileInfo]:
  185. clause, ids = make_in_list_sql_clause(
  186. self.database_engine, "c.state_key", user_ids
  187. )
  188. sql = """
  189. SELECT state_key, display_name, avatar_url FROM room_memberships as m
  190. INNER JOIN current_state_events as c
  191. ON m.event_id = c.event_id
  192. AND m.room_id = c.room_id
  193. AND m.user_id = c.state_key
  194. WHERE c.type = 'm.room.member' AND c.room_id = ? AND m.membership = ? AND %s
  195. """ % (
  196. clause,
  197. )
  198. txn.execute(sql, (room_id, Membership.JOIN, *ids))
  199. return {r[0]: ProfileInfo(display_name=r[1], avatar_url=r[2]) for r in txn}
  200. return await self.db_pool.runInteraction(
  201. "get_subset_users_in_room_with_profiles",
  202. _get_subset_users_in_room_with_profiles,
  203. )
  204. @cached(max_entries=100000, iterable=True)
  205. async def get_users_in_room_with_profiles(
  206. self, room_id: str
  207. ) -> Mapping[str, ProfileInfo]:
  208. """Get a mapping from user ID to profile information for all users in a given room.
  209. The profile information comes directly from this room's `m.room.member`
  210. events, and so may be specific to this room rather than part of a user's
  211. global profile. To avoid privacy leaks, the profile data should only be
  212. revealed to users who are already in this room.
  213. Args:
  214. room_id: The ID of the room to retrieve the users of.
  215. Returns:
  216. A mapping from user ID to ProfileInfo.
  217. Preconditions:
  218. - There is full state available for the room (it is not partial-stated).
  219. """
  220. def _get_users_in_room_with_profiles(
  221. txn: LoggingTransaction,
  222. ) -> Dict[str, ProfileInfo]:
  223. sql = """
  224. SELECT state_key, display_name, avatar_url FROM room_memberships as m
  225. INNER JOIN current_state_events as c
  226. ON m.event_id = c.event_id
  227. AND m.room_id = c.room_id
  228. AND m.user_id = c.state_key
  229. WHERE c.type = 'm.room.member' AND c.room_id = ? AND m.membership = ?
  230. """
  231. txn.execute(sql, (room_id, Membership.JOIN))
  232. return {r[0]: ProfileInfo(display_name=r[1], avatar_url=r[2]) for r in txn}
  233. return await self.db_pool.runInteraction(
  234. "get_users_in_room_with_profiles",
  235. _get_users_in_room_with_profiles,
  236. )
  237. @cached(max_entries=100000) # type: ignore[synapse-@cached-mutable]
  238. async def get_room_summary(self, room_id: str) -> Mapping[str, MemberSummary]:
  239. """Get the details of a room roughly suitable for use by the room
  240. summary extension to /sync. Useful when lazy loading room members.
  241. Args:
  242. room_id: The room ID to query
  243. Returns:
  244. dict of membership states, pointing to a MemberSummary named tuple.
  245. """
  246. def _get_room_summary_txn(
  247. txn: LoggingTransaction,
  248. ) -> Dict[str, MemberSummary]:
  249. # first get counts.
  250. # We do this all in one transaction to keep the cache small.
  251. # FIXME: get rid of this when we have room_stats
  252. # Note, rejected events will have a null membership field, so
  253. # we we manually filter them out.
  254. sql = """
  255. SELECT count(*), membership FROM current_state_events
  256. WHERE type = 'm.room.member' AND room_id = ?
  257. AND membership IS NOT NULL
  258. GROUP BY membership
  259. """
  260. txn.execute(sql, (room_id,))
  261. res: Dict[str, MemberSummary] = {}
  262. for count, membership in txn:
  263. res.setdefault(membership, MemberSummary([], count))
  264. # we order by membership and then fairly arbitrarily by event_id so
  265. # heroes are consistent
  266. # Note, rejected events will have a null membership field, so
  267. # we we manually filter them out.
  268. sql = """
  269. SELECT state_key, membership, event_id
  270. FROM current_state_events
  271. WHERE type = 'm.room.member' AND room_id = ?
  272. AND membership IS NOT NULL
  273. ORDER BY
  274. CASE membership WHEN ? THEN 1 WHEN ? THEN 2 ELSE 3 END ASC,
  275. event_id ASC
  276. LIMIT ?
  277. """
  278. # 6 is 5 (number of heroes) plus 1, in case one of them is the calling user.
  279. txn.execute(sql, (room_id, Membership.JOIN, Membership.INVITE, 6))
  280. for user_id, membership, event_id in txn:
  281. summary = res[membership]
  282. # we will always have a summary for this membership type at this
  283. # point given the summary currently contains the counts.
  284. members = summary.members
  285. members.append((user_id, event_id))
  286. return res
  287. return await self.db_pool.runInteraction(
  288. "get_room_summary", _get_room_summary_txn
  289. )
  290. @cached()
  291. async def get_number_joined_users_in_room(self, room_id: str) -> int:
  292. return await self.db_pool.simple_select_one_onecol(
  293. table="current_state_events",
  294. keyvalues={"room_id": room_id, "membership": Membership.JOIN},
  295. retcol="COUNT(*)",
  296. desc="get_number_joined_users_in_room",
  297. )
  298. @cached()
  299. async def get_invited_rooms_for_local_user(
  300. self, user_id: str
  301. ) -> Sequence[RoomsForUser]:
  302. """Get all the rooms the *local* user is invited to.
  303. Args:
  304. user_id: The user ID.
  305. Returns:
  306. A list of RoomsForUser.
  307. """
  308. return await self.get_rooms_for_local_user_where_membership_is(
  309. user_id, [Membership.INVITE]
  310. )
  311. async def get_invite_for_local_user_in_room(
  312. self, user_id: str, room_id: str
  313. ) -> Optional[RoomsForUser]:
  314. """Gets the invite for the given *local* user and room.
  315. Args:
  316. user_id: The user ID to find the invite of.
  317. room_id: The room to user was invited to.
  318. Returns:
  319. Either a RoomsForUser or None if no invite was found.
  320. """
  321. invites = await self.get_invited_rooms_for_local_user(user_id)
  322. for invite in invites:
  323. if invite.room_id == room_id:
  324. return invite
  325. return None
  326. async def get_rooms_for_local_user_where_membership_is(
  327. self,
  328. user_id: str,
  329. membership_list: Collection[str],
  330. excluded_rooms: StrCollection = (),
  331. ) -> List[RoomsForUser]:
  332. """Get all the rooms for this *local* user where the membership for this user
  333. matches one in the membership list.
  334. Filters out forgotten rooms.
  335. Args:
  336. user_id: The user ID.
  337. membership_list: A list of synapse.api.constants.Membership
  338. values which the user must be in.
  339. excluded_rooms: A list of rooms to ignore.
  340. Returns:
  341. The RoomsForUser that the user matches the membership types.
  342. """
  343. if not membership_list:
  344. return []
  345. rooms = await self.db_pool.runInteraction(
  346. "get_rooms_for_local_user_where_membership_is",
  347. self._get_rooms_for_local_user_where_membership_is_txn,
  348. user_id,
  349. membership_list,
  350. )
  351. # Now we filter out forgotten and excluded rooms
  352. rooms_to_exclude: AbstractSet[str] = set()
  353. # Users can't forget joined/invited rooms, so we skip the check for such look ups.
  354. if any(m not in (Membership.JOIN, Membership.INVITE) for m in membership_list):
  355. rooms_to_exclude = await self.get_forgotten_rooms_for_user(user_id)
  356. if excluded_rooms is not None:
  357. # Take a copy to avoid mutating the in-cache set
  358. rooms_to_exclude = set(rooms_to_exclude)
  359. rooms_to_exclude.update(excluded_rooms)
  360. return [room for room in rooms if room.room_id not in rooms_to_exclude]
  361. def _get_rooms_for_local_user_where_membership_is_txn(
  362. self,
  363. txn: LoggingTransaction,
  364. user_id: str,
  365. membership_list: List[str],
  366. ) -> List[RoomsForUser]:
  367. """Get all the rooms for this *local* user where the membership for this user
  368. matches one in the membership list.
  369. Args:
  370. user_id: The user ID.
  371. membership_list: A list of synapse.api.constants.Membership
  372. values which the user must be in.
  373. Returns:
  374. The RoomsForUser that the user matches the membership types.
  375. """
  376. # Paranoia check.
  377. if not self.hs.is_mine_id(user_id):
  378. raise Exception(
  379. "Cannot call 'get_rooms_for_local_user_where_membership_is' on non-local user %r"
  380. % (user_id,),
  381. )
  382. clause, args = make_in_list_sql_clause(
  383. self.database_engine, "c.membership", membership_list
  384. )
  385. sql = """
  386. SELECT room_id, e.sender, c.membership, event_id, e.stream_ordering, r.room_version
  387. FROM local_current_membership AS c
  388. INNER JOIN events AS e USING (room_id, event_id)
  389. INNER JOIN rooms AS r USING (room_id)
  390. WHERE
  391. user_id = ?
  392. AND %s
  393. """ % (
  394. clause,
  395. )
  396. txn.execute(sql, (user_id, *args))
  397. results = [RoomsForUser(*r) for r in txn]
  398. return results
  399. @cached(iterable=True)
  400. async def get_local_users_in_room(self, room_id: str) -> Sequence[str]:
  401. """
  402. Retrieves a list of the current roommembers who are local to the server.
  403. """
  404. return await self.db_pool.simple_select_onecol(
  405. table="local_current_membership",
  406. keyvalues={"room_id": room_id, "membership": Membership.JOIN},
  407. retcol="user_id",
  408. desc="get_local_users_in_room",
  409. )
  410. async def check_local_user_in_room(self, user_id: str, room_id: str) -> bool:
  411. """
  412. Check whether a given local user is currently joined to the given room.
  413. Returns:
  414. A boolean indicating whether the user is currently joined to the room
  415. Raises:
  416. Exeption when called with a non-local user to this homeserver
  417. """
  418. if not self.hs.is_mine_id(user_id):
  419. raise Exception(
  420. "Cannot call 'check_local_user_in_room' on "
  421. "non-local user %s" % (user_id,),
  422. )
  423. (
  424. membership,
  425. member_event_id,
  426. ) = await self.get_local_current_membership_for_user_in_room(
  427. user_id=user_id,
  428. room_id=room_id,
  429. )
  430. return membership == Membership.JOIN
  431. async def is_server_notice_room(self, room_id: str) -> bool:
  432. """
  433. Determines whether the given room is a 'Server Notices' room, used for
  434. sending server notices to a user.
  435. This is determined by seeing whether the server notices user is present
  436. in the room.
  437. """
  438. if self._server_notices_mxid is None:
  439. return False
  440. is_server_notices_room = await self.check_local_user_in_room(
  441. user_id=self._server_notices_mxid, room_id=room_id
  442. )
  443. return is_server_notices_room
  444. async def get_local_current_membership_for_user_in_room(
  445. self, user_id: str, room_id: str
  446. ) -> Tuple[Optional[str], Optional[str]]:
  447. """Retrieve the current local membership state and event ID for a user in a room.
  448. Args:
  449. user_id: The ID of the user.
  450. room_id: The ID of the room.
  451. Returns:
  452. A tuple of (membership_type, event_id). Both will be None if a
  453. room_id/user_id pair is not found.
  454. """
  455. # Paranoia check.
  456. if not self.hs.is_mine_id(user_id):
  457. raise Exception(
  458. "Cannot call 'get_local_current_membership_for_user_in_room' on "
  459. "non-local user %s" % (user_id,),
  460. )
  461. results_dict = await self.db_pool.simple_select_one(
  462. "local_current_membership",
  463. {"room_id": room_id, "user_id": user_id},
  464. ("membership", "event_id"),
  465. allow_none=True,
  466. desc="get_local_current_membership_for_user_in_room",
  467. )
  468. if not results_dict:
  469. return None, None
  470. return results_dict.get("membership"), results_dict.get("event_id")
  471. @cached(max_entries=500000, iterable=True)
  472. async def get_rooms_for_user_with_stream_ordering(
  473. self, user_id: str
  474. ) -> FrozenSet[GetRoomsForUserWithStreamOrdering]:
  475. """Returns a set of room_ids the user is currently joined to.
  476. If a remote user only returns rooms this server is currently
  477. participating in.
  478. Args:
  479. user_id
  480. Returns:
  481. Returns the rooms the user is in currently, along with the stream
  482. ordering of the most recent join for that user and room, along with
  483. the room version of the room.
  484. """
  485. return await self.db_pool.runInteraction(
  486. "get_rooms_for_user_with_stream_ordering",
  487. self._get_rooms_for_user_with_stream_ordering_txn,
  488. user_id,
  489. )
  490. def _get_rooms_for_user_with_stream_ordering_txn(
  491. self, txn: LoggingTransaction, user_id: str
  492. ) -> FrozenSet[GetRoomsForUserWithStreamOrdering]:
  493. # We use `current_state_events` here and not `local_current_membership`
  494. # as a) this gets called with remote users and b) this only gets called
  495. # for rooms the server is participating in.
  496. sql = """
  497. SELECT room_id, e.instance_name, e.stream_ordering
  498. FROM current_state_events AS c
  499. INNER JOIN events AS e USING (room_id, event_id)
  500. WHERE
  501. c.type = 'm.room.member'
  502. AND c.state_key = ?
  503. AND c.membership = ?
  504. """
  505. txn.execute(sql, (user_id, Membership.JOIN))
  506. return frozenset(
  507. GetRoomsForUserWithStreamOrdering(
  508. room_id, PersistedEventPosition(instance, stream_id)
  509. )
  510. for room_id, instance, stream_id in txn
  511. )
  512. async def get_users_server_still_shares_room_with(
  513. self, user_ids: Collection[str]
  514. ) -> Set[str]:
  515. """Given a list of users return the set that the server still share a
  516. room with.
  517. """
  518. if not user_ids:
  519. return set()
  520. return await self.db_pool.runInteraction(
  521. "get_users_server_still_shares_room_with",
  522. self.get_users_server_still_shares_room_with_txn,
  523. user_ids,
  524. )
  525. def get_users_server_still_shares_room_with_txn(
  526. self,
  527. txn: LoggingTransaction,
  528. user_ids: Collection[str],
  529. ) -> Set[str]:
  530. if not user_ids:
  531. return set()
  532. sql = """
  533. SELECT state_key FROM current_state_events
  534. WHERE
  535. type = 'm.room.member'
  536. AND membership = 'join'
  537. AND %s
  538. GROUP BY state_key
  539. """
  540. clause, args = make_in_list_sql_clause(
  541. self.database_engine, "state_key", user_ids
  542. )
  543. txn.execute(sql % (clause,), args)
  544. return {row[0] for row in txn}
  545. @cached(max_entries=500000, iterable=True)
  546. async def get_rooms_for_user(self, user_id: str) -> FrozenSet[str]:
  547. """Returns a set of room_ids the user is currently joined to.
  548. If a remote user only returns rooms this server is currently
  549. participating in.
  550. """
  551. rooms = self.get_rooms_for_user_with_stream_ordering.cache.get_immediate(
  552. (user_id,),
  553. None,
  554. update_metrics=False,
  555. )
  556. if rooms:
  557. return frozenset(r.room_id for r in rooms)
  558. room_ids = await self.db_pool.simple_select_onecol(
  559. table="current_state_events",
  560. keyvalues={
  561. "type": EventTypes.Member,
  562. "membership": Membership.JOIN,
  563. "state_key": user_id,
  564. },
  565. retcol="room_id",
  566. desc="get_rooms_for_user",
  567. )
  568. return frozenset(room_ids)
  569. @cachedList(
  570. cached_method_name="get_rooms_for_user",
  571. list_name="user_ids",
  572. )
  573. async def _get_rooms_for_users(
  574. self, user_ids: Collection[str]
  575. ) -> Mapping[str, FrozenSet[str]]:
  576. """A batched version of `get_rooms_for_user`.
  577. Returns:
  578. Map from user_id to set of rooms that is currently in.
  579. """
  580. rows = await self.db_pool.simple_select_many_batch(
  581. table="current_state_events",
  582. column="state_key",
  583. iterable=user_ids,
  584. retcols=(
  585. "state_key",
  586. "room_id",
  587. ),
  588. keyvalues={
  589. "type": EventTypes.Member,
  590. "membership": Membership.JOIN,
  591. },
  592. desc="get_rooms_for_users",
  593. )
  594. user_rooms: Dict[str, Set[str]] = {user_id: set() for user_id in user_ids}
  595. for row in rows:
  596. user_rooms[row["state_key"]].add(row["room_id"])
  597. return {key: frozenset(rooms) for key, rooms in user_rooms.items()}
  598. async def get_rooms_for_users(
  599. self, user_ids: Collection[str]
  600. ) -> Dict[str, FrozenSet[str]]:
  601. """A batched wrapper around `_get_rooms_for_users`, to prevent locking
  602. other calls to `get_rooms_for_user` for large user lists.
  603. """
  604. all_user_rooms: Dict[str, FrozenSet[str]] = {}
  605. # 250 users is pretty arbitrary but the data can be quite large if users
  606. # are in many rooms.
  607. for batch_user_ids in batch_iter(user_ids, 250):
  608. all_user_rooms.update(await self._get_rooms_for_users(batch_user_ids))
  609. return all_user_rooms
  610. @cached(max_entries=10000)
  611. async def does_pair_of_users_share_a_room(
  612. self, user_id: str, other_user_id: str
  613. ) -> bool:
  614. raise NotImplementedError()
  615. @cachedList(
  616. cached_method_name="does_pair_of_users_share_a_room", list_name="other_user_ids"
  617. )
  618. async def _do_users_share_a_room(
  619. self, user_id: str, other_user_ids: Collection[str]
  620. ) -> Mapping[str, Optional[bool]]:
  621. """Return mapping from user ID to whether they share a room with the
  622. given user.
  623. Note: `None` and `False` are equivalent and mean they don't share a
  624. room.
  625. """
  626. def do_users_share_a_room_txn(
  627. txn: LoggingTransaction, user_ids: Collection[str]
  628. ) -> Dict[str, bool]:
  629. clause, args = make_in_list_sql_clause(
  630. self.database_engine, "state_key", user_ids
  631. )
  632. # This query works by fetching both the list of rooms for the target
  633. # user and the set of other users, and then checking if there is any
  634. # overlap.
  635. sql = f"""
  636. SELECT DISTINCT b.state_key
  637. FROM (
  638. SELECT room_id FROM current_state_events
  639. WHERE type = 'm.room.member' AND membership = 'join' AND state_key = ?
  640. ) AS a
  641. INNER JOIN (
  642. SELECT room_id, state_key FROM current_state_events
  643. WHERE type = 'm.room.member' AND membership = 'join' AND {clause}
  644. ) AS b using (room_id)
  645. """
  646. txn.execute(sql, (user_id, *args))
  647. return {u: True for u, in txn}
  648. to_return = {}
  649. for batch_user_ids in batch_iter(other_user_ids, 1000):
  650. res = await self.db_pool.runInteraction(
  651. "do_users_share_a_room", do_users_share_a_room_txn, batch_user_ids
  652. )
  653. to_return.update(res)
  654. return to_return
  655. async def do_users_share_a_room(
  656. self, user_id: str, other_user_ids: Collection[str]
  657. ) -> Set[str]:
  658. """Return the set of users who share a room with the first users"""
  659. user_dict = await self._do_users_share_a_room(user_id, other_user_ids)
  660. return {u for u, share_room in user_dict.items() if share_room}
  661. async def get_users_who_share_room_with_user(self, user_id: str) -> Set[str]:
  662. """Returns the set of users who share a room with `user_id`"""
  663. room_ids = await self.get_rooms_for_user(user_id)
  664. user_who_share_room: Set[str] = set()
  665. for room_id in room_ids:
  666. user_ids = await self.get_users_in_room(room_id)
  667. user_who_share_room.update(user_ids)
  668. return user_who_share_room
  669. @cached(cache_context=True, iterable=True)
  670. async def get_mutual_rooms_between_users(
  671. self, user_ids: FrozenSet[str], cache_context: _CacheContext
  672. ) -> FrozenSet[str]:
  673. """
  674. Returns the set of rooms that all users in `user_ids` share.
  675. Args:
  676. user_ids: A frozen set of all users to investigate and return
  677. overlapping joined rooms for.
  678. cache_context
  679. """
  680. shared_room_ids: Optional[FrozenSet[str]] = None
  681. for user_id in user_ids:
  682. room_ids = await self.get_rooms_for_user(
  683. user_id, on_invalidate=cache_context.invalidate
  684. )
  685. if shared_room_ids is not None:
  686. shared_room_ids &= room_ids
  687. else:
  688. shared_room_ids = room_ids
  689. return shared_room_ids or frozenset()
  690. async def get_joined_user_ids_from_state(
  691. self, room_id: str, state: StateMap[str]
  692. ) -> Set[str]:
  693. """
  694. For a given set of state IDs, get a set of user IDs in the room.
  695. This method checks the local event cache, before calling
  696. `_get_user_ids_from_membership_event_ids` for any uncached events.
  697. """
  698. with Measure(self._clock, "get_joined_user_ids_from_state"):
  699. users_in_room = set()
  700. member_event_ids = [
  701. e_id for key, e_id in state.items() if key[0] == EventTypes.Member
  702. ]
  703. # We check if we have any of the member event ids in the event cache
  704. # before we ask the DB
  705. # We don't update the event cache hit ratio as it completely throws off
  706. # the hit ratio counts. After all, we don't populate the cache if we
  707. # miss it here
  708. event_map = self._get_events_from_local_cache(
  709. member_event_ids, update_metrics=False
  710. )
  711. missing_member_event_ids = []
  712. for event_id in member_event_ids:
  713. ev_entry = event_map.get(event_id)
  714. if ev_entry and not ev_entry.event.rejected_reason:
  715. if ev_entry.event.membership == Membership.JOIN:
  716. users_in_room.add(ev_entry.event.state_key)
  717. else:
  718. missing_member_event_ids.append(event_id)
  719. if missing_member_event_ids:
  720. event_to_memberships = (
  721. await self._get_user_ids_from_membership_event_ids(
  722. missing_member_event_ids
  723. )
  724. )
  725. users_in_room.update(
  726. user_id for user_id in event_to_memberships.values() if user_id
  727. )
  728. return users_in_room
  729. @cached(
  730. max_entries=10000,
  731. # This name matches the old function that has been replaced - the cache name
  732. # is kept here to maintain backwards compatibility.
  733. name="_get_joined_profile_from_event_id",
  734. )
  735. def _get_user_id_from_membership_event_id(
  736. self, event_id: str
  737. ) -> Optional[Tuple[str, ProfileInfo]]:
  738. raise NotImplementedError()
  739. @cachedList(
  740. cached_method_name="_get_user_id_from_membership_event_id",
  741. list_name="event_ids",
  742. )
  743. async def _get_user_ids_from_membership_event_ids(
  744. self, event_ids: Iterable[str]
  745. ) -> Mapping[str, Optional[str]]:
  746. """For given set of member event_ids check if they point to a join
  747. event.
  748. Args:
  749. event_ids: The member event IDs to lookup
  750. Returns:
  751. Map from event ID to `user_id`, or None if event is not a join.
  752. """
  753. rows = await self.db_pool.simple_select_many_batch(
  754. table="room_memberships",
  755. column="event_id",
  756. iterable=event_ids,
  757. retcols=("user_id", "event_id"),
  758. keyvalues={"membership": Membership.JOIN},
  759. batch_size=1000,
  760. desc="_get_user_ids_from_membership_event_ids",
  761. )
  762. return {row["event_id"]: row["user_id"] for row in rows}
  763. @cached(max_entries=10000)
  764. async def is_host_joined(self, room_id: str, host: str) -> bool:
  765. return await self._check_host_room_membership(room_id, host, Membership.JOIN)
  766. @cached(max_entries=10000)
  767. async def is_host_invited(self, room_id: str, host: str) -> bool:
  768. return await self._check_host_room_membership(room_id, host, Membership.INVITE)
  769. async def _check_host_room_membership(
  770. self, room_id: str, host: str, membership: str
  771. ) -> bool:
  772. if "%" in host or "_" in host:
  773. raise Exception("Invalid host name")
  774. sql = """
  775. SELECT state_key FROM current_state_events
  776. WHERE membership = ?
  777. AND type = 'm.room.member'
  778. AND room_id = ?
  779. AND state_key LIKE ?
  780. LIMIT 1
  781. """
  782. # We do need to be careful to ensure that host doesn't have any wild cards
  783. # in it, but we checked above for known ones and we'll check below that
  784. # the returned user actually has the correct domain.
  785. like_clause = "%:" + host
  786. rows = await self.db_pool.execute(
  787. "is_host_joined", None, sql, membership, room_id, like_clause
  788. )
  789. if not rows:
  790. return False
  791. user_id = rows[0][0]
  792. if get_domain_from_id(user_id) != host:
  793. # This can only happen if the host name has something funky in it
  794. raise Exception("Invalid host name")
  795. return True
  796. @cached(iterable=True, max_entries=10000)
  797. async def get_current_hosts_in_room(self, room_id: str) -> AbstractSet[str]:
  798. """Get current hosts in room based on current state."""
  799. # First we check if we already have `get_users_in_room` in the cache, as
  800. # we can just calculate result from that
  801. users = self.get_users_in_room.cache.get_immediate(
  802. (room_id,), None, update_metrics=False
  803. )
  804. if users is not None:
  805. return {get_domain_from_id(u) for u in users}
  806. if isinstance(self.database_engine, Sqlite3Engine):
  807. # If we're using SQLite then let's just always use
  808. # `get_users_in_room` rather than funky SQL.
  809. users = await self.get_users_in_room(room_id)
  810. return {get_domain_from_id(u) for u in users}
  811. # For PostgreSQL we can use a regex to pull out the domains from the
  812. # joined users in `current_state_events` via regex.
  813. def get_current_hosts_in_room_txn(txn: LoggingTransaction) -> Set[str]:
  814. sql = """
  815. SELECT DISTINCT substring(state_key FROM '@[^:]*:(.*)$')
  816. FROM current_state_events
  817. WHERE
  818. type = 'm.room.member'
  819. AND membership = 'join'
  820. AND room_id = ?
  821. """
  822. txn.execute(sql, (room_id,))
  823. return {d for d, in txn}
  824. return await self.db_pool.runInteraction(
  825. "get_current_hosts_in_room", get_current_hosts_in_room_txn
  826. )
  827. @cached(iterable=True, max_entries=10000)
  828. async def get_current_hosts_in_room_ordered(self, room_id: str) -> Tuple[str, ...]:
  829. """
  830. Get current hosts in room based on current state.
  831. The heuristic of sorting by servers who have been in the room the
  832. longest is good because they're most likely to have anything we ask
  833. about.
  834. For SQLite the returned list is not ordered, as SQLite doesn't support
  835. the appropriate SQL.
  836. Uses `m.room.member`s in the room state at the current forward
  837. extremities to determine which hosts are in the room.
  838. Will return inaccurate results for rooms with partial state, since the
  839. state for the forward extremities of those rooms will exclude most
  840. members. We may also calculate room state incorrectly for such rooms and
  841. believe that a host is or is not in the room when the opposite is true.
  842. Returns:
  843. Returns a list of servers sorted by longest in the room first. (aka.
  844. sorted by join with the lowest depth first).
  845. """
  846. if isinstance(self.database_engine, Sqlite3Engine):
  847. # If we're using SQLite then let's just always use
  848. # `get_users_in_room` rather than funky SQL.
  849. domains = await self.get_current_hosts_in_room(room_id)
  850. return tuple(domains)
  851. # For PostgreSQL we can use a regex to pull out the domains from the
  852. # joined users in `current_state_events` via regex.
  853. def get_current_hosts_in_room_ordered_txn(
  854. txn: LoggingTransaction,
  855. ) -> Tuple[str, ...]:
  856. # Returns a list of servers currently joined in the room sorted by
  857. # longest in the room first (aka. with the lowest depth). The
  858. # heuristic of sorting by servers who have been in the room the
  859. # longest is good because they're most likely to have anything we
  860. # ask about.
  861. sql = """
  862. SELECT
  863. /* Match the domain part of the MXID */
  864. substring(c.state_key FROM '@[^:]*:(.*)$') as server_domain
  865. FROM current_state_events c
  866. /* Get the depth of the event from the events table */
  867. INNER JOIN events AS e USING (event_id)
  868. WHERE
  869. /* Find any join state events in the room */
  870. c.type = 'm.room.member'
  871. AND c.membership = 'join'
  872. AND c.room_id = ?
  873. /* Group all state events from the same domain into their own buckets (groups) */
  874. GROUP BY server_domain
  875. /* Sorted by lowest depth first */
  876. ORDER BY min(e.depth) ASC;
  877. """
  878. txn.execute(sql, (room_id,))
  879. # `server_domain` will be `NULL` for malformed MXIDs with no colons.
  880. return tuple(d for d, in txn if d is not None)
  881. return await self.db_pool.runInteraction(
  882. "get_current_hosts_in_room_ordered", get_current_hosts_in_room_ordered_txn
  883. )
  884. async def _get_approximate_current_memberships_in_room(
  885. self, room_id: str
  886. ) -> Mapping[str, Optional[str]]:
  887. """Build a map from event id to membership, for all events in the current state.
  888. The event ids of non-memberships events (e.g. `m.room.power_levels`) are present
  889. in the result, mapped to values of `None`.
  890. The result is approximate for partially-joined rooms. It is fully accurate
  891. for fully-joined rooms.
  892. """
  893. rows = await self.db_pool.simple_select_list(
  894. "current_state_events",
  895. keyvalues={"room_id": room_id},
  896. retcols=("event_id", "membership"),
  897. desc="has_completed_background_updates",
  898. )
  899. return {row["event_id"]: row["membership"] for row in rows}
  900. # TODO This returns a mutable object, which is generally confusing when using a cache.
  901. @cached(max_entries=10000) # type: ignore[synapse-@cached-mutable]
  902. def _get_joined_hosts_cache(self, room_id: str) -> "_JoinedHostsCache":
  903. return _JoinedHostsCache()
  904. @cached(num_args=2)
  905. async def did_forget(self, user_id: str, room_id: str) -> bool:
  906. """Returns whether user_id has elected to discard history for room_id.
  907. Returns False if they have since re-joined."""
  908. def f(txn: LoggingTransaction) -> int:
  909. sql = (
  910. "SELECT"
  911. " COUNT(*)"
  912. " FROM"
  913. " room_memberships"
  914. " WHERE"
  915. " user_id = ?"
  916. " AND"
  917. " room_id = ?"
  918. " AND"
  919. " forgotten = 0"
  920. )
  921. txn.execute(sql, (user_id, room_id))
  922. rows = txn.fetchall()
  923. return rows[0][0]
  924. count = await self.db_pool.runInteraction("did_forget_membership", f)
  925. return count == 0
  926. @cached()
  927. async def get_forgotten_rooms_for_user(self, user_id: str) -> AbstractSet[str]:
  928. """Gets all rooms the user has forgotten.
  929. Args:
  930. user_id: The user ID to query the rooms of.
  931. Returns:
  932. The forgotten rooms.
  933. """
  934. def _get_forgotten_rooms_for_user_txn(txn: LoggingTransaction) -> Set[str]:
  935. # This is a slightly convoluted query that first looks up all rooms
  936. # that the user has forgotten in the past, then rechecks that list
  937. # to see if any have subsequently been updated. This is done so that
  938. # we can use a partial index on `forgotten = 1` on the assumption
  939. # that few users will actually forget many rooms.
  940. #
  941. # Note that a room is considered "forgotten" if *all* membership
  942. # events for that user and room have the forgotten field set (as
  943. # when a user forgets a room we update all rows for that user and
  944. # room, not just the current one).
  945. sql = """
  946. SELECT room_id, (
  947. SELECT count(*) FROM room_memberships
  948. WHERE room_id = m.room_id AND user_id = m.user_id AND forgotten = 0
  949. ) AS count
  950. FROM room_memberships AS m
  951. WHERE user_id = ? AND forgotten = 1
  952. GROUP BY room_id, user_id;
  953. """
  954. txn.execute(sql, (user_id,))
  955. return {row[0] for row in txn if row[1] == 0}
  956. return await self.db_pool.runInteraction(
  957. "get_forgotten_rooms_for_user", _get_forgotten_rooms_for_user_txn
  958. )
  959. async def is_locally_forgotten_room(self, room_id: str) -> bool:
  960. """Returns whether all local users have forgotten this room_id.
  961. Args:
  962. room_id: The room ID to query.
  963. Returns:
  964. Whether the room is forgotten.
  965. """
  966. sql = """
  967. SELECT count(*) > 0 FROM local_current_membership
  968. INNER JOIN room_memberships USING (room_id, event_id)
  969. WHERE
  970. room_id = ?
  971. AND forgotten = 0;
  972. """
  973. rows = await self.db_pool.execute("is_forgotten_room", None, sql, room_id)
  974. # `count(*)` returns always an integer
  975. # If any rows still exist it means someone has not forgotten this room yet
  976. return not rows[0][0]
  977. async def get_rooms_user_has_been_in(self, user_id: str) -> Set[str]:
  978. """Get all rooms that the user has ever been in.
  979. Args:
  980. user_id: The user ID to get the rooms of.
  981. Returns:
  982. Set of room IDs.
  983. """
  984. room_ids = await self.db_pool.simple_select_onecol(
  985. table="room_memberships",
  986. keyvalues={"membership": Membership.JOIN, "user_id": user_id},
  987. retcol="room_id",
  988. desc="get_rooms_user_has_been_in",
  989. )
  990. return set(room_ids)
  991. @cached(max_entries=5000)
  992. async def _get_membership_from_event_id(
  993. self, member_event_id: str
  994. ) -> Optional[EventIdMembership]:
  995. raise NotImplementedError()
  996. @cachedList(
  997. cached_method_name="_get_membership_from_event_id", list_name="member_event_ids"
  998. )
  999. async def get_membership_from_event_ids(
  1000. self, member_event_ids: Iterable[str]
  1001. ) -> Mapping[str, Optional[EventIdMembership]]:
  1002. """Get user_id and membership of a set of event IDs.
  1003. Returns:
  1004. Mapping from event ID to `EventIdMembership` if the event is a
  1005. membership event, otherwise the value is None.
  1006. """
  1007. rows = await self.db_pool.simple_select_many_batch(
  1008. table="room_memberships",
  1009. column="event_id",
  1010. iterable=member_event_ids,
  1011. retcols=("user_id", "membership", "event_id"),
  1012. keyvalues={},
  1013. batch_size=500,
  1014. desc="get_membership_from_event_ids",
  1015. )
  1016. return {
  1017. row["event_id"]: EventIdMembership(
  1018. membership=row["membership"], user_id=row["user_id"]
  1019. )
  1020. for row in rows
  1021. }
  1022. async def is_local_host_in_room_ignoring_users(
  1023. self, room_id: str, ignore_users: Collection[str]
  1024. ) -> bool:
  1025. """Check if there are any local users, excluding those in the given
  1026. list, in the room.
  1027. """
  1028. clause, args = make_in_list_sql_clause(
  1029. self.database_engine, "user_id", ignore_users
  1030. )
  1031. sql = """
  1032. SELECT 1 FROM local_current_membership
  1033. WHERE
  1034. room_id = ? AND membership = ?
  1035. AND NOT (%s)
  1036. LIMIT 1
  1037. """ % (
  1038. clause,
  1039. )
  1040. def _is_local_host_in_room_ignoring_users_txn(
  1041. txn: LoggingTransaction,
  1042. ) -> bool:
  1043. txn.execute(sql, (room_id, Membership.JOIN, *args))
  1044. return bool(txn.fetchone())
  1045. return await self.db_pool.runInteraction(
  1046. "is_local_host_in_room_ignoring_users",
  1047. _is_local_host_in_room_ignoring_users_txn,
  1048. )
  1049. async def forget(self, user_id: str, room_id: str) -> None:
  1050. """Indicate that user_id wishes to discard history for room_id."""
  1051. def f(txn: LoggingTransaction) -> None:
  1052. self.db_pool.simple_update_txn(
  1053. txn,
  1054. table="room_memberships",
  1055. keyvalues={"user_id": user_id, "room_id": room_id},
  1056. updatevalues={"forgotten": 1},
  1057. )
  1058. self._invalidate_cache_and_stream(txn, self.did_forget, (user_id, room_id))
  1059. self._invalidate_cache_and_stream(
  1060. txn, self.get_forgotten_rooms_for_user, (user_id,)
  1061. )
  1062. await self.db_pool.runInteraction("forget_membership", f)
  1063. async def get_room_forgetter_stream_pos(self) -> int:
  1064. """Get the stream position of the background process to forget rooms when left
  1065. by users.
  1066. """
  1067. return await self.db_pool.simple_select_one_onecol(
  1068. table="room_forgetter_stream_pos",
  1069. keyvalues={},
  1070. retcol="stream_id",
  1071. desc="room_forgetter_stream_pos",
  1072. )
  1073. async def update_room_forgetter_stream_pos(self, stream_id: int) -> None:
  1074. """Update the stream position of the background process to forget rooms when
  1075. left by users.
  1076. Must only be used by the worker running the background process.
  1077. """
  1078. assert self.hs.config.worker.run_background_tasks
  1079. await self.db_pool.simple_update_one(
  1080. table="room_forgetter_stream_pos",
  1081. keyvalues={},
  1082. updatevalues={"stream_id": stream_id},
  1083. desc="room_forgetter_stream_pos",
  1084. )
  1085. class RoomMemberBackgroundUpdateStore(SQLBaseStore):
  1086. def __init__(
  1087. self,
  1088. database: DatabasePool,
  1089. db_conn: LoggingDatabaseConnection,
  1090. hs: "HomeServer",
  1091. ):
  1092. super().__init__(database, db_conn, hs)
  1093. self.db_pool.updates.register_background_update_handler(
  1094. _MEMBERSHIP_PROFILE_UPDATE_NAME, self._background_add_membership_profile
  1095. )
  1096. self.db_pool.updates.register_background_update_handler(
  1097. _CURRENT_STATE_MEMBERSHIP_UPDATE_NAME,
  1098. self._background_current_state_membership,
  1099. )
  1100. self.db_pool.updates.register_background_index_update(
  1101. "room_membership_forgotten_idx",
  1102. index_name="room_memberships_user_room_forgotten",
  1103. table="room_memberships",
  1104. columns=["user_id", "room_id"],
  1105. where_clause="forgotten = 1",
  1106. )
  1107. self.db_pool.updates.register_background_index_update(
  1108. "room_membership_user_room_index",
  1109. index_name="room_membership_user_room_idx",
  1110. table="room_memberships",
  1111. columns=["user_id", "room_id"],
  1112. )
  1113. async def _background_add_membership_profile(
  1114. self, progress: JsonDict, batch_size: int
  1115. ) -> int:
  1116. target_min_stream_id = progress.get(
  1117. "target_min_stream_id_inclusive", self._min_stream_order_on_start # type: ignore[attr-defined]
  1118. )
  1119. max_stream_id = progress.get(
  1120. "max_stream_id_exclusive", self._stream_order_on_start + 1 # type: ignore[attr-defined]
  1121. )
  1122. def add_membership_profile_txn(txn: LoggingTransaction) -> int:
  1123. sql = """
  1124. SELECT stream_ordering, event_id, events.room_id, event_json.json
  1125. FROM events
  1126. INNER JOIN event_json USING (event_id)
  1127. WHERE ? <= stream_ordering AND stream_ordering < ?
  1128. AND type = 'm.room.member'
  1129. ORDER BY stream_ordering DESC
  1130. LIMIT ?
  1131. """
  1132. txn.execute(sql, (target_min_stream_id, max_stream_id, batch_size))
  1133. rows = self.db_pool.cursor_to_dict(txn)
  1134. if not rows:
  1135. return 0
  1136. min_stream_id = rows[-1]["stream_ordering"]
  1137. to_update = []
  1138. for row in rows:
  1139. event_id = row["event_id"]
  1140. room_id = row["room_id"]
  1141. try:
  1142. event_json = db_to_json(row["json"])
  1143. content = event_json["content"]
  1144. except Exception:
  1145. continue
  1146. display_name = content.get("displayname", None)
  1147. avatar_url = content.get("avatar_url", None)
  1148. if display_name or avatar_url:
  1149. to_update.append((display_name, avatar_url, event_id, room_id))
  1150. to_update_sql = """
  1151. UPDATE room_memberships SET display_name = ?, avatar_url = ?
  1152. WHERE event_id = ? AND room_id = ?
  1153. """
  1154. txn.execute_batch(to_update_sql, to_update)
  1155. progress = {
  1156. "target_min_stream_id_inclusive": target_min_stream_id,
  1157. "max_stream_id_exclusive": min_stream_id,
  1158. }
  1159. self.db_pool.updates._background_update_progress_txn(
  1160. txn, _MEMBERSHIP_PROFILE_UPDATE_NAME, progress
  1161. )
  1162. return len(rows)
  1163. result = await self.db_pool.runInteraction(
  1164. _MEMBERSHIP_PROFILE_UPDATE_NAME, add_membership_profile_txn
  1165. )
  1166. if not result:
  1167. await self.db_pool.updates._end_background_update(
  1168. _MEMBERSHIP_PROFILE_UPDATE_NAME
  1169. )
  1170. return result
  1171. async def _background_current_state_membership(
  1172. self, progress: JsonDict, batch_size: int
  1173. ) -> int:
  1174. """Update the new membership column on current_state_events.
  1175. This works by iterating over all rooms in alphebetical order.
  1176. """
  1177. def _background_current_state_membership_txn(
  1178. txn: LoggingTransaction, last_processed_room: str
  1179. ) -> Tuple[int, bool]:
  1180. processed = 0
  1181. while processed < batch_size:
  1182. txn.execute(
  1183. """
  1184. SELECT MIN(room_id) FROM current_state_events WHERE room_id > ?
  1185. """,
  1186. (last_processed_room,),
  1187. )
  1188. row = txn.fetchone()
  1189. if not row or not row[0]:
  1190. return processed, True
  1191. (next_room,) = row
  1192. sql = """
  1193. UPDATE current_state_events
  1194. SET membership = (
  1195. SELECT membership FROM room_memberships
  1196. WHERE event_id = current_state_events.event_id
  1197. )
  1198. WHERE room_id = ?
  1199. """
  1200. txn.execute(sql, (next_room,))
  1201. processed += txn.rowcount
  1202. last_processed_room = next_room
  1203. self.db_pool.updates._background_update_progress_txn(
  1204. txn,
  1205. _CURRENT_STATE_MEMBERSHIP_UPDATE_NAME,
  1206. {"last_processed_room": last_processed_room},
  1207. )
  1208. return processed, False
  1209. # If we haven't got a last processed room then just use the empty
  1210. # string, which will compare before all room IDs correctly.
  1211. last_processed_room = progress.get("last_processed_room", "")
  1212. row_count, finished = await self.db_pool.runInteraction(
  1213. "_background_current_state_membership_update",
  1214. _background_current_state_membership_txn,
  1215. last_processed_room,
  1216. )
  1217. if finished:
  1218. await self.db_pool.updates._end_background_update(
  1219. _CURRENT_STATE_MEMBERSHIP_UPDATE_NAME
  1220. )
  1221. return row_count
  1222. class RoomMemberStore(
  1223. RoomMemberWorkerStore,
  1224. RoomMemberBackgroundUpdateStore,
  1225. CacheInvalidationWorkerStore,
  1226. ):
  1227. def __init__(
  1228. self,
  1229. database: DatabasePool,
  1230. db_conn: LoggingDatabaseConnection,
  1231. hs: "HomeServer",
  1232. ):
  1233. super().__init__(database, db_conn, hs)
  1234. def extract_heroes_from_room_summary(
  1235. details: Mapping[str, MemberSummary], me: str
  1236. ) -> List[str]:
  1237. """Determine the users that represent a room, from the perspective of the `me` user.
  1238. The rules which say which users we select are specified in the "Room Summary"
  1239. section of
  1240. https://spec.matrix.org/v1.4/client-server-api/#get_matrixclientv3sync
  1241. Returns a list (possibly empty) of heroes' mxids.
  1242. """
  1243. empty_ms = MemberSummary([], 0)
  1244. joined_user_ids = [
  1245. r[0] for r in details.get(Membership.JOIN, empty_ms).members if r[0] != me
  1246. ]
  1247. invited_user_ids = [
  1248. r[0] for r in details.get(Membership.INVITE, empty_ms).members if r[0] != me
  1249. ]
  1250. gone_user_ids = [
  1251. r[0] for r in details.get(Membership.LEAVE, empty_ms).members if r[0] != me
  1252. ] + [r[0] for r in details.get(Membership.BAN, empty_ms).members if r[0] != me]
  1253. # FIXME: order by stream ordering rather than as returned by SQL
  1254. if joined_user_ids or invited_user_ids:
  1255. return sorted(joined_user_ids + invited_user_ids)[0:5]
  1256. else:
  1257. return sorted(gone_user_ids)[0:5]
  1258. @attr.s(slots=True, auto_attribs=True)
  1259. class _JoinedHostsCache:
  1260. """The cached data used by the `_get_joined_hosts_cache`."""
  1261. # Dict of host to the set of their users in the room at the state group.
  1262. hosts_to_joined_users: Dict[str, Set[str]] = attr.Factory(dict)
  1263. # The state group `hosts_to_joined_users` is derived from. Will be an object
  1264. # if the instance is newly created or if the state is not based on a state
  1265. # group. (An object is used as a sentinel value to ensure that it never is
  1266. # equal to anything else).
  1267. state_group: Union[object, int] = attr.Factory(object)
  1268. def __len__(self) -> int:
  1269. return sum(len(v) for v in self.hosts_to_joined_users.values())