lektor_ng.environment.config_old

src/lektor_ng/environment/config_old.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
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
import copy
import os
import re
from collections import OrderedDict
from urllib.parse import urlsplit

from werkzeug.utils import cached_property

from lektor_ng.constants import PRIMARY_ALT
from lektor_ng.i18n import get_i18n_block
from lektor_ng.inifile import IniFile
from lektor_ng.utils import bool_from_string, secure_url

DEFAULT_CONFIG = {
    "EPHEMERAL_RECORD_CACHE_SIZE": 500,
    "ATTACHMENT_TYPES": {
        # Only enable image formats here that we can handle in imagetools.
        # Right now this is limited to jpg, png and gif.
        ".jpg": "image",
        ".jpeg": "image",
        ".png": "image",
        ".gif": "image",
        ".svg": "image",
        ".avi": "video",
        ".mpg": "video",
        ".mpeg": "video",
        ".wmv": "video",
        ".ogv": "video",
        ".mp4": "video",
        ".mp3": "audio",
        ".wav": "audio",
        ".ogg": "audio",
        ".pdf": "document",
        ".doc": "document",
        ".docx": "document",
        ".htm": "document",
        ".html": "document",
        ".txt": "text",
        ".log": "text",
    },
    "PROJECT": {
        "name": None,
        "locale": "en_US",
        "url": None,
        "url_style": "relative",
    },
    "THEME_SETTINGS": {},
    "PACKAGES": {},
    "ALTERNATIVES": OrderedDict(),
    "PRIMARY_ALTERNATIVE": None,
    "SERVERS": {},
}


def update_config_from_ini(config, inifile):
    for section_name in ("ATTACHMENT_TYPES", "PROJECT", "PACKAGES", "THEME_SETTINGS"):
        section_config = inifile.section_as_dict(section_name.lower())
        config[section_name].update(section_config)

    for sect in inifile.sections():
        if sect.startswith("servers."):
            server_id = sect.split(".")[1]
            config["SERVERS"][server_id] = inifile.section_as_dict(sect)
        elif sect.startswith("alternatives."):
            alt = sect.split(".")[1]
            config["ALTERNATIVES"][alt] = {
                "name": get_i18n_block(inifile, f"alternatives.{alt}.name"),
                "url_prefix": inifile.get(f"alternatives.{alt}.url_prefix"),
                "url_suffix": inifile.get(f"alternatives.{alt}.url_suffix"),
                "primary": inifile.get_bool(f"alternatives.{alt}.primary"),
                "locale": inifile.get(f"alternatives.{alt}.locale", "en_US"),
            }

    for alt, alt_data in config["ALTERNATIVES"].items():
        if alt_data["primary"]:
            config["PRIMARY_ALTERNATIVE"] = alt
            break
    else:
        if config["ALTERNATIVES"]:
            raise RuntimeError("Alternatives defined but no primary set.")


class ServerInfo:
    def __init__(self, id, name_i18n, target, enabled=True, default=False, extra=None):
        self.id = id
        self.name_i18n = name_i18n
        self.target = target
        self.enabled = enabled
        self.default = default
        self.extra = extra or {}

    @property
    def name(self):
        return self.name_i18n.get("en") or self.id

    @property
    def short_target(self):
        match = re.match(r"([a-z]+)://([^/]+)", self.target)
        if match is not None:
            protocol, server = match.groups()
            return f"{server} via {protocol}"
        return self.target

    def to_json(self):
        return {
            "id": self.id,
            "name": self.name,
            "name_i18n": self.name_i18n,
            "target": self.target,
            "short_target": self.short_target,
            "enabled": self.enabled,
            "default": self.default,
            "extra": self.extra,
        }


class Config:
    def __init__(self, filename=None):
        self.filename = filename
        self.values = copy.deepcopy(DEFAULT_CONFIG)

        if filename is not None and os.path.isfile(filename):
            inifile = IniFile(filename)
            update_config_from_ini(self.values, inifile)

    def __getitem__(self, name):
        return self.values[name]

    @property
    def site_locale(self):
        """The locale of this project."""
        return self.values["PROJECT"]["locale"]

    def get_servers(self, public=False):
        """Returns a list of servers."""
        rv = {}
        for server in self.values["SERVERS"]:
            server_info = self.get_server(server, public=public)
            if server_info is None:
                continue
            rv[server] = server_info
        return rv

    def get_default_server(self, public=False):
        """Returns the default server."""
        choices = []
        for server in self.values["SERVERS"]:
            server_info = self.get_server(server, public=public)
            if server_info is not None:
                if server_info.default:
                    return server_info
                choices.append(server_info)
        if len(choices) == 1:
            return choices[0]
        return None

    def get_server(self, name, public=False):
        """Looks up a server info by name."""
        info = self.values["SERVERS"].get(name)
        if info is None or "target" not in info:
            return None
        info = info.copy()
        target = info.pop("target")
        if public:
            target = secure_url(target)
        return ServerInfo(
            id=name,
            name_i18n=get_i18n_block(info, "name", pop=True),
            target=target,
            enabled=bool_from_string(info.pop("enabled", None), True),
            default=bool_from_string(info.pop("default", None), False),
            extra=info,
        )

    def is_valid_alternative(self, alt):
        """Checks if an alternative ID is known."""
        if alt == PRIMARY_ALT:
            return True
        return alt in self.values["ALTERNATIVES"]

    def list_alternatives(self):
        """Returns a sorted list of alternative IDs."""
        return sorted(self.values["ALTERNATIVES"])

    def iter_alternatives(self):
        """Iterates over all alternatives.  If the system is disabled this
        yields '_primary'.
        """
        found = False
        for alt in self.values["ALTERNATIVES"]:
            if alt != PRIMARY_ALT:
                yield alt
                found = True
        if not found:
            yield PRIMARY_ALT

    def get_alternative(self, alt):
        """Returns the config setting of the given alt."""
        if alt == PRIMARY_ALT:
            alt = self.primary_alternative
        return self.values["ALTERNATIVES"].get(alt)

    def get_alternative_url_prefixes(self):
        """Returns a list of alternative url prefixes by length."""
        items = [(v["url_prefix"].lstrip("/"), k) for k, v in self.values["ALTERNATIVES"].items() if v["url_prefix"]]
        items.sort(key=lambda x: -len(x[0]))
        return items

    def get_alternative_url_suffixes(self):
        """Returns a list of alternative url suffixes by length."""
        items = [(v["url_suffix"].rstrip("/"), k) for k, v in self.values["ALTERNATIVES"].items() if v["url_suffix"]]
        items.sort(key=lambda x: -len(x[0]))
        return items

    def get_alternative_url_span(self, alt=PRIMARY_ALT):
        """Returns the URL span (prefix, suffix) for an alt."""
        if alt == PRIMARY_ALT:
            alt = self.primary_alternative
        cfg = self.values["ALTERNATIVES"].get(alt)
        if cfg is not None:
            return cfg["url_prefix"] or "", cfg["url_suffix"] or ""
        return "", ""

    @cached_property
    def primary_alternative_is_rooted(self):
        """`True` if the primary alternative is sitting at the root of
        the URL handler.
        """
        primary = self.primary_alternative
        if primary is None:
            return True

        cfg = self.values["ALTERNATIVES"].get(primary)
        if not (cfg["url_prefix"] or "").lstrip("/") and not (cfg["url_suffix"] or "").rstrip("/"):
            return True

        return False

    @property
    def primary_alternative(self):
        """The identifier that acts as primary alternative."""
        return self.values["PRIMARY_ALTERNATIVE"]

    @cached_property
    def base_url(self):
        """The external base URL."""
        url = self.values["PROJECT"].get("url")
        if url and urlsplit(url).scheme:
            return url.rstrip("/") + "/"
        return None

    @cached_property
    def base_path(self):
        """The base path of the URL."""
        url = self.values["PROJECT"].get("url")
        if url:
            return urlsplit(url).path.rstrip("/") + "/"
        return "/"

    @cached_property
    def url_style(self):
        """The intended URL style."""
        style = self.values["PROJECT"].get("url_style")
        if style in ("relative", "absolute", "external"):
            return style
        return "relative"