No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

431 líneas
17 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. 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. 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 MatchChange.now_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. continue
  183. else:
  184. logger.debug("Server is still in room: %r", room_id)
  185. include_in_dir = not self.is_mine_id(
  186. state_key
  187. ) or await self.store.should_include_local_user_in_dir(state_key)
  188. if include_in_dir:
  189. if change is MatchChange.no_change:
  190. # Handle any profile changes
  191. await self._handle_profile_change(
  192. state_key, room_id, prev_event_id, event_id
  193. )
  194. continue
  195. if change is MatchChange.now_true: # The user joined
  196. event = await self.store.get_event(event_id, allow_none=True)
  197. # It isn't expected for this event to not exist, but we
  198. # don't want the entire background process to break.
  199. if event is None:
  200. continue
  201. profile = ProfileInfo(
  202. avatar_url=event.content.get("avatar_url"),
  203. display_name=event.content.get("displayname"),
  204. )
  205. await self._handle_new_user(room_id, state_key, profile)
  206. else: # The user left
  207. await self._handle_remove_user(room_id, state_key)
  208. else:
  209. logger.debug("Ignoring irrelevant type: %r", typ)
  210. async def _handle_room_publicity_change(
  211. self,
  212. room_id: str,
  213. prev_event_id: Optional[str],
  214. event_id: Optional[str],
  215. typ: str,
  216. ) -> None:
  217. """Handle a room having potentially changed from/to world_readable/publicly
  218. joinable.
  219. Args:
  220. room_id: The ID of the room which changed.
  221. prev_event_id: The previous event before the state change
  222. event_id: The new event after the state change
  223. typ: Type of the event
  224. """
  225. logger.debug("Handling change for %s: %s", typ, room_id)
  226. if typ == EventTypes.RoomHistoryVisibility:
  227. publicness = await self._get_key_change(
  228. prev_event_id,
  229. event_id,
  230. key_name="history_visibility",
  231. public_value=HistoryVisibility.WORLD_READABLE,
  232. )
  233. elif typ == EventTypes.JoinRules:
  234. publicness = await self._get_key_change(
  235. prev_event_id,
  236. event_id,
  237. key_name="join_rule",
  238. public_value=JoinRules.PUBLIC,
  239. )
  240. else:
  241. raise Exception("Invalid event type")
  242. if publicness is MatchChange.no_change:
  243. logger.debug("No change")
  244. return
  245. # There's been a change to or from being world readable.
  246. is_public = await self.store.is_room_world_readable_or_publicly_joinable(
  247. room_id
  248. )
  249. logger.debug("Change: %r, publicness: %r", publicness, is_public)
  250. if publicness is MatchChange.now_true and not is_public:
  251. # If we became world readable but room isn't currently public then
  252. # we ignore the change
  253. return
  254. elif publicness is MatchChange.now_false and is_public:
  255. # If we stopped being world readable but are still public,
  256. # ignore the change
  257. return
  258. other_users_in_room_with_profiles = (
  259. await self.store.get_users_in_room_with_profiles(room_id)
  260. )
  261. # Remove every user from the sharing tables for that room.
  262. for user_id in other_users_in_room_with_profiles.keys():
  263. await self.store.remove_user_who_share_room(user_id, room_id)
  264. # Then, re-add them to the tables.
  265. # NOTE: this is not the most efficient method, as handle_new_user sets
  266. # up local_user -> other_user and other_user_whos_local -> local_user,
  267. # which when ran over an entire room, will result in the same values
  268. # being added multiple times. The batching upserts shouldn't make this
  269. # too bad, though.
  270. for user_id, profile in other_users_in_room_with_profiles.items():
  271. await self._handle_new_user(room_id, user_id, profile)
  272. async def _handle_new_user(
  273. self, room_id: str, user_id: str, profile: ProfileInfo
  274. ) -> None:
  275. """Called when we might need to add user to directory
  276. Args:
  277. room_id: The room ID that user joined or started being public
  278. user_id
  279. """
  280. logger.debug("Adding new user to dir, %r", user_id)
  281. await self.store.update_profile_in_user_dir(
  282. user_id, profile.display_name, profile.avatar_url
  283. )
  284. is_public = await self.store.is_room_world_readable_or_publicly_joinable(
  285. room_id
  286. )
  287. # Now we update users who share rooms with users.
  288. other_users_in_room = await self.store.get_users_in_room(room_id)
  289. if is_public:
  290. await self.store.add_users_in_public_rooms(room_id, (user_id,))
  291. else:
  292. to_insert = set()
  293. # First, if they're our user then we need to update for every user
  294. if self.is_mine_id(user_id):
  295. if await self.store.should_include_local_user_in_dir(user_id):
  296. for other_user_id in other_users_in_room:
  297. if user_id == other_user_id:
  298. continue
  299. to_insert.add((user_id, other_user_id))
  300. # Next we need to update for every local user in the room
  301. for other_user_id in other_users_in_room:
  302. if user_id == other_user_id:
  303. continue
  304. include_other_user = self.is_mine_id(
  305. other_user_id
  306. ) and await self.store.should_include_local_user_in_dir(other_user_id)
  307. if include_other_user:
  308. to_insert.add((other_user_id, user_id))
  309. if to_insert:
  310. await self.store.add_users_who_share_private_room(room_id, to_insert)
  311. async def _handle_remove_user(self, room_id: str, user_id: str) -> None:
  312. """Called when we might need to remove user from directory
  313. Args:
  314. room_id: The room ID that user left or stopped being public that
  315. user_id
  316. """
  317. logger.debug("Removing user %r", user_id)
  318. # Remove user from sharing tables
  319. await self.store.remove_user_who_share_room(user_id, room_id)
  320. # Are they still in any rooms? If not, remove them entirely.
  321. rooms_user_is_in = await self.store.get_user_dir_rooms_user_is_in(user_id)
  322. if len(rooms_user_is_in) == 0:
  323. await self.store.remove_from_user_dir(user_id)
  324. async def _handle_profile_change(
  325. self,
  326. user_id: str,
  327. room_id: str,
  328. prev_event_id: Optional[str],
  329. event_id: Optional[str],
  330. ) -> None:
  331. """Check member event changes for any profile changes and update the
  332. database if there are.
  333. """
  334. if not prev_event_id or not event_id:
  335. return
  336. prev_event = await self.store.get_event(prev_event_id, allow_none=True)
  337. event = await self.store.get_event(event_id, allow_none=True)
  338. if not prev_event or not event:
  339. return
  340. if event.membership != Membership.JOIN:
  341. return
  342. prev_name = prev_event.content.get("displayname")
  343. new_name = event.content.get("displayname")
  344. # If the new name is an unexpected form, do not update the directory.
  345. if not isinstance(new_name, str):
  346. new_name = prev_name
  347. prev_avatar = prev_event.content.get("avatar_url")
  348. new_avatar = event.content.get("avatar_url")
  349. # If the new avatar is an unexpected form, do not update the directory.
  350. if not isinstance(new_avatar, str):
  351. new_avatar = prev_avatar
  352. if prev_name != new_name or prev_avatar != new_avatar:
  353. await self.store.update_profile_in_user_dir(user_id, new_name, new_avatar)