aboutsummaryrefslogtreecommitdiff
path: root/site.py
blob: 38f61c19d33065749a9c70d41bc905752f4dbcdb (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
# Copyright (C) 2019 GNUnet e.V.
#
# This code is derived from code contributed to GNUnet e.V.
# by ng0 <ng0@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 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

# 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.fileproc import copy_files, copy_tree
from inc.make_rss import *

class gen_site:
    def __init__(self, debug):
        self.debug = debug

    def load_config(self, name="www.yml"):
        yaml = YAML(typ='safe')
        site_configfile = Path(name)
        return 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, conf, name, member, pages, length):
        if self.debug:
            print("generating abstracts...")
        for item in conf[name]:
            item[member] = cut_news_text(item[pages], length)
        if self.debug:
            print("cwd: " + str(Path.cwd()))
        if self.debug > 1:
            print(conf["newsposts"])
        if self.debug:
            print("[done] generating abstracts")

    def gen_newspost_content(self, conf, name, member, pages, lang):
        if self.debug:
            print("generating newspost content...")
        for item in conf[name]:
            item[member] = cut_article(item[pages], conf, lang)
        if self.debug:
            print("cwd: " + str(Path.cwd()))
        if self.debug > 1:
            print(conf["newsposts"])
        if self.debug:
            print("[done] generating newspost content")

    def gen_rss(self, directory, conf, env):
        make_rss(directory, conf, env)

    def run(self, root, conf, env):
        # root = "../" + root
        if self.debug > 1:
            _ = Path(".")
            q = list(_.glob("**/*.j2"))
            print(q)
        # for in_file in glob.glob(root + "/*.j2"):
        for in_file in Path(".").glob(root + "/*.j2"):
            in_file = str(in_file)
            if self.debug > 1:
                print(in_file)
            name, ext = re.match(r"(.*)\.([^.]+)$",
                                 in_file.rstrip(".j2")).groups()
            tmpl = env.get_template(in_file)

            def self_localized(other_locale):
                """
                Return URL for the current page in another locale.
                """
                if root == "news":
                    return "../../" + other_locale + "/news/" + in_file.replace(
                       root + '/', '').rstrip(".j2")
                else:
                    return "../" + other_locale + "/" + in_file.replace(
                       root + '/', '').rstrip(".j2")

            def url_localized(filename):
                if root == "news":
                    return "../../" + locale + "/" + filename
                else:
                    return "../" + locale + "/" + filename

            def url_static(filename):
                if root == "news":
                    return "../../static/" + filename
                else:
                    return "../static/" + filename

            def url_dist(filename):
                if root == "news":
                    return "../../dist/" + filename
                else:
                    return "../dist/" + filename

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

            def url(x):
                # TODO: look at the app root environment variable
                # TODO: check if file exists
                #if root == "news":
                #    return "../" + "../" + x
                #else:
                #    return "../" + x
                return "../" + x

            # for l in glob.glob("locale/*/"):
            # https://bugs.python.org/issue22276
            for l in list(x for x in Path(".").glob("locale/*/") if x.is_dir()):
                l = str(PurePath(l).name)
                if self.debug > 1:
                    print(l)
                # locale = os.path.basename(l[:-1])
                locale = l

                tr = gettext.translation("messages",
                                         localedir="locale",
                                         languages=[locale])

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

                env.install_gettext_translations(tr, newstyle=True)

                content = tmpl.render(lang=locale,
                                      lang_full=conf["langs_full"][locale],
                                      url=url,
                                      conf=conf,
                                      siteconf=conf["siteconf"],
                                      meetingnotesdata=conf["meetingnotes"],
                                      newsdata=conf["newsposts"],
                                      videosdata=conf["videoslist"],
                                      self_localized=self_localized,
                                      url_localized=url_localized,
                                      url_static=url_static,
                                      url_dist=url_dist,
                                      svg_localized=svg_localized,
                                      filename=name + "." + ext)

                if root == "news":
                    out_name = "./rendered/" + locale + "/" + root + "/" + in_file.replace(
                        root + '/', '').rstrip(".j2")
                else:
                    out_name = "./rendered/" + locale + "/" + in_file.replace(
                        root + '/', '').rstrip(".j2")

                outdir = Path("rendered")

                if root == "news":
                    langdir = outdir / locale / root
                else:
                    langdir = outdir / locale

                try:
                    langdir.mkdir(parents=True, exist_ok=True)
                except e as FileNotFoundError:
                    print(e)

                with codecs.open(out_name, "w", encoding='utf-8') as f:
                    try:
                        if self.debug > 1:
                            print(Path.cwd())
                        f.write(content)
                    except e as Error:
                        print(e)