1
0

test_html_preview.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. # Copyright 2014-2016 OpenMarket Ltd
  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. from synapse.media.preview_html import (
  15. _get_html_media_encodings,
  16. decode_body,
  17. parse_html_to_open_graph,
  18. summarize_paragraphs,
  19. )
  20. from tests import unittest
  21. try:
  22. import lxml
  23. except ImportError:
  24. lxml = None # type: ignore[assignment]
  25. class SummarizeTestCase(unittest.TestCase):
  26. if not lxml:
  27. skip = "url preview feature requires lxml"
  28. def test_long_summarize(self) -> None:
  29. example_paras = [
  30. """Tromsø (Norwegian pronunciation: [ˈtrʊmsœ] ( listen); Northern Sami:
  31. Romsa; Finnish: Tromssa[2] Kven: Tromssa) is a city and municipality in
  32. Troms county, Norway. The administrative centre of the municipality is
  33. the city of Tromsø. Outside of Norway, Tromso and Tromsö are
  34. alternative spellings of the city.Tromsø is considered the northernmost
  35. city in the world with a population above 50,000. The most populous town
  36. north of it is Alta, Norway, with a population of 14,272 (2013).""",
  37. """Tromsø lies in Northern Norway. The municipality has a population of
  38. (2015) 72,066, but with an annual influx of students it has over 75,000
  39. most of the year. It is the largest urban area in Northern Norway and the
  40. third largest north of the Arctic Circle (following Murmansk and Norilsk).
  41. Most of Tromsø, including the city centre, is located on the island of
  42. Tromsøya, 350 kilometres (217 mi) north of the Arctic Circle. In 2012,
  43. Tromsøya had a population of 36,088. Substantial parts of the urban area
  44. are also situated on the mainland to the east, and on parts of Kvaløya—a
  45. large island to the west. Tromsøya is connected to the mainland by the Tromsø
  46. Bridge and the Tromsøysund Tunnel, and to the island of Kvaløya by the
  47. Sandnessund Bridge. Tromsø Airport connects the city to many destinations
  48. in Europe. The city is warmer than most other places located on the same
  49. latitude, due to the warming effect of the Gulf Stream.""",
  50. """The city centre of Tromsø contains the highest number of old wooden
  51. houses in Northern Norway, the oldest house dating from 1789. The Arctic
  52. Cathedral, a modern church from 1965, is probably the most famous landmark
  53. in Tromsø. The city is a cultural centre for its region, with several
  54. festivals taking place in the summer. Some of Norway's best-known
  55. musicians, Torbjørn Brundtland and Svein Berge of the electronica duo
  56. Röyksopp and Lene Marlin grew up and started their careers in Tromsø.
  57. Noted electronic musician Geir Jenssen also hails from Tromsø.""",
  58. ]
  59. desc = summarize_paragraphs(example_paras, min_size=200, max_size=500)
  60. self.assertEqual(
  61. desc,
  62. "Tromsø (Norwegian pronunciation: [ˈtrʊmsœ] ( listen); Northern Sami:"
  63. " Romsa; Finnish: Tromssa[2] Kven: Tromssa) is a city and municipality in"
  64. " Troms county, Norway. The administrative centre of the municipality is"
  65. " the city of Tromsø. Outside of Norway, Tromso and Tromsö are"
  66. " alternative spellings of the city.Tromsø is considered the northernmost"
  67. " city in the world with a population above 50,000. The most populous town"
  68. " north of it is Alta, Norway, with a population of 14,272 (2013).",
  69. )
  70. desc = summarize_paragraphs(example_paras[1:], min_size=200, max_size=500)
  71. self.assertEqual(
  72. desc,
  73. "Tromsø lies in Northern Norway. The municipality has a population of"
  74. " (2015) 72,066, but with an annual influx of students it has over 75,000"
  75. " most of the year. It is the largest urban area in Northern Norway and the"
  76. " third largest north of the Arctic Circle (following Murmansk and Norilsk)."
  77. " Most of Tromsø, including the city centre, is located on the island of"
  78. " Tromsøya, 350 kilometres (217 mi) north of the Arctic Circle. In 2012,"
  79. " Tromsøya had a population of 36,088. Substantial parts of the urban…",
  80. )
  81. def test_short_summarize(self) -> None:
  82. example_paras = [
  83. "Tromsø (Norwegian pronunciation: [ˈtrʊmsœ] ( listen); Northern Sami:"
  84. " Romsa; Finnish: Tromssa[2] Kven: Tromssa) is a city and municipality in"
  85. " Troms county, Norway.",
  86. "Tromsø lies in Northern Norway. The municipality has a population of"
  87. " (2015) 72,066, but with an annual influx of students it has over 75,000"
  88. " most of the year.",
  89. "The city centre of Tromsø contains the highest number of old wooden"
  90. " houses in Northern Norway, the oldest house dating from 1789. The Arctic"
  91. " Cathedral, a modern church from 1965, is probably the most famous landmark"
  92. " in Tromsø.",
  93. ]
  94. desc = summarize_paragraphs(example_paras, min_size=200, max_size=500)
  95. self.assertEqual(
  96. desc,
  97. "Tromsø (Norwegian pronunciation: [ˈtrʊmsœ] ( listen); Northern Sami:"
  98. " Romsa; Finnish: Tromssa[2] Kven: Tromssa) is a city and municipality in"
  99. " Troms county, Norway.\n"
  100. "\n"
  101. "Tromsø lies in Northern Norway. The municipality has a population of"
  102. " (2015) 72,066, but with an annual influx of students it has over 75,000"
  103. " most of the year.",
  104. )
  105. def test_small_then_large_summarize(self) -> None:
  106. example_paras = [
  107. "Tromsø (Norwegian pronunciation: [ˈtrʊmsœ] ( listen); Northern Sami:"
  108. " Romsa; Finnish: Tromssa[2] Kven: Tromssa) is a city and municipality in"
  109. " Troms county, Norway.",
  110. "Tromsø lies in Northern Norway. The municipality has a population of"
  111. " (2015) 72,066, but with an annual influx of students it has over 75,000"
  112. " most of the year."
  113. " The city centre of Tromsø contains the highest number of old wooden"
  114. " houses in Northern Norway, the oldest house dating from 1789. The Arctic"
  115. " Cathedral, a modern church from 1965, is probably the most famous landmark"
  116. " in Tromsø.",
  117. ]
  118. desc = summarize_paragraphs(example_paras, min_size=200, max_size=500)
  119. self.assertEqual(
  120. desc,
  121. "Tromsø (Norwegian pronunciation: [ˈtrʊmsœ] ( listen); Northern Sami:"
  122. " Romsa; Finnish: Tromssa[2] Kven: Tromssa) is a city and municipality in"
  123. " Troms county, Norway.\n"
  124. "\n"
  125. "Tromsø lies in Northern Norway. The municipality has a population of"
  126. " (2015) 72,066, but with an annual influx of students it has over 75,000"
  127. " most of the year. The city centre of Tromsø contains the highest number"
  128. " of old wooden houses in Northern Norway, the oldest house dating from"
  129. " 1789. The Arctic Cathedral, a modern church from…",
  130. )
  131. class OpenGraphFromHtmlTestCase(unittest.TestCase):
  132. if not lxml:
  133. skip = "url preview feature requires lxml"
  134. def test_simple(self) -> None:
  135. html = b"""
  136. <html>
  137. <head><title>Foo</title></head>
  138. <body>
  139. Some text.
  140. </body>
  141. </html>
  142. """
  143. tree = decode_body(html, "http://example.com/test.html")
  144. assert tree is not None
  145. og = parse_html_to_open_graph(tree)
  146. self.assertEqual(og, {"og:title": "Foo", "og:description": "Some text."})
  147. def test_comment(self) -> None:
  148. html = b"""
  149. <html>
  150. <head><title>Foo</title></head>
  151. <body>
  152. <!-- HTML comment -->
  153. Some text.
  154. </body>
  155. </html>
  156. """
  157. tree = decode_body(html, "http://example.com/test.html")
  158. assert tree is not None
  159. og = parse_html_to_open_graph(tree)
  160. self.assertEqual(og, {"og:title": "Foo", "og:description": "Some text."})
  161. def test_comment2(self) -> None:
  162. html = b"""
  163. <html>
  164. <head><title>Foo</title></head>
  165. <body>
  166. Some text.
  167. <!-- HTML comment -->
  168. Some more text.
  169. <p>Text</p>
  170. More text
  171. </body>
  172. </html>
  173. """
  174. tree = decode_body(html, "http://example.com/test.html")
  175. assert tree is not None
  176. og = parse_html_to_open_graph(tree)
  177. self.assertEqual(
  178. og,
  179. {
  180. "og:title": "Foo",
  181. "og:description": "Some text.\n\nSome more text.\n\nText\n\nMore text",
  182. },
  183. )
  184. def test_script(self) -> None:
  185. html = b"""
  186. <html>
  187. <head><title>Foo</title></head>
  188. <body>
  189. <script> (function() {})() </script>
  190. Some text.
  191. </body>
  192. </html>
  193. """
  194. tree = decode_body(html, "http://example.com/test.html")
  195. assert tree is not None
  196. og = parse_html_to_open_graph(tree)
  197. self.assertEqual(og, {"og:title": "Foo", "og:description": "Some text."})
  198. def test_missing_title(self) -> None:
  199. html = b"""
  200. <html>
  201. <body>
  202. Some text.
  203. </body>
  204. </html>
  205. """
  206. tree = decode_body(html, "http://example.com/test.html")
  207. assert tree is not None
  208. og = parse_html_to_open_graph(tree)
  209. self.assertEqual(og, {"og:title": None, "og:description": "Some text."})
  210. # Another variant is a title with no content.
  211. html = b"""
  212. <html>
  213. <head><title></title></head>
  214. <body>
  215. <h1>Title</h1>
  216. </body>
  217. </html>
  218. """
  219. tree = decode_body(html, "http://example.com/test.html")
  220. assert tree is not None
  221. og = parse_html_to_open_graph(tree)
  222. self.assertEqual(og, {"og:title": "Title", "og:description": "Title"})
  223. def test_h1_as_title(self) -> None:
  224. html = b"""
  225. <html>
  226. <meta property="og:description" content="Some text."/>
  227. <body>
  228. <h1>Title</h1>
  229. </body>
  230. </html>
  231. """
  232. tree = decode_body(html, "http://example.com/test.html")
  233. assert tree is not None
  234. og = parse_html_to_open_graph(tree)
  235. self.assertEqual(og, {"og:title": "Title", "og:description": "Some text."})
  236. def test_empty_description(self) -> None:
  237. """Description tags with empty content should be ignored."""
  238. html = b"""
  239. <html>
  240. <meta property="og:description" content=""/>
  241. <meta property="og:description"/>
  242. <meta name="description" content=""/>
  243. <meta name="description"/>
  244. <meta name="description" content="Finally!"/>
  245. <body>
  246. <h1>Title</h1>
  247. </body>
  248. </html>
  249. """
  250. tree = decode_body(html, "http://example.com/test.html")
  251. assert tree is not None
  252. og = parse_html_to_open_graph(tree)
  253. self.assertEqual(og, {"og:title": "Title", "og:description": "Finally!"})
  254. def test_missing_title_and_broken_h1(self) -> None:
  255. html = b"""
  256. <html>
  257. <body>
  258. <h1><a href="foo"/></h1>
  259. Some text.
  260. </body>
  261. </html>
  262. """
  263. tree = decode_body(html, "http://example.com/test.html")
  264. assert tree is not None
  265. og = parse_html_to_open_graph(tree)
  266. self.assertEqual(og, {"og:title": None, "og:description": "Some text."})
  267. def test_empty(self) -> None:
  268. """Test a body with no data in it."""
  269. html = b""
  270. tree = decode_body(html, "http://example.com/test.html")
  271. self.assertIsNone(tree)
  272. def test_no_tree(self) -> None:
  273. """A valid body with no tree in it."""
  274. html = b"\x00"
  275. tree = decode_body(html, "http://example.com/test.html")
  276. self.assertIsNone(tree)
  277. def test_xml(self) -> None:
  278. """Test decoding XML and ensure it works properly."""
  279. # Note that the strip() call is important to ensure the xml tag starts
  280. # at the initial byte.
  281. html = b"""
  282. <?xml version="1.0" encoding="UTF-8"?>
  283. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  284. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  285. <head><title>Foo</title></head><body>Some text.</body></html>
  286. """.strip()
  287. tree = decode_body(html, "http://example.com/test.html")
  288. assert tree is not None
  289. og = parse_html_to_open_graph(tree)
  290. self.assertEqual(og, {"og:title": "Foo", "og:description": "Some text."})
  291. def test_invalid_encoding(self) -> None:
  292. """An invalid character encoding should be ignored and treated as UTF-8, if possible."""
  293. html = b"""
  294. <html>
  295. <head><title>Foo</title></head>
  296. <body>
  297. Some text.
  298. </body>
  299. </html>
  300. """
  301. tree = decode_body(html, "http://example.com/test.html", "invalid-encoding")
  302. assert tree is not None
  303. og = parse_html_to_open_graph(tree)
  304. self.assertEqual(og, {"og:title": "Foo", "og:description": "Some text."})
  305. def test_invalid_encoding2(self) -> None:
  306. """A body which doesn't match the sent character encoding."""
  307. # Note that this contains an invalid UTF-8 sequence in the title.
  308. html = b"""
  309. <html>
  310. <head><title>\xff\xff Foo</title></head>
  311. <body>
  312. Some text.
  313. </body>
  314. </html>
  315. """
  316. tree = decode_body(html, "http://example.com/test.html")
  317. assert tree is not None
  318. og = parse_html_to_open_graph(tree)
  319. self.assertEqual(og, {"og:title": "ÿÿ Foo", "og:description": "Some text."})
  320. def test_windows_1252(self) -> None:
  321. """A body which uses cp1252, but doesn't declare that."""
  322. html = b"""
  323. <html>
  324. <head><title>\xf3</title></head>
  325. <body>
  326. Some text.
  327. </body>
  328. </html>
  329. """
  330. tree = decode_body(html, "http://example.com/test.html")
  331. assert tree is not None
  332. og = parse_html_to_open_graph(tree)
  333. self.assertEqual(og, {"og:title": "ó", "og:description": "Some text."})
  334. def test_twitter_tag(self) -> None:
  335. """Twitter card tags should be used if nothing else is available."""
  336. html = b"""
  337. <html>
  338. <meta name="twitter:card" content="summary">
  339. <meta name="twitter:description" content="Description">
  340. <meta name="twitter:site" content="@matrixdotorg">
  341. </html>
  342. """
  343. tree = decode_body(html, "http://example.com/test.html")
  344. assert tree is not None
  345. og = parse_html_to_open_graph(tree)
  346. self.assertEqual(
  347. og,
  348. {
  349. "og:title": None,
  350. "og:description": "Description",
  351. "og:site_name": "@matrixdotorg",
  352. },
  353. )
  354. # But they shouldn't override Open Graph values.
  355. html = b"""
  356. <html>
  357. <meta name="twitter:card" content="summary">
  358. <meta name="twitter:description" content="Description">
  359. <meta property="og:description" content="Real Description">
  360. <meta name="twitter:site" content="@matrixdotorg">
  361. <meta property="og:site_name" content="matrix.org">
  362. </html>
  363. """
  364. tree = decode_body(html, "http://example.com/test.html")
  365. assert tree is not None
  366. og = parse_html_to_open_graph(tree)
  367. self.assertEqual(
  368. og,
  369. {
  370. "og:title": None,
  371. "og:description": "Real Description",
  372. "og:site_name": "matrix.org",
  373. },
  374. )
  375. def test_nested_nodes(self) -> None:
  376. """A body with some nested nodes. Tests that we iterate over children
  377. in the right order (and don't reverse the order of the text)."""
  378. html = b"""
  379. <a href="somewhere">Welcome <b>the bold <u>and underlined text <svg>
  380. with a cheeky SVG</svg></u> and <strong>some</strong> tail text</b></a>
  381. """
  382. tree = decode_body(html, "http://example.com/test.html")
  383. assert tree is not None
  384. og = parse_html_to_open_graph(tree)
  385. self.assertEqual(
  386. og,
  387. {
  388. "og:title": None,
  389. "og:description": "Welcome\n\nthe bold\n\nand underlined text\n\nand\n\nsome\n\ntail text",
  390. },
  391. )
  392. class MediaEncodingTestCase(unittest.TestCase):
  393. def test_meta_charset(self) -> None:
  394. """A character encoding is found via the meta tag."""
  395. encodings = _get_html_media_encodings(
  396. b"""
  397. <html>
  398. <head><meta charset="ascii">
  399. </head>
  400. </html>
  401. """,
  402. "text/html",
  403. )
  404. self.assertEqual(list(encodings), ["ascii", "utf-8", "cp1252"])
  405. # A less well-formed version.
  406. encodings = _get_html_media_encodings(
  407. b"""
  408. <html>
  409. <head>< meta charset = ascii>
  410. </head>
  411. </html>
  412. """,
  413. "text/html",
  414. )
  415. self.assertEqual(list(encodings), ["ascii", "utf-8", "cp1252"])
  416. def test_meta_charset_underscores(self) -> None:
  417. """A character encoding contains underscore."""
  418. encodings = _get_html_media_encodings(
  419. b"""
  420. <html>
  421. <head><meta charset="Shift_JIS">
  422. </head>
  423. </html>
  424. """,
  425. "text/html",
  426. )
  427. self.assertEqual(list(encodings), ["shift_jis", "utf-8", "cp1252"])
  428. def test_xml_encoding(self) -> None:
  429. """A character encoding is found via the meta tag."""
  430. encodings = _get_html_media_encodings(
  431. b"""
  432. <?xml version="1.0" encoding="ascii"?>
  433. <html>
  434. </html>
  435. """,
  436. "text/html",
  437. )
  438. self.assertEqual(list(encodings), ["ascii", "utf-8", "cp1252"])
  439. def test_meta_xml_encoding(self) -> None:
  440. """Meta tags take precedence over XML encoding."""
  441. encodings = _get_html_media_encodings(
  442. b"""
  443. <?xml version="1.0" encoding="ascii"?>
  444. <html>
  445. <head><meta charset="UTF-16">
  446. </head>
  447. </html>
  448. """,
  449. "text/html",
  450. )
  451. self.assertEqual(list(encodings), ["utf-16", "ascii", "utf-8", "cp1252"])
  452. def test_content_type(self) -> None:
  453. """A character encoding is found via the Content-Type header."""
  454. # Test a few variations of the header.
  455. headers = (
  456. 'text/html; charset="ascii";',
  457. "text/html;charset=ascii;",
  458. 'text/html; charset="ascii"',
  459. "text/html; charset=ascii",
  460. 'text/html; charset="ascii;',
  461. 'text/html; charset=ascii";',
  462. )
  463. for header in headers:
  464. encodings = _get_html_media_encodings(b"", header)
  465. self.assertEqual(list(encodings), ["ascii", "utf-8", "cp1252"])
  466. def test_fallback(self) -> None:
  467. """A character encoding cannot be found in the body or header."""
  468. encodings = _get_html_media_encodings(b"", "text/html")
  469. self.assertEqual(list(encodings), ["utf-8", "cp1252"])
  470. def test_duplicates(self) -> None:
  471. """Ensure each encoding is only attempted once."""
  472. encodings = _get_html_media_encodings(
  473. b"""
  474. <?xml version="1.0" encoding="utf8"?>
  475. <html>
  476. <head><meta charset="UTF-8">
  477. </head>
  478. </html>
  479. """,
  480. 'text/html; charset="UTF_8"',
  481. )
  482. self.assertEqual(list(encodings), ["utf-8", "cp1252"])
  483. def test_unknown_invalid(self) -> None:
  484. """A character encoding should be ignored if it is unknown or invalid."""
  485. encodings = _get_html_media_encodings(
  486. b"""
  487. <html>
  488. <head><meta charset="invalid">
  489. </head>
  490. </html>
  491. """,
  492. 'text/html; charset="invalid"',
  493. )
  494. self.assertEqual(list(encodings), ["utf-8", "cp1252"])