roommember.py 58 KB

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