user_directory.py 19 KB

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