aboutsummaryrefslogtreecommitdiff
path: root/site.py
blob: 260921f10fc861394da479959a87a6efb47ba1ac (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
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
# Copyright (C) 2019 GNUnet e.V.
#
# This code is derived from code contributed to GNUnet e.V.
# by nikita <nikita@n0.is> and based on code by Florian Dold.
#
# Permission to use, copy, modify, and/or distribute this software for
# any purpose with or without fee is hereby granted.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
# WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
# AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
# DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
# OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
# TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#
# SPDX-License-Identifier: 0BSD
import os
import shutil
import os.path
import sys
import re
import gettext
import glob
import codecs
import jinja2
from pathlib import Path, PurePosixPath, PurePath
from ruamel.yaml import YAML
from datetime import datetime

# Make sure the current directory is in the search path when trying
# to import i18nfix.
sys.path.insert(0, ".")

import inc.i18nfix as i18nfix
from inc.textproc import cut_news_text, cut_article
from inc.time import time_rfc822, time_now, conv_date_rfc822


def make_helpers(root, in_file, locale):
    """Return a dictionary of helpers that should be available in
    the template."""

    def self_localized(other_locale, relative=False):
        """
        Return URL for the current page in another locale.
        """
        abs_file = Path(in_file).resolve()
        baseurl = os.environ.get("BASEURL")
        if relative or not baseurl:
            return (
                "../"
                + other_locale
                + "/"
                + str(in_file.relative_to(root / "template")).rstrip(".j2")
            )
        else:
            return (
                baseurl
                + other_locale
                + "/"
                + str(Path(abs_file).relative_to(root / "template")).rstrip(".j2")
            )

    def url(x):
        abs_file = Path(in_file).resolve()
        url = ""
        current_location = Path(abs_file).relative_to(root / "template")
        for p in current_location.parts:
            url += "../"
        return url + x

    def url_static(filename):
        return url(filename)

    def url_dist(filename):
        return url("dist/" + filename)

    def url_localized(filename):
        return url(locale + "/" + filename)

    def svg_localized(filename):
        lf = root / "static" / filename / "." / locale / ".svg"
        if locale == "en" or not lf.is_file():
            return url(filename + ".svg")
        else:
            return url(filename + "." + locale + ".svg")

    return dict(
        self_localized=self_localized,
        url_localized=url_localized,
        url_static=url_static,
        url_dist=url_dist,
        url=url,
        svg_localized=svg_localized,
        now=time_rfc822(time_now()),
        conv_date_rfc822=conv_date_rfc822,
    )


def copytree(src, dst, symlinks=False, ignore=None):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isdir(s):
            shutil.copytree(s, d, symlinks, ignore, dirs_exist_ok=True)
        else:
            shutil.copy2(s, d)


class SiteGenerator:
    def __init__(self, debug=0, root="."):
        self.root = Path(root).resolve()
        self.debug = debug
        loader = jinja2.ChoiceLoader(
            [
                jinja2.FileSystemLoader(str(self.root / "template")),
                jinja2.PrefixLoader(
                    {"common": jinja2.FileSystemLoader(str(self.root / "common"))}
                ),
            ]
        )
        env = jinja2.Environment(
            loader=loader,
            extensions=["jinja2.ext.i18n"],
            lstrip_blocks=True,
            trim_blocks=True,
            undefined=jinja2.StrictUndefined,
            autoescape=False,
        )
        env.newstyle_gettext = True
        self.env = env
        yaml = YAML(typ="safe")
        site_configfile = self.root / "www.yml"
        self.config = yaml.load(site_configfile)

    def copy_trees(self, directory):
        """ Take a directory name (string) and pass it to copy_tree() as Path object. """
        i = Path(directory)
        o = Path("rendered/" + directory)
        copy_tree(i, o)

    def gen_abstract(self, name, member, pages, length):
        conf = self.config
        for item in conf[name]:
            item[member] = cut_news_text(item[pages], length)

    def gen_newspost_content(self, name, member, pages, lang):
        conf = self.config
        for item in conf[name]:
            item[member] = cut_article(item[pages], conf, lang)

    def run_localized(self, locale, tr):
        conf = self.config
        root = self.root
        env = self.env
        template_dir = root / "template"
        for in_file in template_dir.glob("**/*.j2"):
            tmpl_filename = str(in_file.resolve().relative_to(template_dir))
            tmpl = env.get_template(tmpl_filename)

            filename = tmpl_filename.rstrip(".j2")

            content = tmpl.render(
                lang=locale,
                lang_full=conf["langs_full"][locale],
                conf=conf,
                siteconf=conf["siteconf"],
                meetingnotesdata=conf["meetingnotes"],
                newsdata=conf["newsposts"],
                newsposts=conf["newsposts"],
                videosdata=conf["videoslist"],
                filename=filename,
                **make_helpers(root, in_file, locale),
            )

            out_name = root / "rendered" / locale / str(tmpl_filename).rstrip(".j2")
            Path(out_name).parent.mkdir(parents=True, exist_ok=True)
            with codecs.open(out_name, "w", encoding="utf-8") as f:
                try:
                    f.write(content)
                except:
                    print(e)

    def emit_sitemap(self):
        p = self.root / "rendered"
        links = sorted(p.rglob("*.html"))
        t0 = datetime.now()
        timestamp = t0.strftime("%Y-%m-%d")

        o = p / "sitemap.xml"
        with o.open("w") as f:
            f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
            f.write("<urlset\n")
            f.write('xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"\n')
            f.write('xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 ')
            f.write('http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"\n')
            f.write('xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n')
            for link in links:
                f.write(
                    "<url><loc>"
                    + str(link).lstrip("rendered")
                    + "</loc><lastmod>"
                    + timestamp
                    + "</lastmod><priority>1.0</priority></url>\n"
                )
            f.write("</urlset>\n")

    def run(self):
        conf = self.config
        root = self.root

        for l in root.glob("locale/*/"):

            if not l.is_dir():
                # https://bugs.python.org/issue22276
                continue

            locale = str(PurePath(l).name)

            try:
                tr = gettext.translation(
                    "messages", localedir="locale", languages=[locale]
                )
            except FileNotFoundError as e:
                print(
                    f"WARNING: unable to find translations for locale '{locale}'",
                    file=sys.stderr,
                )
                continue

            tr.gettext = i18nfix.wrap_gettext(tr.gettext)
            env = self.env

            env.install_gettext_translations(tr, newstyle=True)

            if locale not in conf["langs_full"]:
                print(
                    f"WARNING: skipping '{locale}, as 'langs_full' is not configured'",
                    file=sys.stderr,
                )
                continue

            self.run_localized(locale, tr)

        self.emit_sitemap()

        copytree(root / "static", root / "rendered")