user_directory.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 Vector Creations Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import logging
  16. from typing import TYPE_CHECKING, Any, Dict, List, Optional
  17. import synapse.metrics
  18. from synapse.api.constants import EventTypes, HistoryVisibility, JoinRules, Membership
  19. from synapse.handlers.state_deltas import StateDeltasHandler
  20. from synapse.metrics.background_process_metrics import run_as_background_process
  21. from synapse.storage.roommember import ProfileInfo
  22. from synapse.types import JsonDict
  23. from synapse.util.metrics import Measure
  24. if TYPE_CHECKING:
  25. from synapse.app.homeserver import HomeServer
  26. logger = logging.getLogger(__name__)
  27. class UserDirectoryHandler(StateDeltasHandler):
  28. """Handles querying of and keeping updated the user_directory.
  29. N.B.: ASSUMES IT IS THE ONLY THING THAT MODIFIES THE USER DIRECTORY
  30. The user directory is filled with users who this server can see are joined to a
  31. world_readable or publicly joinable room. We keep a database table up to date
  32. by streaming changes of the current state and recalculating whether users should
  33. be in the directory or not when necessary.
  34. """
  35. def __init__(self, hs: "HomeServer"):
  36. super().__init__(hs)
  37. self.store = hs.get_datastore()
  38. self.state = hs.get_state_handler()
  39. self.server_name = hs.hostname
  40. self.clock = hs.get_clock()
  41. self.notifier = hs.get_notifier()
  42. self.is_mine_id = hs.is_mine_id
  43. self.update_user_directory = hs.config.update_user_directory
  44. self.search_all_users = hs.config.user_directory_search_all_users
  45. self.spam_checker = hs.get_spam_checker()
  46. # The current position in the current_state_delta stream
  47. self.pos = None # type: Optional[int]
  48. # Guard to ensure we only process deltas one at a time
  49. self._is_processing = False
  50. if self.update_user_directory:
  51. self.notifier.add_replication_callback(self.notify_new_event)
  52. # We kick this off so that we don't have to wait for a change before
  53. # we start populating the user directory
  54. self.clock.call_later(0, self.notify_new_event)
  55. async def search_users(
  56. self, user_id: str, search_term: str, limit: int
  57. ) -> JsonDict:
  58. """Searches for users in directory
  59. Returns:
  60. dict of the form::
  61. {
  62. "limited": <bool>, # whether there were more results or not
  63. "results": [ # Ordered by best match first
  64. {
  65. "user_id": <user_id>,
  66. "display_name": <display_name>,
  67. "avatar_url": <avatar_url>
  68. }
  69. ]
  70. }
  71. """
  72. results = await self.store.search_user_dir(user_id, search_term, limit)
  73. # Remove any spammy users from the results.
  74. non_spammy_users = []
  75. for user in results["results"]:
  76. if not await self.spam_checker.check_username_for_spam(user):
  77. non_spammy_users.append(user)
  78. results["results"] = non_spammy_users
  79. return results
  80. def notify_new_event(self) -> None:
  81. """Called when there may be more deltas to process
  82. """
  83. if not self.update_user_directory:
  84. return
  85. if self._is_processing:
  86. return
  87. async def process():
  88. try:
  89. await self._unsafe_process()
  90. finally:
  91. self._is_processing = False
  92. self._is_processing = True
  93. run_as_background_process("user_directory.notify_new_event", process)
  94. async def handle_local_profile_change(
  95. self, user_id: str, profile: ProfileInfo
  96. ) -> None:
  97. """Called to update index of our local user profiles when they change
  98. irrespective of any rooms the user may be in.
  99. """
  100. # FIXME(#3714): We should probably do this in the same worker as all
  101. # the other changes.
  102. # Support users are for diagnostics and should not appear in the user directory.
  103. is_support = await self.store.is_support_user(user_id)
  104. # When change profile information of deactivated user it should not appear in the user directory.
  105. is_deactivated = await self.store.get_user_deactivated_status(user_id)
  106. if not (is_support or is_deactivated):
  107. await self.store.update_profile_in_user_dir(
  108. user_id, profile.display_name, profile.avatar_url
  109. )
  110. async def handle_user_deactivated(self, user_id: str) -> None:
  111. """Called when a user ID is deactivated
  112. """
  113. # FIXME(#3714): We should probably do this in the same worker as all
  114. # the other changes.
  115. await self.store.remove_from_user_dir(user_id)
  116. async def _unsafe_process(self) -> None:
  117. # If self.pos is None then means we haven't fetched it from DB
  118. if self.pos is None:
  119. self.pos = await self.store.get_user_directory_stream_pos()
  120. # If still None then the initial background update hasn't happened yet
  121. if self.pos is None:
  122. return None
  123. # Loop round handling deltas until we're up to date
  124. while True:
  125. with Measure(self.clock, "user_dir_delta"):
  126. room_max_stream_ordering = self.store.get_room_max_stream_ordering()
  127. if self.pos == room_max_stream_ordering:
  128. return
  129. logger.debug(
  130. "Processing user stats %s->%s", self.pos, room_max_stream_ordering
  131. )
  132. max_pos, deltas = await self.store.get_current_state_deltas(
  133. self.pos, room_max_stream_ordering
  134. )
  135. logger.debug("Handling %d state deltas", len(deltas))
  136. await self._handle_deltas(deltas)
  137. self.pos = max_pos
  138. # Expose current event processing position to prometheus
  139. synapse.metrics.event_processing_positions.labels("user_dir").set(
  140. max_pos
  141. )
  142. await self.store.update_user_directory_stream_pos(max_pos)
  143. async def _handle_deltas(self, deltas: List[Dict[str, Any]]) -> None:
  144. """Called with the state deltas to process
  145. """
  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. change = await self._get_key_change(
  161. prev_event_id,
  162. event_id,
  163. key_name="membership",
  164. public_value=Membership.JOIN,
  165. )
  166. if change is False:
  167. # Need to check if the server left the room entirely, if so
  168. # we might need to remove all the users in that room
  169. is_in_room = await self.store.is_host_joined(
  170. room_id, self.server_name
  171. )
  172. if not is_in_room:
  173. logger.debug("Server left room: %r", room_id)
  174. # Fetch all the users that we marked as being in user
  175. # directory due to being in the room and then check if
  176. # need to remove those users or not
  177. user_ids = await self.store.get_users_in_dir_due_to_room(
  178. room_id
  179. )
  180. for user_id in user_ids:
  181. await self._handle_remove_user(room_id, user_id)
  182. return
  183. else:
  184. logger.debug("Server is still in room: %r", room_id)
  185. is_support = await self.store.is_support_user(state_key)
  186. if not is_support:
  187. if change is None:
  188. # Handle any profile changes
  189. await self._handle_profile_change(
  190. state_key, room_id, prev_event_id, event_id
  191. )
  192. continue
  193. if change: # The user joined
  194. event = await self.store.get_event(event_id, allow_none=True)
  195. profile = ProfileInfo(
  196. avatar_url=event.content.get("avatar_url"),
  197. display_name=event.content.get("displayname"),
  198. )
  199. await self._handle_new_user(room_id, state_key, profile)
  200. else: # The user left
  201. await self._handle_remove_user(room_id, state_key)
  202. else:
  203. logger.debug("Ignoring irrelevant type: %r", typ)
  204. async def _handle_room_publicity_change(
  205. self,
  206. room_id: str,
  207. prev_event_id: Optional[str],
  208. event_id: Optional[str],
  209. typ: str,
  210. ) -> None:
  211. """Handle a room having potentially changed from/to world_readable/publicly
  212. joinable.
  213. Args:
  214. room_id: The ID of the room which changed.
  215. prev_event_id: The previous event before the state change
  216. event_id: The new event after the state change
  217. typ: Type of the event
  218. """
  219. logger.debug("Handling change for %s: %s", typ, room_id)
  220. if typ == EventTypes.RoomHistoryVisibility:
  221. change = await self._get_key_change(
  222. prev_event_id,
  223. event_id,
  224. key_name="history_visibility",
  225. public_value=HistoryVisibility.WORLD_READABLE,
  226. )
  227. elif typ == EventTypes.JoinRules:
  228. change = await self._get_key_change(
  229. prev_event_id,
  230. event_id,
  231. key_name="join_rule",
  232. public_value=JoinRules.PUBLIC,
  233. )
  234. else:
  235. raise Exception("Invalid event type")
  236. # If change is None, no change. True => become world_readable/public,
  237. # False => was world_readable/public
  238. if change is None:
  239. logger.debug("No change")
  240. return
  241. # There's been a change to or from being world readable.
  242. is_public = await self.store.is_room_world_readable_or_publicly_joinable(
  243. room_id
  244. )
  245. logger.debug("Change: %r, is_public: %r", change, is_public)
  246. if change and not is_public:
  247. # If we became world readable but room isn't currently public then
  248. # we ignore the change
  249. return
  250. elif not change and is_public:
  251. # If we stopped being world readable but are still public,
  252. # ignore the change
  253. return
  254. users_with_profile = await self.state.get_current_users_in_room(room_id)
  255. # Remove every user from the sharing tables for that room.
  256. for user_id in users_with_profile.keys():
  257. await self.store.remove_user_who_share_room(user_id, room_id)
  258. # Then, re-add them to the tables.
  259. # NOTE: this is not the most efficient method, as handle_new_user sets
  260. # up local_user -> other_user and other_user_whos_local -> local_user,
  261. # which when ran over an entire room, will result in the same values
  262. # being added multiple times. The batching upserts shouldn't make this
  263. # too bad, though.
  264. for user_id, profile in users_with_profile.items():
  265. await self._handle_new_user(room_id, user_id, profile)
  266. async def _handle_new_user(
  267. self, room_id: str, user_id: str, profile: ProfileInfo
  268. ) -> None:
  269. """Called when we might need to add user to directory
  270. Args:
  271. room_id: The room ID that user joined or started being public
  272. user_id
  273. """
  274. logger.debug("Adding new user to dir, %r", user_id)
  275. await self.store.update_profile_in_user_dir(
  276. user_id, profile.display_name, profile.avatar_url
  277. )
  278. is_public = await self.store.is_room_world_readable_or_publicly_joinable(
  279. room_id
  280. )
  281. # Now we update users who share rooms with users.
  282. users_with_profile = await self.state.get_current_users_in_room(room_id)
  283. if is_public:
  284. await self.store.add_users_in_public_rooms(room_id, (user_id,))
  285. else:
  286. to_insert = set()
  287. # First, if they're our user then we need to update for every user
  288. if self.is_mine_id(user_id):
  289. is_appservice = self.store.get_if_app_services_interested_in_user(
  290. user_id
  291. )
  292. # We don't care about appservice users.
  293. if not is_appservice:
  294. for other_user_id in users_with_profile:
  295. if user_id == other_user_id:
  296. continue
  297. to_insert.add((user_id, other_user_id))
  298. # Next we need to update for every local user in the room
  299. for other_user_id in users_with_profile:
  300. if user_id == other_user_id:
  301. continue
  302. is_appservice = self.store.get_if_app_services_interested_in_user(
  303. other_user_id
  304. )
  305. if self.is_mine_id(other_user_id) and not is_appservice:
  306. to_insert.add((other_user_id, user_id))
  307. if to_insert:
  308. await self.store.add_users_who_share_private_room(room_id, to_insert)
  309. async def _handle_remove_user(self, room_id: str, user_id: str) -> None:
  310. """Called when we might need to remove user from directory
  311. Args:
  312. room_id: The room ID that user left or stopped being public that
  313. user_id
  314. """
  315. logger.debug("Removing user %r", user_id)
  316. # Remove user from sharing tables
  317. await self.store.remove_user_who_share_room(user_id, room_id)
  318. # Are they still in any rooms? If not, remove them entirely.
  319. rooms_user_is_in = await self.store.get_user_dir_rooms_user_is_in(user_id)
  320. if len(rooms_user_is_in) == 0:
  321. await self.store.remove_from_user_dir(user_id)
  322. async def _handle_profile_change(
  323. self,
  324. user_id: str,
  325. room_id: str,
  326. prev_event_id: Optional[str],
  327. event_id: Optional[str],
  328. ) -> None:
  329. """Check member event changes for any profile changes and update the
  330. database if there are.
  331. """
  332. if not prev_event_id or not event_id:
  333. return
  334. prev_event = await self.store.get_event(prev_event_id, allow_none=True)
  335. event = await self.store.get_event(event_id, allow_none=True)
  336. if not prev_event or not event:
  337. return
  338. if event.membership != Membership.JOIN:
  339. return
  340. prev_name = prev_event.content.get("displayname")
  341. new_name = event.content.get("displayname")
  342. # If the new name is an unexpected form, do not update the directory.
  343. if not isinstance(new_name, str):
  344. new_name = prev_name
  345. prev_avatar = prev_event.content.get("avatar_url")
  346. new_avatar = event.content.get("avatar_url")
  347. # If the new avatar is an unexpected form, do not update the directory.
  348. if not isinstance(new_avatar, str):
  349. new_avatar = prev_avatar
  350. if prev_name != new_name or prev_avatar != new_avatar:
  351. await self.store.update_profile_in_user_dir(user_id, new_name, new_avatar)