This repository was archived by the owner on Oct 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 447
/
Copy pathviews.py
394 lines (335 loc) · 13.5 KB
/
views.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
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
383
384
385
386
387
388
389
390
391
392
393
394
import hashlib
import PyRSS2Gen as pyrss
from datetime import datetime, timedelta
from flask import current_app as app, render_template, abort, request
from flask.views import MethodView
from flask_simplelogin import is_logged_in
# from werkzeug.contrib.atom import AtomFeed
# The werkzeug AtomFeed escapes all html tags
from quokka.utils.atom import AtomFeed
from .models import make_model, make_paginator, Category, Tag, Author
from quokka.utils.text import (
slugify_category, normalize_var, slugify, cdata, make_external_url
)
class BaseView(MethodView):
def set_content_var_map(self, context, content):
"""Export variables from `content` to theme context
example:
CONTENT_VAR_MAP:
author_avatar: AVATAR
Will get the `article.author_avatar` and export as `AVATAR`
:param: content must be a `model` of type Content
"""
MAP = app.theme_context.get('CONTENT_VAR_MAP', {})
for attr, variable in MAP.items():
value = getattr(content, attr, None)
if value is not None:
context[variable] = value
def set_elements_visibility(self, context, content_type):
"""Set elements visibility according to content type
This works with botstrap3 and malt templates
Default content_types:
index, article, page, category, tag, author,
categories, tags, authors
Custom content types:
Any category, page or article can be accepted
`blog/news` or `blog/news/my-article`
"""
if not content_type:
return
CONTENT_TYPE = normalize_var(content_type).upper()
context['CONTENT_TYPE'] = content_type
for rule in app.theme_context.get('DYNAMIC_VARS', []):
where = rule.get('where')
var_list = rule.get('var')
if not where or not var_list:
continue
if not isinstance(var_list, list):
var_list = [var_list]
if not isinstance(where, list):
where = [where]
WHERE = [normalize_var(item).upper() for item in where]
if CONTENT_TYPE in WHERE:
for var in var_list:
context[var] = rule.get('value', True)
# content specific visibility items
content = context.get('content')
if content:
# comments visibility control
hide = False
disqus_sitename = app.theme_context.get('DISQUS_SITENAME')
if 'HIDE_COMMENTS' in app.theme_context:
hide = app.theme_context['HIDE_COMMENTS']
if 'HIDE_COMMENTS' in context:
hide = context['HIDE_COMMENTS']
else:
context['HIDE_COMMENTS'] = hide
if content.comments in ('closed', False):
hide = True
elif content.comments in ('opened', True):
hide = False
if hide is True:
context['HIDE_COMMENTS'] = True
context['DISQUS_SITENAME'] = False
else:
context['HIDE_COMMENTS'] = False
context['DISQUS_SITENAME'] = disqus_sitename
class ArticleListView(BaseView):
def get(self, category=None, tag=None, author=None,
page_number=1, ext=None):
context = {}
query = {'published': True}
home_template = app.theme_context.get('HOME_TEMPLATE')
list_categories = app.theme_context.get('LIST_CATEGORIES', [])
index_category = app.theme_context.get('INDEX_CATEGORY')
content_type = 'index'
template = custom_template = 'index.html'
ext = ext or app.config.get('CONTENT_EXTENSION', 'html')
FEED_ALL_ATOM = app.theme_context.get('FEED_ALL_ATOM')
FEED_ALL_RSS = app.theme_context.get('FEED_ALL_RSS')
if category:
FEED_ALL_ATOM = f"{category}/index.atom"
FEED_ALL_RSS = f"{category}/index.rss"
content_type = 'category'
custom_template = f'{content_type}/{normalize_var(category)}.html'
if category != index_category:
query['category_slug'] = {'$regex': f"^{category.rstrip('/')}"}
if category not in list_categories:
template = 'category.html'
else:
content_type = 'index'
else:
content_type = 'index'
elif tag:
FEED_ALL_ATOM = f"tag/{tag}/index.atom"
FEED_ALL_RSS = f"tag/{tag}/index.rss"
content_type = 'tag'
custom_template = f'{content_type}/{normalize_var(tag)}.html'
template = 'tag.html'
# https://github.com/schapman1974/tinymongo/issues/42
query['tags_string'] = {'$regex': f'.*,{tag},.*'}
elif author:
FEED_ALL_ATOM = f"author/{author}/index.atom"
FEED_ALL_RSS = f"author/{author}/index.rss"
content_type = 'author'
custom_template = f'{content_type}/{normalize_var(author)}.html'
template = 'author.html'
# https://github.com/schapman1974/tinymongo/issues/42
author_slugs = author.split('/')
if len(author_slugs) > 1:
query['$or'] = [
{'authors_string': {'$regex': f'.*,{author_slug},.*'}}
for author_slug in author_slugs
]
else:
query['authors_string'] = {'$regex': f'.*,{author},.*'}
elif home_template:
# use custom template only when categoty is blank '/'
# and INDEX_TEMPLATE is defined
template = home_template
custom_template = f'{content_type}/{home_template}.html'
content_type = 'home'
articles = [
make_model(article)
for article in app.db.article_set(query)
]
if content_type not in ['index', 'home', 'direct', 'author'] and not articles: # noqa
# on `index`, `home` and direct templates no need for articles
# but category pages should never show empty unless it is author
# profile
abort(404)
page_name = ''
if category:
page_name = category
elif tag:
page_name = f'tag/{tag}'
elif author:
page_name = f'author/{author}'
paginator = make_paginator(articles, name=page_name)
page = paginator.page(page_number)
context.update(
{
'articles': articles,
'page_name': page_name,
'category': Category(category) if category else None,
'tag': Tag(tag) if tag else None,
'author': Author(author) if author else None,
'articles_paginator': paginator,
'articles_page': page,
'articles_next_page': page.next_page,
'articles_previous_page': page.previous_page,
'FEED_ALL_ATOM': FEED_ALL_ATOM,
'FEED_ALL_RSS': FEED_ALL_RSS
}
)
self.set_elements_visibility(context, content_type)
self.set_elements_visibility(context, category)
templates = [f'custom/{custom_template}', template]
return self.render(ext, content_type, templates, **context)
def render(self, ext, content_type, templates, **context):
extension_map = app.config.get('CONTENT_EXTENSION_MAP', {})
method_name = extension_map.get(ext, 'render_template')
return getattr(self, method_name)(content_type, templates, **context)
def render_template(self, content_type, templates, **context):
return render_template(templates, **context)
def render_atom(self, content_type, templates, **context):
feed_name = (
f"{app.theme_context.get('SITENAME')}"
f" | {content_type.title()} | atom feed"
)
if context.get('articles_page'):
contents = context['articles_page'].object_list
else:
contents = context['articles']
feed = AtomFeed(
feed_name,
feed_url=request.url,
url=request.url_root
)
for content in contents:
content = make_model(content)
feed.add(
content.title,
cdata(content.content),
content_type="html",
author=content.author,
url=make_external_url(content.url),
updated=content.modified,
published=content.date
)
return feed.get_response()
def render_rss(self, content_type, templates, **context):
feed_name = description = (
f"{app.theme_context.get('SITENAME')}"
f" | {content_type.title()} | RSS feed"
)
if context.get('articles_page'):
contents = context['articles_page'].object_list
else:
contents = context['articles']
rss = pyrss.RSS2(
title=feed_name,
link=request.url_root,
description=description,
language=app.config.get('RSS_LANGUAGE', 'en-us'),
copyright=app.config.get('RSS_COPYRIGHT', 'All rights reserved.'),
lastBuildDate=datetime.now(),
categories=[str(context.get('tag') or context.get('category'))],
)
# set rss.pubDate to the newest post in the collection
# back 10 years in the past
rss_pubdate = datetime.today() - timedelta(days=365 * 10)
for content in contents:
content = make_model(content)
content_data = content.title.encode('utf-8')
content_data += content.url.encode('utf-8')
if content.date > rss_pubdate:
rss_pubdate = content.date
rss.items.append(
pyrss.RSSItem(
title=content.title,
link=make_external_url(content.url),
description=cdata(content.content),
author=str(content.author),
categories=[str(content.tags)],
guid=hashlib.sha1(
content_data
).hexdigest(),
pubDate=content.date,
)
)
# set the new published date after iterating the contents
rss.pubDate = rss_pubdate
return rss.to_xml(encoding=app.config.get('RSS_ENCODING', 'utf-8'))
class CategoryListView(BaseView):
def build_query(self, cat):
query = {'published': True}
if cat == app.theme_context.get('INDEX_CATEGORY', 'index'):
return query
if cat:
query['category_slug'] = {
'$regex': f"^{slugify_category(cat).rstrip('/')}"
}
else:
query['category_slug'] = cat
return query
def get(self, ext=None):
categories = [
(
Category(cat),
[
make_model(article)
for article in app.db.article_set(self.build_query(cat))
]
)
for cat in app.db.category_set(
filter={'published': True}
) + ['index']
]
context = {
'categories': categories
}
self.set_elements_visibility(context, 'categories')
return render_template('categories.html', **context)
class TagListView(BaseView):
def get(self, page_number=1, ext=None):
tags = [
(Tag(tag), [])
for tag in app.db.tag_set(filter={'published': True})
]
context = {'tags': tags}
self.set_elements_visibility(context, 'tags')
return render_template('tags.html', **context)
class AuthorListView(BaseView):
def get(self, ext=None):
authors = [
(
Author(author),
[
make_model(article)
for article in app.db.article_set(
{'authors_string': {
'$regex': f'.*,{slugify(author)},.*'},
'published': True}
)
]
)
for author in app.db.author_set(filter={'published': True})
]
context = {
'authors': authors
}
self.set_elements_visibility(context, 'authors')
return render_template('authors.html', **context)
class DetailView(BaseView):
is_preview = False
def get(self, slug, ext=None):
category, _, item_slug = slug.rpartition('/')
content = app.db.get_with_content(
slug=item_slug,
category_slug=category
)
if not content:
abort(404)
content = make_model(content)
if content.status == 'draft' and not self.is_preview:
abort(404)
if self.is_preview and not is_logged_in():
# access denied
abort(403)
context = {
'category': content.category,
'author': content.author,
'content': content,
content.content_type: content
}
self.set_elements_visibility(context, content.content_type)
self.set_elements_visibility(context, slug)
self.set_content_var_map(context, content)
templates = [
f'custom/{content.content_type}/{normalize_var(slug)}.html',
f'{content.content_type}.html'
]
return render_template(templates, **context)
class PreviewView(DetailView):
is_preview = True