/
archive.py
166 lines (148 loc) · 7.28 KB
/
archive.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
# -*- coding: utf-8 -*-
# Copyright © 2012-2016 Roberto Alsina and others.
# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial portions of
# the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Classify the posts in archives."""
import os
import nikola.utils
import datetime
from nikola.plugin_categories import Taxonomy
class Archive(Taxonomy):
"""Classify the post archives."""
name = "classify_archive"
classification_name = "archive"
metadata_name = None
overview_page_variable_name = "archive"
more_than_one_classifications_per_post = False
has_hierarchy = True
include_posts_from_subhierarchies = True
include_posts_into_hierarchy_root = True
subcategories_list_template = "list.tmpl"
generate_atom_feeds_for_post_lists = False
template_for_classification_overview = None
always_disable_rss = True
apply_to_posts = True
apply_to_pages = False
minimum_post_count_per_classification_in_overview = 1
omit_empty_classifications = False
also_create_classifications_from_other_languages = False
def set_site(self, site):
"""Set Nikola site."""
# Sanity checks
if (site.config['CREATE_MONTHLY_ARCHIVE'] and site.config['CREATE_SINGLE_ARCHIVE']) and not site.config['CREATE_FULL_ARCHIVES']:
raise Exception('Cannot create monthly and single archives at the same time.')
# Finish setup
self.show_list_as_subcategories_list = not site.config['CREATE_FULL_ARCHIVES']
self.show_list_as_index = site.config['ARCHIVES_ARE_INDEXES']
self.template_for_single_list = "archiveindex.tmpl" if site.config['ARCHIVES_ARE_INDEXES'] else "list_post.tmpl"
# Determine maximum hierarchy height
if site.config['CREATE_DAILY_ARCHIVE'] or site.config['CREATE_FULL_ARCHIVES']:
self.max_levels = 3
elif site.config['CREATE_MONTHLY_ARCHIVE']:
self.max_levels = 2
elif site.config['CREATE_SINGLE_ARCHIVE']:
self.max_levels = 0
else:
self.max_levels = 1
return super(Archive, self).set_site(site)
def get_implicit_classifications(self, lang):
"""Return a list of classification strings which should always appear in posts_per_classification."""
return ['']
def classify(self, post, lang):
"""Classify the given post for the given language."""
levels = [str(post.date.year).zfill(4), str(post.date.month).zfill(2), str(post.date.day).zfill(2)]
return ['/'.join(levels[:self.max_levels])]
def sort_classifications(self, classifications, lang, level=None):
"""Sort the given list of classification strings."""
if level in (0, 1):
# Years or months: sort descending
classifications.sort()
classifications.reverse()
def get_classification_friendly_name(self, classification, lang, only_last_component=False):
"""Extract a friendly name from the classification."""
classification = self.extract_hierarchy(classification)
if len(classification) == 0:
return ""
elif len(classification) == 1:
return classification[0]
elif len(classification) == 2:
nikola.utils.LocaleBorg().get_month_name(int(classification[1]), lang)
else:
# Fallback
return '/'.join(classification)
def get_path(self, classification, lang, type='page'):
"""A path handler for the given classification."""
components = [self.site.config['ARCHIVE_PATH']]
if classification:
components.extend(classification)
add_index = 'always'
else:
components.append(os.path.splitext(self.site.config['ARCHIVE_FILENAME'])[0])
add_index = 'never'
return [_f for _f in components if _f], add_index
def extract_hierarchy(self, classification):
"""Given a classification, return a list of parts in the hierarchy."""
return classification.split('/') if classification else []
def recombine_classification_from_hierarchy(self, hierarchy):
"""Given a list of parts in the hierarchy, return the classification string."""
return '/'.join(hierarchy)
def provide_context_and_uptodate(self, classification, lang, node=None):
"""Provide data for the context and the uptodate list for the list of the given classifiation."""
hierarchy = self.extract_hierarchy(classification)
kw = {
"messages": self.site.MESSAGES,
}
page_kind = "list"
if self.show_list_as_index:
if not self.show_list_as_subcategories_list or len(hierarchy) == self.max_levels:
page_kind = "index"
if len(hierarchy) == 0:
title = kw["messages"][lang]["Archive"]
kw["is_feed_stale"] = False
elif len(hierarchy) == 1:
title = kw["messages"][lang]["Posts for year %s"] % hierarchy[0]
kw["is_feed_stale"] = (datetime.datetime.utcnow().strftime("%Y") != hierarchy[0])
elif len(hierarchy) == 2:
title = kw["messages"][lang]["Posts for {month} {year}"].format(
year=hierarchy[0],
month=nikola.utils.LocaleBorg().get_month_name(int(hierarchy[1]), lang))
kw["is_feed_stale"] = (datetime.datetime.utcnow().strftime("%Y/%m") != classification)
elif len(hierarchy) == 3:
title = kw["messages"][lang]["Posts for {month} {day}, {year}"].format(
year=hierarchy[0],
month=nikola.utils.LocaleBorg().get_month_name(int(hierarchy[1]), lang),
day=int(hierarchy[2]))
kw["is_feed_stale"] = (datetime.datetime.utcnow().strftime("%Y/%m/%d") != classification)
else:
raise Exception("Cannot interpret classification {}!".format(repr(classification)))
context = {
"title": title,
"pagekind": [page_kind, "archive_page"],
}
if page_kind == 'index':
context["archive_name"] = classification if classification else None
context["is_feed_stale"] = kw["is_feed_stale"]
kw.update(context)
return context, kw
def should_generate_classification_list(self, classification, post_list, lang):
"""Only generates list of posts for classification if this function returns True."""
return len(classification.split('/')) < 3 or len(post_list) > 0