user_directory.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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 synapse.api.errors import SynapseError
  17. from synapse.http.servlet import RestServlet, parse_json_object_from_request
  18. from ._base import client_patterns
  19. logger = logging.getLogger(__name__)
  20. class UserDirectorySearchRestServlet(RestServlet):
  21. PATTERNS = client_patterns("/user_directory/search$")
  22. def __init__(self, hs):
  23. """
  24. Args:
  25. hs (synapse.server.HomeServer): server
  26. """
  27. super().__init__()
  28. self.hs = hs
  29. self.auth = hs.get_auth()
  30. self.user_directory_handler = hs.get_user_directory_handler()
  31. async def on_POST(self, request):
  32. """Searches for users in directory
  33. Returns:
  34. dict of the form::
  35. {
  36. "limited": <bool>, # whether there were more results or not
  37. "results": [ # Ordered by best match first
  38. {
  39. "user_id": <user_id>,
  40. "display_name": <display_name>,
  41. "avatar_url": <avatar_url>
  42. }
  43. ]
  44. }
  45. """
  46. requester = await self.auth.get_user_by_req(request, allow_guest=False)
  47. user_id = requester.user.to_string()
  48. if not self.hs.config.user_directory_search_enabled:
  49. return 200, {"limited": False, "results": []}
  50. body = parse_json_object_from_request(request)
  51. limit = body.get("limit", 10)
  52. limit = min(limit, 50)
  53. try:
  54. search_term = body["search_term"]
  55. except Exception:
  56. raise SynapseError(400, "`search_term` is required field")
  57. results = await self.user_directory_handler.search_users(
  58. user_id, search_term, limit
  59. )
  60. return 200, results
  61. def register_servlets(hs, http_server):
  62. UserDirectorySearchRestServlet(hs).register(http_server)