preview_url_resource.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  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 simplejson as json
  27. import urlparse
  28. from twisted.web.server import NOT_DONE_YET
  29. from twisted.internet import defer
  30. from twisted.web.resource import Resource
  31. from ._base import FileInfo
  32. from synapse.api.errors import (
  33. SynapseError, Codes,
  34. )
  35. from synapse.util.logcontext import preserve_fn, make_deferred_yieldable
  36. from synapse.util.stringutils import random_string
  37. from synapse.util.caches.expiringcache import ExpiringCache
  38. from synapse.http.client import SpiderHttpClient
  39. from synapse.http.server import (
  40. request_handler, respond_with_json_bytes,
  41. respond_with_json,
  42. )
  43. from synapse.util.async import ObservableDeferred
  44. from synapse.util.stringutils import is_ascii
  45. logger = logging.getLogger(__name__)
  46. class PreviewUrlResource(Resource):
  47. isLeaf = True
  48. def __init__(self, hs, media_repo, media_storage):
  49. Resource.__init__(self)
  50. self.auth = hs.get_auth()
  51. self.clock = hs.get_clock()
  52. self.version_string = hs.version_string
  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._cache.start()
  71. self._cleaner_loop = self.clock.looping_call(
  72. self._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. @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 = request.args.get("url")[0]
  85. if "ts" in request.args:
  86. ts = int(request.args.get("ts")[0])
  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 = preserve_fn(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)
  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_type, e),
  257. ),
  258. Codes.UNKNOWN,
  259. )
  260. yield finish()
  261. try:
  262. if "Content-Type" in headers:
  263. media_type = headers["Content-Type"][0]
  264. else:
  265. media_type = "application/octet-stream"
  266. time_now_ms = self.clock.time_msec()
  267. content_disposition = headers.get("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. @defer.inlineCallbacks
  319. def _expire_url_cache_data(self):
  320. """Clean up expired url cache content, media and thumbnails.
  321. """
  322. # TODO: Delete from backup media store
  323. now = self.clock.time_msec()
  324. logger.info("Running url preview cache expiry")
  325. if not (yield self.store.has_completed_background_updates()):
  326. logger.info("Still running DB updates; skipping expiry")
  327. return
  328. # First we delete expired url cache entries
  329. media_ids = yield self.store.get_expired_url_cache(now)
  330. removed_media = []
  331. for media_id in media_ids:
  332. fname = self.filepaths.url_cache_filepath(media_id)
  333. try:
  334. os.remove(fname)
  335. except OSError as e:
  336. # If the path doesn't exist, meh
  337. if e.errno != errno.ENOENT:
  338. logger.warn("Failed to remove media: %r: %s", media_id, e)
  339. continue
  340. removed_media.append(media_id)
  341. try:
  342. dirs = self.filepaths.url_cache_filepath_dirs_to_delete(media_id)
  343. for dir in dirs:
  344. os.rmdir(dir)
  345. except Exception:
  346. pass
  347. yield self.store.delete_url_cache(removed_media)
  348. if removed_media:
  349. logger.info("Deleted %d entries from url cache", len(removed_media))
  350. # Now we delete old images associated with the url cache.
  351. # These may be cached for a bit on the client (i.e., they
  352. # may have a room open with a preview url thing open).
  353. # So we wait a couple of days before deleting, just in case.
  354. expire_before = now - 2 * 24 * 60 * 60 * 1000
  355. media_ids = yield self.store.get_url_cache_media_before(expire_before)
  356. removed_media = []
  357. for media_id in media_ids:
  358. fname = self.filepaths.url_cache_filepath(media_id)
  359. try:
  360. os.remove(fname)
  361. except OSError as e:
  362. # If the path doesn't exist, meh
  363. if e.errno != errno.ENOENT:
  364. logger.warn("Failed to remove media: %r: %s", media_id, e)
  365. continue
  366. try:
  367. dirs = self.filepaths.url_cache_filepath_dirs_to_delete(media_id)
  368. for dir in dirs:
  369. os.rmdir(dir)
  370. except Exception:
  371. pass
  372. thumbnail_dir = self.filepaths.url_cache_thumbnail_directory(media_id)
  373. try:
  374. shutil.rmtree(thumbnail_dir)
  375. except OSError as e:
  376. # If the path doesn't exist, meh
  377. if e.errno != errno.ENOENT:
  378. logger.warn("Failed to remove media: %r: %s", media_id, e)
  379. continue
  380. removed_media.append(media_id)
  381. try:
  382. dirs = self.filepaths.url_cache_thumbnail_dirs_to_delete(media_id)
  383. for dir in dirs:
  384. os.rmdir(dir)
  385. except Exception:
  386. pass
  387. yield self.store.delete_url_cache_media(removed_media)
  388. logger.info("Deleted %d media from url cache", len(removed_media))
  389. def decode_and_calc_og(body, media_uri, request_encoding=None):
  390. from lxml import etree
  391. try:
  392. parser = etree.HTMLParser(recover=True, encoding=request_encoding)
  393. tree = etree.fromstring(body, parser)
  394. og = _calc_og(tree, media_uri)
  395. except UnicodeDecodeError:
  396. # blindly try decoding the body as utf-8, which seems to fix
  397. # the charset mismatches on https://google.com
  398. parser = etree.HTMLParser(recover=True, encoding=request_encoding)
  399. tree = etree.fromstring(body.decode('utf-8', 'ignore'), parser)
  400. og = _calc_og(tree, media_uri)
  401. return og
  402. def _calc_og(tree, media_uri):
  403. # suck our tree into lxml and define our OG response.
  404. # if we see any image URLs in the OG response, then spider them
  405. # (although the client could choose to do this by asking for previews of those
  406. # URLs to avoid DoSing the server)
  407. # "og:type" : "video",
  408. # "og:url" : "https://www.youtube.com/watch?v=LXDBoHyjmtw",
  409. # "og:site_name" : "YouTube",
  410. # "og:video:type" : "application/x-shockwave-flash",
  411. # "og:description" : "Fun stuff happening here",
  412. # "og:title" : "RemoteJam - Matrix team hack for Disrupt Europe Hackathon",
  413. # "og:image" : "https://i.ytimg.com/vi/LXDBoHyjmtw/maxresdefault.jpg",
  414. # "og:video:url" : "http://www.youtube.com/v/LXDBoHyjmtw?version=3&autohide=1",
  415. # "og:video:width" : "1280"
  416. # "og:video:height" : "720",
  417. # "og:video:secure_url": "https://www.youtube.com/v/LXDBoHyjmtw?version=3",
  418. og = {}
  419. for tag in tree.xpath("//*/meta[starts-with(@property, 'og:')]"):
  420. if 'content' in tag.attrib:
  421. og[tag.attrib['property']] = tag.attrib['content']
  422. # TODO: grab article: meta tags too, e.g.:
  423. # "article:publisher" : "https://www.facebook.com/thethudonline" />
  424. # "article:author" content="https://www.facebook.com/thethudonline" />
  425. # "article:tag" content="baby" />
  426. # "article:section" content="Breaking News" />
  427. # "article:published_time" content="2016-03-31T19:58:24+00:00" />
  428. # "article:modified_time" content="2016-04-01T18:31:53+00:00" />
  429. if 'og:title' not in og:
  430. # do some basic spidering of the HTML
  431. title = tree.xpath("(//title)[1] | (//h1)[1] | (//h2)[1] | (//h3)[1]")
  432. if title and title[0].text is not None:
  433. og['og:title'] = title[0].text.strip()
  434. else:
  435. og['og:title'] = None
  436. if 'og:image' not in og:
  437. # TODO: extract a favicon failing all else
  438. meta_image = tree.xpath(
  439. "//*/meta[translate(@itemprop, 'IMAGE', 'image')='image']/@content"
  440. )
  441. if meta_image:
  442. og['og:image'] = _rebase_url(meta_image[0], media_uri)
  443. else:
  444. # TODO: consider inlined CSS styles as well as width & height attribs
  445. images = tree.xpath("//img[@src][number(@width)>10][number(@height)>10]")
  446. images = sorted(images, key=lambda i: (
  447. -1 * float(i.attrib['width']) * float(i.attrib['height'])
  448. ))
  449. if not images:
  450. images = tree.xpath("//img[@src]")
  451. if images:
  452. og['og:image'] = images[0].attrib['src']
  453. if 'og:description' not in og:
  454. meta_description = tree.xpath(
  455. "//*/meta"
  456. "[translate(@name, 'DESCRIPTION', 'description')='description']"
  457. "/@content")
  458. if meta_description:
  459. og['og:description'] = meta_description[0]
  460. else:
  461. # grab any text nodes which are inside the <body/> tag...
  462. # unless they are within an HTML5 semantic markup tag...
  463. # <header/>, <nav/>, <aside/>, <footer/>
  464. # ...or if they are within a <script/> or <style/> tag.
  465. # This is a very very very coarse approximation to a plain text
  466. # render of the page.
  467. # We don't just use XPATH here as that is slow on some machines.
  468. from lxml import etree
  469. TAGS_TO_REMOVE = (
  470. "header",
  471. "nav",
  472. "aside",
  473. "footer",
  474. "script",
  475. "noscript",
  476. "style",
  477. etree.Comment
  478. )
  479. # Split all the text nodes into paragraphs (by splitting on new
  480. # lines)
  481. text_nodes = (
  482. re.sub(r'\s+', '\n', el).strip()
  483. for el in _iterate_over_text(tree.find("body"), *TAGS_TO_REMOVE)
  484. )
  485. og['og:description'] = summarize_paragraphs(text_nodes)
  486. else:
  487. og['og:description'] = summarize_paragraphs([og['og:description']])
  488. # TODO: delete the url downloads to stop diskfilling,
  489. # as we only ever cared about its OG
  490. return og
  491. def _iterate_over_text(tree, *tags_to_ignore):
  492. """Iterate over the tree returning text nodes in a depth first fashion,
  493. skipping text nodes inside certain tags.
  494. """
  495. # This is basically a stack that we extend using itertools.chain.
  496. # This will either consist of an element to iterate over *or* a string
  497. # to be returned.
  498. elements = iter([tree])
  499. while True:
  500. el = elements.next()
  501. if isinstance(el, basestring):
  502. yield el
  503. elif el is not None and el.tag not in tags_to_ignore:
  504. # el.text is the text before the first child, so we can immediately
  505. # return it if the text exists.
  506. if el.text:
  507. yield el.text
  508. # We add to the stack all the elements children, interspersed with
  509. # each child's tail text (if it exists). The tail text of a node
  510. # is text that comes *after* the node, so we always include it even
  511. # if we ignore the child node.
  512. elements = itertools.chain(
  513. itertools.chain.from_iterable( # Basically a flatmap
  514. [child, child.tail] if child.tail else [child]
  515. for child in el.iterchildren()
  516. ),
  517. elements
  518. )
  519. def _rebase_url(url, base):
  520. base = list(urlparse.urlparse(base))
  521. url = list(urlparse.urlparse(url))
  522. if not url[0]: # fix up schema
  523. url[0] = base[0] or "http"
  524. if not url[1]: # fix up hostname
  525. url[1] = base[1]
  526. if not url[2].startswith('/'):
  527. url[2] = re.sub(r'/[^/]+$', '/', base[2]) + url[2]
  528. return urlparse.urlunparse(url)
  529. def _is_media(content_type):
  530. if content_type.lower().startswith("image/"):
  531. return True
  532. def _is_html(content_type):
  533. content_type = content_type.lower()
  534. if (
  535. content_type.startswith("text/html") or
  536. content_type.startswith("application/xhtml")
  537. ):
  538. return True
  539. def summarize_paragraphs(text_nodes, min_size=200, max_size=500):
  540. # Try to get a summary of between 200 and 500 words, respecting
  541. # first paragraph and then word boundaries.
  542. # TODO: Respect sentences?
  543. description = ''
  544. # Keep adding paragraphs until we get to the MIN_SIZE.
  545. for text_node in text_nodes:
  546. if len(description) < min_size:
  547. text_node = re.sub(r'[\t \r\n]+', ' ', text_node)
  548. description += text_node + '\n\n'
  549. else:
  550. break
  551. description = description.strip()
  552. description = re.sub(r'[\t ]+', ' ', description)
  553. description = re.sub(r'[\t \r\n]*[\r\n]+', '\n\n', description)
  554. # If the concatenation of paragraphs to get above MIN_SIZE
  555. # took us over MAX_SIZE, then we need to truncate mid paragraph
  556. if len(description) > max_size:
  557. new_desc = ""
  558. # This splits the paragraph into words, but keeping the
  559. # (preceeding) whitespace intact so we can easily concat
  560. # words back together.
  561. for match in re.finditer("\s*\S+", description):
  562. word = match.group()
  563. # Keep adding words while the total length is less than
  564. # MAX_SIZE.
  565. if len(word) + len(new_desc) < max_size:
  566. new_desc += word
  567. else:
  568. # At this point the next word *will* take us over
  569. # MAX_SIZE, but we also want to ensure that its not
  570. # a huge word. If it is add it anyway and we'll
  571. # truncate later.
  572. if len(new_desc) < min_size:
  573. new_desc += word
  574. break
  575. # Double check that we're not over the limit
  576. if len(new_desc) > max_size:
  577. new_desc = new_desc[:max_size]
  578. # We always add an ellipsis because at the very least
  579. # we chopped mid paragraph.
  580. description = new_desc.strip() + u"…"
  581. return description if description else None