/
liquid.py
212 lines (160 loc) · 6.49 KB
/
liquid.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
# -*- encoding: utf-8 -*-
#
# Copyright 2013 Martin Zimmermann <info@posativ.org>. All rights reserved.
# License: BSD Style, 2 clauses -- see LICENSE.
import io
import re
import json
from os.path import join
from functools import partial
from urllib import urlencode
from urlparse import urlparse, parse_qs
try:
import cPickle as pickle
except ImportError:
import pickle # NOQA
from acrylamid import core, utils, lib
from acrylamid.core import cache
from acrylamid.utils import Struct
from acrylamid.filters import Filter
from acrylamid.lib import requests
__img_re = r'(?P<class>\S.*\s+)?(?P<src>(?:https?:\/\/|\/|\S+\/)\S+)(?:\s+(?P<width>\d+))?(?:\s+(?P<height>\d+))?(?P<title>\s+.+)?'
__img_re_title = r'(?:"|\')(?P<title>[^"\']+)?(?:"|\')\s+(?:"|\')(?P<alt>[^"\']+)?(?:"|\')'
def blockquote(header, body):
"""Mimic Octopress's blockquote plugin. See
http://octopress.org/docs/plugins/blockquote/ for examples."""
# TODO: use python-titlecase if available or use this implementation:
# https://github.com/imathis/octopress/blob/master/plugins/titlecase.rb
def paragraphize(text):
return '<p>' + text.strip().replace('\n\n', '</p><p>').replace('\n', '<br/>') + '</p>'
by, source, title = None, None, None
m = re.match(r'(\S.*)\s+(https?:\/\/)(\S+)\s+(.+)', header, flags=re.I)
if m:
by = m.group(1)
source = m.group(2) + m.group(3)
title = m.group(4) # titlecase
else:
m = re.match(r'(\S.*)\s+(https?:\/\/)(\S+)', header, re.I)
if m:
by = m.group(1)
source = m.group(2) + m.group(3)
else:
m = re.match(r'([^,]+),([^,]+)', header)
if m:
by = m.group(1)
title = m.group(2) # titlecase
else:
m = re.match(r'(.+)', header)
if m:
by = m.group(1)
quote = paragraphize(body)
author = '<strong>%s</strong>' % (by.strip() or '')
if source:
url = re.match(r'https?:\/\/(.+)', source).group(1)
parts = []
for part in url.split('/'):
if not part or len('/'.join(parts + [part])) >= 32:
break
parts.append(part)
else:
parts.append('…')
href = '/'.join(parts)
if source:
cite = ' <cite><a href="%s">%s</a></cite>' % (source, (title or href))
elif title:
cite = ' <cite>%s</cite>' % title
if not author:
blockquote = quote
elif cite:
blockquote = quote + "<footer>%s</footer>" % (author + cite)
else:
blockquote = quote + "<footer>%s</footer>" % author
return "<blockquote>%s</blockquote>" % blockquote
def img(header, body=None):
"""Alternate to Markdown's image tag. See
http://octopress.org/docs/plugins/image-tag/ for usage."""
attrs = re.match(__img_re, header).groupdict()
m = re.match(__img_re_title, attrs['title'])
if m:
attrs['title'] = m.groupdict()['title']
attrs['alt'] = m.groupdict()['alt']
elif 'title' in attrs:
attrs['alt'] = attrs['title'].replace('"', '"')
if 'class' in attrs:
attrs['class'] = attrs['class'].replace('"', '')
if attrs:
return '<img ' + ' '.join('%s="%s"' % (k, v) for k, v in attrs.items() if v) + ' />'
return ("Error processing input, expected syntax: "
"{% img [class name(s)] [http[s]:/]/path/to/image [width [height]] "
"[title text | \"title text\" [\"alt text\"]] %}")
def youtube(header, body=None):
# TODO add options similar to rstx_youtube directive
if header.startswith(('http://', 'https://')):
header = parse_qs(urlparse(header).query)['v'][0]
return '<div class="video">' + \
'<iframe src="http://www.youtube.com/embed/%s"></iframe>' % header + \
'</div>'
def pullquote(header, body):
"""Semantic pullquote using CSS only. Defaults to right alignment. See
http://octopress.org/docs/plugins/pullquote/ for details."""
# TODO support a markup language somehow
align = 'left' if 'left' in header.lower() else 'right'
m = re.search(r'{"\s*(.+?)\s*"}', body, re.MULTILINE | re.DOTALL)
if m:
return '<span class="pullquote-{0}" data-pullquote="{1}">{2}</span>'.format(
align, m.group(1), re.sub(r'\{"\s*|\s*"\}', '', body))
return "Surround your pullquote like this {\" text to be quoted \"}"
def tweet(header, body=None):
"""Easy embedding of Tweets. The Twitter oEmbed API is rate-limited,
hence we are caching the response per configuration to `.cache/`."""
oembed = 'https://api.twitter.com/1/statuses/oembed.json'
args = map(unicode.strip, re.split(r'\s+', header))
params = Struct(url=args.pop(0))
for arg in args:
k, v = map(unicode.strip, arg.split('='))
if k and v:
v = v.strip('\'')
params[k] = v
try:
with io.open(join(core.cache.cache_dir, 'tweets'), 'rb') as fp:
cache = pickle.load(fp)
except (IOError, pickle.PickleError):
cache = {}
if params in cache:
body = cache[params]
else:
try:
body = json.loads(requests.get(oembed + '?' + urlencode(params)).read())['html']
except (requests.HTTPError, requests.URLError):
log.exception('unable to fetch tweet')
body = "Tweet could not be fetched"
except (ValueError, KeyError):
log.exception('could not parse response')
body = "Tweet could not be processed"
else:
cache[params] = body
try:
with io.open(join(core.cache.cache_dir, 'tweets'), 'wb') as fp:
pickle.dump(cache, fp, pickle.HIGHEST_PROTOCOL)
except (IOError, pickle.PickleError):
log.exception('uncaught exception during pickle.dump')
return "<div class='embed tweet'>%s</div>" % body
class Liquid(Filter):
match = [re.compile('^(liquid|octopress)$', re.I)]
priority = 80.0
directives = {
'blockquote': blockquote, 'pullquote': pullquote,
'img': img, 'tweet': tweet,
'youtube': youtube
}
def block(self, tag):
return re.compile(''.join([
r'{%% %s (.*?) ?%%}' % tag,
'(?:',
'\n(.+?)\n',
r'{%% end%s %%}' % tag,
')?']), re.MULTILINE | re.DOTALL)
def transform(self, text, entry, *args):
for tag, func in self.directives.iteritems():
text = re.sub(self.block(tag), lambda m: func(*m.groups()), text)
return text