user_directory.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. from typing import TYPE_CHECKING, Any, Dict, List, Optional, Set, Tuple
  16. import synapse.metrics
  17. from synapse.api.constants import EventTypes, HistoryVisibility, JoinRules, Membership
  18. from synapse.handlers.state_deltas import MatchChange, StateDeltasHandler
  19. from synapse.metrics.background_process_metrics import run_as_background_process
  20. from synapse.storage.databases.main.user_directory import SearchResult
  21. from synapse.storage.roommember import ProfileInfo
  22. from synapse.util.metrics import Measure
  23. if TYPE_CHECKING:
  24. from synapse.server import HomeServer
  25. logger = logging.getLogger(__name__)
  26. class UserDirectoryHandler(StateDeltasHandler):
  27. """Handles queries and updates for the user_directory.
  28. N.B.: ASSUMES IT IS THE ONLY THING THAT MODIFIES THE USER DIRECTORY
  29. When a local user searches the user_directory, we report two kinds of users:
  30. - users this server can see are joined to a world_readable or publicly
  31. joinable room, and
  32. - users belonging to a private room shared by that local user.
  33. The two cases are tracked separately in the `users_in_public_rooms` and
  34. `users_who_share_private_rooms` tables. Both kinds of users have their
  35. username and avatar tracked in a `user_directory` table.
  36. This handler has three responsibilities:
  37. 1. Forwarding requests to `/user_directory/search` to the UserDirectoryStore.
  38. 2. Providing hooks for the application to call when local users are added,
  39. removed, or have their profile changed.
  40. 3. Listening for room state changes that indicate remote users have
  41. joined or left a room, or that their profile has changed.
  42. """
  43. def __init__(self, hs: "HomeServer"):
  44. super().__init__(hs)
  45. self.store = hs.get_datastores().main
  46. self._storage_controllers = hs.get_storage_controllers()
  47. self.server_name = hs.hostname
  48. self.clock = hs.get_clock()
  49. self.notifier = hs.get_notifier()
  50. self.is_mine_id = hs.is_mine_id
  51. self.update_user_directory = hs.config.worker.should_update_user_directory
  52. self.search_all_users = hs.config.userdirectory.user_directory_search_all_users
  53. self.spam_checker = hs.get_spam_checker()
  54. # The current position in the current_state_delta stream
  55. self.pos: Optional[int] = None
  56. # Guard to ensure we only process deltas one at a time
  57. self._is_processing = False
  58. if self.update_user_directory:
  59. self.notifier.add_replication_callback(self.notify_new_event)
  60. # We kick this off so that we don't have to wait for a change before
  61. # we start populating the user directory
  62. self.clock.call_later(0, self.notify_new_event)
  63. async def search_users(
  64. self, user_id: str, search_term: str, limit: int
  65. ) -> SearchResult:
  66. """Searches for users in directory
  67. Returns:
  68. dict of the form::
  69. {
  70. "limited": <bool>, # whether there were more results or not
  71. "results": [ # Ordered by best match first
  72. {
  73. "user_id": <user_id>,
  74. "display_name": <display_name>,
  75. "avatar_url": <avatar_url>
  76. }
  77. ]
  78. }
  79. """
  80. results = await self.store.search_user_dir(user_id, search_term, limit)
  81. # Remove any spammy users from the results.
  82. non_spammy_users = []
  83. for user in results["results"]:
  84. if not await self.spam_checker.check_username_for_spam(user):
  85. non_spammy_users.append(user)
  86. results["results"] = non_spammy_users
  87. return results
  88. def notify_new_event(self) -> None:
  89. """Called when there may be more deltas to process"""
  90. if not self.update_user_directory:
  91. return
  92. if self._is_processing:
  93. return
  94. async def process() -> None:
  95. try:
  96. await self._unsafe_process()
  97. finally:
  98. self._is_processing = False
  99. self._is_processing = True
  100. run_as_background_process("user_directory.notify_new_event", process)
  101. async def handle_local_profile_change(
  102. self, user_id: str, profile: ProfileInfo
  103. ) -> None:
  104. """Called to update index of our local user profiles when they change
  105. irrespective of any rooms the user may be in.
  106. """
  107. # FIXME(#3714): We should probably do this in the same worker as all
  108. # the other changes.
  109. if await self.store.should_include_local_user_in_dir(user_id):
  110. await self.store.update_profile_in_user_dir(
  111. user_id, profile.display_name, profile.avatar_url
  112. )
  113. async def handle_local_user_deactivated(self, user_id: str) -> None:
  114. """Called when a user ID is deactivated"""
  115. # FIXME(#3714): We should probably do this in the same worker as all
  116. # the other changes.
  117. await self.store.remove_from_user_dir(user_id)
  118. async def _unsafe_process(self) -> None:
  119. # If self.pos is None then means we haven't fetched it from DB
  120. if self.pos is None:
  121. self.pos = await self.store.get_user_directory_stream_pos()
  122. # If still None then the initial background update hasn't happened yet.
  123. if self.pos is None:
  124. return None
  125. room_max_stream_ordering = self.store.get_room_max_stream_ordering()
  126. if self.pos > room_max_stream_ordering:
  127. # apparently, we've processed more events than exist in the database!
  128. # this can happen if events are removed with history purge or similar.
  129. logger.warning(
  130. "Event stream ordering appears to have gone backwards (%i -> %i): "
  131. "rewinding user directory processor",
  132. self.pos,
  133. room_max_stream_ordering,
  134. )
  135. self.pos = room_max_stream_ordering
  136. # Loop round handling deltas until we're up to date
  137. while True:
  138. with Measure(self.clock, "user_dir_delta"):
  139. room_max_stream_ordering = self.store.get_room_max_stream_ordering()
  140. if self.pos == room_max_stream_ordering:
  141. return
  142. logger.debug(
  143. "Processing user stats %s->%s", self.pos, room_max_stream_ordering
  144. )
  145. (
  146. max_pos,
  147. deltas,
  148. ) = await self._storage_controllers.state.get_current_state_deltas(
  149. self.pos, room_max_stream_ordering
  150. )
  151. logger.debug("Handling %d state deltas", len(deltas))
  152. await self._handle_deltas(deltas)
  153. self.pos = max_pos
  154. # Expose current event processing position to prometheus
  155. synapse.metrics.event_processing_positions.labels("user_dir").set(
  156. max_pos
  157. )
  158. await self.store.update_user_directory_stream_pos(max_pos)
  159. async def _handle_deltas(self, deltas: List[Dict[str, Any]]) -> None:
  160. """Called with the state deltas to process"""
  161. for delta in deltas:
  162. typ = delta["type"]
  163. state_key = delta["state_key"]
  164. room_id = delta["room_id"]
  165. event_id = delta["event_id"]
  166. prev_event_id = delta["prev_event_id"]
  167. logger.debug("Handling: %r %r, %s", typ, state_key, event_id)
  168. # For join rule and visibility changes we need to check if the room
  169. # may have become public or not and add/remove the users in said room
  170. if typ in (EventTypes.RoomHistoryVisibility, EventTypes.JoinRules):
  171. await self._handle_room_publicity_change(
  172. room_id, prev_event_id, event_id, typ
  173. )
  174. elif typ == EventTypes.Member:
  175. await self._handle_room_membership_event(
  176. room_id,
  177. prev_event_id,
  178. event_id,
  179. state_key,
  180. )
  181. else:
  182. logger.debug("Ignoring irrelevant type: %r", typ)
  183. async def _handle_room_publicity_change(
  184. self,
  185. room_id: str,
  186. prev_event_id: Optional[str],
  187. event_id: Optional[str],
  188. typ: str,
  189. ) -> None:
  190. """Handle a room having potentially changed from/to world_readable/publicly
  191. joinable.
  192. Args:
  193. room_id: The ID of the room which changed.
  194. prev_event_id: The previous event before the state change
  195. event_id: The new event after the state change
  196. typ: Type of the event
  197. """
  198. logger.debug("Handling change for %s: %s", typ, room_id)
  199. if typ == EventTypes.RoomHistoryVisibility:
  200. publicness = await self._get_key_change(
  201. prev_event_id,
  202. event_id,
  203. key_name="history_visibility",
  204. public_value=HistoryVisibility.WORLD_READABLE,
  205. )
  206. elif typ == EventTypes.JoinRules:
  207. publicness = await self._get_key_change(
  208. prev_event_id,
  209. event_id,
  210. key_name="join_rule",
  211. public_value=JoinRules.PUBLIC,
  212. )
  213. else:
  214. raise Exception("Invalid event type")
  215. if publicness is MatchChange.no_change:
  216. logger.debug("No change")
  217. return
  218. # There's been a change to or from being world readable.
  219. is_public = await self.store.is_room_world_readable_or_publicly_joinable(
  220. room_id
  221. )
  222. logger.debug("Publicness change: %r, is_public: %r", publicness, is_public)
  223. if publicness is MatchChange.now_true and not is_public:
  224. # If we became world readable but room isn't currently public then
  225. # we ignore the change
  226. return
  227. elif publicness is MatchChange.now_false and is_public:
  228. # If we stopped being world readable but are still public,
  229. # ignore the change
  230. return
  231. users_in_room = await self.store.get_users_in_room(room_id)
  232. # Remove every user from the sharing tables for that room.
  233. for user_id in users_in_room:
  234. await self.store.remove_user_who_share_room(user_id, room_id)
  235. # Then, re-add all remote users and some local users to the tables.
  236. # NOTE: this is not the most efficient method, as _track_user_joined_room sets
  237. # up local_user -> other_user and other_user_whos_local -> local_user,
  238. # which when ran over an entire room, will result in the same values
  239. # being added multiple times. The batching upserts shouldn't make this
  240. # too bad, though.
  241. for user_id in users_in_room:
  242. if not self.is_mine_id(
  243. user_id
  244. ) or await self.store.should_include_local_user_in_dir(user_id):
  245. await self._track_user_joined_room(room_id, user_id)
  246. async def _handle_room_membership_event(
  247. self,
  248. room_id: str,
  249. prev_event_id: str,
  250. event_id: str,
  251. state_key: str,
  252. ) -> None:
  253. """Process a single room membershp event.
  254. We have to do two things:
  255. 1. Update the room-sharing tables.
  256. This applies to remote users and non-excluded local users.
  257. 2. Update the user_directory and user_directory_search tables.
  258. This applies to remote users only, because we only become aware of
  259. the (and any profile changes) by listening to these events.
  260. The rest of the application knows exactly when local users are
  261. created or their profile changed---it will directly call methods
  262. on this class.
  263. """
  264. joined = await self._get_key_change(
  265. prev_event_id,
  266. event_id,
  267. key_name="membership",
  268. public_value=Membership.JOIN,
  269. )
  270. # Both cases ignore excluded local users, so start by discarding them.
  271. is_remote = not self.is_mine_id(state_key)
  272. if not is_remote and not await self.store.should_include_local_user_in_dir(
  273. state_key
  274. ):
  275. return
  276. if joined is MatchChange.now_false:
  277. # Need to check if the server left the room entirely, if so
  278. # we might need to remove all the users in that room
  279. is_in_room = await self.store.is_host_joined(room_id, self.server_name)
  280. if not is_in_room:
  281. logger.debug("Server left room: %r", room_id)
  282. # Fetch all the users that we marked as being in user
  283. # directory due to being in the room and then check if
  284. # need to remove those users or not
  285. user_ids = await self.store.get_users_in_dir_due_to_room(room_id)
  286. for user_id in user_ids:
  287. await self._handle_remove_user(room_id, user_id)
  288. else:
  289. logger.debug("Server is still in room: %r", room_id)
  290. await self._handle_remove_user(room_id, state_key)
  291. elif joined is MatchChange.no_change:
  292. # Handle any profile changes for remote users.
  293. # (For local users the rest of the application calls
  294. # `handle_local_profile_change`.)
  295. if is_remote:
  296. await self._handle_possible_remote_profile_change(
  297. state_key, room_id, prev_event_id, event_id
  298. )
  299. elif joined is MatchChange.now_true: # The user joined
  300. # This may be the first time we've seen a remote user. If
  301. # so, ensure we have a directory entry for them. (For local users,
  302. # the rest of the application calls `handle_local_profile_change`.)
  303. if is_remote:
  304. await self._upsert_directory_entry_for_remote_user(state_key, event_id)
  305. await self._track_user_joined_room(room_id, state_key)
  306. async def _upsert_directory_entry_for_remote_user(
  307. self, user_id: str, event_id: str
  308. ) -> None:
  309. """A remote user has just joined a room. Ensure they have an entry in
  310. the user directory. The caller is responsible for making sure they're
  311. remote.
  312. """
  313. event = await self.store.get_event(event_id, allow_none=True)
  314. # It isn't expected for this event to not exist, but we
  315. # don't want the entire background process to break.
  316. if event is None:
  317. return
  318. logger.debug("Adding new user to dir, %r", user_id)
  319. await self.store.update_profile_in_user_dir(
  320. user_id, event.content.get("displayname"), event.content.get("avatar_url")
  321. )
  322. async def _track_user_joined_room(self, room_id: str, joining_user_id: str) -> None:
  323. """Someone's just joined a room. Update `users_in_public_rooms` or
  324. `users_who_share_private_rooms` as appropriate.
  325. The caller is responsible for ensuring that the given user should be
  326. included in the user directory.
  327. """
  328. is_public = await self.store.is_room_world_readable_or_publicly_joinable(
  329. room_id
  330. )
  331. if is_public:
  332. await self.store.add_users_in_public_rooms(room_id, (joining_user_id,))
  333. else:
  334. users_in_room = await self.store.get_users_in_room(room_id)
  335. other_users_in_room = [
  336. other
  337. for other in users_in_room
  338. if other != joining_user_id
  339. and (
  340. # We can't apply any special rules to remote users so
  341. # they're always included
  342. not self.is_mine_id(other)
  343. # Check the special rules whether the local user should be
  344. # included in the user directory
  345. or await self.store.should_include_local_user_in_dir(other)
  346. )
  347. ]
  348. updates_to_users_who_share_rooms: Set[Tuple[str, str]] = set()
  349. # First, if the joining user is our local user then we need an
  350. # update for every other user in the room.
  351. if self.is_mine_id(joining_user_id):
  352. for other_user_id in other_users_in_room:
  353. updates_to_users_who_share_rooms.add(
  354. (joining_user_id, other_user_id)
  355. )
  356. # Next, we need an update for every other local user in the room
  357. # that they now share a room with the joining user.
  358. for other_user_id in other_users_in_room:
  359. if self.is_mine_id(other_user_id):
  360. updates_to_users_who_share_rooms.add(
  361. (other_user_id, joining_user_id)
  362. )
  363. if updates_to_users_who_share_rooms:
  364. await self.store.add_users_who_share_private_room(
  365. room_id, updates_to_users_who_share_rooms
  366. )
  367. async def _handle_remove_user(self, room_id: str, user_id: str) -> None:
  368. """Called when when someone leaves a room. The user may be local or remote.
  369. (If the person who left was the last local user in this room, the server
  370. is no longer in the room. We call this function to forget that the remaining
  371. remote users are in the room, even though they haven't left. So the name is
  372. a little misleading!)
  373. Args:
  374. room_id: The room ID that user left or stopped being public that
  375. user_id
  376. """
  377. logger.debug("Removing user %r from room %r", user_id, room_id)
  378. # Remove user from sharing tables
  379. await self.store.remove_user_who_share_room(user_id, room_id)
  380. # Additionally, if they're a remote user and we're no longer joined
  381. # to any rooms they're in, remove them from the user directory.
  382. if not self.is_mine_id(user_id):
  383. rooms_user_is_in = await self.store.get_user_dir_rooms_user_is_in(user_id)
  384. if len(rooms_user_is_in) == 0:
  385. logger.debug("Removing user %r from directory", user_id)
  386. await self.store.remove_from_user_dir(user_id)
  387. async def _handle_possible_remote_profile_change(
  388. self,
  389. user_id: str,
  390. room_id: str,
  391. prev_event_id: Optional[str],
  392. event_id: Optional[str],
  393. ) -> None:
  394. """Check member event changes for any profile changes and update the
  395. database if there are. This is intended for remote users only. The caller
  396. is responsible for checking that the given user is remote.
  397. """
  398. if not prev_event_id or not event_id:
  399. return
  400. prev_event = await self.store.get_event(prev_event_id, allow_none=True)
  401. event = await self.store.get_event(event_id, allow_none=True)
  402. if not prev_event or not event:
  403. return
  404. if event.membership != Membership.JOIN:
  405. return
  406. prev_name = prev_event.content.get("displayname")
  407. new_name = event.content.get("displayname")
  408. # If the new name is an unexpected form, do not update the directory.
  409. if not isinstance(new_name, str):
  410. new_name = prev_name
  411. prev_avatar = prev_event.content.get("avatar_url")
  412. new_avatar = event.content.get("avatar_url")
  413. # If the new avatar is an unexpected form, do not update the directory.
  414. if not isinstance(new_avatar, str):
  415. new_avatar = prev_avatar
  416. if prev_name != new_name or prev_avatar != new_avatar:
  417. await self.store.update_profile_in_user_dir(user_id, new_name, new_avatar)