2013-10-10 21:37:26 +02:00
|
|
|
from __future__ import absolute_import
|
|
|
|
|
2012-10-15 22:03:50 +02:00
|
|
|
import markdown
|
2012-10-22 05:06:28 +02:00
|
|
|
import logging
|
|
|
|
import traceback
|
2012-12-04 19:57:54 +01:00
|
|
|
import urlparse
|
2012-10-25 21:38:47 +02:00
|
|
|
import re
|
2013-03-01 22:07:27 +01:00
|
|
|
import os.path
|
|
|
|
import glob
|
2013-03-08 20:48:14 +01:00
|
|
|
import twitter
|
2013-05-07 00:31:46 +02:00
|
|
|
import platform
|
2013-05-21 23:59:27 +02:00
|
|
|
import time
|
2013-08-12 22:38:36 +02:00
|
|
|
import HTMLParser
|
2013-05-07 20:50:25 +02:00
|
|
|
import httplib2
|
|
|
|
|
2013-08-28 22:45:26 +02:00
|
|
|
import hashlib
|
2013-12-11 20:06:37 +01:00
|
|
|
|
|
|
|
from collections import defaultdict
|
2013-08-28 22:45:26 +02:00
|
|
|
import hmac
|
2013-05-01 22:49:16 +02:00
|
|
|
|
2013-01-31 19:57:25 +01:00
|
|
|
from django.core import mail
|
2013-03-08 06:27:16 +01:00
|
|
|
from django.conf import settings
|
2013-01-31 19:57:25 +01:00
|
|
|
|
2013-07-29 23:03:31 +02:00
|
|
|
from zerver.lib.avatar import gravatar_hash
|
|
|
|
from zerver.lib.bugdown import codehilite, fenced_code
|
|
|
|
from zerver.lib.bugdown.fenced_code import FENCE_RE
|
|
|
|
from zerver.lib.timeout import timeout, TimeoutExpired
|
|
|
|
from zerver.lib.cache import cache_with_key, cache_get_many, cache_set_many
|
2013-09-03 22:41:17 +02:00
|
|
|
import zerver.lib.alert_words as alert_words
|
2013-07-29 23:03:31 +02:00
|
|
|
import zerver.lib.mention as mention
|
2013-04-29 22:22:07 +02:00
|
|
|
|
2013-06-21 16:52:46 +02:00
|
|
|
|
|
|
|
if settings.USING_EMBEDLY:
|
|
|
|
from embedly import Embedly
|
|
|
|
embedly_client = Embedly(settings.EMBEDLY_KEY, timeout=2.5)
|
2012-10-17 04:42:19 +02:00
|
|
|
|
2013-03-18 22:51:08 +01:00
|
|
|
# Format version of the bugdown rendering; stored along with rendered
|
|
|
|
# messages so that we can efficiently determine what needs to be re-rendered
|
|
|
|
version = 1
|
|
|
|
|
2013-04-02 17:08:00 +02:00
|
|
|
def list_of_tlds():
|
|
|
|
# HACK we manually blacklist .py
|
|
|
|
blacklist = ['PY\n', ]
|
|
|
|
|
|
|
|
# tlds-alpha-by-domain.txt comes from http://data.iana.org/TLD/tlds-alpha-by-domain.txt
|
|
|
|
tlds_file = os.path.join(os.path.dirname(__file__), 'tlds-alpha-by-domain.txt')
|
|
|
|
tlds = [tld.lower().strip() for tld in open(tlds_file, 'r')
|
|
|
|
if not tld in blacklist and not tld[0].startswith('#')]
|
|
|
|
tlds.sort(key=len, reverse=True)
|
|
|
|
return tlds
|
|
|
|
|
2013-03-08 21:44:06 +01:00
|
|
|
def walk_tree(root, processor, stop_after_first=False):
|
2013-03-08 20:07:46 +01:00
|
|
|
results = []
|
|
|
|
stack = [root]
|
|
|
|
|
|
|
|
while stack:
|
|
|
|
currElement = stack.pop()
|
|
|
|
for child in currElement.getchildren():
|
|
|
|
if child.getchildren():
|
|
|
|
stack.append(child)
|
|
|
|
|
|
|
|
result = processor(child)
|
|
|
|
if result is not None:
|
|
|
|
results.append(result)
|
2013-03-08 21:44:06 +01:00
|
|
|
if stop_after_first:
|
|
|
|
return results
|
2013-03-08 20:07:46 +01:00
|
|
|
|
|
|
|
return results
|
|
|
|
|
2013-04-29 22:17:17 +02:00
|
|
|
def add_a(root, url, link, height=None):
|
|
|
|
div = markdown.util.etree.SubElement(root, "div")
|
|
|
|
div.set("class", "message_inline_image");
|
|
|
|
a = markdown.util.etree.SubElement(div, "a")
|
|
|
|
a.set("href", link)
|
|
|
|
a.set("target", "_blank")
|
2013-10-23 21:45:15 +02:00
|
|
|
a.set("title", url_filename(link))
|
2013-04-29 22:17:17 +02:00
|
|
|
img = markdown.util.etree.SubElement(a, "img")
|
|
|
|
img.set("src", url)
|
|
|
|
|
2013-05-01 22:49:16 +02:00
|
|
|
def hash_embedly_url(link):
|
2013-08-28 22:45:26 +02:00
|
|
|
return 'embedly:' + hashlib.sha1(link).hexdigest()
|
2013-05-01 22:49:16 +02:00
|
|
|
|
2013-05-11 15:50:02 +02:00
|
|
|
@cache_with_key(lambda tweet_id: tweet_id, cache_name="database", with_statsd_key="tweet_data")
|
2013-03-11 16:23:34 +01:00
|
|
|
def fetch_tweet_data(tweet_id):
|
|
|
|
if settings.TEST_SUITE:
|
2013-10-10 21:37:26 +02:00
|
|
|
from . import testing_mocks
|
2013-03-11 16:23:34 +01:00
|
|
|
res = testing_mocks.twitter(tweet_id)
|
|
|
|
else:
|
2013-10-10 21:30:35 +02:00
|
|
|
if settings.TWITTER_CONSUMER_KEY == '' or \
|
|
|
|
settings.TWITTER_CONSUMER_SECRET == '' or \
|
|
|
|
settings.TWITTER_ACCESS_TOKEN_KEY == '' or \
|
|
|
|
settings.TWITTER_ACCESS_TOKEN_SECRET == '':
|
|
|
|
return None
|
|
|
|
|
2013-09-24 20:38:12 +02:00
|
|
|
api = twitter.Api(consumer_key = settings.TWITTER_CONSUMER_KEY,
|
|
|
|
consumer_secret = settings.TWITTER_CONSUMER_SECRET,
|
|
|
|
access_token_key = settings.TWITTER_ACCESS_TOKEN_KEY,
|
|
|
|
access_token_secret = settings.TWITTER_ACCESS_TOKEN_SECRET)
|
|
|
|
|
2013-03-12 23:40:41 +01:00
|
|
|
try:
|
2013-04-23 17:01:33 +02:00
|
|
|
# Sometimes Twitter hangs on responses. Timing out here
|
|
|
|
# will cause the Tweet to go through as-is with no inline
|
|
|
|
# preview, rather than having the message be rejected
|
|
|
|
# entirely. This timeout needs to be less than our overall
|
|
|
|
# formatting timeout.
|
|
|
|
res = timeout(3, api.GetStatus, tweet_id).AsDict()
|
|
|
|
except TimeoutExpired as e:
|
|
|
|
# We'd like to try again later and not cache the bad result,
|
|
|
|
# so we need to re-raise the exception (just as though
|
|
|
|
# we were being rate-limited)
|
|
|
|
raise
|
2013-03-12 23:40:41 +01:00
|
|
|
except twitter.TwitterError as e:
|
|
|
|
t = e.args[0]
|
|
|
|
if len(t) == 1 and ('code' in t[0]) and (t[0]['code'] == 34):
|
|
|
|
# Code 34 means that the message doesn't exist; return
|
|
|
|
# None so that we will cache the error
|
|
|
|
return None
|
|
|
|
elif len(t) == 1 and ('code' in t[0]) and (t[0]['code'] == 88 or
|
|
|
|
t[0]['code'] == 130):
|
|
|
|
# Code 88 means that we were rate-limited and 130
|
|
|
|
# means Twitter is having capacity issues; either way
|
|
|
|
# just raise the error so we don't cache None and will
|
|
|
|
# try again later.
|
|
|
|
raise
|
|
|
|
else:
|
|
|
|
# It's not clear what to do in cases of other errors,
|
|
|
|
# but for now it seems reasonable to log at error
|
|
|
|
# level (so that we get notified), but then cache the
|
|
|
|
# failure to proceed with our usual work
|
|
|
|
logging.error(traceback.format_exc())
|
|
|
|
return None
|
2013-03-11 16:23:34 +01:00
|
|
|
return res
|
|
|
|
|
2013-04-30 21:37:22 +02:00
|
|
|
def get_tweet_id(url):
|
|
|
|
parsed_url = urlparse.urlparse(url)
|
|
|
|
if not (parsed_url.netloc == 'twitter.com' or parsed_url.netloc.endswith('.twitter.com')):
|
|
|
|
return False
|
2013-12-13 23:45:01 +01:00
|
|
|
to_match = parsed_url.path
|
|
|
|
# In old-style twitter.com/#!/wdaher/status/1231241234-style URLs, we need to look at the fragment instead
|
|
|
|
if parsed_url.path == '/' and len(parsed_url.fragment) > 5:
|
|
|
|
to_match= parsed_url.fragment
|
2013-04-30 21:37:22 +02:00
|
|
|
|
2013-12-13 23:45:01 +01:00
|
|
|
tweet_id_match = re.match(r'^!?/.*?/status(es)?/(?P<tweetid>\d{10,18})(/photo/[0-9])?/?$', to_match)
|
2013-04-30 21:37:22 +02:00
|
|
|
if not tweet_id_match:
|
|
|
|
return False
|
|
|
|
return tweet_id_match.group("tweetid")
|
|
|
|
|
2013-08-28 22:45:26 +02:00
|
|
|
class InlineHttpsProcessor(markdown.treeprocessors.Treeprocessor):
|
|
|
|
def run(self, root):
|
|
|
|
# Get all URLs from the blob
|
|
|
|
found_imgs = walk_tree(root, lambda e: e if e.tag == "img" else None)
|
|
|
|
for img in found_imgs:
|
|
|
|
url = img.get("src")
|
2013-12-13 19:39:30 +01:00
|
|
|
if not url.startswith("http://"):
|
2013-08-28 22:45:26 +02:00
|
|
|
# Don't rewrite images on our own site (e.g. emoji).
|
|
|
|
continue
|
|
|
|
digest = hmac.new(settings.CAMO_KEY, url, hashlib.sha1).hexdigest()
|
|
|
|
encoded_url = url.encode("hex")
|
2013-11-15 19:53:04 +01:00
|
|
|
img.set("src", "%s%s/%s" % (settings.CAMO_URI, digest, encoded_url))
|
2013-04-30 21:37:22 +02:00
|
|
|
|
2013-03-08 06:27:16 +01:00
|
|
|
class InlineInterestingLinkProcessor(markdown.treeprocessors.Treeprocessor):
|
2013-05-21 16:59:09 +02:00
|
|
|
def is_image(self, url):
|
2013-11-14 14:37:39 +01:00
|
|
|
if not settings.INLINE_IMAGE_PREVIEW:
|
|
|
|
return False
|
2013-05-21 16:59:09 +02:00
|
|
|
parsed_url = urlparse.urlparse(url)
|
|
|
|
# List from http://support.google.com/chromeos/bin/answer.py?hl=en&answer=183093
|
|
|
|
for ext in [".bmp", ".gif", ".jpg", "jpeg", ".png", ".webp"]:
|
|
|
|
if parsed_url.path.lower().endswith(ext):
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
|
|
|
def dropbox_image(self, url):
|
|
|
|
if not self.is_image(url):
|
|
|
|
return None
|
|
|
|
parsed_url = urlparse.urlparse(url)
|
|
|
|
if (parsed_url.netloc == 'dropbox.com' or parsed_url.netloc.endswith('.dropbox.com')) \
|
|
|
|
and (parsed_url.path.startswith('/s/') or parsed_url.path.startswith('/sh/')):
|
|
|
|
return "%s?dl=1" % (url,)
|
|
|
|
return None
|
|
|
|
|
|
|
|
def youtube_image(self, url):
|
2013-11-14 14:37:39 +01:00
|
|
|
if not settings.INLINE_IMAGE_PREVIEW:
|
|
|
|
return None
|
2013-05-21 16:59:09 +02:00
|
|
|
# Youtube video id extraction regular expression from http://pastebin.com/KyKAFv1s
|
|
|
|
# If it matches, match.group(2) is the video id.
|
|
|
|
youtube_re = r'^((?:https?://)?(?:youtu\.be/|(?:\w+\.)?youtube(?:-nocookie)?\.com/)(?:(?:(?:v|embed)/)|(?:(?:watch(?:_popup)?(?:\.php)?)?(?:\?|#!?)(?:.+&)?v=)))?([0-9A-Za-z_-]+)(?(1).+)?$'
|
|
|
|
match = re.match(youtube_re, url)
|
|
|
|
if match is None:
|
|
|
|
return None
|
2013-09-04 21:12:33 +02:00
|
|
|
return "https://i.ytimg.com/vi/%s/default.jpg" % (match.group(2),)
|
2013-05-21 16:59:09 +02:00
|
|
|
|
2013-03-08 06:27:16 +01:00
|
|
|
def twitter_link(self, url):
|
2013-04-30 21:37:22 +02:00
|
|
|
tweet_id = get_tweet_id(url)
|
2013-03-08 06:27:16 +01:00
|
|
|
|
2013-04-30 21:37:22 +02:00
|
|
|
if not tweet_id:
|
2013-03-08 06:27:16 +01:00
|
|
|
return None
|
|
|
|
|
|
|
|
try:
|
2013-03-11 16:23:34 +01:00
|
|
|
res = fetch_tweet_data(tweet_id)
|
2013-03-12 23:40:41 +01:00
|
|
|
if res is None:
|
|
|
|
return None
|
2013-03-08 06:27:16 +01:00
|
|
|
user = res['user']
|
|
|
|
tweet = markdown.util.etree.Element("div")
|
|
|
|
tweet.set("class", "twitter-tweet")
|
|
|
|
img_a = markdown.util.etree.SubElement(tweet, 'a')
|
|
|
|
img_a.set("href", url)
|
|
|
|
img_a.set("target", "_blank")
|
|
|
|
profile_img = markdown.util.etree.SubElement(img_a, 'img')
|
|
|
|
profile_img.set('class', 'twitter-avatar')
|
2013-03-08 20:48:14 +01:00
|
|
|
# For some reason, for, e.g. tweet 285072525413724161,
|
|
|
|
# python-twitter does not give us a
|
|
|
|
# profile_image_url_https, but instead puts that URL in
|
|
|
|
# profile_image_url. So use _https if available, but fall
|
|
|
|
# back gracefully.
|
|
|
|
image_url = user.get('profile_image_url_https', user['profile_image_url'])
|
|
|
|
profile_img.set('src', image_url)
|
2013-03-08 06:27:16 +01:00
|
|
|
p = markdown.util.etree.SubElement(tweet, 'p')
|
2013-08-12 22:38:36 +02:00
|
|
|
## TODO: unescape is an internal function, so we should
|
|
|
|
## use something else if we can find it
|
|
|
|
p.text = HTMLParser.HTMLParser().unescape(res['text'])
|
2013-03-08 06:27:16 +01:00
|
|
|
span = markdown.util.etree.SubElement(tweet, 'span')
|
|
|
|
span.text = "- %s (@%s)" % (user['name'], user['screen_name'])
|
|
|
|
|
2013-05-21 16:59:09 +02:00
|
|
|
return tweet
|
2013-03-08 06:27:16 +01:00
|
|
|
except:
|
|
|
|
# We put this in its own try-except because it requires external
|
|
|
|
# connectivity. If Twitter flakes out, we don't want to not-render
|
|
|
|
# the entire message; we just want to not show the Twitter preview.
|
2013-03-11 16:23:34 +01:00
|
|
|
logging.warning(traceback.format_exc())
|
2013-03-08 06:27:16 +01:00
|
|
|
return None
|
|
|
|
|
2013-05-21 16:59:09 +02:00
|
|
|
def do_embedly(self, root, supported_urls):
|
2013-06-21 16:52:46 +02:00
|
|
|
# embed.ly support is disabled until it can be
|
2013-05-24 21:09:01 +02:00
|
|
|
# properly debugged.
|
|
|
|
#
|
|
|
|
# We're not deleting the code for now, since we expect to
|
|
|
|
# restore it and want to be able to update it along with
|
|
|
|
# future refactorings rather than keeping it as a separate
|
|
|
|
# branch.
|
2013-06-21 16:52:46 +02:00
|
|
|
if not settings.USING_EMBEDLY:
|
2013-05-21 16:59:09 +02:00
|
|
|
return
|
2013-03-08 06:27:16 +01:00
|
|
|
|
2013-05-21 16:59:09 +02:00
|
|
|
# We want this to be able to easily reverse the hashing later
|
|
|
|
keys_to_links = dict((hash_embedly_url(link), link) for link in supported_urls)
|
|
|
|
cache_hits = cache_get_many(keys_to_links.keys(), cache_name="database")
|
2013-03-08 06:27:16 +01:00
|
|
|
|
2013-05-21 16:59:09 +02:00
|
|
|
# Construct a dict of url => oembed_data pairs
|
|
|
|
oembeds = dict((keys_to_links[key], cache_hits[key]) for key in cache_hits)
|
2013-03-08 06:27:16 +01:00
|
|
|
|
2013-05-21 16:59:09 +02:00
|
|
|
to_process = [url for url in supported_urls if not url in oembeds]
|
|
|
|
to_cache = {}
|
|
|
|
|
|
|
|
if to_process:
|
|
|
|
# Don't touch embed.ly if we have everything cached.
|
|
|
|
try:
|
|
|
|
responses = embedly_client.oembed(to_process, maxwidth=250)
|
|
|
|
except httplib2.socket.timeout:
|
|
|
|
# We put this in its own try-except because it requires external
|
|
|
|
# connectivity. If embedly flakes out, we don't want to not-render
|
|
|
|
# the entire message; we just want to not show the embedly preview.
|
|
|
|
logging.warning("Embedly Embed timeout for URLs: %s" % (" ".join(to_process)))
|
|
|
|
logging.warning(traceback.format_exc())
|
|
|
|
return root
|
|
|
|
except Exception:
|
|
|
|
# If things break for any other reason, don't make things sad.
|
|
|
|
logging.warning(traceback.format_exc())
|
|
|
|
return root
|
|
|
|
for oembed_data in responses:
|
|
|
|
# Don't cache permanent errors
|
|
|
|
if oembed_data["type"] == "error" and \
|
|
|
|
oembed_data["error_code"] in (500, 501, 503):
|
|
|
|
continue
|
|
|
|
# Convert to dict because otherwise pickling won't work.
|
|
|
|
to_cache[oembed_data["original_url"]] = dict(oembed_data)
|
|
|
|
|
|
|
|
# Cache the newly collected data to the database
|
|
|
|
cache_set_many(dict((hash_embedly_url(link), to_cache[link]) for link in to_cache),
|
|
|
|
cache_name="database")
|
|
|
|
oembeds.update(to_cache)
|
|
|
|
|
|
|
|
# Now let's process the URLs in order
|
|
|
|
for link in supported_urls:
|
|
|
|
oembed_data = oembeds[link]
|
|
|
|
|
|
|
|
if oembed_data["type"] in ("link"):
|
|
|
|
continue
|
|
|
|
elif oembed_data["type"] in ("video", "rich") and "script" not in oembed_data["html"]:
|
|
|
|
placeholder = self.markdown.htmlStash.store(oembed_data["html"], safe=True)
|
|
|
|
el = markdown.util.etree.SubElement(root, "p")
|
|
|
|
el.text = placeholder
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
add_a(root,
|
|
|
|
oembed_data["thumbnail_url"],
|
|
|
|
link,
|
|
|
|
height=oembed_data["thumbnail_height"])
|
|
|
|
except KeyError:
|
|
|
|
# We didn't have a thumbnail, so let's just bail and keep on going...
|
|
|
|
continue
|
2013-03-08 06:27:16 +01:00
|
|
|
return root
|
|
|
|
|
2013-05-21 16:59:09 +02:00
|
|
|
def run(self, root):
|
|
|
|
# Get all URLs from the blob
|
|
|
|
found_urls = walk_tree(root, lambda e: e.get("href") if e.tag == "a" else None)
|
|
|
|
|
|
|
|
# If there are more than 5 URLs in the message, don't do inline previews
|
|
|
|
if len(found_urls) == 0 or len(found_urls) > 5:
|
|
|
|
return
|
|
|
|
|
|
|
|
rendered_tweet = False
|
|
|
|
embedly_urls = []
|
|
|
|
for url in found_urls:
|
|
|
|
dropbox = self.dropbox_image(url)
|
|
|
|
if dropbox is not None:
|
|
|
|
add_a(root, dropbox, url)
|
|
|
|
continue
|
|
|
|
if self.is_image(url):
|
|
|
|
add_a(root, url, url)
|
|
|
|
continue
|
|
|
|
if get_tweet_id(url):
|
|
|
|
if rendered_tweet:
|
|
|
|
# Only render at most one tweet per message
|
|
|
|
continue
|
2013-05-29 21:38:16 +02:00
|
|
|
twitter_data = self.twitter_link(url)
|
|
|
|
if twitter_data is None:
|
|
|
|
# This link is not actually a tweet known to twitter
|
|
|
|
continue
|
2013-05-21 16:59:09 +02:00
|
|
|
rendered_tweet = True
|
|
|
|
div = markdown.util.etree.SubElement(root, "div")
|
|
|
|
div.set("class", "inline-preview-twitter")
|
2013-05-29 21:38:16 +02:00
|
|
|
div.insert(0, twitter_data)
|
2013-05-21 16:59:09 +02:00
|
|
|
continue
|
2013-06-21 16:52:46 +02:00
|
|
|
if settings.USING_EMBEDLY:
|
|
|
|
if embedly_client.is_supported(url):
|
|
|
|
embedly_urls.append(url)
|
|
|
|
continue
|
2013-11-14 14:37:39 +01:00
|
|
|
# NOTE: settings.USING_EMBEDLY will prevent the below from running
|
2013-05-21 16:59:09 +02:00
|
|
|
youtube = self.youtube_image(url)
|
|
|
|
if youtube is not None:
|
|
|
|
add_a(root, youtube, url)
|
|
|
|
continue
|
|
|
|
|
2013-06-21 16:52:46 +02:00
|
|
|
if settings.USING_EMBEDLY:
|
|
|
|
self.do_embedly(root, embedly_urls)
|
2013-05-21 16:59:09 +02:00
|
|
|
|
2013-11-12 23:37:33 +01:00
|
|
|
class Avatar(markdown.inlinepatterns.Pattern):
|
2012-10-17 04:42:19 +02:00
|
|
|
def handleMatch(self, match):
|
|
|
|
img = markdown.util.etree.Element('img')
|
2013-10-30 16:52:28 +01:00
|
|
|
email_address = match.group('email')
|
|
|
|
img.set('class', 'message_body_gravatar')
|
2013-11-12 23:06:36 +01:00
|
|
|
img.set('src', '/avatar/%s?s=30' % (email_address,))
|
2013-10-30 16:52:28 +01:00
|
|
|
img.set('title', email_address)
|
|
|
|
img.set('alt', email_address)
|
2012-10-17 04:42:19 +02:00
|
|
|
return img
|
|
|
|
|
2013-11-14 16:36:29 +01:00
|
|
|
if settings.ENTERPRISE:
|
|
|
|
path_to_emoji = os.path.join(os.path.dirname(__file__), '..', '..', '..',
|
|
|
|
'prod-static', 'serve', 'third', 'gemoji', 'images', 'emoji', '*.png')
|
|
|
|
else:
|
|
|
|
path_to_emoji = os.path.join(os.path.dirname(__file__), '..', '..', '..',
|
|
|
|
# This should be the root
|
|
|
|
'static', 'third', 'gemoji', 'images', 'emoji', '*.png')
|
|
|
|
|
2013-03-01 22:07:27 +01:00
|
|
|
emoji_list = [os.path.splitext(os.path.basename(fn))[0] for fn in glob.glob(path_to_emoji)]
|
|
|
|
|
2013-11-14 16:36:29 +01:00
|
|
|
|
2013-08-22 20:50:00 +02:00
|
|
|
def make_emoji(emoji_name, src, display_string):
|
2013-03-01 22:07:27 +01:00
|
|
|
elt = markdown.util.etree.Element('img')
|
2013-08-22 20:50:00 +02:00
|
|
|
elt.set('src', src)
|
2013-03-01 22:07:27 +01:00
|
|
|
elt.set('class', 'emoji')
|
|
|
|
elt.set("alt", display_string)
|
|
|
|
elt.set("title", display_string)
|
|
|
|
return elt
|
|
|
|
|
|
|
|
class Emoji(markdown.inlinepatterns.Pattern):
|
|
|
|
def handleMatch(self, match):
|
|
|
|
orig_syntax = match.group("syntax")
|
|
|
|
name = orig_syntax[1:-1]
|
2013-08-22 20:50:00 +02:00
|
|
|
|
2013-10-09 20:48:05 +02:00
|
|
|
realm_emoji = {}
|
|
|
|
if db_data is not None:
|
|
|
|
realm_emoji = db_data['emoji']
|
2013-08-22 20:50:00 +02:00
|
|
|
|
|
|
|
if current_message and name in realm_emoji:
|
|
|
|
return make_emoji(name, realm_emoji[name], orig_syntax)
|
|
|
|
elif name in emoji_list:
|
|
|
|
src = 'static/third/gemoji/images/emoji/%s.png' % (name)
|
|
|
|
return make_emoji(name, src, orig_syntax)
|
|
|
|
else:
|
2013-09-27 20:04:46 +02:00
|
|
|
return None
|
2013-03-01 22:07:27 +01:00
|
|
|
|
2013-10-23 21:45:15 +02:00
|
|
|
upload_re = re.compile(r"^(?:https://%s.s3.amazonaws.com|/user_uploads/\d+)/[^/]*/([^/]*)$" % (settings.S3_BUCKET,))
|
|
|
|
def url_filename(url):
|
|
|
|
"""Extract the filename if a URL is an uploaded file, or return the original URL"""
|
|
|
|
match = upload_re.match(url)
|
|
|
|
if match:
|
|
|
|
return match.group(1)
|
|
|
|
else:
|
|
|
|
return url
|
|
|
|
|
2013-03-29 20:17:33 +01:00
|
|
|
def fixup_link(link, target_blank=True):
|
2012-12-04 20:15:50 +01:00
|
|
|
"""Set certain attributes we want on every link."""
|
2013-03-29 20:17:33 +01:00
|
|
|
if target_blank:
|
|
|
|
link.set('target', '_blank')
|
2013-10-23 21:45:15 +02:00
|
|
|
link.set('title', url_filename(link.get('href')))
|
2012-12-04 20:15:50 +01:00
|
|
|
|
2013-02-01 23:15:05 +01:00
|
|
|
|
|
|
|
def sanitize_url(url):
|
|
|
|
"""
|
|
|
|
Sanitize a url against xss attacks.
|
|
|
|
See the docstring on markdown.inlinepatterns.LinkPattern.sanitize_url.
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
parts = urlparse.urlparse(url.replace(' ', '%20'))
|
|
|
|
scheme, netloc, path, params, query, fragment = parts
|
|
|
|
except ValueError:
|
|
|
|
# Bad url - so bad it couldn't be parsed.
|
|
|
|
return ''
|
|
|
|
|
2013-03-29 20:17:33 +01:00
|
|
|
# If there is no scheme or netloc and there is a '@' in the path,
|
|
|
|
# treat it as a mailto: and set the appropriate scheme
|
|
|
|
if scheme == '' and netloc == '' and '@' in path:
|
|
|
|
scheme = 'mailto'
|
2013-10-24 18:06:33 +02:00
|
|
|
elif scheme == '' and netloc == '' and len(path) > 0 and path[0] == '/':
|
|
|
|
# Allow domain-relative links
|
|
|
|
return urlparse.urlunparse(('', '', path, params, query, fragment))
|
|
|
|
elif (scheme, netloc, path, params, query) == ('', '', '', '', '') and len(fragment) > 0:
|
|
|
|
# Allow fragment links
|
|
|
|
return urlparse.urlunparse(('', '', '', '', '', fragment))
|
2013-03-29 20:17:33 +01:00
|
|
|
|
2013-08-06 21:32:15 +02:00
|
|
|
# Zulip modification: If scheme is not specified, assume http://
|
2013-02-01 23:15:05 +01:00
|
|
|
# We re-enter sanitize_url because netloc etc. need to be re-parsed.
|
|
|
|
if not scheme:
|
|
|
|
return sanitize_url('http://' + url)
|
|
|
|
|
2013-04-02 19:36:37 +02:00
|
|
|
locless_schemes = ['mailto', 'news']
|
2013-02-01 23:15:05 +01:00
|
|
|
if netloc == '' and scheme not in locless_schemes:
|
|
|
|
# This fails regardless of anything else.
|
|
|
|
# Return immediately to save additional proccessing
|
2013-02-26 22:41:39 +01:00
|
|
|
return None
|
2013-02-01 23:15:05 +01:00
|
|
|
|
2013-04-02 19:57:35 +02:00
|
|
|
# Upstream code will accept a URL like javascript://foo because it
|
|
|
|
# appears to have a netloc. Additionally there are plenty of other
|
|
|
|
# schemes that do weird things like launch external programs. To be
|
|
|
|
# on the safe side, we whitelist the scheme.
|
|
|
|
if scheme not in ('http', 'https', 'ftp', 'mailto'):
|
|
|
|
return None
|
|
|
|
|
2013-04-02 19:36:37 +02:00
|
|
|
# Upstream code scans path, parameters, and query for colon characters
|
|
|
|
# because
|
|
|
|
#
|
|
|
|
# some aliases [for javascript:] will appear to urlparse() to have
|
|
|
|
# no scheme. On top of that relative links (i.e.: "foo/bar.html")
|
|
|
|
# have no scheme.
|
|
|
|
#
|
|
|
|
# We already converted an empty scheme to http:// above, so we skip
|
|
|
|
# the colon check, which would also forbid a lot of legitimate URLs.
|
2013-02-01 23:15:05 +01:00
|
|
|
|
|
|
|
# Url passes all tests. Return url as-is.
|
2013-03-29 20:17:33 +01:00
|
|
|
return urlparse.urlunparse((scheme, netloc, path, params, query, fragment))
|
2013-02-01 23:15:05 +01:00
|
|
|
|
2013-06-05 17:45:57 +02:00
|
|
|
def url_to_a(url, text = None):
|
2013-02-11 20:49:48 +01:00
|
|
|
a = markdown.util.etree.Element('a')
|
2013-02-26 22:41:39 +01:00
|
|
|
|
2013-03-29 20:17:33 +01:00
|
|
|
href = sanitize_url(url)
|
2013-02-26 22:41:39 +01:00
|
|
|
if href is None:
|
|
|
|
# Rejected by sanitize_url; render it as plain text.
|
|
|
|
return url
|
2013-06-05 17:45:57 +02:00
|
|
|
if text is None:
|
2013-10-02 21:14:22 +02:00
|
|
|
text = markdown.util.AtomicString(url)
|
2013-02-26 22:41:39 +01:00
|
|
|
|
|
|
|
a.set('href', href)
|
2013-06-05 17:45:57 +02:00
|
|
|
a.text = text
|
2013-03-29 20:17:33 +01:00
|
|
|
fixup_link(a, not 'mailto:' in href[:7])
|
2013-02-11 20:49:48 +01:00
|
|
|
return a
|
|
|
|
|
2012-10-22 02:32:18 +02:00
|
|
|
class AutoLink(markdown.inlinepatterns.Pattern):
|
2013-06-21 23:42:33 +02:00
|
|
|
def __init__(self, pattern):
|
|
|
|
markdown.inlinepatterns.Pattern.__init__(self, ' ')
|
|
|
|
|
|
|
|
# HACK: we just had python-markdown compile an empty regex.
|
|
|
|
# Now replace with the real regex compiled with the flags we want.
|
|
|
|
|
|
|
|
self.pattern = pattern
|
|
|
|
self.compiled_re = re.compile("^(.*?)%s(.*?)$" % pattern,
|
|
|
|
re.DOTALL | re.UNICODE | re.VERBOSE)
|
|
|
|
|
2013-02-11 20:49:48 +01:00
|
|
|
def handleMatch(self, match):
|
|
|
|
url = match.group('url')
|
|
|
|
return url_to_a(url)
|
2012-10-22 02:32:18 +02:00
|
|
|
|
2012-11-02 18:25:37 +01:00
|
|
|
class UListProcessor(markdown.blockprocessors.OListProcessor):
|
|
|
|
""" Process unordered list blocks.
|
|
|
|
|
|
|
|
Based on markdown.blockprocessors.UListProcessor, but does not accept
|
2013-01-23 23:07:01 +01:00
|
|
|
'+' or '-' as a bullet character."""
|
2012-11-02 18:25:37 +01:00
|
|
|
|
|
|
|
TAG = 'ul'
|
2013-01-23 23:07:01 +01:00
|
|
|
RE = re.compile(r'^[ ]{0,3}[*][ ]+(.*)')
|
2012-11-02 18:25:37 +01:00
|
|
|
|
2013-01-24 19:35:20 +01:00
|
|
|
class BugdownUListPreprocessor(markdown.preprocessors.Preprocessor):
|
|
|
|
""" Allows unordered list blocks that come directly after a
|
|
|
|
paragraph to be rendered as an unordered list
|
|
|
|
|
|
|
|
Detects paragraphs that have a matching list item that comes
|
|
|
|
directly after a line of text, and inserts a newline between
|
|
|
|
to satisfy Markdown"""
|
|
|
|
|
|
|
|
LI_RE = re.compile(r'^[ ]{0,3}[*][ ]+(.*)', re.MULTILINE)
|
|
|
|
HANGING_ULIST_RE = re.compile(r'^.+\n([ ]{0,3}[*][ ]+.*)', re.MULTILINE)
|
|
|
|
|
|
|
|
def run(self, lines):
|
|
|
|
""" Insert a newline between a paragraph and ulist if missing """
|
|
|
|
inserts = 0
|
|
|
|
fence = None
|
|
|
|
copy = lines[:]
|
|
|
|
for i in xrange(len(lines) - 1):
|
|
|
|
# Ignore anything that is inside a fenced code block
|
|
|
|
m = FENCE_RE.match(lines[i])
|
|
|
|
if not fence and m:
|
|
|
|
fence = m.group('fence')
|
|
|
|
elif fence and m and fence == m.group('fence'):
|
|
|
|
fence = None
|
|
|
|
|
|
|
|
# If we're not in a fenced block and we detect an upcoming list
|
|
|
|
# hanging off a paragraph, add a newline
|
|
|
|
if not fence and lines[i] and \
|
|
|
|
self.LI_RE.match(lines[i+1]) and not self.LI_RE.match(lines[i]):
|
|
|
|
copy.insert(i+inserts+1, '')
|
|
|
|
inserts += 1
|
|
|
|
return copy
|
|
|
|
|
2012-12-04 19:57:54 +01:00
|
|
|
# Based on markdown.inlinepatterns.LinkPattern
|
|
|
|
class LinkPattern(markdown.inlinepatterns.Pattern):
|
|
|
|
""" Return a link element from the given match. """
|
|
|
|
def handleMatch(self, m):
|
|
|
|
href = m.group(9)
|
2013-02-26 22:41:39 +01:00
|
|
|
if not href:
|
2013-09-18 22:04:18 +02:00
|
|
|
return None
|
2012-12-04 19:57:54 +01:00
|
|
|
|
2013-02-26 22:41:39 +01:00
|
|
|
if href[0] == "<":
|
|
|
|
href = href[1:-1]
|
|
|
|
href = sanitize_url(self.unescape(href.strip()))
|
|
|
|
if href is None:
|
2013-09-18 22:04:18 +02:00
|
|
|
return None
|
2012-12-04 19:57:54 +01:00
|
|
|
|
2013-02-26 22:41:39 +01:00
|
|
|
el = markdown.util.etree.Element('a')
|
|
|
|
el.text = m.group(2)
|
|
|
|
el.set('href', href)
|
2013-11-25 23:24:27 +01:00
|
|
|
fixup_link(el, target_blank = (href[:1] != '#'))
|
2012-12-04 19:57:54 +01:00
|
|
|
return el
|
|
|
|
|
2013-07-15 17:56:45 +02:00
|
|
|
def prepare_realm_pattern(source):
|
|
|
|
""" Augment a realm filter so it only matches after start-of-string,
|
|
|
|
whitespace, or opening delimiters, won't match if there are word
|
|
|
|
characters directly after, and saves what was matched as "name". """
|
|
|
|
return r"""(?<![^\s'"\(,:<])(?P<name>""" + source + ')(?!\w)'
|
|
|
|
|
2013-06-05 17:45:57 +02:00
|
|
|
# Given a regular expression pattern, linkifies groups that match it
|
|
|
|
# using the provided format string to construct the URL.
|
|
|
|
class RealmFilterPattern(markdown.inlinepatterns.Pattern):
|
|
|
|
""" Applied a given realm filter to the input """
|
|
|
|
def __init__(self, source_pattern, format_string, markdown_instance=None):
|
2013-07-15 17:56:45 +02:00
|
|
|
self.pattern = prepare_realm_pattern(source_pattern)
|
2013-06-05 17:45:57 +02:00
|
|
|
self.format_string = format_string
|
|
|
|
markdown.inlinepatterns.Pattern.__init__(self, self.pattern, markdown_instance)
|
|
|
|
|
|
|
|
def handleMatch(self, m):
|
|
|
|
return url_to_a(self.format_string % m.groupdict(),
|
|
|
|
m.group("name"))
|
|
|
|
|
2013-06-28 16:02:58 +02:00
|
|
|
class UserMentionPattern(markdown.inlinepatterns.Pattern):
|
2013-10-09 20:48:05 +02:00
|
|
|
def find_user_for_mention(self, name):
|
|
|
|
if db_data is None:
|
|
|
|
return (False, None)
|
|
|
|
|
|
|
|
if mention.user_mention_matches_wildcard(name):
|
|
|
|
return (True, None)
|
|
|
|
|
|
|
|
user = db_data['full_names'].get(name.lower(), None)
|
|
|
|
if user is None:
|
|
|
|
user = db_data['short_names'].get(name.lower(), None)
|
|
|
|
|
|
|
|
return (False, user)
|
|
|
|
|
2013-06-28 16:02:58 +02:00
|
|
|
def handleMatch(self, m):
|
|
|
|
name = m.group(2) or m.group(3)
|
|
|
|
|
|
|
|
if current_message:
|
2013-10-09 20:48:05 +02:00
|
|
|
wildcard, user = self.find_user_for_mention(name)
|
2013-06-28 16:02:58 +02:00
|
|
|
|
|
|
|
if wildcard:
|
|
|
|
current_message.mentions_wildcard = True
|
|
|
|
email = "*"
|
|
|
|
elif user:
|
2013-10-09 20:48:05 +02:00
|
|
|
current_message.mentions_user_ids.add(user['id'])
|
|
|
|
name = user['full_name']
|
|
|
|
email = user['email']
|
2013-06-28 16:02:58 +02:00
|
|
|
else:
|
|
|
|
# Don't highlight @mentions that don't refer to a valid user
|
|
|
|
return None
|
|
|
|
|
|
|
|
el = markdown.util.etree.Element("span")
|
|
|
|
el.set('class', 'user-mention')
|
|
|
|
el.set('data-user-email', email)
|
|
|
|
el.text = "@%s" % (name,)
|
|
|
|
return el
|
|
|
|
|
2013-09-03 22:41:17 +02:00
|
|
|
class AlertWordsNotificationProcessor(markdown.preprocessors.Preprocessor):
|
|
|
|
def run(self, lines):
|
2013-10-09 20:48:05 +02:00
|
|
|
if current_message and db_data is not None:
|
2013-09-03 22:41:17 +02:00
|
|
|
# We check for a user's custom notifications here, as we want
|
|
|
|
# to check for plaintext words that depend on the recipient.
|
2013-10-09 20:48:05 +02:00
|
|
|
realm_words = db_data['realm_alert_words']
|
2013-10-09 20:09:48 +02:00
|
|
|
content = '\n'.join(lines).lower()
|
|
|
|
|
|
|
|
allowed_before_punctuation = "|".join([r'\s', '^', r'[\(\"]'])
|
|
|
|
allowed_after_punctuation = "|".join([r'\s', '$', r'[\)\"\?:.,]'])
|
2013-10-09 20:48:05 +02:00
|
|
|
|
|
|
|
for user_id, words in realm_words.iteritems():
|
2013-09-03 22:41:17 +02:00
|
|
|
for word in words:
|
2013-10-09 20:09:48 +02:00
|
|
|
escaped = re.escape(word.lower())
|
|
|
|
match_re = re.compile(r'(?:%s)%s(?:%s)' %
|
|
|
|
(allowed_before_punctuation,
|
|
|
|
escaped,
|
|
|
|
allowed_after_punctuation))
|
2013-09-03 22:41:17 +02:00
|
|
|
if re.search(match_re, content):
|
2013-10-09 20:48:05 +02:00
|
|
|
current_message.user_ids_with_alert_words.add(user_id)
|
2013-09-03 22:41:17 +02:00
|
|
|
|
|
|
|
return lines
|
|
|
|
|
2013-07-31 22:53:15 +02:00
|
|
|
# This prevents realm_filters from running on the content of a
|
|
|
|
# Markdown link, breaking up the link. This is a monkey-patch, but it
|
|
|
|
# might be worth sending a version of this change upstream.
|
|
|
|
class AtomicLinkPattern(LinkPattern):
|
|
|
|
def handleMatch(self, m):
|
|
|
|
ret = LinkPattern.handleMatch(self, m)
|
2013-09-18 22:04:18 +02:00
|
|
|
if ret is None:
|
|
|
|
return None
|
2013-07-31 22:53:15 +02:00
|
|
|
if not isinstance(ret, basestring):
|
|
|
|
ret.text = markdown.util.AtomicString(ret.text)
|
|
|
|
return ret
|
|
|
|
|
2012-10-16 17:35:58 +02:00
|
|
|
class Bugdown(markdown.Extension):
|
|
|
|
def extendMarkdown(self, md, md_globals):
|
2012-12-04 20:22:14 +01:00
|
|
|
del md.preprocessors['reference']
|
|
|
|
|
|
|
|
for k in ('image_link', 'image_reference', 'automail',
|
2012-12-11 21:19:15 +01:00
|
|
|
'autolink', 'link', 'reference', 'short_reference',
|
2013-01-31 21:13:09 +01:00
|
|
|
'escape', 'strong_em', 'emphasis', 'emphasis2',
|
2013-10-22 20:30:14 +02:00
|
|
|
'linebreak', 'strong'):
|
2012-10-22 02:35:36 +02:00
|
|
|
del md.inlinePatterns[k]
|
2013-10-22 20:30:14 +02:00
|
|
|
try:
|
|
|
|
# linebreak2 was removed upstream in version 3.2.1, so
|
|
|
|
# don't throw an error if it is not there
|
|
|
|
del md.inlinePatterns['linebreak2']
|
|
|
|
except Exception:
|
|
|
|
pass
|
2012-10-22 02:35:36 +02:00
|
|
|
|
2013-09-06 20:51:40 +02:00
|
|
|
md.preprocessors.add("custom_text_notifications", AlertWordsNotificationProcessor(md), "_end")
|
2013-09-03 22:41:17 +02:00
|
|
|
|
2013-01-31 21:13:09 +01:00
|
|
|
# Custom bold syntax: **foo** but not __foo__
|
|
|
|
md.inlinePatterns.add('strong',
|
2013-02-14 17:45:04 +01:00
|
|
|
markdown.inlinepatterns.SimpleTagPattern(r'(\*\*)([^\n]+?)\2', 'strong'),
|
2013-01-31 21:13:09 +01:00
|
|
|
'>not_strong')
|
|
|
|
|
2012-11-02 18:25:37 +01:00
|
|
|
for k in ('hashheader', 'setextheader', 'olist', 'ulist'):
|
2012-10-22 02:35:36 +02:00
|
|
|
del md.parser.blockprocessors[k]
|
2012-10-16 17:35:58 +02:00
|
|
|
|
2012-11-02 18:25:37 +01:00
|
|
|
md.parser.blockprocessors.add('ulist', UListProcessor(md.parser), '>hr')
|
|
|
|
|
2013-11-12 23:48:05 +01:00
|
|
|
# Note that !gravatar syntax should be deprecated long term.
|
|
|
|
md.inlinePatterns.add('avatar', Avatar(r'!avatar\((?P<email>[^)]*)\)'), '_begin')
|
2013-11-12 23:37:33 +01:00
|
|
|
md.inlinePatterns.add('gravatar', Avatar(r'!gravatar\((?P<email>[^)]*)\)'), '_begin')
|
2013-11-12 23:48:05 +01:00
|
|
|
|
2013-06-28 16:02:58 +02:00
|
|
|
md.inlinePatterns.add('usermention', UserMentionPattern(mention.find_mentions), '>backtick')
|
2013-10-02 21:14:22 +02:00
|
|
|
md.inlinePatterns.add('emoji', Emoji(r'(?<!\w)(?P<syntax>:[^:\s]+:)(?!\w)'), '_end')
|
2013-07-31 22:53:15 +02:00
|
|
|
md.inlinePatterns.add('link', AtomicLinkPattern(markdown.inlinepatterns.LINK_RE, md), '>backtick')
|
2012-10-17 04:42:19 +02:00
|
|
|
|
2013-06-05 17:45:57 +02:00
|
|
|
for (pattern, format_string) in self.getConfig("realm_filters"):
|
|
|
|
md.inlinePatterns.add('realm_filters/%s' % (pattern,),
|
2013-07-31 22:53:15 +02:00
|
|
|
RealmFilterPattern(pattern, format_string), '>link')
|
2013-06-05 17:45:57 +02:00
|
|
|
|
2013-02-01 20:04:28 +01:00
|
|
|
# A link starts at a word boundary, and ends at space, punctuation, or end-of-input.
|
2012-11-20 19:33:10 +01:00
|
|
|
#
|
2013-06-21 23:44:22 +02:00
|
|
|
# We detect a url either by the `https?://` or by building around the TLD.
|
2013-04-02 17:08:00 +02:00
|
|
|
tlds = '|'.join(list_of_tlds())
|
2013-06-21 23:42:33 +02:00
|
|
|
link_regex = r"""
|
2013-07-08 16:46:52 +02:00
|
|
|
(?<![^\s'"\(,:<]) # Start after whitespace or specified chars
|
2013-07-05 19:23:14 +02:00
|
|
|
# (Double-negative lookbehind to allow start-of-string)
|
2013-06-21 23:42:33 +02:00
|
|
|
(?P<url> # Main group
|
2013-07-08 16:46:52 +02:00
|
|
|
(?:(?: # Domain part
|
2013-07-05 19:23:14 +02:00
|
|
|
https?://[\w.:@-]+? # If it has a protocol, anything goes.
|
2013-07-08 16:46:52 +02:00
|
|
|
|(?: # Or, if not, be more strict to avoid false-positives
|
|
|
|
(?:[\w-]+\.)+ # One or more domain components, separated by dots
|
|
|
|
(?:%s) # TLDs (filled in via format from tlds-alpha-by-domain.txt)
|
2013-06-21 23:44:22 +02:00
|
|
|
)
|
|
|
|
)
|
2013-06-21 23:42:33 +02:00
|
|
|
(?:/ # A path, beginning with /
|
2013-06-21 23:44:22 +02:00
|
|
|
[^\s()\"]*? # Containing characters that won't end the URL
|
|
|
|
(?: \( [^\s()\"]* \) # and more characters in matched parens
|
|
|
|
[^\s()\"]*? # followed by more characters
|
2013-07-08 16:46:52 +02:00
|
|
|
)* # zero-or-more sets of paired parens
|
|
|
|
)?) # Path is optional
|
|
|
|
| (?:[\w.-]+\@[\w.-]+\.[\w]+) # Email is separate, since it can't have a path
|
2013-06-21 23:42:33 +02:00
|
|
|
)
|
2013-07-08 16:46:52 +02:00
|
|
|
(?= # URL must be followed by (not included in group)
|
|
|
|
[:;\?\),\.\'\"\>]* # Optional punctuation characters
|
|
|
|
(?:\Z|\s) # followed by whitespace or end of string
|
2013-06-21 23:42:33 +02:00
|
|
|
)
|
|
|
|
""" % (tlds,)
|
2013-06-21 23:44:22 +02:00
|
|
|
md.inlinePatterns.add('autolink', AutoLink(link_regex), '>link')
|
2012-10-22 02:32:18 +02:00
|
|
|
|
2013-01-24 19:35:20 +01:00
|
|
|
md.preprocessors.add('hanging_ulists',
|
|
|
|
BugdownUListPreprocessor(md),
|
|
|
|
"_begin")
|
|
|
|
|
2013-03-14 22:48:17 +01:00
|
|
|
md.treeprocessors.add("inline_interesting_links", InlineInterestingLinkProcessor(md), "_end")
|
2013-11-15 19:53:04 +01:00
|
|
|
|
|
|
|
if settings.CAMO_URI:
|
|
|
|
md.treeprocessors.add("rewrite_to_https", InlineHttpsProcessor(md), "_end")
|
2013-03-01 19:20:53 +01:00
|
|
|
|
2013-07-29 23:57:26 +02:00
|
|
|
if self.getConfig("realm") == "mit.edu/zephyr_mirror":
|
2013-08-28 21:26:21 +02:00
|
|
|
# Disable almost all inline patterns for mit.edu users' traffic that is mirrored
|
|
|
|
# Note that inline_interesting_links is a treeprocessor and thus is not removed
|
2013-07-29 23:57:26 +02:00
|
|
|
for k in md.inlinePatterns.keys():
|
2013-08-28 21:26:21 +02:00
|
|
|
if k not in ["autolink"]:
|
2013-07-29 23:57:26 +02:00
|
|
|
del md.inlinePatterns[k]
|
|
|
|
|
2013-06-05 17:45:57 +02:00
|
|
|
|
|
|
|
md_engines = {}
|
2013-12-11 20:06:37 +01:00
|
|
|
realm_filter_data = {}
|
2013-06-05 17:45:57 +02:00
|
|
|
|
|
|
|
def make_md_engine(key, opts):
|
|
|
|
md_engines[key] = markdown.Markdown(
|
|
|
|
safe_mode = 'escape',
|
|
|
|
output_format = 'html',
|
|
|
|
extensions = ['nl2br',
|
2013-10-10 22:05:12 +02:00
|
|
|
'tables',
|
2013-06-05 17:45:57 +02:00
|
|
|
codehilite.makeExtension(configs=[
|
|
|
|
('force_linenos', False),
|
|
|
|
('guess_lang', False)]),
|
|
|
|
fenced_code.makeExtension(),
|
|
|
|
Bugdown(opts)])
|
|
|
|
|
2013-07-12 22:29:25 +02:00
|
|
|
def subject_links(domain, subject):
|
2013-12-11 20:06:37 +01:00
|
|
|
from zerver.models import get_realm, RealmFilter, realm_filters_for_domain
|
2013-07-12 22:29:25 +02:00
|
|
|
matches = []
|
|
|
|
|
2013-12-11 20:06:37 +01:00
|
|
|
try:
|
|
|
|
realm_filters = realm_filters_for_domain(domain)
|
|
|
|
|
|
|
|
for realm_filter in realm_filters:
|
|
|
|
pattern = prepare_realm_pattern(realm_filter[0])
|
|
|
|
for m in re.finditer(pattern, subject):
|
|
|
|
matches += [realm_filter[1] % m.groupdict()]
|
|
|
|
return matches
|
|
|
|
except RealmFilter.DoesNotExist:
|
|
|
|
return matches
|
|
|
|
|
|
|
|
def make_realm_filters(domain, filters):
|
|
|
|
global md_engines, realm_filter_data
|
|
|
|
if domain in md_engines:
|
|
|
|
del md_engines[domain]
|
|
|
|
realm_filter_data[domain] = filters
|
|
|
|
|
2013-06-05 17:45:57 +02:00
|
|
|
# Because of how the Markdown config API works, this has confusing
|
|
|
|
# large number of layers of dicts/arrays :(
|
2013-12-11 20:06:37 +01:00
|
|
|
make_md_engine(domain, {"realm_filters": [filters, "Realm-specific filters for %s" % (domain,)],
|
|
|
|
"realm": [domain, "Realm name"]})
|
|
|
|
|
|
|
|
def maybe_update_realm_filters(domain):
|
|
|
|
from zerver.models import realm_filters_for_domain, all_realm_filters
|
|
|
|
|
|
|
|
# If domain is None, load all filters
|
|
|
|
if domain is None:
|
|
|
|
all_filters = all_realm_filters()
|
|
|
|
all_filters['default'] = []
|
|
|
|
for domain, filters in all_filters.iteritems():
|
|
|
|
make_realm_filters(domain, filters)
|
|
|
|
else:
|
|
|
|
realm_filters = realm_filters_for_domain(domain)
|
|
|
|
if domain not in realm_filter_data or realm_filter_data[domain] != realm_filters:
|
|
|
|
# Data has changed, re-load filters
|
|
|
|
make_realm_filters(domain, realm_filters)
|
|
|
|
|
|
|
|
maybe_update_realm_filters(domain=None)
|
2012-10-15 22:03:50 +02:00
|
|
|
|
2012-10-25 21:38:47 +02:00
|
|
|
# We want to log Markdown parser failures, but shouldn't log the actual input
|
|
|
|
# message for privacy reasons. The compromise is to replace all alphanumeric
|
|
|
|
# characters with 'x'.
|
|
|
|
#
|
|
|
|
# We also use repr() to improve reproducibility, and to escape terminal control
|
|
|
|
# codes, which can do surprisingly nasty things.
|
|
|
|
_privacy_re = re.compile(r'\w', flags=re.UNICODE)
|
|
|
|
def _sanitize_for_log(md):
|
|
|
|
return repr(_privacy_re.sub('x', md))
|
|
|
|
|
2013-06-28 16:02:58 +02:00
|
|
|
|
|
|
|
# Filters such as UserMentionPattern need a message, but python-markdown
|
|
|
|
# provides no way to pass extra params through to a pattern. Thus, a global.
|
|
|
|
current_message = None
|
|
|
|
|
2013-10-09 20:48:05 +02:00
|
|
|
# We avoid doing DB queries in our markdown thread to avoid the overhead of
|
|
|
|
# opening a new DB connection. These connections tend to live longer than the
|
|
|
|
# threads themselves, as well.
|
|
|
|
db_data = None
|
|
|
|
|
2013-06-28 16:02:58 +02:00
|
|
|
def do_convert(md, realm_domain=None, message=None):
|
2013-08-06 21:32:15 +02:00
|
|
|
"""Convert Markdown to HTML, with Zulip-specific settings and hacks."""
|
2013-12-11 20:06:37 +01:00
|
|
|
from zerver.models import get_active_user_dicts_in_realm, UserProfile
|
|
|
|
|
|
|
|
if message:
|
|
|
|
maybe_update_realm_filters(message.get_realm().domain)
|
2012-11-20 20:15:55 +01:00
|
|
|
|
2013-06-28 16:02:58 +02:00
|
|
|
if realm_domain in md_engines:
|
|
|
|
_md_engine = md_engines[realm_domain]
|
2013-06-05 17:45:57 +02:00
|
|
|
else:
|
|
|
|
_md_engine = md_engines["default"]
|
2012-11-20 20:15:55 +01:00
|
|
|
# Reset the parser; otherwise it will get slower over time.
|
|
|
|
_md_engine.reset()
|
2012-10-15 22:03:50 +02:00
|
|
|
|
2013-06-28 16:02:58 +02:00
|
|
|
global current_message
|
|
|
|
current_message = message
|
2013-10-09 20:48:05 +02:00
|
|
|
|
|
|
|
# Pre-fetch data from the DB that is used in the bugdown thread
|
|
|
|
global db_data
|
|
|
|
if message:
|
2013-10-23 23:16:39 +02:00
|
|
|
realm_users = get_active_user_dicts_in_realm(message.get_realm())
|
2013-10-09 20:48:05 +02:00
|
|
|
|
|
|
|
db_data = {'realm_alert_words': alert_words.alert_words_in_realm(message.get_realm()),
|
|
|
|
'full_names': dict((user['full_name'].lower(), user) for user in realm_users),
|
|
|
|
'short_names': dict((user['short_name'].lower(), user) for user in realm_users),
|
|
|
|
'emoji': message.get_realm().get_emoji()}
|
|
|
|
|
2012-10-15 22:03:50 +02:00
|
|
|
try:
|
2013-01-29 21:47:53 +01:00
|
|
|
# Spend at most 5 seconds rendering.
|
|
|
|
# Sometimes Python-Markdown is really slow; see
|
2013-09-05 21:24:18 +02:00
|
|
|
# https://trac.zulip.net/ticket/345
|
2013-03-08 20:34:10 +01:00
|
|
|
return timeout(5, _md_engine.convert, md)
|
2012-10-15 22:03:50 +02:00
|
|
|
except:
|
2013-07-29 23:03:31 +02:00
|
|
|
from zerver.lib.actions import internal_send_message
|
2013-01-31 19:57:25 +01:00
|
|
|
|
|
|
|
cleaned = _sanitize_for_log(md)
|
|
|
|
|
2013-10-04 19:27:01 +02:00
|
|
|
# Output error to log as well as sending a zulip and email
|
2012-10-25 21:38:47 +02:00
|
|
|
logging.getLogger('').error('Exception in Markdown parser: %sInput (sanitized) was: %s'
|
2013-01-31 19:57:25 +01:00
|
|
|
% (traceback.format_exc(), cleaned))
|
2013-05-07 00:31:46 +02:00
|
|
|
subject = "Markdown parser failure on %s" % (platform.node(),)
|
2013-10-31 18:33:19 +01:00
|
|
|
if settings.ERROR_BOT is not None:
|
|
|
|
internal_send_message(settings.ERROR_BOT, "stream",
|
|
|
|
"errors", subject, "Markdown parser failed, email sent with details.")
|
2013-01-31 19:57:25 +01:00
|
|
|
mail.mail_admins(subject, "Failed message: %s\n\n%s\n\n" % (
|
|
|
|
cleaned, traceback.format_exc()),
|
|
|
|
fail_silently=False)
|
2013-03-08 20:34:10 +01:00
|
|
|
return None
|
2013-06-28 16:02:58 +02:00
|
|
|
finally:
|
|
|
|
current_message = None
|
2013-10-09 20:48:05 +02:00
|
|
|
db_data = None
|
2013-05-21 23:59:27 +02:00
|
|
|
|
|
|
|
bugdown_time_start = 0
|
|
|
|
bugdown_total_time = 0
|
|
|
|
bugdown_total_requests = 0
|
|
|
|
|
|
|
|
def get_bugdown_time():
|
|
|
|
return bugdown_total_time
|
|
|
|
|
|
|
|
def get_bugdown_requests():
|
|
|
|
return bugdown_total_requests
|
|
|
|
|
|
|
|
def bugdown_stats_start():
|
|
|
|
global bugdown_time_start
|
|
|
|
bugdown_time_start = time.time()
|
|
|
|
|
|
|
|
def bugdown_stats_finish():
|
|
|
|
global bugdown_total_time
|
|
|
|
global bugdown_total_requests
|
|
|
|
global bugdown_time_start
|
|
|
|
bugdown_total_requests += 1
|
|
|
|
bugdown_total_time += (time.time() - bugdown_time_start)
|
|
|
|
|
2013-06-28 16:02:58 +02:00
|
|
|
def convert(md, realm_domain=None, message=None):
|
2013-05-21 23:59:27 +02:00
|
|
|
bugdown_stats_start()
|
2013-06-28 16:02:58 +02:00
|
|
|
ret = do_convert(md, realm_domain, message)
|
2013-05-21 23:59:27 +02:00
|
|
|
bugdown_stats_finish()
|
|
|
|
return ret
|