You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

535 rivejä
19 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 codecs
  15. import logging
  16. import re
  17. from typing import (
  18. TYPE_CHECKING,
  19. Callable,
  20. Dict,
  21. Generator,
  22. Iterable,
  23. List,
  24. Optional,
  25. Set,
  26. Union,
  27. cast,
  28. )
  29. if TYPE_CHECKING:
  30. from lxml import etree
  31. logger = logging.getLogger(__name__)
  32. _charset_match = re.compile(
  33. rb'<\s*meta[^>]*charset\s*=\s*"?([a-z0-9_-]+)"?', flags=re.I
  34. )
  35. _xml_encoding_match = re.compile(
  36. rb'\s*<\s*\?\s*xml[^>]*encoding="([a-z0-9_-]+)"', flags=re.I
  37. )
  38. _content_type_match = re.compile(r'.*; *charset="?(.*?)"?(;|$)', flags=re.I)
  39. # Certain elements aren't meant for display.
  40. ARIA_ROLES_TO_IGNORE = {"directory", "menu", "menubar", "toolbar"}
  41. def _normalise_encoding(encoding: str) -> Optional[str]:
  42. """Use the Python codec's name as the normalised entry."""
  43. try:
  44. return codecs.lookup(encoding).name
  45. except LookupError:
  46. return None
  47. def _get_html_media_encodings(
  48. body: bytes, content_type: Optional[str]
  49. ) -> Iterable[str]:
  50. """
  51. Get potential encoding of the body based on the (presumably) HTML body or the content-type header.
  52. The precedence used for finding a character encoding is:
  53. 1. <meta> tag with a charset declared.
  54. 2. The XML document's character encoding attribute.
  55. 3. The Content-Type header.
  56. 4. Fallback to utf-8.
  57. 5. Fallback to windows-1252.
  58. This roughly follows the algorithm used by BeautifulSoup's bs4.dammit.EncodingDetector.
  59. Args:
  60. body: The HTML document, as bytes.
  61. content_type: The Content-Type header.
  62. Returns:
  63. The character encoding of the body, as a string.
  64. """
  65. # There's no point in returning an encoding more than once.
  66. attempted_encodings: Set[str] = set()
  67. # Limit searches to the first 1kb, since it ought to be at the top.
  68. body_start = body[:1024]
  69. # Check if it has an encoding set in a meta tag.
  70. match = _charset_match.search(body_start)
  71. if match:
  72. encoding = _normalise_encoding(match.group(1).decode("ascii"))
  73. if encoding:
  74. attempted_encodings.add(encoding)
  75. yield encoding
  76. # TODO Support <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  77. # Check if it has an XML document with an encoding.
  78. match = _xml_encoding_match.match(body_start)
  79. if match:
  80. encoding = _normalise_encoding(match.group(1).decode("ascii"))
  81. if encoding and encoding not in attempted_encodings:
  82. attempted_encodings.add(encoding)
  83. yield encoding
  84. # Check the HTTP Content-Type header for a character set.
  85. if content_type:
  86. content_match = _content_type_match.match(content_type)
  87. if content_match:
  88. encoding = _normalise_encoding(content_match.group(1))
  89. if encoding and encoding not in attempted_encodings:
  90. attempted_encodings.add(encoding)
  91. yield encoding
  92. # Finally, fallback to UTF-8, then windows-1252.
  93. for fallback in ("utf-8", "cp1252"):
  94. if fallback not in attempted_encodings:
  95. yield fallback
  96. def decode_body(
  97. body: bytes, uri: str, content_type: Optional[str] = None
  98. ) -> Optional["etree._Element"]:
  99. """
  100. This uses lxml to parse the HTML document.
  101. Args:
  102. body: The HTML document, as bytes.
  103. uri: The URI used to download the body.
  104. content_type: The Content-Type header.
  105. Returns:
  106. The parsed HTML body, or None if an error occurred during processed.
  107. """
  108. # If there's no body, nothing useful is going to be found.
  109. if not body:
  110. return None
  111. # The idea here is that multiple encodings are tried until one works.
  112. # Unfortunately the result is never used and then LXML will decode the string
  113. # again with the found encoding.
  114. for encoding in _get_html_media_encodings(body, content_type):
  115. try:
  116. body.decode(encoding)
  117. except Exception:
  118. pass
  119. else:
  120. break
  121. else:
  122. logger.warning("Unable to decode HTML body for %s", uri)
  123. return None
  124. from lxml import etree
  125. # Create an HTML parser.
  126. parser = etree.HTMLParser(recover=True, encoding=encoding)
  127. # Attempt to parse the body. Returns None if the body was successfully
  128. # parsed, but no tree was found.
  129. # TODO Develop of lxml-stubs has this correct.
  130. return etree.fromstring(body, parser) # type: ignore[arg-type]
  131. def _get_meta_tags(
  132. tree: "etree._Element",
  133. property: str,
  134. prefix: str,
  135. property_mapper: Optional[Callable[[str], Optional[str]]] = None,
  136. ) -> Dict[str, Optional[str]]:
  137. """
  138. Search for meta tags prefixed with a particular string.
  139. Args:
  140. tree: The parsed HTML document.
  141. property: The name of the property which contains the tag name, e.g.
  142. "property" for Open Graph.
  143. prefix: The prefix on the property to search for, e.g. "og" for Open Graph.
  144. property_mapper: An optional callable to map the property to the Open Graph
  145. form. Can return None for a key to ignore that key.
  146. Returns:
  147. A map of tag name to value.
  148. """
  149. # This actually returns Dict[str, str], but the caller sets this as a variable
  150. # which is Dict[str, Optional[str]].
  151. results: Dict[str, Optional[str]] = {}
  152. # Cast: the type returned by xpath depends on the xpath expression: mypy can't deduce this.
  153. for tag in cast(
  154. List["etree._Element"],
  155. tree.xpath(
  156. f"//*/meta[starts-with(@{property}, '{prefix}:')][@content][not(@content='')]"
  157. ),
  158. ):
  159. # if we've got more than 50 tags, someone is taking the piss
  160. if len(results) >= 50:
  161. logger.warning(
  162. "Skipping parsing of Open Graph for page with too many '%s:' tags",
  163. prefix,
  164. )
  165. return {}
  166. key = cast(str, tag.attrib[property])
  167. if property_mapper:
  168. new_key = property_mapper(key)
  169. # None is a special value used to ignore a value.
  170. if new_key is None:
  171. continue
  172. key = new_key
  173. results[key] = cast(str, tag.attrib["content"])
  174. return results
  175. def _map_twitter_to_open_graph(key: str) -> Optional[str]:
  176. """
  177. Map a Twitter card property to the analogous Open Graph property.
  178. Args:
  179. key: The Twitter card property (starts with "twitter:").
  180. Returns:
  181. The Open Graph property (starts with "og:") or None to have this property
  182. be ignored.
  183. """
  184. # Twitter card properties with no analogous Open Graph property.
  185. if key == "twitter:card" or key == "twitter:creator":
  186. return None
  187. if key == "twitter:site":
  188. return "og:site_name"
  189. # Otherwise, swap twitter to og.
  190. return "og" + key[7:]
  191. def parse_html_to_open_graph(tree: "etree._Element") -> Dict[str, Optional[str]]:
  192. """
  193. Parse the HTML document into an Open Graph response.
  194. This uses lxml to search the HTML document for Open Graph data (or
  195. synthesizes it from the document).
  196. Args:
  197. tree: The parsed HTML document.
  198. Returns:
  199. The Open Graph response as a dictionary.
  200. """
  201. # Search for Open Graph (og:) meta tags, e.g.:
  202. #
  203. # "og:type" : "video",
  204. # "og:url" : "https://www.youtube.com/watch?v=LXDBoHyjmtw",
  205. # "og:site_name" : "YouTube",
  206. # "og:video:type" : "application/x-shockwave-flash",
  207. # "og:description" : "Fun stuff happening here",
  208. # "og:title" : "RemoteJam - Matrix team hack for Disrupt Europe Hackathon",
  209. # "og:image" : "https://i.ytimg.com/vi/LXDBoHyjmtw/maxresdefault.jpg",
  210. # "og:video:url" : "http://www.youtube.com/v/LXDBoHyjmtw?version=3&autohide=1",
  211. # "og:video:width" : "1280"
  212. # "og:video:height" : "720",
  213. # "og:video:secure_url": "https://www.youtube.com/v/LXDBoHyjmtw?version=3",
  214. og = _get_meta_tags(tree, "property", "og")
  215. # TODO: Search for properties specific to the different Open Graph types,
  216. # such as article: meta tags, e.g.:
  217. #
  218. # "article:publisher" : "https://www.facebook.com/thethudonline" />
  219. # "article:author" content="https://www.facebook.com/thethudonline" />
  220. # "article:tag" content="baby" />
  221. # "article:section" content="Breaking News" />
  222. # "article:published_time" content="2016-03-31T19:58:24+00:00" />
  223. # "article:modified_time" content="2016-04-01T18:31:53+00:00" />
  224. # Search for Twitter Card (twitter:) meta tags, e.g.:
  225. #
  226. # "twitter:site" : "@matrixdotorg"
  227. # "twitter:creator" : "@matrixdotorg"
  228. #
  229. # Twitter cards tags also duplicate Open Graph tags.
  230. #
  231. # See https://developer.twitter.com/en/docs/twitter-for-websites/cards/guides/getting-started
  232. twitter = _get_meta_tags(tree, "name", "twitter", _map_twitter_to_open_graph)
  233. # Merge the Twitter values with the Open Graph values, but do not overwrite
  234. # information from Open Graph tags.
  235. for key, value in twitter.items():
  236. if key not in og:
  237. og[key] = value
  238. if "og:title" not in og:
  239. # Attempt to find a title from the title tag, or the biggest header on the page.
  240. # Cast: the type returned by xpath depends on the xpath expression: mypy can't deduce this.
  241. title = cast(
  242. List["etree._ElementUnicodeResult"],
  243. tree.xpath("((//title)[1] | (//h1)[1] | (//h2)[1] | (//h3)[1])/text()"),
  244. )
  245. if title:
  246. og["og:title"] = title[0].strip()
  247. else:
  248. og["og:title"] = None
  249. if "og:image" not in og:
  250. # Cast: the type returned by xpath depends on the xpath expression: mypy can't deduce this.
  251. meta_image = cast(
  252. List["etree._ElementUnicodeResult"],
  253. tree.xpath(
  254. "//*/meta[translate(@itemprop, 'IMAGE', 'image')='image'][not(@content='')]/@content[1]"
  255. ),
  256. )
  257. # If a meta image is found, use it.
  258. if meta_image:
  259. og["og:image"] = meta_image[0]
  260. else:
  261. # Try to find images which are larger than 10px by 10px.
  262. # Cast: the type returned by xpath depends on the xpath expression: mypy can't deduce this.
  263. #
  264. # TODO: consider inlined CSS styles as well as width & height attribs
  265. images = cast(
  266. List["etree._Element"],
  267. tree.xpath("//img[@src][number(@width)>10][number(@height)>10]"),
  268. )
  269. images = sorted(
  270. images,
  271. key=lambda i: (
  272. -1 * float(i.attrib["width"]) * float(i.attrib["height"])
  273. ),
  274. )
  275. # If no images were found, try to find *any* images.
  276. if not images:
  277. # Cast: the type returned by xpath depends on the xpath expression: mypy can't deduce this.
  278. images = cast(List["etree._Element"], tree.xpath("//img[@src][1]"))
  279. if images:
  280. og["og:image"] = cast(str, images[0].attrib["src"])
  281. # Finally, fallback to the favicon if nothing else.
  282. else:
  283. # Cast: the type returned by xpath depends on the xpath expression: mypy can't deduce this.
  284. favicons = cast(
  285. List["etree._ElementUnicodeResult"],
  286. tree.xpath("//link[@href][contains(@rel, 'icon')]/@href[1]"),
  287. )
  288. if favicons:
  289. og["og:image"] = favicons[0]
  290. if "og:description" not in og:
  291. # Check the first meta description tag for content.
  292. # Cast: the type returned by xpath depends on the xpath expression: mypy can't deduce this.
  293. meta_description = cast(
  294. List["etree._ElementUnicodeResult"],
  295. tree.xpath(
  296. "//*/meta[translate(@name, 'DESCRIPTION', 'description')='description'][not(@content='')]/@content[1]"
  297. ),
  298. )
  299. # If a meta description is found with content, use it.
  300. if meta_description:
  301. og["og:description"] = meta_description[0]
  302. else:
  303. og["og:description"] = parse_html_description(tree)
  304. elif og["og:description"]:
  305. # This must be a non-empty string at this point.
  306. assert isinstance(og["og:description"], str)
  307. og["og:description"] = summarize_paragraphs([og["og:description"]])
  308. # TODO: delete the url downloads to stop diskfilling,
  309. # as we only ever cared about its OG
  310. return og
  311. def parse_html_description(tree: "etree._Element") -> Optional[str]:
  312. """
  313. Calculate a text description based on an HTML document.
  314. Grabs any text nodes which are inside the <body/> tag, unless they are within
  315. an HTML5 semantic markup tag (<header/>, <nav/>, <aside/>, <footer/>), or
  316. if they are within a <script/>, <svg/> or <style/> tag, or if they are within
  317. a tag whose content is usually only shown to old browsers
  318. (<iframe/>, <video/>, <canvas/>, <picture/>).
  319. This is a very very very coarse approximation to a plain text render of the page.
  320. Args:
  321. tree: The parsed HTML document.
  322. Returns:
  323. The plain text description, or None if one cannot be generated.
  324. """
  325. # We don't just use XPATH here as that is slow on some machines.
  326. from lxml import etree
  327. TAGS_TO_REMOVE = {
  328. "header",
  329. "nav",
  330. "aside",
  331. "footer",
  332. "script",
  333. "noscript",
  334. "style",
  335. "svg",
  336. "iframe",
  337. "video",
  338. "canvas",
  339. "img",
  340. "picture",
  341. # etree.Comment is a function which creates an etree._Comment element.
  342. # The "tag" attribute of an etree._Comment instance is confusingly the
  343. # etree.Comment function instead of a string.
  344. etree.Comment,
  345. }
  346. # Split all the text nodes into paragraphs (by splitting on new
  347. # lines)
  348. text_nodes = (
  349. re.sub(r"\s+", "\n", el).strip()
  350. for el in _iterate_over_text(tree.find("body"), TAGS_TO_REMOVE)
  351. )
  352. return summarize_paragraphs(text_nodes)
  353. def _iterate_over_text(
  354. tree: Optional["etree._Element"],
  355. tags_to_ignore: Set[object],
  356. stack_limit: int = 1024,
  357. ) -> Generator[str, None, None]:
  358. """Iterate over the tree returning text nodes in a depth first fashion,
  359. skipping text nodes inside certain tags.
  360. Args:
  361. tree: The parent element to iterate. Can be None if there isn't one.
  362. tags_to_ignore: Set of tags to ignore
  363. stack_limit: Maximum stack size limit for depth-first traversal.
  364. Nodes will be dropped if this limit is hit, which may truncate the
  365. textual result.
  366. Intended to limit the maximum working memory when generating a preview.
  367. """
  368. if tree is None:
  369. return
  370. # This is a stack whose items are elements to iterate over *or* strings
  371. # to be returned.
  372. elements: List[Union[str, "etree._Element"]] = [tree]
  373. while elements:
  374. el = elements.pop()
  375. if isinstance(el, str):
  376. yield el
  377. elif el.tag not in tags_to_ignore:
  378. # If the element isn't meant for display, ignore it.
  379. if el.get("role") in ARIA_ROLES_TO_IGNORE:
  380. continue
  381. # el.text is the text before the first child, so we can immediately
  382. # return it if the text exists.
  383. if el.text:
  384. yield el.text
  385. # We add to the stack all the element's children, interspersed with
  386. # each child's tail text (if it exists).
  387. #
  388. # We iterate in reverse order so that earlier pieces of text appear
  389. # closer to the top of the stack.
  390. for child in el.iterchildren(reversed=True):
  391. if len(elements) > stack_limit:
  392. # We've hit our limit for working memory
  393. break
  394. if child.tail:
  395. # The tail text of a node is text that comes *after* the node,
  396. # so we always include it even if we ignore the child node.
  397. elements.append(child.tail)
  398. elements.append(child)
  399. def summarize_paragraphs(
  400. text_nodes: Iterable[str], min_size: int = 200, max_size: int = 500
  401. ) -> Optional[str]:
  402. """
  403. Try to get a summary respecting first paragraph and then word boundaries.
  404. Args:
  405. text_nodes: The paragraphs to summarize.
  406. min_size: The minimum number of words to include.
  407. max_size: The maximum number of words to include.
  408. Returns:
  409. A summary of the text nodes, or None if that was not possible.
  410. """
  411. # TODO: Respect sentences?
  412. description = ""
  413. # Keep adding paragraphs until we get to the MIN_SIZE.
  414. for text_node in text_nodes:
  415. if len(description) < min_size:
  416. text_node = re.sub(r"[\t \r\n]+", " ", text_node)
  417. description += text_node + "\n\n"
  418. else:
  419. break
  420. description = description.strip()
  421. description = re.sub(r"[\t ]+", " ", description)
  422. description = re.sub(r"[\t \r\n]*[\r\n]+", "\n\n", description)
  423. # If the concatenation of paragraphs to get above MIN_SIZE
  424. # took us over MAX_SIZE, then we need to truncate mid paragraph
  425. if len(description) > max_size:
  426. new_desc = ""
  427. # This splits the paragraph into words, but keeping the
  428. # (preceding) whitespace intact so we can easily concat
  429. # words back together.
  430. for match in re.finditer(r"\s*\S+", description):
  431. word = match.group()
  432. # Keep adding words while the total length is less than
  433. # MAX_SIZE.
  434. if len(word) + len(new_desc) < max_size:
  435. new_desc += word
  436. else:
  437. # At this point the next word *will* take us over
  438. # MAX_SIZE, but we also want to ensure that its not
  439. # a huge word. If it is add it anyway and we'll
  440. # truncate later.
  441. if len(new_desc) < min_size:
  442. new_desc += word
  443. break
  444. # Double check that we're not over the limit
  445. if len(new_desc) > max_size:
  446. new_desc = new_desc[:max_size]
  447. # We always add an ellipsis because at the very least
  448. # we chopped mid paragraph.
  449. description = new_desc.strip() + "…"
  450. return description if description else None