preview_url_resource.py 26 KB

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