well_known.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector 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 json
  16. import logging
  17. from twisted.web.resource import Resource
  18. from synapse.http.server import set_cors_headers
  19. logger = logging.getLogger(__name__)
  20. class WellKnownBuilder(object):
  21. """Utility to construct the well-known response
  22. Args:
  23. hs (synapse.server.HomeServer):
  24. """
  25. def __init__(self, hs):
  26. self._config = hs.config
  27. def get_well_known(self):
  28. # if we don't have a public_baseurl, we can't help much here.
  29. if self._config.public_baseurl is None:
  30. return None
  31. result = {"m.homeserver": {"base_url": self._config.public_baseurl}}
  32. if self._config.default_identity_server:
  33. result["m.identity_server"] = {
  34. "base_url": self._config.default_identity_server
  35. }
  36. return result
  37. class WellKnownResource(Resource):
  38. """A Twisted web resource which renders the .well-known file"""
  39. isLeaf = 1
  40. def __init__(self, hs):
  41. Resource.__init__(self)
  42. self._well_known_builder = WellKnownBuilder(hs)
  43. def render_GET(self, request):
  44. set_cors_headers(request)
  45. r = self._well_known_builder.get_well_known()
  46. if not r:
  47. request.setResponseCode(404)
  48. request.setHeader(b"Content-Type", b"text/plain")
  49. return b".well-known not available"
  50. logger.debug("returning: %s", r)
  51. request.setHeader(b"Content-Type", b"application/json")
  52. return json.dumps(r).encode("utf-8")