preview_url_resource.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 OpenMarket 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 datetime
  16. import errno
  17. import fnmatch
  18. import itertools
  19. import logging
  20. import os
  21. import re
  22. import shutil
  23. import sys
  24. import traceback
  25. from typing import Dict, Optional
  26. from urllib import parse as urlparse
  27. from canonicaljson import json
  28. from twisted.internet import defer
  29. from twisted.internet.error import DNSLookupError
  30. from synapse.api.errors import Codes, SynapseError
  31. from synapse.http.client import SimpleHttpClient
  32. from synapse.http.server import (
  33. DirectServeResource,
  34. respond_with_json,
  35. respond_with_json_bytes,
  36. wrap_json_request_handler,
  37. )
  38. from synapse.http.servlet import parse_integer, parse_string
  39. from synapse.logging.context import make_deferred_yieldable, run_in_background
  40. from synapse.metrics.background_process_metrics import run_as_background_process
  41. from synapse.rest.media.v1._base import get_filename_from_headers
  42. from synapse.util.async_helpers import ObservableDeferred
  43. from synapse.util.caches.expiringcache import ExpiringCache
  44. from synapse.util.stringutils import random_string
  45. from ._base import FileInfo
  46. logger = logging.getLogger(__name__)
  47. _charset_match = re.compile(br"<\s*meta[^>]*charset\s*=\s*([a-z0-9-]+)", flags=re.I)
  48. _content_type_match = re.compile(r'.*; *charset="?(.*?)"?(;|$)', flags=re.I)
  49. OG_TAG_NAME_MAXLEN = 50
  50. OG_TAG_VALUE_MAXLEN = 1000
  51. class PreviewUrlResource(DirectServeResource):
  52. isLeaf = True
  53. def __init__(self, hs, media_repo, media_storage):
  54. super().__init__()
  55. self.auth = hs.get_auth()
  56. self.clock = hs.get_clock()
  57. self.filepaths = media_repo.filepaths
  58. self.max_spider_size = hs.config.max_spider_size
  59. self.server_name = hs.hostname
  60. self.store = hs.get_datastore()
  61. self.client = SimpleHttpClient(
  62. hs,
  63. treq_args={"browser_like_redirects": True},
  64. ip_whitelist=hs.config.url_preview_ip_range_whitelist,
  65. ip_blacklist=hs.config.url_preview_ip_range_blacklist,
  66. http_proxy=os.getenvb(b"http_proxy"),
  67. https_proxy=os.getenvb(b"HTTPS_PROXY"),
  68. )
  69. self.media_repo = media_repo
  70. self.primary_base_path = media_repo.primary_base_path
  71. self.media_storage = media_storage
  72. self.url_preview_url_blacklist = hs.config.url_preview_url_blacklist
  73. self.url_preview_accept_language = hs.config.url_preview_accept_language
  74. # memory cache mapping urls to an ObservableDeferred returning
  75. # JSON-encoded OG metadata
  76. self._cache = ExpiringCache(
  77. cache_name="url_previews",
  78. clock=self.clock,
  79. # don't spider URLs more often than once an hour
  80. expiry_ms=60 * 60 * 1000,
  81. )
  82. self._cleaner_loop = self.clock.looping_call(
  83. self._start_expire_url_cache_data, 10 * 1000
  84. )
  85. def render_OPTIONS(self, request):
  86. request.setHeader(b"Allow", b"OPTIONS, GET")
  87. return respond_with_json(request, 200, {}, send_cors=True)
  88. @wrap_json_request_handler
  89. async def _async_render_GET(self, request):
  90. # XXX: if get_user_by_req fails, what should we do in an async render?
  91. requester = await self.auth.get_user_by_req(request)
  92. url = parse_string(request, "url")
  93. if b"ts" in request.args:
  94. ts = parse_integer(request, "ts")
  95. else:
  96. ts = self.clock.time_msec()
  97. # XXX: we could move this into _do_preview if we wanted.
  98. url_tuple = urlparse.urlsplit(url)
  99. for entry in self.url_preview_url_blacklist:
  100. match = True
  101. for attrib in entry:
  102. pattern = entry[attrib]
  103. value = getattr(url_tuple, attrib)
  104. logger.debug(
  105. "Matching attrib '%s' with value '%s' against pattern '%s'",
  106. attrib,
  107. value,
  108. pattern,
  109. )
  110. if value is None:
  111. match = False
  112. continue
  113. if pattern.startswith("^"):
  114. if not re.match(pattern, getattr(url_tuple, attrib)):
  115. match = False
  116. continue
  117. else:
  118. if not fnmatch.fnmatch(getattr(url_tuple, attrib), pattern):
  119. match = False
  120. continue
  121. if match:
  122. logger.warning("URL %s blocked by url_blacklist entry %s", url, entry)
  123. raise SynapseError(
  124. 403, "URL blocked by url pattern blacklist entry", Codes.UNKNOWN
  125. )
  126. # the in-memory cache:
  127. # * ensures that only one request is active at a time
  128. # * takes load off the DB for the thundering herds
  129. # * also caches any failures (unlike the DB) so we don't keep
  130. # requesting the same endpoint
  131. observable = self._cache.get(url)
  132. if not observable:
  133. download = run_in_background(self._do_preview, url, requester.user, ts)
  134. observable = ObservableDeferred(download, consumeErrors=True)
  135. self._cache[url] = observable
  136. else:
  137. logger.info("Returning cached response")
  138. og = await make_deferred_yieldable(defer.maybeDeferred(observable.observe))
  139. respond_with_json_bytes(request, 200, og, send_cors=True)
  140. async def _do_preview(self, url, user, ts):
  141. """Check the db, and download the URL and build a preview
  142. Args:
  143. url (str):
  144. user (str):
  145. ts (int):
  146. Returns:
  147. Deferred[bytes]: json-encoded og data
  148. """
  149. # check the URL cache in the DB (which will also provide us with
  150. # historical previews, if we have any)
  151. cache_result = await self.store.get_url_cache(url, ts)
  152. if (
  153. cache_result
  154. and cache_result["expires_ts"] > ts
  155. and cache_result["response_code"] / 100 == 2
  156. ):
  157. # It may be stored as text in the database, not as bytes (such as
  158. # PostgreSQL). If so, encode it back before handing it on.
  159. og = cache_result["og"]
  160. if isinstance(og, str):
  161. og = og.encode("utf8")
  162. return og
  163. media_info = await self._download_url(url, user)
  164. logger.debug("got media_info of '%s'", media_info)
  165. if _is_media(media_info["media_type"]):
  166. file_id = media_info["filesystem_id"]
  167. dims = await self.media_repo._generate_thumbnails(
  168. None, file_id, file_id, media_info["media_type"], url_cache=True
  169. )
  170. og = {
  171. "og:description": media_info["download_name"],
  172. "og:image": "mxc://%s/%s"
  173. % (self.server_name, media_info["filesystem_id"]),
  174. "og:image:type": media_info["media_type"],
  175. "matrix:image:size": media_info["media_length"],
  176. }
  177. if dims:
  178. og["og:image:width"] = dims["width"]
  179. og["og:image:height"] = dims["height"]
  180. else:
  181. logger.warning("Couldn't get dims for %s" % url)
  182. # define our OG response for this media
  183. elif _is_html(media_info["media_type"]):
  184. # TODO: somehow stop a big HTML tree from exploding synapse's RAM
  185. with open(media_info["filename"], "rb") as file:
  186. body = file.read()
  187. encoding = None
  188. # Let's try and figure out if it has an encoding set in a meta tag.
  189. # Limit it to the first 1kb, since it ought to be in the meta tags
  190. # at the top.
  191. match = _charset_match.search(body[:1000])
  192. # If we find a match, it should take precedence over the
  193. # Content-Type header, so set it here.
  194. if match:
  195. encoding = match.group(1).decode("ascii")
  196. # If we don't find a match, we'll look at the HTTP Content-Type, and
  197. # if that doesn't exist, we'll fall back to UTF-8.
  198. if not encoding:
  199. content_match = _content_type_match.match(media_info["media_type"])
  200. encoding = content_match.group(1) if content_match else "utf-8"
  201. og = decode_and_calc_og(body, media_info["uri"], encoding)
  202. # pre-cache the image for posterity
  203. # FIXME: it might be cleaner to use the same flow as the main /preview_url
  204. # request itself and benefit from the same caching etc. But for now we
  205. # just rely on the caching on the master request to speed things up.
  206. if "og:image" in og and og["og:image"]:
  207. image_info = await self._download_url(
  208. _rebase_url(og["og:image"], media_info["uri"]), user
  209. )
  210. if _is_media(image_info["media_type"]):
  211. # TODO: make sure we don't choke on white-on-transparent images
  212. file_id = image_info["filesystem_id"]
  213. dims = await self.media_repo._generate_thumbnails(
  214. None, file_id, file_id, image_info["media_type"], url_cache=True
  215. )
  216. if dims:
  217. og["og:image:width"] = dims["width"]
  218. og["og:image:height"] = dims["height"]
  219. else:
  220. logger.warning("Couldn't get dims for %s", og["og:image"])
  221. og["og:image"] = "mxc://%s/%s" % (
  222. self.server_name,
  223. image_info["filesystem_id"],
  224. )
  225. og["og:image:type"] = image_info["media_type"]
  226. og["matrix:image:size"] = image_info["media_length"]
  227. else:
  228. del og["og:image"]
  229. else:
  230. logger.warning("Failed to find any OG data in %s", url)
  231. og = {}
  232. # filter out any stupidly long values
  233. keys_to_remove = []
  234. for k, v in og.items():
  235. # values can be numeric as well as strings, hence the cast to str
  236. if len(k) > OG_TAG_NAME_MAXLEN or len(str(v)) > OG_TAG_VALUE_MAXLEN:
  237. logger.warning(
  238. "Pruning overlong tag %s from OG data", k[:OG_TAG_NAME_MAXLEN]
  239. )
  240. keys_to_remove.append(k)
  241. for k in keys_to_remove:
  242. del og[k]
  243. logger.debug("Calculated OG for %s as %s", url, og)
  244. jsonog = json.dumps(og)
  245. # store OG in history-aware DB cache
  246. await self.store.store_url_cache(
  247. url,
  248. media_info["response_code"],
  249. media_info["etag"],
  250. media_info["expires"] + media_info["created_ts"],
  251. jsonog,
  252. media_info["filesystem_id"],
  253. media_info["created_ts"],
  254. )
  255. return jsonog.encode("utf8")
  256. async def _download_url(self, url, user):
  257. # TODO: we should probably honour robots.txt... except in practice
  258. # we're most likely being explicitly triggered by a human rather than a
  259. # bot, so are we really a robot?
  260. file_id = datetime.date.today().isoformat() + "_" + random_string(16)
  261. file_info = FileInfo(server_name=None, file_id=file_id, url_cache=True)
  262. with self.media_storage.store_into_file(file_info) as (f, fname, finish):
  263. try:
  264. logger.debug("Trying to get preview for url '%s'", url)
  265. length, headers, uri, code = await self.client.get_file(
  266. url,
  267. output_stream=f,
  268. max_size=self.max_spider_size,
  269. headers={"Accept-Language": self.url_preview_accept_language},
  270. )
  271. except SynapseError:
  272. # Pass SynapseErrors through directly, so that the servlet
  273. # handler will return a SynapseError to the client instead of
  274. # blank data or a 500.
  275. raise
  276. except DNSLookupError:
  277. # DNS lookup returned no results
  278. # Note: This will also be the case if one of the resolved IP
  279. # addresses is blacklisted
  280. raise SynapseError(
  281. 502,
  282. "DNS resolution failure during URL preview generation",
  283. Codes.UNKNOWN,
  284. )
  285. except Exception as e:
  286. # FIXME: pass through 404s and other error messages nicely
  287. logger.warning("Error downloading %s: %r", url, e)
  288. raise SynapseError(
  289. 500,
  290. "Failed to download content: %s"
  291. % (traceback.format_exception_only(sys.exc_info()[0], e),),
  292. Codes.UNKNOWN,
  293. )
  294. await finish()
  295. try:
  296. if b"Content-Type" in headers:
  297. media_type = headers[b"Content-Type"][0].decode("ascii")
  298. else:
  299. media_type = "application/octet-stream"
  300. time_now_ms = self.clock.time_msec()
  301. download_name = get_filename_from_headers(headers)
  302. await self.store.store_local_media(
  303. media_id=file_id,
  304. media_type=media_type,
  305. time_now_ms=self.clock.time_msec(),
  306. upload_name=download_name,
  307. media_length=length,
  308. user_id=user,
  309. url_cache=url,
  310. )
  311. except Exception as e:
  312. logger.error("Error handling downloaded %s: %r", url, e)
  313. # TODO: we really ought to delete the downloaded file in this
  314. # case, since we won't have recorded it in the db, and will
  315. # therefore not expire it.
  316. raise
  317. return {
  318. "media_type": media_type,
  319. "media_length": length,
  320. "download_name": download_name,
  321. "created_ts": time_now_ms,
  322. "filesystem_id": file_id,
  323. "filename": fname,
  324. "uri": uri,
  325. "response_code": code,
  326. # FIXME: we should calculate a proper expiration based on the
  327. # Cache-Control and Expire headers. But for now, assume 1 hour.
  328. "expires": 60 * 60 * 1000,
  329. "etag": headers["ETag"][0] if "ETag" in headers else None,
  330. }
  331. def _start_expire_url_cache_data(self):
  332. return run_as_background_process(
  333. "expire_url_cache_data", self._expire_url_cache_data
  334. )
  335. async def _expire_url_cache_data(self):
  336. """Clean up expired url cache content, media and thumbnails.
  337. """
  338. # TODO: Delete from backup media store
  339. now = self.clock.time_msec()
  340. logger.debug("Running url preview cache expiry")
  341. if not (await self.store.db.updates.has_completed_background_updates()):
  342. logger.info("Still running DB updates; skipping expiry")
  343. return
  344. # First we delete expired url cache entries
  345. media_ids = await self.store.get_expired_url_cache(now)
  346. removed_media = []
  347. for media_id in media_ids:
  348. fname = self.filepaths.url_cache_filepath(media_id)
  349. try:
  350. os.remove(fname)
  351. except OSError as e:
  352. # If the path doesn't exist, meh
  353. if e.errno != errno.ENOENT:
  354. logger.warning("Failed to remove media: %r: %s", media_id, e)
  355. continue
  356. removed_media.append(media_id)
  357. try:
  358. dirs = self.filepaths.url_cache_filepath_dirs_to_delete(media_id)
  359. for dir in dirs:
  360. os.rmdir(dir)
  361. except Exception:
  362. pass
  363. await self.store.delete_url_cache(removed_media)
  364. if removed_media:
  365. logger.info("Deleted %d entries from url cache", len(removed_media))
  366. else:
  367. logger.debug("No entries removed from url cache")
  368. # Now we delete old images associated with the url cache.
  369. # These may be cached for a bit on the client (i.e., they
  370. # may have a room open with a preview url thing open).
  371. # So we wait a couple of days before deleting, just in case.
  372. expire_before = now - 2 * 24 * 60 * 60 * 1000
  373. media_ids = await self.store.get_url_cache_media_before(expire_before)
  374. removed_media = []
  375. for media_id in media_ids:
  376. fname = self.filepaths.url_cache_filepath(media_id)
  377. try:
  378. os.remove(fname)
  379. except OSError as e:
  380. # If the path doesn't exist, meh
  381. if e.errno != errno.ENOENT:
  382. logger.warning("Failed to remove media: %r: %s", media_id, e)
  383. continue
  384. try:
  385. dirs = self.filepaths.url_cache_filepath_dirs_to_delete(media_id)
  386. for dir in dirs:
  387. os.rmdir(dir)
  388. except Exception:
  389. pass
  390. thumbnail_dir = self.filepaths.url_cache_thumbnail_directory(media_id)
  391. try:
  392. shutil.rmtree(thumbnail_dir)
  393. except OSError as e:
  394. # If the path doesn't exist, meh
  395. if e.errno != errno.ENOENT:
  396. logger.warning("Failed to remove media: %r: %s", media_id, e)
  397. continue
  398. removed_media.append(media_id)
  399. try:
  400. dirs = self.filepaths.url_cache_thumbnail_dirs_to_delete(media_id)
  401. for dir in dirs:
  402. os.rmdir(dir)
  403. except Exception:
  404. pass
  405. await self.store.delete_url_cache_media(removed_media)
  406. if removed_media:
  407. logger.info("Deleted %d media from url cache", len(removed_media))
  408. else:
  409. logger.debug("No media removed from url cache")
  410. def decode_and_calc_og(body, media_uri, request_encoding=None):
  411. from lxml import etree
  412. try:
  413. parser = etree.HTMLParser(recover=True, encoding=request_encoding)
  414. tree = etree.fromstring(body, parser)
  415. og = _calc_og(tree, media_uri)
  416. except UnicodeDecodeError:
  417. # blindly try decoding the body as utf-8, which seems to fix
  418. # the charset mismatches on https://google.com
  419. parser = etree.HTMLParser(recover=True, encoding=request_encoding)
  420. tree = etree.fromstring(body.decode("utf-8", "ignore"), parser)
  421. og = _calc_og(tree, media_uri)
  422. return og
  423. def _calc_og(tree, media_uri):
  424. # suck our tree into lxml and define our OG response.
  425. # if we see any image URLs in the OG response, then spider them
  426. # (although the client could choose to do this by asking for previews of those
  427. # URLs to avoid DoSing the server)
  428. # "og:type" : "video",
  429. # "og:url" : "https://www.youtube.com/watch?v=LXDBoHyjmtw",
  430. # "og:site_name" : "YouTube",
  431. # "og:video:type" : "application/x-shockwave-flash",
  432. # "og:description" : "Fun stuff happening here",
  433. # "og:title" : "RemoteJam - Matrix team hack for Disrupt Europe Hackathon",
  434. # "og:image" : "https://i.ytimg.com/vi/LXDBoHyjmtw/maxresdefault.jpg",
  435. # "og:video:url" : "http://www.youtube.com/v/LXDBoHyjmtw?version=3&autohide=1",
  436. # "og:video:width" : "1280"
  437. # "og:video:height" : "720",
  438. # "og:video:secure_url": "https://www.youtube.com/v/LXDBoHyjmtw?version=3",
  439. og = {} # type: Dict[str, Optional[str]]
  440. for tag in tree.xpath("//*/meta[starts-with(@property, 'og:')]"):
  441. if "content" in tag.attrib:
  442. # if we've got more than 50 tags, someone is taking the piss
  443. if len(og) >= 50:
  444. logger.warning("Skipping OG for page with too many 'og:' tags")
  445. return {}
  446. og[tag.attrib["property"]] = tag.attrib["content"]
  447. # TODO: grab article: meta tags too, e.g.:
  448. # "article:publisher" : "https://www.facebook.com/thethudonline" />
  449. # "article:author" content="https://www.facebook.com/thethudonline" />
  450. # "article:tag" content="baby" />
  451. # "article:section" content="Breaking News" />
  452. # "article:published_time" content="2016-03-31T19:58:24+00:00" />
  453. # "article:modified_time" content="2016-04-01T18:31:53+00:00" />
  454. if "og:title" not in og:
  455. # do some basic spidering of the HTML
  456. title = tree.xpath("(//title)[1] | (//h1)[1] | (//h2)[1] | (//h3)[1]")
  457. if title and title[0].text is not None:
  458. og["og:title"] = title[0].text.strip()
  459. else:
  460. og["og:title"] = None
  461. if "og:image" not in og:
  462. # TODO: extract a favicon failing all else
  463. meta_image = tree.xpath(
  464. "//*/meta[translate(@itemprop, 'IMAGE', 'image')='image']/@content"
  465. )
  466. if meta_image:
  467. og["og:image"] = _rebase_url(meta_image[0], media_uri)
  468. else:
  469. # TODO: consider inlined CSS styles as well as width & height attribs
  470. images = tree.xpath("//img[@src][number(@width)>10][number(@height)>10]")
  471. images = sorted(
  472. images,
  473. key=lambda i: (
  474. -1 * float(i.attrib["width"]) * float(i.attrib["height"])
  475. ),
  476. )
  477. if not images:
  478. images = tree.xpath("//img[@src]")
  479. if images:
  480. og["og:image"] = images[0].attrib["src"]
  481. if "og:description" not in og:
  482. meta_description = tree.xpath(
  483. "//*/meta"
  484. "[translate(@name, 'DESCRIPTION', 'description')='description']"
  485. "/@content"
  486. )
  487. if meta_description:
  488. og["og:description"] = meta_description[0]
  489. else:
  490. # grab any text nodes which are inside the <body/> tag...
  491. # unless they are within an HTML5 semantic markup tag...
  492. # <header/>, <nav/>, <aside/>, <footer/>
  493. # ...or if they are within a <script/> or <style/> tag.
  494. # This is a very very very coarse approximation to a plain text
  495. # render of the page.
  496. # We don't just use XPATH here as that is slow on some machines.
  497. from lxml import etree
  498. TAGS_TO_REMOVE = (
  499. "header",
  500. "nav",
  501. "aside",
  502. "footer",
  503. "script",
  504. "noscript",
  505. "style",
  506. etree.Comment,
  507. )
  508. # Split all the text nodes into paragraphs (by splitting on new
  509. # lines)
  510. text_nodes = (
  511. re.sub(r"\s+", "\n", el).strip()
  512. for el in _iterate_over_text(tree.find("body"), *TAGS_TO_REMOVE)
  513. )
  514. og["og:description"] = summarize_paragraphs(text_nodes)
  515. else:
  516. og["og:description"] = summarize_paragraphs([og["og:description"]])
  517. # TODO: delete the url downloads to stop diskfilling,
  518. # as we only ever cared about its OG
  519. return og
  520. def _iterate_over_text(tree, *tags_to_ignore):
  521. """Iterate over the tree returning text nodes in a depth first fashion,
  522. skipping text nodes inside certain tags.
  523. """
  524. # This is basically a stack that we extend using itertools.chain.
  525. # This will either consist of an element to iterate over *or* a string
  526. # to be returned.
  527. elements = iter([tree])
  528. while True:
  529. el = next(elements, None)
  530. if el is None:
  531. return
  532. if isinstance(el, str):
  533. yield el
  534. elif el.tag not in tags_to_ignore:
  535. # el.text is the text before the first child, so we can immediately
  536. # return it if the text exists.
  537. if el.text:
  538. yield el.text
  539. # We add to the stack all the elements children, interspersed with
  540. # each child's tail text (if it exists). The tail text of a node
  541. # is text that comes *after* the node, so we always include it even
  542. # if we ignore the child node.
  543. elements = itertools.chain(
  544. itertools.chain.from_iterable( # Basically a flatmap
  545. [child, child.tail] if child.tail else [child]
  546. for child in el.iterchildren()
  547. ),
  548. elements,
  549. )
  550. def _rebase_url(url, base):
  551. base = list(urlparse.urlparse(base))
  552. url = list(urlparse.urlparse(url))
  553. if not url[0]: # fix up schema
  554. url[0] = base[0] or "http"
  555. if not url[1]: # fix up hostname
  556. url[1] = base[1]
  557. if not url[2].startswith("/"):
  558. url[2] = re.sub(r"/[^/]+$", "/", base[2]) + url[2]
  559. return urlparse.urlunparse(url)
  560. def _is_media(content_type):
  561. if content_type.lower().startswith("image/"):
  562. return True
  563. def _is_html(content_type):
  564. content_type = content_type.lower()
  565. if content_type.startswith("text/html") or content_type.startswith(
  566. "application/xhtml"
  567. ):
  568. return True
  569. def summarize_paragraphs(text_nodes, min_size=200, max_size=500):
  570. # Try to get a summary of between 200 and 500 words, respecting
  571. # first paragraph and then word boundaries.
  572. # TODO: Respect sentences?
  573. description = ""
  574. # Keep adding paragraphs until we get to the MIN_SIZE.
  575. for text_node in text_nodes:
  576. if len(description) < min_size:
  577. text_node = re.sub(r"[\t \r\n]+", " ", text_node)
  578. description += text_node + "\n\n"
  579. else:
  580. break
  581. description = description.strip()
  582. description = re.sub(r"[\t ]+", " ", description)
  583. description = re.sub(r"[\t \r\n]*[\r\n]+", "\n\n", description)
  584. # If the concatenation of paragraphs to get above MIN_SIZE
  585. # took us over MAX_SIZE, then we need to truncate mid paragraph
  586. if len(description) > max_size:
  587. new_desc = ""
  588. # This splits the paragraph into words, but keeping the
  589. # (preceeding) whitespace intact so we can easily concat
  590. # words back together.
  591. for match in re.finditer(r"\s*\S+", description):
  592. word = match.group()
  593. # Keep adding words while the total length is less than
  594. # MAX_SIZE.
  595. if len(word) + len(new_desc) < max_size:
  596. new_desc += word
  597. else:
  598. # At this point the next word *will* take us over
  599. # MAX_SIZE, but we also want to ensure that its not
  600. # a huge word. If it is add it anyway and we'll
  601. # truncate later.
  602. if len(new_desc) < min_size:
  603. new_desc += word
  604. break
  605. # Double check that we're not over the limit
  606. if len(new_desc) > max_size:
  607. new_desc = new_desc[:max_size]
  608. # We always add an ellipsis because at the very least
  609. # we chopped mid paragraph.
  610. description = new_desc.strip() + "…"
  611. return description if description else None