preview_url_resource.py 26 KB

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