oembed.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 logging
  15. import urllib.parse
  16. from typing import TYPE_CHECKING, List, Optional
  17. import attr
  18. from synapse.types import JsonDict
  19. from synapse.util import json_decoder
  20. if TYPE_CHECKING:
  21. from lxml import etree
  22. from synapse.server import HomeServer
  23. logger = logging.getLogger(__name__)
  24. @attr.s(slots=True, frozen=True, auto_attribs=True)
  25. class OEmbedResult:
  26. # The Open Graph result (converted from the oEmbed result).
  27. open_graph_result: JsonDict
  28. # Number of milliseconds to cache the content, according to the oEmbed response.
  29. #
  30. # This will be None if no cache-age is provided in the oEmbed response (or
  31. # if the oEmbed response cannot be turned into an Open Graph response).
  32. cache_age: Optional[int]
  33. class OEmbedProvider:
  34. """
  35. A helper for accessing oEmbed content.
  36. It can be used to check if a URL should be accessed via oEmbed and for
  37. requesting/parsing oEmbed content.
  38. """
  39. def __init__(self, hs: "HomeServer"):
  40. self._oembed_patterns = {}
  41. for oembed_endpoint in hs.config.oembed.oembed_patterns:
  42. api_endpoint = oembed_endpoint.api_endpoint
  43. # Only JSON is supported at the moment. This could be declared in
  44. # the formats field. Otherwise, if the endpoint ends in .xml assume
  45. # it doesn't support JSON.
  46. if (
  47. oembed_endpoint.formats is not None
  48. and "json" not in oembed_endpoint.formats
  49. ) or api_endpoint.endswith(".xml"):
  50. logger.info(
  51. "Ignoring oEmbed endpoint due to not supporting JSON: %s",
  52. api_endpoint,
  53. )
  54. continue
  55. # Iterate through each URL pattern and point it to the endpoint.
  56. for pattern in oembed_endpoint.url_patterns:
  57. self._oembed_patterns[pattern] = api_endpoint
  58. def get_oembed_url(self, url: str) -> Optional[str]:
  59. """
  60. Check whether the URL should be downloaded as oEmbed content instead.
  61. Args:
  62. url: The URL to check.
  63. Returns:
  64. A URL to use instead or None if the original URL should be used.
  65. """
  66. for url_pattern, endpoint in self._oembed_patterns.items():
  67. if url_pattern.fullmatch(url):
  68. # TODO Specify max height / width.
  69. # Note that only the JSON format is supported, some endpoints want
  70. # this in the URL, others want it as an argument.
  71. endpoint = endpoint.replace("{format}", "json")
  72. args = {"url": url, "format": "json"}
  73. query_str = urllib.parse.urlencode(args, True)
  74. return f"{endpoint}?{query_str}"
  75. # No match.
  76. return None
  77. def autodiscover_from_html(self, tree: "etree.Element") -> Optional[str]:
  78. """
  79. Search an HTML document for oEmbed autodiscovery information.
  80. Args:
  81. tree: The parsed HTML body.
  82. Returns:
  83. The URL to use for oEmbed information, or None if no URL was found.
  84. """
  85. # Search for link elements with the proper rel and type attributes.
  86. for tag in tree.xpath(
  87. "//link[@rel='alternate'][@type='application/json+oembed']"
  88. ):
  89. if "href" in tag.attrib:
  90. return tag.attrib["href"]
  91. # Some providers (e.g. Flickr) use alternative instead of alternate.
  92. for tag in tree.xpath(
  93. "//link[@rel='alternative'][@type='application/json+oembed']"
  94. ):
  95. if "href" in tag.attrib:
  96. return tag.attrib["href"]
  97. return None
  98. def parse_oembed_response(self, url: str, raw_body: bytes) -> OEmbedResult:
  99. """
  100. Parse the oEmbed response into an Open Graph response.
  101. Args:
  102. url: The URL which is being previewed (not the one which was
  103. requested).
  104. raw_body: The oEmbed response as JSON encoded as bytes.
  105. Returns:
  106. json-encoded Open Graph data
  107. """
  108. try:
  109. # oEmbed responses *must* be UTF-8 according to the spec.
  110. oembed = json_decoder.decode(raw_body.decode("utf-8"))
  111. # The version is a required string field, but not always provided,
  112. # or sometimes provided as a float. Be lenient.
  113. oembed_version = oembed.get("version", "1.0")
  114. if oembed_version != "1.0" and oembed_version != 1:
  115. raise RuntimeError(f"Invalid oEmbed version: {oembed_version}")
  116. # Ensure the cache age is None or an int.
  117. cache_age = oembed.get("cache_age")
  118. if cache_age:
  119. cache_age = int(cache_age) * 1000
  120. # The results.
  121. open_graph_response = {
  122. "og:url": url,
  123. }
  124. # Use either title or author's name as the title.
  125. title = oembed.get("title") or oembed.get("author_name")
  126. if title:
  127. open_graph_response["og:title"] = title
  128. # Use the provider name and as the site.
  129. provider_name = oembed.get("provider_name")
  130. if provider_name:
  131. open_graph_response["og:site_name"] = provider_name
  132. # If a thumbnail exists, use it. Note that dimensions will be calculated later.
  133. if "thumbnail_url" in oembed:
  134. open_graph_response["og:image"] = oembed["thumbnail_url"]
  135. # Process each type separately.
  136. oembed_type = oembed["type"]
  137. if oembed_type == "rich":
  138. calc_description_and_urls(open_graph_response, oembed["html"])
  139. elif oembed_type == "photo":
  140. # If this is a photo, use the full image, not the thumbnail.
  141. open_graph_response["og:image"] = oembed["url"]
  142. elif oembed_type == "video":
  143. open_graph_response["og:type"] = "video.other"
  144. calc_description_and_urls(open_graph_response, oembed["html"])
  145. open_graph_response["og:video:width"] = oembed["width"]
  146. open_graph_response["og:video:height"] = oembed["height"]
  147. elif oembed_type == "link":
  148. open_graph_response["og:type"] = "website"
  149. else:
  150. raise RuntimeError(f"Unknown oEmbed type: {oembed_type}")
  151. except Exception as e:
  152. # Trap any exception and let the code follow as usual.
  153. logger.warning("Error parsing oEmbed metadata from %s: %r", url, e)
  154. open_graph_response = {}
  155. cache_age = None
  156. return OEmbedResult(open_graph_response, cache_age)
  157. def _fetch_urls(tree: "etree.Element", tag_name: str) -> List[str]:
  158. results = []
  159. for tag in tree.xpath("//*/" + tag_name):
  160. if "src" in tag.attrib:
  161. results.append(tag.attrib["src"])
  162. return results
  163. def calc_description_and_urls(open_graph_response: JsonDict, html_body: str) -> None:
  164. """
  165. Calculate description for an HTML document.
  166. This uses lxml to convert the HTML document into plaintext. If errors
  167. occur during processing of the document, an empty response is returned.
  168. Args:
  169. open_graph_response: The current Open Graph summary. This is updated with additional fields.
  170. html_body: The HTML document, as bytes.
  171. Returns:
  172. The summary
  173. """
  174. # If there's no body, nothing useful is going to be found.
  175. if not html_body:
  176. return
  177. from lxml import etree
  178. # Create an HTML parser. If this fails, log and return no metadata.
  179. parser = etree.HTMLParser(recover=True, encoding="utf-8")
  180. # Attempt to parse the body. If this fails, log and return no metadata.
  181. tree = etree.fromstring(html_body, parser)
  182. # The data was successfully parsed, but no tree was found.
  183. if tree is None:
  184. return
  185. # Attempt to find interesting URLs (images, videos, embeds).
  186. if "og:image" not in open_graph_response:
  187. image_urls = _fetch_urls(tree, "img")
  188. if image_urls:
  189. open_graph_response["og:image"] = image_urls[0]
  190. video_urls = _fetch_urls(tree, "video") + _fetch_urls(tree, "embed")
  191. if video_urls:
  192. open_graph_response["og:video"] = video_urls[0]
  193. from synapse.rest.media.v1.preview_url_resource import _calc_description
  194. description = _calc_description(tree)
  195. if description:
  196. open_graph_response["og:description"] = description