preview_url_resource.py 25 KB

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