Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 
 

174 рядки
6.1 KiB

  1. # Copyright 2021 The Matrix.org Foundation C.I.C.
  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 json
  15. import re
  16. from typing import Any, Dict, Iterable, List, Optional, Pattern
  17. from urllib import parse as urlparse
  18. import attr
  19. import pkg_resources
  20. from synapse.types import JsonDict, StrSequence
  21. from ._base import Config, ConfigError
  22. from ._util import validate_config
  23. @attr.s(slots=True, frozen=True, auto_attribs=True)
  24. class OEmbedEndpointConfig:
  25. # The API endpoint to fetch.
  26. api_endpoint: str
  27. # The patterns to match.
  28. url_patterns: List[Pattern[str]]
  29. # The supported formats.
  30. formats: Optional[List[str]]
  31. class OembedConfig(Config):
  32. """oEmbed Configuration"""
  33. section = "oembed"
  34. def read_config(self, config: JsonDict, **kwargs: Any) -> None:
  35. oembed_config: Dict[str, Any] = config.get("oembed") or {}
  36. # A list of patterns which will be used.
  37. self.oembed_patterns: List[OEmbedEndpointConfig] = list(
  38. self._parse_and_validate_providers(oembed_config)
  39. )
  40. def _parse_and_validate_providers(
  41. self, oembed_config: dict
  42. ) -> Iterable[OEmbedEndpointConfig]:
  43. """Extract and parse the oEmbed providers from the given JSON file.
  44. Returns a generator which yields the OidcProviderConfig objects
  45. """
  46. # Whether to use the packaged providers.json file.
  47. if not oembed_config.get("disable_default_providers") or False:
  48. with pkg_resources.resource_stream("synapse", "res/providers.json") as s:
  49. providers = json.load(s)
  50. yield from self._parse_and_validate_provider(
  51. providers, config_path=("oembed",)
  52. )
  53. # The JSON files which includes additional provider information.
  54. for i, file in enumerate(oembed_config.get("additional_providers") or []):
  55. # TODO Error checking.
  56. with open(file) as f:
  57. providers = json.load(f)
  58. yield from self._parse_and_validate_provider(
  59. providers,
  60. config_path=(
  61. "oembed",
  62. "additional_providers",
  63. f"<item {i}>",
  64. ),
  65. )
  66. def _parse_and_validate_provider(
  67. self, providers: List[JsonDict], config_path: StrSequence
  68. ) -> Iterable[OEmbedEndpointConfig]:
  69. # Ensure it is the proper form.
  70. validate_config(
  71. _OEMBED_PROVIDER_SCHEMA,
  72. providers,
  73. config_path=config_path,
  74. )
  75. # Parse it and yield each result.
  76. for provider in providers:
  77. # Each provider might have multiple API endpoints, each which
  78. # might have multiple patterns to match.
  79. for endpoint in provider["endpoints"]:
  80. api_endpoint = endpoint["url"]
  81. # The API endpoint must be an HTTP(S) URL.
  82. results = urlparse.urlparse(api_endpoint)
  83. if results.scheme not in {"http", "https"}:
  84. raise ConfigError(
  85. f"Unsupported oEmbed scheme ({results.scheme}) for endpoint {api_endpoint}",
  86. config_path,
  87. )
  88. patterns = [
  89. self._glob_to_pattern(glob, config_path)
  90. for glob in endpoint["schemes"]
  91. ]
  92. yield OEmbedEndpointConfig(
  93. api_endpoint, patterns, endpoint.get("formats")
  94. )
  95. def _glob_to_pattern(self, glob: str, config_path: StrSequence) -> Pattern:
  96. """
  97. Convert the glob into a sane regular expression to match against. The
  98. rules followed will be slightly different for the domain portion vs.
  99. the rest.
  100. 1. The scheme must be one of HTTP / HTTPS (and have no globs).
  101. 2. The domain can have globs, but we limit it to characters that can
  102. reasonably be a domain part.
  103. TODO: This does not attempt to handle Unicode domain names.
  104. TODO: The domain should not allow wildcard TLDs.
  105. 3. Other parts allow a glob to be any one, or more, characters.
  106. """
  107. results = urlparse.urlparse(glob)
  108. # The scheme must be HTTP(S) (and cannot contain wildcards).
  109. if results.scheme not in {"http", "https"}:
  110. raise ConfigError(
  111. f"Unsupported oEmbed scheme ({results.scheme}) for pattern: {glob}",
  112. config_path,
  113. )
  114. pattern = urlparse.urlunparse(
  115. [
  116. results.scheme,
  117. re.escape(results.netloc).replace("\\*", "[a-zA-Z0-9_-]+"),
  118. ]
  119. + [re.escape(part).replace("\\*", ".+") for part in results[2:]]
  120. )
  121. return re.compile(pattern)
  122. _OEMBED_PROVIDER_SCHEMA = {
  123. "type": "array",
  124. "items": {
  125. "type": "object",
  126. "properties": {
  127. "provider_name": {"type": "string"},
  128. "provider_url": {"type": "string"},
  129. "endpoints": {
  130. "type": "array",
  131. "items": {
  132. "type": "object",
  133. "properties": {
  134. "schemes": {
  135. "type": "array",
  136. "items": {"type": "string"},
  137. },
  138. "url": {"type": "string"},
  139. "formats": {"type": "array", "items": {"type": "string"}},
  140. "discovery": {"type": "boolean"},
  141. },
  142. "required": ["schemes", "url"],
  143. },
  144. },
  145. },
  146. "required": ["provider_name", "provider_url", "endpoints"],
  147. },
  148. }