The served page had no way to translate its text: every string was English in
the HTML and the script. Now the English text stays in the code next to a key
(tr("key", "text", vars), data-i18n="key" in the HTML), a language is a catalog
serve/web/locales/<lang>.json, and a catalog that is missing or has no entry for
a key leaves the English text. The language is the user's choice (About >
Settings), kept in this browser; nothing is chosen from the browser's language,
because a page translated in part would mix two languages. /?lang=de shows one
for a visit.
The server hands out /web/locales/<lang>.json and /web/vendor/katex/** from
serve/webfiles.py: whitelisted names and types, no backslash, colon, percent or
dot-dot, and the resolved path must stay inside the folder (also against a link
out of it). tools/web_i18n.py reads the English text out of the code, writes
en.json and checks every catalog for the same keys and {placeholders}; the
check runs once the catalogs exist.
36 lines
1.6 KiB
Python
36 lines
1.6 KiB
Python
"""Which files of serve/web the server hands out below /web/: the page's translations and the vendored KaTeX.
|
|
|
|
The flat files (app.js, app.css, ...) are served by serve/server.py itself. The two folders here hold more than one
|
|
level, so each has its own whitelist: a name pattern and the types it may have. Nothing outside these folders is ever
|
|
read, a name with a backslash, a colon or a percent sign is refused, and the resolved path must stay inside the folder.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from pathlib import Path
|
|
|
|
WEB = Path(__file__).resolve().parent / "web"
|
|
|
|
# /web/locales/<lang>.json e.g. de.json, pt-BR.json
|
|
LOCALE = re.compile(r"^/web/locales/(?P<name>[a-z]{2,3}(?:-[A-Z]{2})?\.json)$")
|
|
# /web/vendor/katex/dist/... : the script, the style sheet and the fonts only
|
|
VENDOR_TYPES = {".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".woff2": "font/woff2"}
|
|
VENDOR_PREFIX = "/web/vendor/katex/"
|
|
|
|
|
|
def subtree_file(path: str, web: Path = WEB):
|
|
"""(file, content type) for a /web/locales or /web/vendor path, or None when it is not served."""
|
|
if any(c in path for c in ("\\", ":", "%", "\0")) or ".." in path:
|
|
return None
|
|
m = LOCALE.match(path)
|
|
if m:
|
|
f = web / "locales" / m.group("name")
|
|
return (f, "application/json; charset=utf-8") if f.is_file() else None
|
|
if path.startswith(VENDOR_PREFIX):
|
|
vendor = (web / "vendor" / "katex").resolve()
|
|
f = (vendor / path[len(VENDOR_PREFIX):]).resolve()
|
|
ctype = VENDOR_TYPES.get(f.suffix)
|
|
if ctype and f.is_relative_to(vendor) and f.is_file():
|
|
return f, ctype
|
|
return None
|