-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsite
executable file
·382 lines (308 loc) · 11.5 KB
/
site
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
#!/usr/bin/env python
# python 3 stdlib
from datetime import date, datetime
from glob import glob
from itertools import groupby
from unicodedata import normalize
import codecs
import locale
import os
import re
import shutil
# see CONTRIBUTING re dependencies
from argh import ArghParser, CommandError
from flask import Flask, render_template, abort
from flask_frozen import Freezer
from flask_flatpages import FlatPages
from flaskext.markdown import Markdown
from flask_assets import Environment as AssetManager
from PIL import Image, ImageOps
from werkzeug.routing import BaseConverter
from meta_compat import MetaCompat
# Configuration
DEBUG = False
BASE_URL = 'http://www.madmode.com/'
ASSETS_DEBUG = DEBUG
FLATPAGES_AUTO_RELOAD = True
FLATPAGES_EXTENSION = '.md'
FLATPAGES_ROOT = 'pages'
FLATPAGES_MARKDOWN_EXTENSIONS = ['markdown.extensions.fenced_code']
# App configuration
FEED_MAX_LINKS = 25
SECTION_MAX_LINKS = 12
class FlaskE(Flask):
def handle_user_exception(self, e):
import traceback
print(traceback.format_exc(e))
import pdb; pdb.set_trace() # noqa
# app = FlaskE(__name__)
app = Flask(__name__)
app.config.from_object(__name__)
pages = MetaCompat(app)
freezer = Freezer(app)
markdown_manager = Markdown(app)
asset_manager = AssetManager(app)
###############################################################################
# Model helpers
def get_pages(pages, offset=None, limit=None, tag=None, year=None, month=None):
""" Retrieves pages matching passec criterias.
"""
articles = [p for p in pages if p.meta.get('date')]
# filter unpublished article
if not app.debug:
articles = [p for p in articles if p.meta.get('published') is True]
if tag:
articles = [p for p in articles if tag in p.meta.get('tags', ())]
# filter year, month
if year:
articles = [p for p in articles if p.meta.get('date').year == year]
if month:
articles = [p for p in articles if p.meta.get('date').month == month]
# sort by date
articles = sorted(articles, reverse=True, key=lambda p: p.meta.get(
'date', date.today()))
# assign prev/next page in serie
articles = sorted(articles, key=lambda p: p.meta.get('date'))
articles = list(reversed(articles))
for i, article in enumerate(articles):
if i != 0:
article.prev = articles[i - 1]
if i != len(articles) - 1:
article.next = articles[i + 1]
# offset and limit
if offset and limit:
return articles[offset:limit]
elif limit:
return articles[:limit]
elif offset:
return articles[offset:]
else:
return articles
def tag_counts(pages):
all_tags = [tag for pg in pages
for tag in pg.meta.get('tags', ())]
count_tags = [(tag, len(list(tag_group)))
for tag, tag_group in groupby(sorted(all_tags))]
return sorted(count_tags, key=lambda x: x[0].lower())
def get_years(pages):
years = sorted(set([page.meta.get('date').year for page in pages]))
years.reverse()
return years
def resize_image(path, box, out=None, fit=True, quality=75):
""" Downsample an image.
@param path: string - path to the original image
@param box: tuple(x, y) - the bounding box of the result image
@param out: file-like-object - save the image into
the output stream
@param fit: boolean - crop the image to fill the box
@param quality: int - JPEG quality
"""
img = Image.open(path)
if fit:
img = ImageOps.fit(img, box, Image.ANTIALIAS)
else:
img.thumbnail(box, Image.ANTIALIAS)
if not out:
out = os.path.splitext(path)[0] + ".tn.jpg"
img.save(out, "JPEG", quality=quality)
def slugify(text, delim=u'-'):
"""Generates an slightly worse ASCII-only slug."""
_punct_re = re.compile(r'[\t !"#$%&\'()*\-/<=>?@\[\\\]^_`{|},.]+')
result = []
for word in _punct_re.split(text.lower()):
word = normalize('NFKD', word).encode('ascii', 'ignore')
if word:
result.append(word)
return unicode(delim.join(result))
###############################################################################
# Filters
@app.template_filter()
def to_rfc2822(dt):
if not dt:
return
current_locale = locale.getlocale(locale.LC_TIME)
locale.setlocale(locale.LC_TIME, "en_US.utf8")
formatted = dt.strftime("%a, %d %b %Y %H:%M:%S +0000")
locale.setlocale(locale.LC_TIME, current_locale)
return formatted
###############################################################################
# Context processors
@app.context_processor
def inject_ga():
return dict(BASE_URL=BASE_URL)
###############################################################################
# url_map converters
class MonthConverter(BaseConverter):
def to_python(self, numeral):
return int(numeral)
def to_url(self, n):
return '%02d' % n
app.url_map.converters['month'] = MonthConverter
###############################################################################
# Routes
@app.route('/contact/')
def contact():
return render_template('contact.html')
@app.route('/feeds/posts/default')
def feed():
articles = get_pages(pages, limit=FEED_MAX_LINKS)
now = datetime.now()
# {'Content-Type': 'text/css; charset=utf-8'}
txt = render_template('base.rss', pages=articles, build_date=now)
return txt, 200, {'Content-Type': 'application/rss+xml'}
@app.route('/sitemap.xml')
def sitemap():
today = date.today()
recently = date(year=today.year, month=today.month, day=1)
# {'Content-Type': 'text/css; charset=utf-8'}
txt = render_template('sitemap.xml', pages=get_pages(pages),
today=today, recently=recently)
return txt, 200, {'Content-Type': 'application/xml'}
@app.route('/')
def index():
articles = pages
if not app.debug:
articles = [p for p in articles if p.meta.get('published') is True]
return render_template('index.html',
posts=get_pages(pages, limit=5),
years=get_years(get_pages(articles)),
tag_counts=tag_counts(articles))
@app.route('/<path:path>.html')
def page(path):
page = pages.get_or_404(path)
# allow preview of unpublished stuff in DEBUG mode
if not app.debug and not page.meta.get('published', False):
abort(404)
template = page.meta.get('template', 'code/page.html')
return render_template(template, page=page)
@app.route('/search/label/<string:tag>/')
def search_tag(tag):
template = 'archives.html'
articles = get_pages(pages, tag=tag)
return render_template(template, pages=articles, tag=tag)
@app.route('/<int:year>/')
def archives_year(year):
template = 'archives.html'
years = get_years(get_pages(pages))
articles = get_pages(pages, year=year)
months = sorted(set([p.meta.get('date').month for p in articles]))
return render_template(template, pages=articles,
years=years, months=reversed(months), year=year)
@app.route('/<int:year>_<month:month>_01_archive.html')
def archives_year_month(year, month):
template = 'archives.html'
years = get_years(get_pages(pages))
articles = get_pages(pages, year=year, month=month)
return render_template(template, pages=articles, years=years, year=year)
@app.route('/403.html')
def error403():
return render_template('403.html')
@app.route('/404.html')
def error404():
return render_template('404.html')
@app.route('/500.html')
def error500():
return render_template('500.html')
@app.errorhandler(404)
def page_not_found(error):
return render_template('404.html'), 404
###############################################################################
# Commands
def build(debug=DEBUG):
""" Builds this site.
"""
print("Building website...")
app.debug = debug
asset_manager.config['ASSETS_DEBUG'] = False
freezer.freeze()
for pat in ['*.ico', '*.txt', '*.xml']:
for name in glob('./static/' + pat):
shutil.copy2(name, './build/')
shutil.rmtree('./build/.well-known', ignore_errors=True)
shutil.copytree('./static/.well-known', './build/.well-known/')
# KLUDGE:
shutil.rmtree('./build/2012/cocogetblk/', ignore_errors=True)
shutil.copytree('./pages/2012/cocogetblk/', './build/2012/cocogetblk/')
print("Done.")
def post(title=None, filename=None):
""" Create a new empty post.
"""
post_date = datetime.today()
title = unicode(title) if title else "Untitled Post"
if not filename:
filename = u"%s.md" % slugify(title)
year = post_date.year
pathargs = [str(year), filename, ]
filepath = os.path.join(os.path.abspath(os.path.dirname(__file__)),
FLATPAGES_ROOT, '/'.join(pathargs))
if os.path.exists(filepath):
raise CommandError("File %s exists" % filepath)
content = '\n'.join([
u"title: %s" % title,
u"date: %s" % post_date.strftime("%Y-%m-%d"),
u"published: false\n\n",
])
try:
codecs.open(filepath, 'w', encoding='utf8').write(content)
print(u'Created %s' % filepath)
except Exception as error:
raise CommandError(error)
def photo(path, slug):
""" Adds a new photo.
"""
photo_date = datetime.today()
# check slug
slug = slugify(unicode(slug))
if not isinstance(slug, basestring) or not slug.strip():
raise CommandError("Invalid slug: " + slug)
# check that the path is valid, is an image
if not os.path.exists(path) or not os.path.isfile(path):
raise CommandError("Invalid path: " + path)
# create directory for images: %year/%slug
photo_dir = os.path.join("static", "photography", str(photo_date.year),
slug)
if os.path.exists(photo_dir):
raise CommandError("path %s already exists" % photo_dir)
os.mkdir(photo_dir, 0o755)
print(u'Created %s' % photo_dir)
# copy original image to original.jpg
original_path = os.path.join(photo_dir, "original.jpg")
shutil.copyfile(path, original_path)
print(u'Copied original to %s' % original_path)
# resize the image: main.jpg and thumb.jpg
thumb_path = os.path.join(photo_dir, "thumb.jpg")
resize_image(original_path, (280, 280), fit=True, out=thumb_path)
print(u'Created %s' % thumb_path)
main_path = os.path.join(photo_dir, "main.jpg")
resize_image(original_path, (900, 900), fit=False, out=main_path)
print(u'Created %s' % main_path)
# post file
filename = slug + FLATPAGES_EXTENSION
pathargs = ["photography", str(photo_date.year), filename, ]
filepath = os.path.join(os.path.abspath(os.path.dirname(__file__)),
FLATPAGES_ROOT, '/'.join(pathargs))
if os.path.exists(filepath):
raise CommandError("File %s exists" % filepath)
content = '\n'.join([
u"title: ",
u"date: %s" % photo_date.strftime("%Y-%m-%d"),
u"type: photo",
u"published: false\n\n\n",
])
try:
codecs.open(filepath, 'w', encoding='utf8').write(content)
print(u'Created %s' % filepath)
except Exception as error:
raise CommandError(error)
print('All done.')
def serve(server='127.0.0.1', port=5000, debug=DEBUG):
""" Serves this site.
"""
asset_manager.config['ASSETS_DEBUG'] = debug
if debug:
app.debug = True
app.run(host=server, port=port, debug=debug)
if __name__ == '__main__':
parser = ArghParser()
parser.add_commands([build, photo, post, serve, ])
parser.dispatch()