user_directory.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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.roommember import ProfileInfo
  21. from synapse.types import JsonDict
  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_datastore()
  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.server.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. ) -> JsonDict:
  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. # Loop round handling deltas until we're up to date
  125. while True:
  126. with Measure(self.clock, "user_dir_delta"):
  127. room_max_stream_ordering = self.store.get_room_max_stream_ordering()
  128. if self.pos == room_max_stream_ordering:
  129. return
  130. logger.debug(
  131. "Processing user stats %s->%s", self.pos, room_max_stream_ordering
  132. )
  133. max_pos, deltas = await self.store.get_current_state_deltas(
  134. self.pos, room_max_stream_ordering
  135. )
  136. logger.debug("Handling %d state deltas", len(deltas))
  137. await self._handle_deltas(deltas)
  138. self.pos = max_pos
  139. # Expose current event processing position to prometheus
  140. synapse.metrics.event_processing_positions.labels("user_dir").set(
  141. max_pos
  142. )
  143. await self.store.update_user_directory_stream_pos(max_pos)
  144. async def _handle_deltas(self, deltas: List[Dict[str, Any]]) -> None:
  145. """Called with the state deltas to process"""
  146. for delta in deltas:
  147. typ = delta["type"]
  148. state_key = delta["state_key"]
  149. room_id = delta["room_id"]
  150. event_id = delta["event_id"]
  151. prev_event_id = delta["prev_event_id"]
  152. logger.debug("Handling: %r %r, %s", typ, state_key, event_id)
  153. # For join rule and visibility changes we need to check if the room
  154. # may have become public or not and add/remove the users in said room
  155. if typ in (EventTypes.RoomHistoryVisibility, EventTypes.JoinRules):
  156. await self._handle_room_publicity_change(
  157. room_id, prev_event_id, event_id, typ
  158. )
  159. elif typ == EventTypes.Member:
  160. await self._handle_room_membership_event(
  161. room_id,
  162. prev_event_id,
  163. event_id,
  164. state_key,
  165. )
  166. else:
  167. logger.debug("Ignoring irrelevant type: %r", typ)
  168. async def _handle_room_publicity_change(
  169. self,
  170. room_id: str,
  171. prev_event_id: Optional[str],
  172. event_id: Optional[str],
  173. typ: str,
  174. ) -> None:
  175. """Handle a room having potentially changed from/to world_readable/publicly
  176. joinable.
  177. Args:
  178. room_id: The ID of the room which changed.
  179. prev_event_id: The previous event before the state change
  180. event_id: The new event after the state change
  181. typ: Type of the event
  182. """
  183. logger.debug("Handling change for %s: %s", typ, room_id)
  184. if typ == EventTypes.RoomHistoryVisibility:
  185. publicness = await self._get_key_change(
  186. prev_event_id,
  187. event_id,
  188. key_name="history_visibility",
  189. public_value=HistoryVisibility.WORLD_READABLE,
  190. )
  191. elif typ == EventTypes.JoinRules:
  192. publicness = await self._get_key_change(
  193. prev_event_id,
  194. event_id,
  195. key_name="join_rule",
  196. public_value=JoinRules.PUBLIC,
  197. )
  198. else:
  199. raise Exception("Invalid event type")
  200. if publicness is MatchChange.no_change:
  201. logger.debug("No change")
  202. return
  203. # There's been a change to or from being world readable.
  204. is_public = await self.store.is_room_world_readable_or_publicly_joinable(
  205. room_id
  206. )
  207. logger.debug("Publicness change: %r, is_public: %r", publicness, is_public)
  208. if publicness is MatchChange.now_true and not is_public:
  209. # If we became world readable but room isn't currently public then
  210. # we ignore the change
  211. return
  212. elif publicness is MatchChange.now_false and is_public:
  213. # If we stopped being world readable but are still public,
  214. # ignore the change
  215. return
  216. users_in_room = await self.store.get_users_in_room(room_id)
  217. # Remove every user from the sharing tables for that room.
  218. for user_id in users_in_room:
  219. await self.store.remove_user_who_share_room(user_id, room_id)
  220. # Then, re-add all remote users and some local users to the tables.
  221. # NOTE: this is not the most efficient method, as _track_user_joined_room sets
  222. # up local_user -> other_user and other_user_whos_local -> local_user,
  223. # which when ran over an entire room, will result in the same values
  224. # being added multiple times. The batching upserts shouldn't make this
  225. # too bad, though.
  226. for user_id in users_in_room:
  227. if not self.is_mine_id(
  228. user_id
  229. ) or await self.store.should_include_local_user_in_dir(user_id):
  230. await self._track_user_joined_room(room_id, user_id)
  231. async def _handle_room_membership_event(
  232. self,
  233. room_id: str,
  234. prev_event_id: str,
  235. event_id: str,
  236. state_key: str,
  237. ) -> None:
  238. """Process a single room membershp event.
  239. We have to do two things:
  240. 1. Update the room-sharing tables.
  241. This applies to remote users and non-excluded local users.
  242. 2. Update the user_directory and user_directory_search tables.
  243. This applies to remote users only, because we only become aware of
  244. the (and any profile changes) by listening to these events.
  245. The rest of the application knows exactly when local users are
  246. created or their profile changed---it will directly call methods
  247. on this class.
  248. """
  249. joined = await self._get_key_change(
  250. prev_event_id,
  251. event_id,
  252. key_name="membership",
  253. public_value=Membership.JOIN,
  254. )
  255. # Both cases ignore excluded local users, so start by discarding them.
  256. is_remote = not self.is_mine_id(state_key)
  257. if not is_remote and not await self.store.should_include_local_user_in_dir(
  258. state_key
  259. ):
  260. return
  261. if joined is MatchChange.now_false:
  262. # Need to check if the server left the room entirely, if so
  263. # we might need to remove all the users in that room
  264. is_in_room = await self.store.is_host_joined(room_id, self.server_name)
  265. if not is_in_room:
  266. logger.debug("Server left room: %r", room_id)
  267. # Fetch all the users that we marked as being in user
  268. # directory due to being in the room and then check if
  269. # need to remove those users or not
  270. user_ids = await self.store.get_users_in_dir_due_to_room(room_id)
  271. for user_id in user_ids:
  272. await self._handle_remove_user(room_id, user_id)
  273. else:
  274. logger.debug("Server is still in room: %r", room_id)
  275. await self._handle_remove_user(room_id, state_key)
  276. elif joined is MatchChange.no_change:
  277. # Handle any profile changes for remote users.
  278. # (For local users the rest of the application calls
  279. # `handle_local_profile_change`.)
  280. if is_remote:
  281. await self._handle_possible_remote_profile_change(
  282. state_key, room_id, prev_event_id, event_id
  283. )
  284. elif joined is MatchChange.now_true: # The user joined
  285. # This may be the first time we've seen a remote user. If
  286. # so, ensure we have a directory entry for them. (For local users,
  287. # the rest of the application calls `handle_local_profile_change`.)
  288. if is_remote:
  289. await self._upsert_directory_entry_for_remote_user(state_key, event_id)
  290. await self._track_user_joined_room(room_id, state_key)
  291. async def _upsert_directory_entry_for_remote_user(
  292. self, user_id: str, event_id: str
  293. ) -> None:
  294. """A remote user has just joined a room. Ensure they have an entry in
  295. the user directory. The caller is responsible for making sure they're
  296. remote.
  297. """
  298. event = await self.store.get_event(event_id, allow_none=True)
  299. # It isn't expected for this event to not exist, but we
  300. # don't want the entire background process to break.
  301. if event is None:
  302. return
  303. logger.debug("Adding new user to dir, %r", user_id)
  304. await self.store.update_profile_in_user_dir(
  305. user_id, event.content.get("displayname"), event.content.get("avatar_url")
  306. )
  307. async def _track_user_joined_room(self, room_id: str, user_id: str) -> None:
  308. """Someone's just joined a room. Update `users_in_public_rooms` or
  309. `users_who_share_private_rooms` as appropriate.
  310. The caller is responsible for ensuring that the given user should be
  311. included in the user directory.
  312. """
  313. is_public = await self.store.is_room_world_readable_or_publicly_joinable(
  314. room_id
  315. )
  316. other_users_in_room = await self.store.get_users_in_room(room_id)
  317. if is_public:
  318. await self.store.add_users_in_public_rooms(room_id, (user_id,))
  319. else:
  320. to_insert = set()
  321. # First, if they're our user then we need to update for every user
  322. if self.is_mine_id(user_id):
  323. if await self.store.should_include_local_user_in_dir(user_id):
  324. for other_user_id in other_users_in_room:
  325. if user_id == other_user_id:
  326. continue
  327. to_insert.add((user_id, other_user_id))
  328. # Next we need to update for every local user in the room
  329. for other_user_id in other_users_in_room:
  330. if user_id == other_user_id:
  331. continue
  332. include_other_user = self.is_mine_id(
  333. other_user_id
  334. ) and await self.store.should_include_local_user_in_dir(other_user_id)
  335. if include_other_user:
  336. to_insert.add((other_user_id, user_id))
  337. if to_insert:
  338. await self.store.add_users_who_share_private_room(room_id, to_insert)
  339. async def _handle_remove_user(self, room_id: str, user_id: str) -> None:
  340. """Called when when someone leaves a room. The user may be local or remote.
  341. (If the person who left was the last local user in this room, the server
  342. is no longer in the room. We call this function to forget that the remaining
  343. remote users are in the room, even though they haven't left. So the name is
  344. a little misleading!)
  345. Args:
  346. room_id: The room ID that user left or stopped being public that
  347. user_id
  348. """
  349. logger.debug("Removing user %r", user_id)
  350. # Remove user from sharing tables
  351. await self.store.remove_user_who_share_room(user_id, room_id)
  352. # Are they still in any rooms? If not, remove them entirely.
  353. rooms_user_is_in = await self.store.get_user_dir_rooms_user_is_in(user_id)
  354. if len(rooms_user_is_in) == 0:
  355. await self.store.remove_from_user_dir(user_id)
  356. async def _handle_possible_remote_profile_change(
  357. self,
  358. user_id: str,
  359. room_id: str,
  360. prev_event_id: Optional[str],
  361. event_id: Optional[str],
  362. ) -> None:
  363. """Check member event changes for any profile changes and update the
  364. database if there are. This is intended for remote users only. The caller
  365. is responsible for checking that the given user is remote.
  366. """
  367. if not prev_event_id or not event_id:
  368. return
  369. prev_event = await self.store.get_event(prev_event_id, allow_none=True)
  370. event = await self.store.get_event(event_id, allow_none=True)
  371. if not prev_event or not event:
  372. return
  373. if event.membership != Membership.JOIN:
  374. return
  375. prev_name = prev_event.content.get("displayname")
  376. new_name = event.content.get("displayname")
  377. # If the new name is an unexpected form, do not update the directory.
  378. if not isinstance(new_name, str):
  379. new_name = prev_name
  380. prev_avatar = prev_event.content.get("avatar_url")
  381. new_avatar = event.content.get("avatar_url")
  382. # If the new avatar is an unexpected form, do not update the directory.
  383. if not isinstance(new_avatar, str):
  384. new_avatar = prev_avatar
  385. if prev_name != new_name or prev_avatar != new_avatar:
  386. await self.store.update_profile_in_user_dir(user_id, new_name, new_avatar)