aboutsummaryrefslogtreecommitdiffstats
path: root/nikola/plugins/task/archive.py
blob: 4f1ab19b1586e046bd7aa0304b599dfc9698b3de (plain) (blame)
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
# -*- coding: utf-8 -*-

# Copyright © 2012-2014 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.

import os

# for tearDown with _reload we cannot use 'import from' to access LocaleBorg
import nikola.utils
from nikola.plugin_categories import Task
from nikola.utils import config_changed


class Archive(Task):
    """Render the post archives."""

    name = "render_archive"

    def set_site(self, site):
        site.register_path_handler('archive', self.archive_path)
        return super(Archive, self).set_site(site)

    def gen_tasks(self):
        kw = {
            "messages": self.site.MESSAGES,
            "translations": self.site.config['TRANSLATIONS'],
            "output_folder": self.site.config['OUTPUT_FOLDER'],
            "filters": self.site.config['FILTERS'],
            "create_monthly_archive": self.site.config['CREATE_MONTHLY_ARCHIVE'],
            "create_single_archive": self.site.config['CREATE_SINGLE_ARCHIVE'],
        }
        self.site.scan_posts()
        yield self.group_task()
        # TODO add next/prev links for years
        if kw['create_monthly_archive'] and kw['create_single_archive']:
            raise Exception('Cannot create monthly and single archives at the same time.')
        for lang in kw["translations"]:
            archdata = self.site.posts_per_year
            # A bit of a hack.
            if kw['create_single_archive']:
                archdata = {None: self.site.posts}

            for year, posts in archdata.items():
                output_name = os.path.join(
                    kw['output_folder'], self.site.path("archive", year, lang))
                context = {}
                context["lang"] = lang
                if year:
                    context["title"] = kw["messages"][lang]["Posts for year %s"] % year
                else:
                    context["title"] = kw["messages"][lang]["Archive"]
                context["permalink"] = self.site.link("archive", year, lang)
                if not kw["create_monthly_archive"]:
                    template_name = "list_post.tmpl"
                    post_list = sorted(posts, key=lambda a: a.date)
                    post_list.reverse()
                    context["posts"] = post_list
                else:  # Monthly archives, just list the months
                    months = set([(m.split('/')[1], self.site.link("archive", m, lang)) for m in self.site.posts_per_month.keys() if m.startswith(str(year))])
                    months = sorted(list(months))
                    months.reverse()
                    template_name = "list.tmpl"
                    context["items"] = [[nikola.utils.LocaleBorg().get_month_name(int(month), lang), link] for month, link in months]
                    post_list = []
                task = self.site.generic_post_list_renderer(
                    lang,
                    [],
                    output_name,
                    template_name,
                    kw['filters'],
                    context,
                )
                n = len(post_list) if 'posts' in context else len(months)

                deps_translatable = {}
                for k in self.site._GLOBAL_CONTEXT_TRANSLATABLE:
                    deps_translatable[k] = self.site.GLOBAL_CONTEXT[k](lang)

                task_cfg = {1: task['uptodate'][0].config, 2: kw, 3: n, 4: deps_translatable}
                task['uptodate'] = [config_changed(task_cfg)]
                task['basename'] = self.name
                yield task

            if not kw["create_monthly_archive"]:
                continue  # Just to avoid nesting the other loop in this if
            template_name = "list_post.tmpl"
            for yearmonth, posts in self.site.posts_per_month.items():
                output_name = os.path.join(
                    kw['output_folder'], self.site.path("archive", yearmonth,
                                                        lang))
                year, month = yearmonth.split('/')
                post_list = sorted(posts, key=lambda a: a.date)
                post_list.reverse()
                context = {}
                context["lang"] = lang
                context["posts"] = post_list
                context["permalink"] = self.site.link("archive", year, lang)

                context["title"] = kw["messages"][lang]["Posts for {month} {year}"].format(
                    year=year, month=nikola.utils.LocaleBorg().get_month_name(int(month), lang))
                task = self.site.generic_post_list_renderer(
                    lang,
                    post_list,
                    output_name,
                    template_name,
                    kw['filters'],
                    context,
                )
                task_cfg = {1: task['uptodate'][0].config, 2: kw, 3: len(post_list)}
                task['uptodate'] = [config_changed(task_cfg)]
                task['basename'] = self.name
                yield task

        if not kw['create_single_archive']:
            # And an "all your years" page for yearly and monthly archives
            years = list(self.site.posts_per_year.keys())
            years.sort(reverse=True)
            template_name = "list.tmpl"
            kw['years'] = years
            for lang in kw["translations"]:
                context = {}
                output_name = os.path.join(
                    kw['output_folder'], self.site.path("archive", None,
                                                        lang))
                context["title"] = kw["messages"][lang]["Archive"]
                context["items"] = [(y, self.site.link("archive", y, lang))
                                    for y in years]
                context["permalink"] = self.site.link("archive", None, lang)
                task = self.site.generic_post_list_renderer(
                    lang,
                    [],
                    output_name,
                    template_name,
                    kw['filters'],
                    context,
                )
                task_cfg = {1: task['uptodate'][0].config, 2: kw, 3: len(years)}
                task['uptodate'] = [config_changed(task_cfg)]
                task['basename'] = self.name
                yield task

    def archive_path(self, name, lang):
        if name:
            return [_f for _f in [self.site.config['TRANSLATIONS'][lang],
                                  self.site.config['ARCHIVE_PATH'], name,
                                  self.site.config['INDEX_FILE']] if _f]
        else:
            return [_f for _f in [self.site.config['TRANSLATIONS'][lang],
                                  self.site.config['ARCHIVE_PATH'],
                                  self.site.config['ARCHIVE_FILENAME']] if _f]