aboutsummaryrefslogtreecommitdiff
path: root/src/koszko_org_website/app.py
blob: 84be22a605c331214857a3c6fcb46479cde8f7b9 (plain)
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
# SPDX-License-Identifier: CC0-1.0

# koszko.org website logic.

# Copyright (C) 2021, 2022 Wojtek Kosior

import gettext
import re
import dataclasses as dc
import typing as t

from pathlib import Path, PurePosixPath

import flask
import werkzeug
import jinja2
import jinja2.exceptions


here = Path(__file__).resolve().parent


pages = {
    'index.html'
}


langs_short_2_long = {
    'en': 'en_US',
    'pl': 'pl_PL'
}

langs_long_2_short = dict((v, k) for k, v in langs_short_2_long.items())

default_locale = 'pl_PL'


def raise_exception(msg) -> t.NoReturn:
    raise Exception(msg)


post_titles_pl = {
    'gospel-despite-no-enthusiasm': 'Dobra Nowina pomimo zniechęcenia'
}

post_titles_en = {
    'gospel-despite-no-enthusiasm': 'Gospel despite lack of enthusiasm'
}

post_titles = {'en': post_titles_en, 'pl': post_titles_pl}

@dc.dataclass(frozen=True)
class PostData:
    date:      str
    page_path: str
    title:     str

    def __lt__(self, other: 'PostData') -> bool:
        return (other.date, self.page_path) < (self.date, other.page_path)

post_filename_re = re.compile(
    r'''
    ^
    (?P<date>20[0-9][0-9]-[0-1][0-9]-[0-3][0-9])
    -
    (?P<post_identifier>.*)
    \.html\.jinja
    $
    ''',
    re.VERBOSE
)

def get_posts(lang: str) -> t.Sequence[PostData]:
    lang_dir = here / 'templates' / lang
    posts_data = []

    for template_path in (lang_dir / 'posts').glob('20*'):
        filename_match = post_filename_re.match(template_path.name)
        assert filename_match is not None

        date = filename_match.group('date')
        post_identifier = filename_match.group('post_identifier')
        page_path = f'posts/{date}-{post_identifier}.html'
        title = post_titles[lang][post_identifier]

        posts_data.append(PostData(date=date, page_path=page_path, title=title))

    return sorted(posts_data)


@dc.dataclass(init=False)
class Website(flask.Flask):
    def __init__(self) -> None:
        super().__init__(__name__)

        self.jinja_options = {
            **self.jinja_options,
            'loader':        jinja2.PackageLoader(__package__),
            'autoescape':    jinja2.select_autoescape(['.jinja']),
            'lstrip_blocks': True,
            'extensions': [
                *self.jinja_options.get('extensions', []),
                'jinja2.ext.i18n',
                'jinja2.ext.do'
            ]
        }

        self.jinja_env.globals['raise'] = raise_exception
        self.jinja_env.globals['get_posts'] = get_posts

    def koszko_install_translations(self, locale: str) -> None:
        translations = gettext.translation(
            'messages',
            localedir = here / 'locales',
            languages = [locale]
        )
        self.jinja_env.install_gettext_translations(translations)


website_app = Website()


def show_page(lang_short: str, page_path: str) -> str:
    for segment in PurePosixPath(page_path).parts:
        if segment.startswith('__'):
            flask.abort(404)

    effective_page_path = '__index.html' if page_path == '' else page_path

    app = t.cast(Website, flask.current_app)
    app.koszko_install_translations(langs_short_2_long[lang_short])

    for prefix in [f'{lang_short}', '']:
        pure_path = PurePosixPath(prefix) / f'{effective_page_path}.jinja'
        footer_path = pure_path.parent / f'__footer_for_{pure_path.name}'
        try:
            html = flask.render_template(
                str(pure_path),
                lang_short            = lang_short,
                page_path             = page_path,
                dedicated_footer_path = str(footer_path)
            )
            break
        except jinja2.exceptions.TemplateNotFound:
            if prefix == '':
                raise

    return html

for lang in langs_short_2_long.keys():
    def __show_page_in_lang(page_path: str, lang_short: str = lang) -> str:
        return show_page(lang_short, page_path)

    website_app.add_url_rule(
        f'/{lang}/<path:page_path>',
        f'show_page_in_{lang}',
        __show_page_in_lang,
        methods=['GET']
    )

    def __show_main_page_in_lang(lang_short: str = lang) -> str:
        return show_page(lang_short, '')

    website_app.add_url_rule(
        f'/{lang}/',
        f'show_main_page_in_{lang}',
        __show_main_page_in_lang,
        methods=['GET']
    )

@website_app.route('/<path:page_path>', methods=['GET'])
def redirect_to_resource(page_path) -> werkzeug.Response:
    if page_path != '':
        path_start = PurePosixPath(page_path).parts[0]

        if path_start == 'sideload':
            return flask.Response(
                "Incomplete server configuration - requests for '/sideload/' not routed as they should be.",
                500
            )

        # Route to other stuff that was on this domain before and has been moved
        # under '/sideload/'.
        for name in ['fraktal', 'mm']:
            if path_start == name:
                return flask.redirect(f'/sideload/{name}')

        # Make all resources from '/static' aliased under '/'.
        if not page_path.endswith('.html'):
            return flask.redirect(f'/static/{page_path}')

    # Redirect to the most suitable language version of a page.
    chosen_locale = flask.request.accept_languages.best_match(
        langs_short_2_long.values(),
        default = default_locale
    )
    if chosen_locale is None:
        chosen_locale = default_locale

    lang_short = langs_long_2_short[chosen_locale]

    url = flask.url_for(
        f'.show_page_in_{lang_short}',
        page_path  = page_path
    )
    return flask.redirect(url)

@website_app.route('/', methods=['GET'])
def redirect_to_lang_main_page() -> werkzeug.Response:
    return redirect_to_resource('')