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.
 
 
 
 
 
 

996 lines
37 KiB

  1. # Copyright 2017 Vector Creations Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. import re
  16. from typing import (
  17. TYPE_CHECKING,
  18. Iterable,
  19. List,
  20. Mapping,
  21. Optional,
  22. Sequence,
  23. Set,
  24. Tuple,
  25. cast,
  26. )
  27. try:
  28. # Figure out if ICU support is available for searching users.
  29. import icu
  30. USE_ICU = True
  31. except ModuleNotFoundError:
  32. USE_ICU = False
  33. from typing_extensions import TypedDict
  34. from synapse.api.errors import StoreError
  35. from synapse.util.stringutils import non_null_str_or_none
  36. if TYPE_CHECKING:
  37. from synapse.server import HomeServer
  38. from synapse.api.constants import EventTypes, HistoryVisibility, JoinRules
  39. from synapse.storage.database import (
  40. DatabasePool,
  41. LoggingDatabaseConnection,
  42. LoggingTransaction,
  43. )
  44. from synapse.storage.databases.main.state import StateFilter
  45. from synapse.storage.databases.main.state_deltas import StateDeltasStore
  46. from synapse.storage.engines import PostgresEngine, Sqlite3Engine
  47. from synapse.types import (
  48. JsonDict,
  49. UserProfile,
  50. get_domain_from_id,
  51. get_localpart_from_id,
  52. )
  53. from synapse.util.caches.descriptors import cached
  54. logger = logging.getLogger(__name__)
  55. TEMP_TABLE = "_temp_populate_user_directory"
  56. class UserDirectoryBackgroundUpdateStore(StateDeltasStore):
  57. # How many records do we calculate before sending it to
  58. # add_users_who_share_private_rooms?
  59. SHARE_PRIVATE_WORKING_SET = 500
  60. def __init__(
  61. self,
  62. database: DatabasePool,
  63. db_conn: LoggingDatabaseConnection,
  64. hs: "HomeServer",
  65. ) -> None:
  66. super().__init__(database, db_conn, hs)
  67. self.server_name: str = hs.hostname
  68. self.db_pool.updates.register_background_update_handler(
  69. "populate_user_directory_createtables",
  70. self._populate_user_directory_createtables,
  71. )
  72. self.db_pool.updates.register_background_update_handler(
  73. "populate_user_directory_process_rooms",
  74. self._populate_user_directory_process_rooms,
  75. )
  76. self.db_pool.updates.register_background_update_handler(
  77. "populate_user_directory_process_users",
  78. self._populate_user_directory_process_users,
  79. )
  80. self.db_pool.updates.register_background_update_handler(
  81. "populate_user_directory_cleanup", self._populate_user_directory_cleanup
  82. )
  83. async def _populate_user_directory_createtables(
  84. self, progress: JsonDict, batch_size: int
  85. ) -> int:
  86. # Get all the rooms that we want to process.
  87. def _make_staging_area(txn: LoggingTransaction) -> None:
  88. sql = (
  89. "CREATE TABLE IF NOT EXISTS "
  90. + TEMP_TABLE
  91. + "_rooms(room_id TEXT NOT NULL, events BIGINT NOT NULL)"
  92. )
  93. txn.execute(sql)
  94. sql = (
  95. "CREATE TABLE IF NOT EXISTS "
  96. + TEMP_TABLE
  97. + "_position(position TEXT NOT NULL)"
  98. )
  99. txn.execute(sql)
  100. # Get rooms we want to process from the database
  101. sql = """
  102. SELECT room_id, count(*) FROM current_state_events
  103. GROUP BY room_id
  104. """
  105. txn.execute(sql)
  106. rooms = list(txn.fetchall())
  107. self.db_pool.simple_insert_many_txn(
  108. txn, TEMP_TABLE + "_rooms", keys=("room_id", "events"), values=rooms
  109. )
  110. del rooms
  111. sql = (
  112. "CREATE TABLE IF NOT EXISTS "
  113. + TEMP_TABLE
  114. + "_users(user_id TEXT NOT NULL)"
  115. )
  116. txn.execute(sql)
  117. txn.execute("SELECT name FROM users")
  118. users = list(txn.fetchall())
  119. self.db_pool.simple_insert_many_txn(
  120. txn, TEMP_TABLE + "_users", keys=("user_id",), values=users
  121. )
  122. new_pos = await self.get_max_stream_id_in_current_state_deltas()
  123. await self.db_pool.runInteraction(
  124. "populate_user_directory_temp_build", _make_staging_area
  125. )
  126. await self.db_pool.simple_insert(
  127. TEMP_TABLE + "_position", {"position": new_pos}
  128. )
  129. await self.db_pool.updates._end_background_update(
  130. "populate_user_directory_createtables"
  131. )
  132. return 1
  133. async def _populate_user_directory_cleanup(
  134. self,
  135. progress: JsonDict,
  136. batch_size: int,
  137. ) -> int:
  138. """
  139. Update the user directory stream position, then clean up the old tables.
  140. """
  141. position = await self.db_pool.simple_select_one_onecol(
  142. TEMP_TABLE + "_position", {}, "position"
  143. )
  144. await self.update_user_directory_stream_pos(position)
  145. def _delete_staging_area(txn: LoggingTransaction) -> None:
  146. txn.execute("DROP TABLE IF EXISTS " + TEMP_TABLE + "_rooms")
  147. txn.execute("DROP TABLE IF EXISTS " + TEMP_TABLE + "_users")
  148. txn.execute("DROP TABLE IF EXISTS " + TEMP_TABLE + "_position")
  149. await self.db_pool.runInteraction(
  150. "populate_user_directory_cleanup", _delete_staging_area
  151. )
  152. await self.db_pool.updates._end_background_update(
  153. "populate_user_directory_cleanup"
  154. )
  155. return 1
  156. async def _populate_user_directory_process_rooms(
  157. self, progress: JsonDict, batch_size: int
  158. ) -> int:
  159. """
  160. Rescan the state of all rooms so we can track
  161. - who's in a public room;
  162. - which local users share a private room with other users (local
  163. and remote); and
  164. - who should be in the user_directory.
  165. Args:
  166. progress
  167. batch_size: Maximum number of state events to process per cycle.
  168. Returns:
  169. number of events processed.
  170. """
  171. # If we don't have progress filed, delete everything.
  172. if not progress:
  173. await self.delete_all_from_user_dir()
  174. def _get_next_batch(
  175. txn: LoggingTransaction,
  176. ) -> Optional[Sequence[Tuple[str, int]]]:
  177. # Only fetch 250 rooms, so we don't fetch too many at once, even
  178. # if those 250 rooms have less than batch_size state events.
  179. sql = """
  180. SELECT room_id, events FROM %s
  181. ORDER BY events DESC
  182. LIMIT 250
  183. """ % (
  184. TEMP_TABLE + "_rooms",
  185. )
  186. txn.execute(sql)
  187. rooms_to_work_on = cast(List[Tuple[str, int]], txn.fetchall())
  188. if not rooms_to_work_on:
  189. return None
  190. # Get how many are left to process, so we can give status on how
  191. # far we are in processing
  192. txn.execute("SELECT COUNT(*) FROM " + TEMP_TABLE + "_rooms")
  193. result = txn.fetchone()
  194. assert result is not None
  195. progress["remaining"] = result[0]
  196. return rooms_to_work_on
  197. rooms_to_work_on = await self.db_pool.runInteraction(
  198. "populate_user_directory_temp_read", _get_next_batch
  199. )
  200. # No more rooms -- complete the transaction.
  201. if not rooms_to_work_on:
  202. await self.db_pool.updates._end_background_update(
  203. "populate_user_directory_process_rooms"
  204. )
  205. return 1
  206. logger.debug(
  207. "Processing the next %d rooms of %d remaining"
  208. % (len(rooms_to_work_on), progress["remaining"])
  209. )
  210. processed_event_count = 0
  211. for room_id, event_count in rooms_to_work_on:
  212. is_in_room = await self.is_host_joined(room_id, self.server_name) # type: ignore[attr-defined]
  213. if is_in_room:
  214. users_with_profile = await self.get_users_in_room_with_profiles(room_id) # type: ignore[attr-defined]
  215. # Throw away users excluded from the directory.
  216. users_with_profile = {
  217. user_id: profile
  218. for user_id, profile in users_with_profile.items()
  219. if not self.hs.is_mine_id(user_id)
  220. or await self.should_include_local_user_in_dir(user_id)
  221. }
  222. # Upsert a user_directory record for each remote user we see.
  223. for user_id, profile in users_with_profile.items():
  224. # Local users are processed separately in
  225. # `_populate_user_directory_users`; there we can read from
  226. # the `profiles` table to ensure we don't leak their per-room
  227. # profiles. It also means we write local users to this table
  228. # exactly once, rather than once for every room they're in.
  229. if self.hs.is_mine_id(user_id):
  230. continue
  231. # TODO `users_with_profile` above reads from the `user_directory`
  232. # table, meaning that `profile` is bespoke to this room.
  233. # and this leaks remote users' per-room profiles to the user directory.
  234. await self.update_profile_in_user_dir(
  235. user_id, profile.display_name, profile.avatar_url
  236. )
  237. # Now update the room sharing tables to include this room.
  238. is_public = await self.is_room_world_readable_or_publicly_joinable(
  239. room_id
  240. )
  241. if is_public:
  242. if users_with_profile:
  243. await self.add_users_in_public_rooms(
  244. room_id, users_with_profile.keys()
  245. )
  246. else:
  247. to_insert = set()
  248. for user_id in users_with_profile:
  249. # We want the set of pairs (L, M) where L and M are
  250. # in `users_with_profile` and L is local.
  251. # Do so by looking for the local user L first.
  252. if not self.hs.is_mine_id(user_id):
  253. continue
  254. for other_user_id in users_with_profile:
  255. if user_id == other_user_id:
  256. continue
  257. user_set = (user_id, other_user_id)
  258. to_insert.add(user_set)
  259. # If it gets too big, stop and write to the database
  260. # to prevent storing too much in RAM.
  261. if len(to_insert) >= self.SHARE_PRIVATE_WORKING_SET:
  262. await self.add_users_who_share_private_room(
  263. room_id, to_insert
  264. )
  265. to_insert.clear()
  266. if to_insert:
  267. await self.add_users_who_share_private_room(room_id, to_insert)
  268. to_insert.clear()
  269. # We've finished a room. Delete it from the table.
  270. await self.db_pool.simple_delete_one(
  271. TEMP_TABLE + "_rooms", {"room_id": room_id}
  272. )
  273. # Update the remaining counter.
  274. progress["remaining"] -= 1
  275. await self.db_pool.runInteraction(
  276. "populate_user_directory",
  277. self.db_pool.updates._background_update_progress_txn,
  278. "populate_user_directory_process_rooms",
  279. progress,
  280. )
  281. processed_event_count += event_count
  282. if processed_event_count > batch_size:
  283. # Don't process any more rooms, we've hit our batch size.
  284. return processed_event_count
  285. return processed_event_count
  286. async def _populate_user_directory_process_users(
  287. self, progress: JsonDict, batch_size: int
  288. ) -> int:
  289. """
  290. Add all local users to the user directory.
  291. """
  292. def _get_next_batch(txn: LoggingTransaction) -> Optional[List[str]]:
  293. sql = "SELECT user_id FROM %s LIMIT %s" % (
  294. TEMP_TABLE + "_users",
  295. str(batch_size),
  296. )
  297. txn.execute(sql)
  298. user_result = cast(List[Tuple[str]], txn.fetchall())
  299. if not user_result:
  300. return None
  301. users_to_work_on = [x[0] for x in user_result]
  302. # Get how many are left to process, so we can give status on how
  303. # far we are in processing
  304. sql = "SELECT COUNT(*) FROM " + TEMP_TABLE + "_users"
  305. txn.execute(sql)
  306. count_result = txn.fetchone()
  307. assert count_result is not None
  308. progress["remaining"] = count_result[0]
  309. return users_to_work_on
  310. users_to_work_on = await self.db_pool.runInteraction(
  311. "populate_user_directory_temp_read", _get_next_batch
  312. )
  313. # No more users -- complete the transaction.
  314. if not users_to_work_on:
  315. await self.db_pool.updates._end_background_update(
  316. "populate_user_directory_process_users"
  317. )
  318. return 1
  319. logger.debug(
  320. "Processing the next %d users of %d remaining"
  321. % (len(users_to_work_on), progress["remaining"])
  322. )
  323. for user_id in users_to_work_on:
  324. if await self.should_include_local_user_in_dir(user_id):
  325. profile = await self.get_profileinfo(get_localpart_from_id(user_id)) # type: ignore[attr-defined]
  326. await self.update_profile_in_user_dir(
  327. user_id, profile.display_name, profile.avatar_url
  328. )
  329. # We've finished processing a user. Delete it from the table.
  330. await self.db_pool.simple_delete_one(
  331. TEMP_TABLE + "_users", {"user_id": user_id}
  332. )
  333. # Update the remaining counter.
  334. progress["remaining"] -= 1
  335. await self.db_pool.runInteraction(
  336. "populate_user_directory",
  337. self.db_pool.updates._background_update_progress_txn,
  338. "populate_user_directory_process_users",
  339. progress,
  340. )
  341. return len(users_to_work_on)
  342. async def should_include_local_user_in_dir(self, user: str) -> bool:
  343. """Certain classes of local user are omitted from the user directory.
  344. Is this user one of them?
  345. """
  346. # We're opting to exclude the appservice sender (user defined by the
  347. # `sender_localpart` in the appservice registration) even though
  348. # technically it could be DM-able. In the future, this could potentially
  349. # be configurable per-appservice whether the appservice sender can be
  350. # contacted.
  351. if self.get_app_service_by_user_id(user) is not None: # type: ignore[attr-defined]
  352. return False
  353. # We're opting to exclude appservice users (anyone matching the user
  354. # namespace regex in the appservice registration) even though technically
  355. # they could be DM-able. In the future, this could potentially
  356. # be configurable per-appservice whether the appservice users can be
  357. # contacted.
  358. if self.get_if_app_services_interested_in_user(user): # type: ignore[attr-defined]
  359. # TODO we might want to make this configurable for each app service
  360. return False
  361. # Support users are for diagnostics and should not appear in the user directory.
  362. if await self.is_support_user(user): # type: ignore[attr-defined]
  363. return False
  364. # Deactivated users aren't contactable, so should not appear in the user directory.
  365. try:
  366. if await self.get_user_deactivated_status(user): # type: ignore[attr-defined]
  367. return False
  368. except StoreError:
  369. # No such user in the users table. No need to do this when calling
  370. # is_support_user---that returns False if the user is missing.
  371. return False
  372. return True
  373. async def is_room_world_readable_or_publicly_joinable(self, room_id: str) -> bool:
  374. """Check if the room is either world_readable or publically joinable"""
  375. # Create a state filter that only queries join and history state event
  376. types_to_filter = (
  377. (EventTypes.JoinRules, ""),
  378. (EventTypes.RoomHistoryVisibility, ""),
  379. )
  380. # Getting the partial state is fine, as we're not looking at membership
  381. # events.
  382. current_state_ids = await self.get_partial_filtered_current_state_ids( # type: ignore[attr-defined]
  383. room_id, StateFilter.from_types(types_to_filter)
  384. )
  385. join_rules_id = current_state_ids.get((EventTypes.JoinRules, ""))
  386. if join_rules_id:
  387. join_rule_ev = await self.get_event(join_rules_id, allow_none=True) # type: ignore[attr-defined]
  388. if join_rule_ev:
  389. if join_rule_ev.content.get("join_rule") == JoinRules.PUBLIC:
  390. return True
  391. hist_vis_id = current_state_ids.get((EventTypes.RoomHistoryVisibility, ""))
  392. if hist_vis_id:
  393. hist_vis_ev = await self.get_event(hist_vis_id, allow_none=True) # type: ignore[attr-defined]
  394. if hist_vis_ev:
  395. if (
  396. hist_vis_ev.content.get("history_visibility")
  397. == HistoryVisibility.WORLD_READABLE
  398. ):
  399. return True
  400. return False
  401. async def update_profile_in_user_dir(
  402. self, user_id: str, display_name: Optional[str], avatar_url: Optional[str]
  403. ) -> None:
  404. """
  405. Update or add a user's profile in the user directory.
  406. """
  407. # If the display name or avatar URL are unexpected types, replace with None.
  408. display_name = non_null_str_or_none(display_name)
  409. avatar_url = non_null_str_or_none(avatar_url)
  410. def _update_profile_in_user_dir_txn(txn: LoggingTransaction) -> None:
  411. self.db_pool.simple_upsert_txn(
  412. txn,
  413. table="user_directory",
  414. keyvalues={"user_id": user_id},
  415. values={"display_name": display_name, "avatar_url": avatar_url},
  416. )
  417. if isinstance(self.database_engine, PostgresEngine):
  418. # We weight the localpart most highly, then display name and finally
  419. # server name
  420. sql = """
  421. INSERT INTO user_directory_search(user_id, vector)
  422. VALUES (?,
  423. setweight(to_tsvector('simple', ?), 'A')
  424. || setweight(to_tsvector('simple', ?), 'D')
  425. || setweight(to_tsvector('simple', COALESCE(?, '')), 'B')
  426. ) ON CONFLICT (user_id) DO UPDATE SET vector=EXCLUDED.vector
  427. """
  428. txn.execute(
  429. sql,
  430. (
  431. user_id,
  432. get_localpart_from_id(user_id),
  433. get_domain_from_id(user_id),
  434. display_name,
  435. ),
  436. )
  437. elif isinstance(self.database_engine, Sqlite3Engine):
  438. value = "%s %s" % (user_id, display_name) if display_name else user_id
  439. self.db_pool.simple_upsert_txn(
  440. txn,
  441. table="user_directory_search",
  442. keyvalues={"user_id": user_id},
  443. values={"value": value},
  444. )
  445. else:
  446. # This should be unreachable.
  447. raise Exception("Unrecognized database engine")
  448. txn.call_after(self.get_user_in_directory.invalidate, (user_id,))
  449. await self.db_pool.runInteraction(
  450. "update_profile_in_user_dir", _update_profile_in_user_dir_txn
  451. )
  452. async def add_users_who_share_private_room(
  453. self, room_id: str, user_id_tuples: Iterable[Tuple[str, str]]
  454. ) -> None:
  455. """Insert entries into the users_who_share_private_rooms table. The first
  456. user should be a local user.
  457. Args:
  458. room_id
  459. user_id_tuples: iterable of 2-tuple of user IDs.
  460. """
  461. await self.db_pool.simple_upsert_many(
  462. table="users_who_share_private_rooms",
  463. key_names=["user_id", "other_user_id", "room_id"],
  464. key_values=[
  465. (user_id, other_user_id, room_id)
  466. for user_id, other_user_id in user_id_tuples
  467. ],
  468. value_names=(),
  469. value_values=(),
  470. desc="add_users_who_share_room",
  471. )
  472. async def add_users_in_public_rooms(
  473. self, room_id: str, user_ids: Iterable[str]
  474. ) -> None:
  475. """Insert entries into the users_in_public_rooms table.
  476. Args:
  477. room_id
  478. user_ids
  479. """
  480. await self.db_pool.simple_upsert_many(
  481. table="users_in_public_rooms",
  482. key_names=["user_id", "room_id"],
  483. key_values=[(user_id, room_id) for user_id in user_ids],
  484. value_names=(),
  485. value_values=(),
  486. desc="add_users_in_public_rooms",
  487. )
  488. async def delete_all_from_user_dir(self) -> None:
  489. """Delete the entire user directory"""
  490. def _delete_all_from_user_dir_txn(txn: LoggingTransaction) -> None:
  491. txn.execute("DELETE FROM user_directory")
  492. txn.execute("DELETE FROM user_directory_search")
  493. txn.execute("DELETE FROM users_in_public_rooms")
  494. txn.execute("DELETE FROM users_who_share_private_rooms")
  495. txn.call_after(self.get_user_in_directory.invalidate_all)
  496. await self.db_pool.runInteraction(
  497. "delete_all_from_user_dir", _delete_all_from_user_dir_txn
  498. )
  499. @cached()
  500. async def get_user_in_directory(self, user_id: str) -> Optional[Mapping[str, str]]:
  501. return await self.db_pool.simple_select_one(
  502. table="user_directory",
  503. keyvalues={"user_id": user_id},
  504. retcols=("display_name", "avatar_url"),
  505. allow_none=True,
  506. desc="get_user_in_directory",
  507. )
  508. async def update_user_directory_stream_pos(self, stream_id: Optional[int]) -> None:
  509. await self.db_pool.simple_update_one(
  510. table="user_directory_stream_pos",
  511. keyvalues={},
  512. updatevalues={"stream_id": stream_id},
  513. desc="update_user_directory_stream_pos",
  514. )
  515. class SearchResult(TypedDict):
  516. limited: bool
  517. results: List[UserProfile]
  518. class UserDirectoryStore(UserDirectoryBackgroundUpdateStore):
  519. # How many records do we calculate before sending it to
  520. # add_users_who_share_private_rooms?
  521. SHARE_PRIVATE_WORKING_SET = 500
  522. def __init__(
  523. self,
  524. database: DatabasePool,
  525. db_conn: LoggingDatabaseConnection,
  526. hs: "HomeServer",
  527. ) -> None:
  528. super().__init__(database, db_conn, hs)
  529. self._prefer_local_users_in_search = (
  530. hs.config.userdirectory.user_directory_search_prefer_local_users
  531. )
  532. self._server_name = hs.config.server.server_name
  533. async def remove_from_user_dir(self, user_id: str) -> None:
  534. def _remove_from_user_dir_txn(txn: LoggingTransaction) -> None:
  535. self.db_pool.simple_delete_txn(
  536. txn, table="user_directory", keyvalues={"user_id": user_id}
  537. )
  538. self.db_pool.simple_delete_txn(
  539. txn, table="user_directory_search", keyvalues={"user_id": user_id}
  540. )
  541. self.db_pool.simple_delete_txn(
  542. txn, table="users_in_public_rooms", keyvalues={"user_id": user_id}
  543. )
  544. self.db_pool.simple_delete_txn(
  545. txn,
  546. table="users_who_share_private_rooms",
  547. keyvalues={"user_id": user_id},
  548. )
  549. self.db_pool.simple_delete_txn(
  550. txn,
  551. table="users_who_share_private_rooms",
  552. keyvalues={"other_user_id": user_id},
  553. )
  554. txn.call_after(self.get_user_in_directory.invalidate, (user_id,))
  555. await self.db_pool.runInteraction(
  556. "remove_from_user_dir", _remove_from_user_dir_txn
  557. )
  558. async def get_users_in_dir_due_to_room(self, room_id: str) -> Set[str]:
  559. """Get all user_ids that are in the room directory because they're
  560. in the given room_id
  561. """
  562. user_ids_share_pub = await self.db_pool.simple_select_onecol(
  563. table="users_in_public_rooms",
  564. keyvalues={"room_id": room_id},
  565. retcol="user_id",
  566. desc="get_users_in_dir_due_to_room",
  567. )
  568. user_ids_share_priv = await self.db_pool.simple_select_onecol(
  569. table="users_who_share_private_rooms",
  570. keyvalues={"room_id": room_id},
  571. retcol="other_user_id",
  572. desc="get_users_in_dir_due_to_room",
  573. )
  574. user_ids = set(user_ids_share_pub)
  575. user_ids.update(user_ids_share_priv)
  576. return user_ids
  577. async def remove_user_who_share_room(self, user_id: str, room_id: str) -> None:
  578. """
  579. Deletes entries in the users_who_share_*_rooms table. The first
  580. user should be a local user.
  581. Args:
  582. user_id
  583. room_id
  584. """
  585. def _remove_user_who_share_room_txn(txn: LoggingTransaction) -> None:
  586. self.db_pool.simple_delete_txn(
  587. txn,
  588. table="users_who_share_private_rooms",
  589. keyvalues={"user_id": user_id, "room_id": room_id},
  590. )
  591. self.db_pool.simple_delete_txn(
  592. txn,
  593. table="users_who_share_private_rooms",
  594. keyvalues={"other_user_id": user_id, "room_id": room_id},
  595. )
  596. self.db_pool.simple_delete_txn(
  597. txn,
  598. table="users_in_public_rooms",
  599. keyvalues={"user_id": user_id, "room_id": room_id},
  600. )
  601. await self.db_pool.runInteraction(
  602. "remove_user_who_share_room", _remove_user_who_share_room_txn
  603. )
  604. async def get_user_dir_rooms_user_is_in(self, user_id: str) -> List[str]:
  605. """
  606. Returns the rooms that a user is in.
  607. Args:
  608. user_id: Must be a local user
  609. Returns:
  610. List of room IDs
  611. """
  612. rows = await self.db_pool.simple_select_onecol(
  613. table="users_who_share_private_rooms",
  614. keyvalues={"user_id": user_id},
  615. retcol="room_id",
  616. desc="get_rooms_user_is_in",
  617. )
  618. pub_rows = await self.db_pool.simple_select_onecol(
  619. table="users_in_public_rooms",
  620. keyvalues={"user_id": user_id},
  621. retcol="room_id",
  622. desc="get_rooms_user_is_in",
  623. )
  624. users = set(pub_rows)
  625. users.update(rows)
  626. return list(users)
  627. async def get_user_directory_stream_pos(self) -> Optional[int]:
  628. """
  629. Get the stream ID of the user directory stream.
  630. Returns:
  631. The stream token or None if the initial background update hasn't happened yet.
  632. """
  633. return await self.db_pool.simple_select_one_onecol(
  634. table="user_directory_stream_pos",
  635. keyvalues={},
  636. retcol="stream_id",
  637. desc="get_user_directory_stream_pos",
  638. )
  639. async def search_user_dir(
  640. self, user_id: str, search_term: str, limit: int
  641. ) -> SearchResult:
  642. """Searches for users in directory
  643. Returns:
  644. dict of the form::
  645. {
  646. "limited": <bool>, # whether there were more results or not
  647. "results": [ # Ordered by best match first
  648. {
  649. "user_id": <user_id>,
  650. "display_name": <display_name>,
  651. "avatar_url": <avatar_url>
  652. }
  653. ]
  654. }
  655. """
  656. if self.hs.config.userdirectory.user_directory_search_all_users:
  657. join_args = (user_id,)
  658. where_clause = "user_id != ?"
  659. else:
  660. join_args = (user_id,)
  661. where_clause = """
  662. (
  663. EXISTS (select 1 from users_in_public_rooms WHERE user_id = t.user_id)
  664. OR EXISTS (
  665. SELECT 1 FROM users_who_share_private_rooms
  666. WHERE user_id = ? AND other_user_id = t.user_id
  667. )
  668. )
  669. """
  670. # We allow manipulating the ranking algorithm by injecting statements
  671. # based on config options.
  672. additional_ordering_statements = []
  673. ordering_arguments: Tuple[str, ...] = ()
  674. if isinstance(self.database_engine, PostgresEngine):
  675. full_query, exact_query, prefix_query = _parse_query_postgres(search_term)
  676. # If enabled, this config option will rank local users higher than those on
  677. # remote instances.
  678. if self._prefer_local_users_in_search:
  679. # This statement checks whether a given user's user ID contains a server name
  680. # that matches the local server
  681. statement = "* (CASE WHEN user_id LIKE ? THEN 2.0 ELSE 1.0 END)"
  682. additional_ordering_statements.append(statement)
  683. ordering_arguments += ("%:" + self._server_name,)
  684. # We order by rank and then if they have profile info
  685. # The ranking algorithm is hand tweaked for "best" results. Broadly
  686. # the idea is we give a higher weight to exact matches.
  687. # The array of numbers are the weights for the various part of the
  688. # search: (domain, _, display name, localpart)
  689. sql = """
  690. SELECT d.user_id AS user_id, display_name, avatar_url
  691. FROM user_directory_search as t
  692. INNER JOIN user_directory AS d USING (user_id)
  693. WHERE
  694. %(where_clause)s
  695. AND vector @@ to_tsquery('simple', ?)
  696. ORDER BY
  697. (CASE WHEN d.user_id IS NOT NULL THEN 4.0 ELSE 1.0 END)
  698. * (CASE WHEN display_name IS NOT NULL THEN 1.2 ELSE 1.0 END)
  699. * (CASE WHEN avatar_url IS NOT NULL THEN 1.2 ELSE 1.0 END)
  700. * (
  701. 3 * ts_rank_cd(
  702. '{0.1, 0.1, 0.9, 1.0}',
  703. vector,
  704. to_tsquery('simple', ?),
  705. 8
  706. )
  707. + ts_rank_cd(
  708. '{0.1, 0.1, 0.9, 1.0}',
  709. vector,
  710. to_tsquery('simple', ?),
  711. 8
  712. )
  713. )
  714. %(order_case_statements)s
  715. DESC,
  716. display_name IS NULL,
  717. avatar_url IS NULL
  718. LIMIT ?
  719. """ % {
  720. "where_clause": where_clause,
  721. "order_case_statements": " ".join(additional_ordering_statements),
  722. }
  723. args = (
  724. join_args
  725. + (full_query, exact_query, prefix_query)
  726. + ordering_arguments
  727. + (limit + 1,)
  728. )
  729. elif isinstance(self.database_engine, Sqlite3Engine):
  730. search_query = _parse_query_sqlite(search_term)
  731. # If enabled, this config option will rank local users higher than those on
  732. # remote instances.
  733. if self._prefer_local_users_in_search:
  734. # This statement checks whether a given user's user ID contains a server name
  735. # that matches the local server
  736. #
  737. # Note that we need to include a comma at the end for valid SQL
  738. statement = "user_id LIKE ? DESC,"
  739. additional_ordering_statements.append(statement)
  740. ordering_arguments += ("%:" + self._server_name,)
  741. sql = """
  742. SELECT d.user_id AS user_id, display_name, avatar_url
  743. FROM user_directory_search as t
  744. INNER JOIN user_directory AS d USING (user_id)
  745. WHERE
  746. %(where_clause)s
  747. AND value MATCH ?
  748. ORDER BY
  749. rank(matchinfo(user_directory_search)) DESC,
  750. %(order_statements)s
  751. display_name IS NULL,
  752. avatar_url IS NULL
  753. LIMIT ?
  754. """ % {
  755. "where_clause": where_clause,
  756. "order_statements": " ".join(additional_ordering_statements),
  757. }
  758. args = join_args + (search_query,) + ordering_arguments + (limit + 1,)
  759. else:
  760. # This should be unreachable.
  761. raise Exception("Unrecognized database engine")
  762. results = cast(
  763. List[UserProfile],
  764. await self.db_pool.execute(
  765. "search_user_dir", self.db_pool.cursor_to_dict, sql, *args
  766. ),
  767. )
  768. limited = len(results) > limit
  769. return {"limited": limited, "results": results[0:limit]}
  770. def _parse_query_sqlite(search_term: str) -> str:
  771. """Takes a plain unicode string from the user and converts it into a form
  772. that can be passed to database.
  773. We use this so that we can add prefix matching, which isn't something
  774. that is supported by default.
  775. We specifically add both a prefix and non prefix matching term so that
  776. exact matches get ranked higher.
  777. """
  778. # Pull out the individual words, discarding any non-word characters.
  779. results = _parse_words(search_term)
  780. return " & ".join("(%s* OR %s)" % (result, result) for result in results)
  781. def _parse_query_postgres(search_term: str) -> Tuple[str, str, str]:
  782. """Takes a plain unicode string from the user and converts it into a form
  783. that can be passed to database.
  784. We use this so that we can add prefix matching, which isn't something
  785. that is supported by default.
  786. """
  787. escaped_words = []
  788. for word in _parse_words(search_term):
  789. # Postgres tsvector and tsquery quoting rules:
  790. # words potentially containing punctuation should be quoted
  791. # and then existing quotes and backslashes should be doubled
  792. # See: https://www.postgresql.org/docs/current/datatype-textsearch.html#DATATYPE-TSQUERY
  793. quoted_word = word.replace("'", "''").replace("\\", "\\\\")
  794. escaped_words.append(f"'{quoted_word}'")
  795. both = " & ".join("(%s:* | %s)" % (word, word) for word in escaped_words)
  796. exact = " & ".join("%s" % (word,) for word in escaped_words)
  797. prefix = " & ".join("%s:*" % (word,) for word in escaped_words)
  798. return both, exact, prefix
  799. def _parse_words(search_term: str) -> List[str]:
  800. """Split the provided search string into a list of its words.
  801. If support for ICU (International Components for Unicode) is available, use it.
  802. Otherwise, fall back to using a regex to detect word boundaries. This latter
  803. solution works well enough for most latin-based languages, but doesn't work as well
  804. with other languages.
  805. Args:
  806. search_term: The search string.
  807. Returns:
  808. A list of the words in the search string.
  809. """
  810. if USE_ICU:
  811. return _parse_words_with_icu(search_term)
  812. return _parse_words_with_regex(search_term)
  813. def _parse_words_with_regex(search_term: str) -> List[str]:
  814. """
  815. Break down search term into words, when we don't have ICU available.
  816. See: `_parse_words`
  817. """
  818. return re.findall(r"([\w\-]+)", search_term, re.UNICODE)
  819. def _parse_words_with_icu(search_term: str) -> List[str]:
  820. """Break down the provided search string into its individual words using ICU
  821. (International Components for Unicode).
  822. Args:
  823. search_term: The search string.
  824. Returns:
  825. A list of the words in the search string.
  826. """
  827. results = []
  828. breaker = icu.BreakIterator.createWordInstance(icu.Locale.getDefault())
  829. breaker.setText(search_term)
  830. i = 0
  831. while True:
  832. j = breaker.nextBoundary()
  833. if j < 0:
  834. break
  835. result = search_term[i:j]
  836. # libicu considers spaces and punctuation between words as words, but we don't
  837. # want to include those in results as they would result in syntax errors in SQL
  838. # queries (e.g. "foo bar" would result in the search query including "foo & &
  839. # bar").
  840. if len(re.findall(r"([\w\-]+)", result, re.UNICODE)):
  841. results.append(result)
  842. i = j
  843. return results