An instance that can be somebody else's

A name, a tagline, a logo, a favicon and the launcher icons derived from it; the
Middle-earth strings as data; themes as token sets; and a stylesheet for what
none of that reaches. All four are on one page, in one settings group.

The snapshot is a Jinja global over a process-level cache, because render() has
no session and four render paths never reach it at all -- the sign-in page, the
error pages, the offline page and the SSE fragments. A context value would have
had to be threaded through every one and would still have missed those. It being
a global is also what lets mark() branch on an uploaded logo without any of its
six call sites learning about branding; the macro that renders the sidebar link
is called brandlink now, because a macro imported as `brand` shadows the global
for the whole template and took out every page at once.

Defaults in code and overrides in the database, as the prompt fragments do, with
one difference stated in the module: an empty fragment means off, an empty
flavour string means the shipped wording. And blanked rather than dropped --
settings_store.update merges, so an omitted key leaves what was stored last time
and "I typed the default back in" would store something different from "I changed
nothing".

A custom theme sets a handful of tokens and inherits the rest, and the
inheritance is a CSS fact: tokens.css matches [data-base="shire"] as well as
[data-theme="shire"], so a custom light theme lands on parchment rather than four
light colours on near-black. Values are validated on read rather than on save,
because a theme written straight into the settings table still has to produce a
stylesheet that parses -- a `}` in a value ends the rule and silently breaks
every rule after it. The soft variants are derived from the accent, or a changed
accent leaves focus rings in the old hue and reads as half-working.

/branding.css is a route, not an inline block: an external stylesheet has no HTML
context to escape from. The link carries a content hash, so a save is not left to
the browser's cache, and it is deliberately outside the service worker's precache
list, which is versioned by the release.

The instance name moved off /admin/general rather than being duplicated there.
An upgrade keeps it: the general row is read as a seed exactly while the branding
row has never mentioned the name, which is `key in row` and not `row[key] is
truthy` -- the two read alike would resurrect the old name underneath a cleared
one.

The theme list stops being a hard-coded pair in five places. Every failure mode
in that area is silent, so it is driven under a DOM stub as well as tested.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jaroslav Beneš
2026-08-06 15:42:25 +02:00
parent 46066150d9
commit 78e5717f77
67 changed files with 1887 additions and 117 deletions
+506
View File
@@ -0,0 +1,506 @@
"""What this installation is called, and what it looks like.
An instance can be somebody else's. That means four separate things, and they
are separate because they fail differently:
- an **identity** — a name, a tagline, a logo, a favicon, the icons a launcher
shows;
- **flavour text** — the Middle-earth lines, which live in the artwork, the
empty states, the loading lines and the error pages and nowhere else (see the
flavour rule in CLAUDE.md), and which somebody rebranding needs to be able to
replace without editing templates;
- **themes**, which are token sets rather than stylesheets, because the
invariant that no component hard-codes a colour is what makes a third one
compose at all;
- **arbitrary CSS**, for the things the first three do not reach.
## Defaults in code, overrides in the database
The prompt-fragment rule, applied again and for the same reason: text equal to
its default is never stored, so a later release improving a default still
reaches an instance whose administrator once pressed Save. `stored_only` is what
enforces it, and every save goes through it.
## Why a snapshot, and why a Jinja global
`web/templating.py:render()` has no database session, and the login page, the
error pages, the offline page and the SSE path do not go through it at all. A
context value would therefore have to be threaded through every one of those,
and the ones that bypass `render()` could not be reached at all.
So this is a **process-level cache** behind a lazy proxy registered as a Jinja
global. One query per process, and after every save; every render path gets it
including the ones that never see a `Request`. `forget()` is called by the admin
page and by nothing else.
The cost of being a cache is stated rather than discovered: with several
workers, a save in one is not seen by the others until each next reads. That is
already true of this application for other reasons -- see the "one worker" note
in PLAN.md -- and this does not make it worse.
"""
from __future__ import annotations
import hashlib
import logging
import re
from dataclasses import dataclass, field
from typing import Any
from lembas.services import settings_store
log = logging.getLogger(__name__)
BRANDING = settings_store.BRANDING
DEFAULT_NAME = "LLeMbas"
# --- Flavour ------------------------------------------------------------------
# Every Middle-earth string in the interface, with its current wording as the
# default. Keyed rather than positional so a template names what it wants, and
# a key nobody has overridden costs nothing to store.
#
# The label is what the admin page calls the field; the hint says where it is
# seen, because a string with no context is one nobody can safely rewrite.
FLAVOUR: dict[str, tuple[str, str, str]] = {
"login_tagline": (
"Under the sign-in mark",
"The one line on the sign-in page, beneath the name.",
"Waybread for the long road of thought.",
),
"chat_empty": (
"Empty chat",
"Above the composer on a chat with nothing in it yet.",
"Speak, friend, and enter.",
),
"offline_title": (
"Offline heading",
"The page the service worker shows when the server cannot be reached.",
"No road from here",
),
"offline_line": (
"Offline line",
"Beneath that heading. The sentence below it is functional and is not "
"editable here.",
"The Road goes ever on and on — but not without a connection.",
),
"error_403": (
"403 — not yours",
"Shown on a page somebody is not allowed to see.",
"Speak, friend, and enter. This door is not yours to open.",
),
"error_404": (
"404 — not found",
"Shown on a page that does not exist.",
"Not all those who wander are lost. This page, however, is.",
),
"error_500": (
"500 — something broke",
"Shown when something went wrong on the server.",
"The Road goes ever on, but this stretch of it has washed out.",
),
"theme_moria": (
"Dark theme name",
"What the built-in dark theme is called, in the settings screen and in "
"the /theme command.",
"Moria",
),
"theme_shire": (
"Light theme name",
"What the built-in light theme is called.",
"Shire",
),
}
# --- Themes -------------------------------------------------------------------
# The two built-ins. `css` is empty for both: their tokens are declared in
# tokens.css, which is the one place colours live, and duplicating them here so
# that a custom theme could "inherit" would be exactly the second copy that
# rule exists to prevent. A custom theme inherits by naming a base instead --
# see `theme_css` below.
SCHEME_DARK = "dark"
SCHEME_LIGHT = "light"
BUILT_IN = (
("moria", SCHEME_DARK, "#101317"),
("shire", SCHEME_LIGHT, "#F6F1E4"),
)
# What a custom theme may set. A curated handful rather than every token a
# theme block declares: sixty colour pickers is not a feature, and everything
# left out inherits from the base, which is what makes a theme that changes
# four things four things long.
#
# `--accent-soft`, `--leaf-soft` and `--danger-soft` are deliberately absent and
# are derived instead: they are the same colour at 14% and an administrator who
# changed the accent without them would get focus rings in the old hue, which
# looks like the setting half-working.
THEME_TOKENS: tuple[tuple[str, str], ...] = (
("bg", "Page background"),
("bg-sunken", "Behind the page — the sidebar and panel gutters"),
("surface", "Cards, menus and the composer"),
("surface-raised", "Anything sitting on a surface"),
("surface-hover", "A surface under the pointer"),
("border", "Ordinary borders"),
("border-strong", "Borders that have to be seen"),
("ink", "Body text"),
("ink-muted", "Secondary text"),
("ink-faint", "Hints and timestamps"),
("accent", "Links, focus and interactive accents"),
("accent-hover", "The accent under the pointer"),
("accent-ink", "Text on top of the accent"),
("leaf", "The brand accent and the assistant's mark"),
("danger", "Errors and destructive actions"),
("success", "Confirmations and unread dots"),
("warning", "Warnings"),
("bubble-user", "Behind your own messages"),
("code-bg", "Behind code"),
)
THEME_TOKEN_NAMES = tuple(name for name, _ in THEME_TOKENS)
# A colour, and nothing else. Values reach a stylesheet, so a `}` in one would
# end the rule and silently break every rule after it -- and `url(…)` in a
# colour slot is a request to a third party from every page. Anything that does
# not match is dropped rather than corrected: a colour nobody can read is a
# setting that did not take, and that is visible, while a mangled one is not.
_COLOUR = re.compile(
r"^(#[0-9a-fA-F]{3,8}"
r"|rgba?\([0-9,.\s%/]+\)"
r"|hsla?\([0-9,.\s%/deg]+\)"
r"|[a-z]{3,20})$"
)
# An id that can be an attribute value and a CSS selector without quoting.
_THEME_ID = re.compile(r"^[a-z][a-z0-9-]{0,23}$")
@dataclass(frozen=True)
class Theme:
"""One theme somebody can choose."""
id: str
label: str
scheme: str
# Which built-in it starts from. A custom theme sets a handful of tokens and
# inherits the rest, and that inheritance is a CSS fact: tokens.css matches
# `[data-base="shire"]` as well as `[data-theme="shire"]`, so a custom light
# theme carries `data-base="shire"` and gets the whole parchment palette
# underneath its own four colours. Without it a light custom theme would be
# four light colours on Moria's near-black surfaces.
base: str = "moria"
tokens: dict[str, str] = field(default_factory=dict)
colour: str = ""
built_in: bool = False
@dataclass(frozen=True)
class Branding:
"""Everything a page needs to know about whose instance this is."""
name: str = DEFAULT_NAME
tagline: str = ""
logo_path: str = ""
favicon_path: str = ""
icon_paths: dict[str, str] = field(default_factory=dict)
custom_css: str = ""
text: dict[str, str] = field(default_factory=dict)
themes: tuple[Theme, ...] = ()
@property
def theme_ids(self) -> tuple[str, ...]:
return tuple(theme.id for theme in self.themes)
@property
def theme_list(self) -> str:
"""`id:base` pairs, space separated, for the `data-themes` attribute.
One attribute rather than a JSON island, because two things in the
browser need it — `/theme` validating a name, and `applyTheme` setting
`data-base` alongside `data-theme` — and both want a list they can split
rather than a document they have to parse.
"""
return " ".join(f"{theme.id}:{theme.base}" for theme in self.themes)
def theme(self, theme_id: str) -> Theme:
for theme in self.themes:
if theme.id == theme_id:
return theme
return self.themes[0]
@property
def revision(self) -> str:
"""A short hash of everything `/branding.css` is built from.
It goes in that link's query string, so the URL changes exactly when the
stylesheet does. Without it the browser's cache is the thing deciding
when a rebrand takes effect, which is the failure this codebase keeps
cataloguing: a save that looks like it worked and did nothing.
"""
material = repr((self.custom_css, [(t.id, t.base, sorted(t.tokens.items())) for t in
self.themes]))
return hashlib.sha256(material.encode("utf-8")).hexdigest()[:12]
# --- Reading ------------------------------------------------------------------
def defaults() -> dict[str, Any]:
return {
"instance_name": "",
"tagline": "",
"logo_path": "",
"favicon_path": "",
# Derived from the logo at save time, so a launcher gets real PNGs at
# the sizes it asks for rather than one image the browser is told to
# scale. Empty means the shipped artwork is used.
"icon_paths": {},
"custom_css": "",
"themes": [],
**{f"text_{key}": "" for key in FLAVOUR},
}
def _theme_from(raw: dict[str, Any]) -> Theme | None:
"""One stored custom theme, or None if it is not usable.
Every field is validated on read rather than trusted from the row: a theme
stored by an earlier version, or written straight into the settings table,
still has to produce a stylesheet that parses.
"""
theme_id = str(raw.get("id") or "").strip().lower()
if not _THEME_ID.match(theme_id) or theme_id in {name for name, _, _ in BUILT_IN}:
return None
base = str(raw.get("base") or "moria")
if base not in {name for name, _, _ in BUILT_IN}:
base = "moria"
tokens = {
name: value
for name, value in (raw.get("tokens") or {}).items()
if name in THEME_TOKEN_NAMES and _COLOUR.match(str(value).strip())
}
scheme = next(s for name, s, _ in BUILT_IN if name == base)
return Theme(
id=theme_id,
label=str(raw.get("label") or theme_id).strip()[:60] or theme_id,
scheme=scheme,
base=base,
tokens=tokens,
colour=tokens.get("bg", ""),
)
def build(values: dict[str, Any]) -> Branding:
"""A snapshot from a settings group. Pure, so it can be tested without a
database and used by the preview on the admin page."""
text = {
key: str(values.get(f"text_{key}") or "").strip() or default
for key, (_, _, default) in FLAVOUR.items()
}
themes = [
Theme(
id=theme_id,
label=text[f"theme_{theme_id}"],
scheme=scheme,
base=theme_id,
colour=colour,
built_in=True,
)
for theme_id, scheme, colour in BUILT_IN
]
seen = {theme.id for theme in themes}
for raw in values.get("themes") or []:
if not isinstance(raw, dict):
continue
theme = _theme_from(raw)
if theme is not None and theme.id not in seen:
seen.add(theme.id)
themes.append(theme)
return Branding(
name=str(values.get("instance_name") or "").strip() or DEFAULT_NAME,
tagline=str(values.get("tagline") or "").strip(),
logo_path=str(values.get("logo_path") or ""),
favicon_path=str(values.get("favicon_path") or ""),
icon_paths=dict(values.get("icon_paths") or {}),
custom_css=str(values.get("custom_css") or ""),
text=text,
themes=tuple(themes),
)
_CACHE: Branding | None = None
def snapshot() -> Branding:
"""The current branding, from a process-level cache.
Never raises. An error page that cannot render because branding could not be
read is a failure that hides the failure it was about to report, so a
database that is not there yet answers with the defaults.
"""
global _CACHE
if _CACHE is not None:
return _CACHE
try:
from lembas.db.session import session_scope
with session_scope() as db:
_CACHE = _read(db)
except Exception: # noqa: BLE001 - defaults are a usable answer, an exception is not
log.debug("could not read branding; using defaults", exc_info=True)
return build(defaults())
return _CACHE
def _read(db) -> Branding:
"""The two groups this is assembled from.
`instance_name` lived in the general group before there was a branding one,
and an upgrade must not quietly rename somebody's instance back to LLeMbas.
So the stored general value is a **seed**, and the test for it is whether the
branding row has said anything about the name at all -- `key in row`, not
`row[key] is truthy`. An empty stored name is somebody clearing the box,
which has to mean the default; a *missing* one is an instance that has never
seen this page. Reading the two the same way would resurrect the old name
underneath a cleared one, which is the failure a cleared reasoning effort
already documents.
That is why this reads the raw row rather than `get_group`, which fills in
defaults and so cannot tell absent from empty.
"""
from lembas.db.models import Setting
values = settings_store.get_group(db, BRANDING)
row = db.get(Setting, BRANDING)
said = isinstance(row, Setting) and isinstance(row.value, dict) and "instance_name" in row.value
if not said:
legacy = settings_store.get_group(db, settings_store.GENERAL).get("instance_name")
if legacy:
values = {**values, "instance_name": legacy}
return build(values)
def forget() -> None:
"""Drop the cache. Called by the admin page's save, and by tests."""
global _CACHE
_CACHE = None
def for_db(db) -> Branding:
"""The snapshot, seeded from a session the caller already has open.
Same value as `snapshot()`; this only spares the extra session on the first
render after a restart, where one is already in hand.
"""
global _CACHE
if _CACHE is None:
_CACHE = _read(db)
return _CACHE
# --- Writing ------------------------------------------------------------------
def stored_only(values: dict[str, Any]) -> dict[str, Any]:
"""Blank anything equal to its shipped wording, so it is not an override.
The prompt-fragment rule, and the reason it is a **blank rather than a
dropped key**: `settings_store.update` merges, so omitting a key leaves
whatever was stored last time. Dropping one would make "I typed the default
back in" and "I changed nothing" store different things, and make clearing a
box do nothing at all.
Empty is the not-overridden marker because `build` reads `stored or
default`. That is deliberately *not* the fragment convention, where an empty
override means the fragment is off: a fragment being off is a state somebody
wants, and a heading with no words is not.
"""
return {
key: ("" if _is_shipped(key, value) else value) for key, value in values.items()
}
def _is_shipped(key: str, value: Any) -> bool:
if key.startswith("text_"):
entry = FLAVOUR.get(key[len("text_") :])
return entry is not None and value == entry[2]
return value == defaults().get(key)
# --- The stylesheet -----------------------------------------------------------
def _soft(colour: str, alpha: str = "0.14") -> str:
"""A colour at low opacity, for the `*-soft` tokens.
Derived rather than asked for: they are the same colour at 14%, and an
administrator who set an accent without them would get focus rings and
selected states in the old hue -- which reads as the setting half-working
rather than as a field they missed.
Only hex is understood. Anything else answers "" and the base theme's own
soft value stands, which is the right failure: a wrong soft colour is worse
than an unchanged one.
"""
value = colour.strip()
if not value.startswith("#"):
return ""
digits = value[1:]
if len(digits) == 3:
digits = "".join(c * 2 for c in digits)
if len(digits) not in (6, 8):
return ""
try:
r, g, b = (int(digits[i : i + 2], 16) for i in (0, 2, 4))
except ValueError:
return ""
return f"rgba({r}, {g}, {b}, {alpha})"
def theme_css(theme: Theme) -> str:
"""One custom theme as a rule.
Two selectors' worth of work in one: the block sets what was chosen, and the
`data-base` attribute on <html> is what brings the rest of the base theme's
palette with it. Written here and served from `/branding.css`, which loads
after `tokens.css`, so these win on order at equal specificity.
"""
if not theme.tokens:
return ""
lines = [f" --{name}: {value};" for name, value in theme.tokens.items()]
for name, alpha in (("accent", "0.14"), ("leaf", "0.14"), ("danger", "0.14")):
soft = _soft(theme.tokens.get(name, ""), alpha)
if soft:
lines.append(f" --{name}-soft: {soft};")
return f':root[data-theme="{theme.id}"] {{\n' + "\n".join(lines) + "\n}\n"
def stylesheet(brand: Branding) -> str:
"""Everything `/branding.css` serves.
A route rather than an inline `<style>`, and that is a security property as
much as a caching one: an external stylesheet has no HTML context to escape
from, so an administrator's CSS cannot become markup however it is written.
Inline, the same text would be one `</style>` away from being a script.
"""
parts = [
"/* Generated by LLeMbas from the customization settings. */",
*(theme_css(theme) for theme in brand.themes if not theme.built_in),
]
if brand.custom_css.strip():
parts += ["/* Custom CSS. */", brand.custom_css.strip(), ""]
return "\n".join(part for part in parts if part)
__all__ = [
"BRANDING",
"BUILT_IN",
"DEFAULT_NAME",
"FLAVOUR",
"THEME_TOKENS",
"THEME_TOKEN_NAMES",
"Branding",
"Theme",
"build",
"defaults",
"for_db",
"forget",
"snapshot",
"stored_only",
"stylesheet",
"theme_css",
]
+2 -2
View File
@@ -39,7 +39,7 @@ from sqlalchemy import select
from sqlalchemy.orm import Session as DBSession
from lembas.db.models import KIND_TASK, User
from lembas.services import prompts, settings_store
from lembas.services import branding, prompts, settings_store
from lembas.services.library import memories as memories_service
from lembas.services.library import skills as skills_service
from lembas.services.schedule import clock
@@ -192,7 +192,7 @@ def context_variables(
# nobody has chosen one, which drops the line rather than printing the
# server's zone as though it were a decision.
"timezone": clock.name_for(user),
"instance_name": str(settings_store.get(db, "instance_name") or "LLeMbas"),
"instance_name": branding.for_db(db).name,
"user_name": (user.name or "") if user is not None else "",
"model_name": "",
# What this request will actually allow, so the model is not told a
+20 -1
View File
@@ -32,6 +32,7 @@ AGENTS = "agents"
IMAGES = "images"
SCHEDULES = "schedules"
SUBAGENTS = "subagents"
BRANDING = "branding"
def _general_defaults() -> dict[str, Any]:
@@ -40,7 +41,12 @@ def _general_defaults() -> dict[str, Any]:
# When on, new accounts land in the `pending` role and cannot sign in
# until an administrator approves them. Reserved for the users pass.
"require_approval": False,
"instance_name": "LLeMbas",
# `instance_name` used to be here and now lives in the BRANDING group,
# with the rest of what makes an instance somebody else's. The key is
# deliberately not listed any more: an upgraded instance still has it in
# its stored general row, and `branding.snapshot` reads that once as a
# seed. Leaving a default here as well would give the name two sources
# and no answer to which one wins.
# Applied to every chat that has no model or chat prompt of its
# own. See services.chat.effective_system_prompt.
"system_prompt": "",
@@ -382,9 +388,22 @@ _DEFAULTS: dict[str, Any] = {
IMAGES: _images_defaults,
SCHEDULES: _schedules_defaults,
SUBAGENTS: _subagents_defaults,
# Whose instance this is. The defaults live in `services/branding.py`
# beside the code that reads them, because every one of them is paired with
# a label and a hint for the admin page and splitting the three across two
# modules is how one of them goes stale.
BRANDING: lambda: _branding_defaults(),
}
def _branding_defaults() -> dict[str, Any]:
"""Imported inside the call: `services/branding.py` imports this module for
the group key, so a top-level import back is a cycle."""
from lembas.services import branding
return branding.defaults()
def defaults(key: str = GENERAL) -> dict[str, Any]:
"""The built-in values for a settings group, with nothing stored applied."""
factory = _DEFAULTS.get(key)
+145
View File
@@ -98,6 +98,151 @@ def delete_model_image(filename: str) -> None:
path.unlink(missing_ok=True)
# --- Branding assets -----------------------------------------------------------
# The logo, the favicon and the launcher icons derived from them. A separate
# directory from the model avatars because the *route* differs: these are served
# unauthenticated, since the sign-in page and the web app manifest both need
# them and neither has a session to check.
#
# SVG stays excluded, and this is where somebody will most want it. Every entry
# in ALLOWED_TYPES is a format that cannot execute in an `<img>`; an SVG can, and
# these are the one set of files served to somebody who is not signed in.
# What a launcher asks for, and what `<link rel="apple-touch-icon">` wants.
# Generated from the uploaded logo rather than asked for separately: an
# administrator who has a logo has said everything they need to say, and five
# upload fields to fill in by hand is how three of them end up wrong.
ICON_SIZES: dict[str, int] = {
"icon-192": 192,
"icon-512": 512,
"apple-touch": 180,
"favicon": 32,
}
# The maskable icon has to survive being cropped to a circle, so the artwork
# sits inside the safe zone with the background showing around it. 80% is the
# standard's own guidance and is what the shipped icon already uses.
MASKABLE_SIZE = 512
MASKABLE_INSET = 0.8
def branding_dir() -> Path:
path = settings.uploads_dir / "branding"
path.mkdir(parents=True, exist_ok=True)
return path
def save_branding_image(payload: bytes, declared_type: str) -> str:
"""Validate and store a logo or favicon. Returns the stored filename."""
if not payload:
raise UploadError("The file was empty.")
if len(payload) > MAX_BYTES:
raise UploadError(f"Images must be under {MAX_BYTES // (1024 * 1024)} MB.")
actual = _detect(payload)
if actual is None:
raise UploadError(
"That does not look like a PNG, JPEG, WEBP or GIF image. "
"SVG is deliberately not accepted: these files are served to people "
"who are not signed in, and an SVG can carry a script."
)
if declared_type and declared_type.split(";")[0].strip() != actual:
log.info("upload declared %s but is actually %s", declared_type, actual)
filename = f"{secrets.token_hex(16)}{ALLOWED_TYPES[actual]}"
(branding_dir() / filename).write_bytes(payload)
return filename
def derive_icons(payload: bytes) -> dict[str, str]:
"""Launcher icons from an uploaded logo, at the sizes a browser asks for.
Best-effort: an instance whose logo cannot be resized keeps the shipped
icons, which is a worse launcher tile and not a broken install. Pillow is
already a dependency (`services/files.py` uses it for attachments), so this
adds nothing to install.
Every output is PNG regardless of what came in, because that is what a
manifest icon has to be, and RGBA so a logo with a transparent background
stays one.
"""
try:
import io
from PIL import Image
except Exception: # noqa: BLE001 - Pillow missing is not a failed save
log.info("Pillow unavailable; keeping the shipped launcher icons")
return {}
try:
with Image.open(io.BytesIO(payload)) as source:
source.load()
image = source.convert("RGBA")
except Exception: # noqa: BLE001 - a file we stored but cannot read
log.info("could not read the uploaded logo for icons", exc_info=True)
return {}
paths: dict[str, str] = {}
for name, size in ICON_SIZES.items():
paths[name] = _write_png(_fitted(image, size, size), f"{name}")
# Cropped to a circle on Android, so the artwork is inset and the corners
# are filled rather than transparent -- a transparent maskable icon is
# rendered as a black square by some launchers.
canvas = _new_canvas(MASKABLE_SIZE, image)
inner = _fitted(image, int(MASKABLE_SIZE * MASKABLE_INSET), int(MASKABLE_SIZE * MASKABLE_INSET))
offset = (MASKABLE_SIZE - inner.width) // 2, (MASKABLE_SIZE - inner.height) // 2
canvas.alpha_composite(inner, offset)
paths["maskable"] = _write_png(canvas, "maskable")
return paths
def _fitted(image, width: int, height: int):
from PIL import Image
return image.copy().resize((width, height), Image.LANCZOS)
def _new_canvas(size: int, source):
"""A square the colour of the logo's top-left pixel, or transparent.
Sampling one pixel rather than averaging: a logo on a flat background gets
that background, which is what the inset needs, and a logo on a transparent
one gets transparency, which the composite below then fills.
"""
from PIL import Image
corner = source.getpixel((0, 0))
fill = corner if isinstance(corner, tuple) and len(corner) == 4 else (0, 0, 0, 0)
return Image.new("RGBA", (size, size), fill)
def _write_png(image, label: str) -> str:
import io
buffer = io.BytesIO()
image.save(buffer, format="PNG", optimize=True)
filename = f"{label}-{secrets.token_hex(8)}.png"
(branding_dir() / filename).write_bytes(buffer.getvalue())
return filename
def branding_image_path(filename: str) -> Path | None:
"""Resolve a stored branding filename, refusing anything outside the dir."""
if not filename or "/" in filename or "\\" in filename or filename.startswith("."):
return None
path = (branding_dir() / filename).resolve()
try:
path.relative_to(branding_dir().resolve())
except ValueError:
return None
return path if path.is_file() else None
def delete_branding_image(filename: str) -> None:
path = branding_image_path(filename)
if path is not None:
path.unlink(missing_ok=True)
def media_type_for(filename: str) -> str:
suffix = Path(filename).suffix.lower()
for media_type, extension in ALLOWED_TYPES.items():