Marca: the admin owns the look, logo included

The brand colours were two identical `:root` blocks — one in the theme, one in
the members area's stylesheet — with a comment in the second reading *"If the
brand colours change, change them in both."* There was no logo anywhere, no
favicon in either `<head>`, and `params.defaultImage` was the empty string with
a comment saying it was waiting for one. Every one of those was a change only
somebody with the repository could make.

`brand.FACTORY` is the single source of truth for the palette now, and
`test_brand.py` parses both stylesheets and fails the build if either drifts
from it. That is what retires the comment: not by merging the two files — they
are served by different things and each has to stand alone — but by making a
divergence fail a test instead of going unnoticed for a month.

**Gestión → Marca**, admins only, saves to two places in one submit, because
the two halves of the site cannot read the same store: SQLite for the members
area, which must render when the git server is down, and `data/brand.yaml` plus
`static/brand/` in the content repository for the public site, which is files
on disk. SQLite is written first and the commits follow — if Gitea is
unreachable the change still takes effect here, `published_at` stays NULL, and
the screen offers to try the publish again. The other order would let a git
outage block a change that does not need git.

The easy half is six colour pickers, each with the name of what it changes, and
a live preview of the real chrome. The three brand shades are worked out from
the brand colour in HLS, so one picked colour gives a coherent set rather than
one red button on an orange background; scaling RGB towards white would have
washed the hue out. A WCAG contrast warning names any pair that will be hard to
read, with its ratio, and saves it anyway: an admin may have a reason, and what
this prevents is shipping an unreadable site without once being told.

The advanced half, behind a fold, is every token as a text field and a free CSS
box appended last so it wins. **The Marca screen deliberately does not load the
generated stylesheet** — every other page does — which is what keeps *Restaurar
lo de fábrica* reachable after somebody writes `* { display: none }` into that
box, and the reason the colours an admin picks do not show on the page where
they pick them. The preview block is where they do.

Only differences from the factory are stored, so a token added later arrives
with its default already in place for every existing install. Both halves serve
a generated stylesheet rather than an inline `<style>`, because the CSP has no
'unsafe-inline' and an inline block would simply not apply.

The logo also fills the gap phase I left: it is the share-card fallback and the
`Organization` logo, ahead of `defaultImage`, and the home page carries
`og:image` for the first time — the front page of the site was the last place
that should share as a bare link.

No SVG and no ICO: the logo takes PNG, JPG or WebP and the favicon PNG, both
identified from their bytes by the sniffer the wall already uses. An SVG is XML
that can carry script and would be served from our own origin.

A new table, so `CREATE TABLE IF NOT EXISTS` is enough and no migration is
involved. `FakeRepo` moved from test_content.py into conftest.py, since two
features commit to the content repository now. Verified by building with Hugo
0.135.0 and the pipeline's flags both ways: with a brand.yaml the second
stylesheet, the favicon and the logo appear, and without one the output is
byte-for-byte identical to the build before any of this existed.

545 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
This commit is contained in:
admin 2026-10-03 20:25:52 +00:00
parent 91aa0c9a9e
commit 7e70004e7b
No known key found for this signature in database
18 changed files with 1540 additions and 64 deletions

View File

@ -94,10 +94,11 @@ def create_app(overrides: dict | None = None) -> Flask:
# restart, which is a confusing way to find out the variable is unset.
raise RuntimeError("BOARD_SECRET_KEY is required (generate one with `openssl rand -hex 32`).")
from . import (auth, board, content, events, home, members, messages,
profiles, submissions, uploads)
from . import (auth, board, brand, content, events, home, members,
messages, profiles, submissions, uploads)
app.register_blueprint(auth.bp, url_prefix=URL_PREFIX)
app.register_blueprint(home.bp, url_prefix=URL_PREFIX)
app.register_blueprint(brand.bp, url_prefix=URL_PREFIX)
app.register_blueprint(submissions.bp, url_prefix=URL_PREFIX)
app.register_blueprint(events.bp, url_prefix=URL_PREFIX)
app.register_blueprint(members.bp, url_prefix=URL_PREFIX)
@ -122,6 +123,13 @@ def create_app(overrides: dict | None = None) -> Flask:
def _year():
return {"current_year": datetime.now(timezone.utc).year}
@app.context_processor
def _brand():
# Not lazy, unlike the badges below: base.html draws the stylesheet
# link, the logo and the favicon on every page, so there is no render
# that would save the query by deferring it.
return {"brand": brand.state()}
@app.context_processor
def _badges():
# Lazily, as functions: base.html is rendered for signed-out pages and

613
apps/board/brand.py Normal file
View File

@ -0,0 +1,613 @@
"""The look of both halves of the site, owned by the admin rather than by me.
Until this existed, the brand colours were two identical `:root` blocks — one in
`themes/vienalatina/assets/css/main.css`, one in `apps/board/static/board.css` —
with a comment in the second saying *"If the brand colours change, change them
in both."* There was no logo anywhere and no favicon in either `<head>`. Every
one of those is a change only somebody with the repository could make.
**The dictionary below is now the single source of truth for the palette**, and
`apps/board/tests/test_brand.py` parses both stylesheets and fails if either
drifts from it. That is what retires the comment: not by merging the two files —
they are served by different things and each has to stand on its own — but by
making a divergence fail the build instead of going unnoticed for a month.
### The two destinations
One form, saved to two places, because the two halves cannot read the same
store:
* **SQLite**, for the members area, which must render correctly when the git
server is unreachable — the same rule the private calendar follows.
* **Git** (`data/brand.yaml` and `static/brand/…`), for the public site, which
is files on disk built by Hugo and has no database to read.
SQLite is written first and the commits follow. If Gitea is down the change
still takes effect here, the row keeps `published_at` NULL, and the screen says
so with a button to try the publish again. The other order would let a git
outage block a change that does not need git.
### Why the custom CSS is a file and not a `<style>`
The Content-Security-Policy in `app.py` has no `'unsafe-inline'`, so an inline
style block is not an error anybody sees — the browser ignores it and the colours
simply do not apply. Both halves therefore serve a generated stylesheet:
`/comunidad/marca.css` here, a fingerprinted `resources.FromString` on the
public site.
"""
from __future__ import annotations
import colorsys
import json
import re
from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
render_template, request, send_from_directory, url_for)
from . import gitea, uploads
from .db import get_db
from .security import admin_required
bp = Blueprint("brand", __name__)
# Every token, with the value it has had since the site was built. Copied from
# the two `:root` blocks, which the test above holds to this.
FACTORY = {
"brand": "#c0391c",
"brand-dark": "#9a2a0f",
"brand-soft": "#fbe2db",
"brand-softer": "#fdf1ed",
"bg": "#f8f3ef",
"surface": "#ffffff",
"surface-soft": "#f2ebe6",
"border": "#c2a89f",
"border-light": "#e0cec8",
"text": "#1a0d09",
"muted": "#5c3d37",
"subtle": "#9a7870",
"danger": "#a11b1b",
}
# The six on the easy form, in the order they are drawn, with what each one is
# for in words an admin can act on. Six rather than thirteen because the other
# seven are shades of these, and a form of thirteen colour pickers is a form
# nobody finishes.
SIMPLE = (
("brand", "Color principal", "Botones, enlaces y la barra de arriba."),
("bg", "Fondo", "El color de la página detrás de todo."),
("surface", "Tarjetas", "El fondo de las tarjetas y los formularios."),
("text", "Texto", "El color de las letras."),
("muted", "Texto secundario", "Fechas, autores y notas al pie."),
("border", "Líneas", "Bordes y separadores."),
)
# Shades worked out from `brand` when they are not given explicitly. The factory
# palette has exactly this relationship, so an admin who picks one colour gets a
# coherent set rather than one red button on an orange background.
#
# Each entry is the lightness the shade gets: a multiplier of the brand's own
# for the dark one, an absolute value for the two tints. Hue and saturation are
# kept, which is what makes them read as the same colour.
DERIVED = {
"brand-dark": ("scale", 0.75),
"brand-soft": ("set", 0.92),
"brand-softer": ("set", 0.96),
}
HEX = re.compile(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
# The free CSS box takes anything but these. `<` and `>` cannot appear in valid
# CSS outside a string, and they are the two characters that could end the
# stylesheet context in a consumer that mishandles it. Everything else is left
# alone on purpose: the point of the box is that an admin who knows CSS is not
# second-guessed.
CSS_FORBIDDEN = ("<", ">")
CSS_MAX = 20_000
LOGO_EXTENSIONS = ("png", "jpg", "webp")
FAVICON_EXTENSIONS = ("png",)
# Where the two pictures land in the content repository. Stable paths, so saving
# twice replaces the file rather than leaving the old one behind.
REPO_FOLDER = "static/brand"
DATA_FILE = "data/brand.yaml"
# --- colour arithmetic, all of it from the standard library ----------------
def _rgb(value: str) -> tuple[float, float, float]:
text = value.lstrip("#")
if len(text) == 3:
text = "".join(c * 2 for c in text)
return tuple(int(text[i:i + 2], 16) / 255 for i in (0, 2, 4))
def _hex(rgb: tuple[float, float, float]) -> str:
return "#" + "".join(f"{round(max(0.0, min(1.0, c)) * 255):02x}" for c in rgb)
def shade(value: str, token: str) -> str:
"""One of the three brand shades, from the brand colour.
In HLS rather than by multiplying the channels: scaling RGB towards white
washes the hue out, and the result of mixing #c0391c with white is pink
rather than the warm tint the design uses.
"""
how, amount = DERIVED[token]
hue, lightness, saturation = colorsys.rgb_to_hls(*_rgb(value))
lightness = lightness * amount if how == "scale" else amount
return _hex(colorsys.hls_to_rgb(hue, lightness, saturation))
def _luminance(value: str) -> float:
"""WCAG 2.1 relative luminance."""
def channel(c: float) -> float:
return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
red, green, blue = (channel(c) for c in _rgb(value))
return 0.2126 * red + 0.7152 * green + 0.0722 * blue
def contrast(a: str, b: str) -> float:
"""The WCAG contrast ratio between two colours, 1.0 to 21.0."""
first, second = _luminance(a), _luminance(b)
lighter, darker = max(first, second), min(first, second)
return (lighter + 0.05) / (darker + 0.05)
# What has to be readable, and the ratio WCAG asks for. Body text is 4.5:1;
# 3:1 is the rule for large text and for the edge of a control, which is what a
# button in the brand colour is.
PAIRS = (
("text", "bg", 4.5, "el texto sobre el fondo"),
("text", "surface", 4.5, "el texto sobre las tarjetas"),
("muted", "surface", 4.5, "el texto secundario sobre las tarjetas"),
)
def warnings(tokens: dict) -> list[str]:
"""Pairs that are hard to read, named with their ratio.
A warning and not a refusal. An admin may have a reason, and a form that
argues is a form people work around; what this prevents is somebody
shipping an unreadable site without once being told.
"""
notes = []
for first, second, needed, description in PAIRS:
ratio = contrast(tokens[first], tokens[second])
if ratio < needed:
notes.append(
f"Poco contraste en {description}: {ratio:.1f}:1, y hacen falta "
f"{needed}:1. Se guarda igual, pero costará leerlo."
)
white = contrast("#ffffff", tokens["brand"])
if white < 3.0:
notes.append(
f"El texto blanco sobre el color principal queda en {white:.1f}:1 "
"(hacen falta 3:1). Los botones costarán de leer."
)
return notes
# --- the stored row --------------------------------------------------------
def _row():
return get_db().execute("SELECT * FROM brand WHERE id = 1").fetchone()
def resolve(stored: dict) -> dict:
"""Every token's value, given what has been stored.
Only differences from the factory are stored, which has two consequences
worth the arrangement: a token added here later arrives with its default
already in place for every existing install, and an admin who has changed
one colour has one row of JSON rather than a snapshot of thirteen.
The three shades are derived from `brand` **only when a brand colour has
been stored**. Without one the factory hexes are used verbatim, so saving
nothing cannot quietly shift the palette by a rounding error.
"""
tokens = dict(FACTORY)
tokens.update({k: v for k, v in stored.items() if k in FACTORY and v})
if stored.get("brand"):
for token in DERIVED:
if not stored.get(token):
tokens[token] = shade(stored["brand"], token)
return tokens
def current() -> dict:
"""What both the form and the stylesheet read. Works with no row at all."""
row = _row()
try:
stored = json.loads(row["tokens_json"]) if row else {}
except (TypeError, ValueError):
# A row we cannot parse must not take the site down. Factory colours
# and a line in the log is the right failure here.
current_app.logger.warning("brand.tokens_json is not readable; using factory")
stored = {}
if not isinstance(stored, dict):
stored = {}
return {
"stored": stored,
"tokens": resolve(stored),
"custom_css": (row["custom_css"] if row else "") or "",
"logo_name": row["logo_name"] if row else None,
"favicon_name": row["favicon_name"] if row else None,
"updated_at": row["updated_at"] if row else None,
"published_at": row["published_at"] if row else None,
"stamp": _stamp(row["updated_at"] if row else None),
"customised": bool(stored or (row and (row["custom_css"] or row["logo_name"]
or row["favicon_name"]))),
}
def _blank() -> dict:
"""The factory look, as `current()` would describe it."""
return {"stored": {}, "tokens": dict(FACTORY), "custom_css": "",
"logo_name": None, "favicon_name": None, "updated_at": None,
"published_at": None, "stamp": "0", "customised": False}
def state() -> dict:
"""`current()`, once per request, and never raising.
`base.html` asks for this on every page, the error pages included — and on a
500 the thing that broke may well be the database. A page in the factory
colours is still a page; a second traceback inside the error handler is not.
"""
if "brand_state" not in g:
try:
g.brand_state = current()
except Exception: # pragma: no cover - defensive
current_app.logger.warning("brand unreadable, using factory", exc_info=True)
g.brand_state = _blank()
return g.brand_state
def _stamp(updated_at: str | None) -> str:
"""A cache-buster safe to put in a query string.
`updated_at` is SQLite's `datetime('now')` — spaces and colons — and both
halves of the site paste this into a URL, so the digits alone are what
travels.
"""
return re.sub(r"\D", "", updated_at or "") or "0"
def stylesheet(state: dict | None = None) -> str:
"""The `:root` overrides and then the custom CSS, in that order.
Only the tokens that differ from the factory are written, so the file reads
as what the admin changed, and an install that has changed nothing serves a
comment and no rules at all.
"""
state = state or current()
lines = [f"\t--{name}: {value};"
for name, value in state["tokens"].items()
if value != FACTORY[name]]
css = "/* Generado desde Gestión → Marca. No editar a mano. */\n"
if lines:
css += ":root {\n" + "\n".join(lines) + "\n}\n"
if state["custom_css"]:
# Last, so it wins over everything above it. That is the whole contract
# of the advanced box.
css += "\n/* CSS propio */\n" + state["custom_css"] + "\n"
return css
# --- reading the form ------------------------------------------------------
def _read_tokens(form, errors: list[str]) -> dict:
"""Only what differs from the factory, and only if it is a colour.
A colour field is not a place to accept arbitrary CSS: `url(...)` in a
custom property is a request to another server on every page view, and
there is a whole textarea below for people who want to write CSS.
"""
stored = {}
for name in FACTORY:
raw = (form.get(f"token-{name}") or "").strip().lower()
if not raw:
continue
if not HEX.match(raw):
errors.append(f"«{raw}» no es un color. Usa la forma #rrggbb.")
continue
if raw != FACTORY[name].lower():
stored[name] = raw
return stored
def _read_css(form, errors: list[str]) -> str:
css = (form.get("custom_css") or "").strip()
if len(css) > CSS_MAX:
errors.append(f"El CSS propio no puede pasar de {CSS_MAX // 1000}.000 caracteres.")
return ""
for character in CSS_FORBIDDEN:
if character in css:
errors.append(
f"El CSS propio no puede contener «{character}». "
"Eso no aparece en CSS válido y sí en una etiqueta HTML."
)
return ""
return css
def _read_picture(field: str, allowed: tuple[str, ...], errors: list[str]):
"""One staged picture, or None if nothing was chosen.
`uploads.stage` does the work that matters — it reads the bytes and decides
the extension from them rather than from the name — so a GIF called
`logo.png` is refused here by the same code that refuses it on the wall.
"""
upload = request.files.get(field)
if not upload or not upload.filename:
return None
try:
staged = uploads.stage([upload])
except uploads.RejectedUpload as exc:
errors.append(str(exc))
return None
if not staged:
return None
item = staged[0]
extension = item["stored_name"].rsplit(".", 1)[-1]
if extension not in allowed:
errors.append(
f"«{item['original_name']}» es un {extension}. "
f"Aquí hace falta {' o '.join(allowed)}."
)
return None
return item
# --- routes ----------------------------------------------------------------
@bp.route("/gestion/marca", methods=["GET", "POST"])
@admin_required
def edit():
if request.method == "GET":
state = current()
return render_template("brand_form.html", state=state,
factory=FACTORY, simple=SIMPLE,
derived=sorted(DERIVED), advanced=_advanced(),
notes=warnings(state["tokens"]))
errors: list[str] = []
stored = _read_tokens(request.form, errors)
css = _read_css(request.form, errors)
logo = _read_picture("logo", LOGO_EXTENSIONS, errors)
favicon = _read_picture("favicon", FAVICON_EXTENSIONS, errors)
if errors:
for message in errors:
flash(message, "error")
return redirect(url_for("brand.edit"))
state = current()
# Written before the commits: the members area must not depend on the git
# server being up to change its own colours.
_store(stored, css, logo, favicon, state)
for note in warnings(resolve(stored)):
flash(note, "error")
if _publish():
flash("Guardado. El sitio público se reconstruye en un par de minutos.", "ok")
return redirect(url_for("brand.edit"))
def _advanced() -> tuple:
"""Every token the easy form does not offer, for the fold-out."""
simple = {name for name, _, _ in SIMPLE}
return tuple(name for name in FACTORY if name not in simple)
def _store(stored: dict, css: str, logo, favicon, state: dict) -> None:
"""The row, and the two pictures on disk.
Files before the row, as `uploads.save` does it and for the same reason: a
row naming a file that is not there renders as a broken image on every
future visit, while a file with no row is invisible.
"""
names = {"logo_name": state["logo_name"], "favicon_name": state["favicon_name"]}
for field, item in (("logo_name", logo), ("favicon_name", favicon)):
if item is None:
continue
uploads.directory().joinpath(item["stored_name"]).write_bytes(item["data"])
names[field] = item["stored_name"]
get_db().execute(
"""INSERT INTO brand (id, tokens_json, custom_css, logo_name, favicon_name,
updated_by, updated_at, published_at)
VALUES (1, ?, ?, ?, ?, ?, datetime('now'), NULL)
ON CONFLICT(id) DO UPDATE SET
tokens_json = excluded.tokens_json,
custom_css = excluded.custom_css,
logo_name = excluded.logo_name,
favicon_name = excluded.favicon_name,
updated_by = excluded.updated_by,
updated_at = excluded.updated_at,
published_at = NULL""",
(json.dumps(stored, sort_keys=True), css,
names["logo_name"], names["favicon_name"], g.member["id"]),
)
# The old pictures, once nothing points at them. After the row, so a
# rollback cannot leave the row naming a file that has been deleted.
for field, item in (("logo_name", logo), ("favicon_name", favicon)):
if item is not None and state[field] and state[field] != names[field]:
uploads.remove(state[field])
@bp.route("/gestion/marca/publicar", methods=["POST"])
@admin_required
def publish():
"""Try the commits again after the git server was unreachable."""
if _publish():
flash("Publicado. El sitio público se reconstruye en un par de minutos.", "ok")
return redirect(url_for("brand.edit"))
@bp.route("/gestion/marca/restaurar", methods=["POST"])
@admin_required
def restore():
"""Back to the colours the site was built with.
Reachable even when the custom CSS has broken every other page, because the
Marca screen deliberately does not load it — see `brand_form.html`.
"""
state = current()
get_db().execute("DELETE FROM brand WHERE id = 1")
for name in (state["logo_name"], state["favicon_name"]):
if name:
uploads.remove(name)
flash("Restaurado lo de fábrica.", "ok")
_publish()
return redirect(url_for("brand.edit"))
@bp.route("/marca.css")
def stylesheet_file():
"""Loaded by every page in the members area, after board.css.
No login: it carries no private data, and the sign-in page should look like
the site it signs you in to. Cached hard and busted by `?v=`, which is why
`base.html` appends the stamp.
"""
response = Response(stylesheet(), mimetype="text/css")
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
return response
@bp.route("/marca/<stored_name>")
def picture(stored_name: str):
"""The logo and the favicon, for the members area.
Its own route rather than `uploads.serve`, which is behind the login: these
two are public by definition, and one of them is in the `<head>` of the
sign-in page. Only the current pair is served — an old logo stops being
reachable the moment it is replaced, which is also when the file goes.
"""
if not uploads.STORED_NAME.match(stored_name):
abort(404)
state = current()
if stored_name not in (state["logo_name"], state["favicon_name"]):
abort(404)
return send_from_directory(uploads.directory(), stored_name)
# --- the public site's copy ------------------------------------------------
def _repo_path(stored_name: str, kind: str) -> str:
"""A stable path per picture: `static/brand/logo.png`.
Stable rather than the stored name so that saving a new logo replaces the
file instead of leaving every previous one in the repository, deployed and
unreferenced.
"""
return f"{REPO_FOLDER}/{kind}.{stored_name.rsplit('.', 1)[-1]}"
def _yaml(state: dict, logo: str | None, favicon: str | None) -> str:
"""`data/brand.yaml`, written rather than dumped.
By hand because the values are known: colours matched against a hex
pattern, a stamp of digits, two paths this module built, and one block of
CSS that goes in as a literal block scalar so nothing in it needs quoting.
PyYAML is not a dependency of the members area and is not worth becoming
one for twenty lines of output.
"""
lines = ["# Generado desde Gestión → Marca en vienalatina.com/comunidad.",
"# No editar a mano: el próximo guardado lo sobrescribe.",
f"stamp: \"{state['stamp']}\"",
"tokens:"]
for name, value in state["tokens"].items():
if value != FACTORY[name]:
lines.append(f" {name}: \"{value}\"")
if logo:
lines.append(f"logo: \"/{logo.removeprefix('static/')}\"")
if favicon:
lines.append(f"favicon: \"/{favicon.removeprefix('static/')}\"")
if state["custom_css"]:
lines.append("custom_css: |")
lines += [f" {line}" for line in state["custom_css"].splitlines()]
return "\n".join(lines) + "\n"
def _publish() -> bool:
"""Commit the brand into the content repository. True if it got there.
Four commits at most, because the contents API writes one file per request.
That is the same trade `content.commit_picture` makes: the git trees API
would batch them, at the cost of noticeably more code to get wrong, for a
benefit nobody sees beyond one fewer pipeline run.
Returns False and says why rather than raising: the colours are already
saved here, and an admin whose change took effect in the members area needs
to know the public site is a step behind, not to meet a traceback.
"""
state = current()
try:
token = gitea.content_token()
except gitea.GiteaError as exc:
flash(f"Guardado aquí. El sitio público no se ha actualizado: {exc}", "error")
return False
try:
logo_path = favicon_path = None
for kind, name in (("logo", state["logo_name"]),
("favicon", state["favicon_name"])):
if not name:
continue
path = _repo_path(name, kind)
data = uploads.directory().joinpath(name).read_bytes()
_write(path, data, f"marca: {kind}", token)
_tidy(kind, path, token)
if kind == "logo":
logo_path = path
else:
favicon_path = path
_write(DATA_FILE, _yaml(state, logo_path, favicon_path).encode("utf-8"),
"marca: colores", token)
except (gitea.GiteaError, OSError) as exc:
current_app.logger.warning("brand publish failed: %s", exc)
flash(f"Guardado aquí. El sitio público no se ha actualizado: {exc}", "error")
return False
get_db().execute(
"UPDATE brand SET published_at = datetime('now') WHERE id = 1")
return True
def _write(path: str, data: bytes, message: str, token: str) -> None:
"""Create or update, whichever this file needs.
The contents API wants the current sha to replace a file and refuses one
when creating, so the read comes first. A missing file is the normal case
the first time.
"""
try:
_, sha = gitea.read_file(path, token)
except gitea.GiteaError:
sha = None
gitea.write_file(path, data, message, token, sha=sha)
def _tidy(kind: str, keep: str, token: str) -> None:
"""Remove a previous picture of the same kind with another extension.
A logo saved as a PNG and then as a WebP would otherwise leave
`static/brand/logo.png` in the repository for good — deployed, unreferenced
and confusing to the next person who looks. Failure here is logged and
swallowed: the new logo is already committed, and a leftover file is not a
reason to tell the admin their change did not work.
"""
try:
for item in gitea.list_directory(REPO_FOLDER, token):
name = item.get("name", "")
path = f"{REPO_FOLDER}/{name}"
if path != keep and name.rsplit(".", 1)[0] == kind:
gitea.delete_file(path, item.get("sha", ""),
f"marca: retirar {name}", token)
except (gitea.GiteaError, OSError) as exc:
current_app.logger.info("brand tidy-up skipped: %s", exc)

View File

@ -115,6 +115,9 @@ CLEARED_ON_ERASE = {
# admin who typed it in: the meeting still happens after they leave, so the
# row stays and the name goes.
("events", "created_by"),
# Same for the colours and the logo. An admin leaving is not a reason for
# the site to go back to looking like a default install.
("brand", "updated_by"),
}
# Private correspondence is not reassigned to the tombstone, it goes. A thread

View File

@ -325,3 +325,29 @@ CREATE TABLE IF NOT EXISTS events (
);
CREATE INDEX IF NOT EXISTS events_month ON events(starts_on);
-- The look of the site, as the admin set it.
--
-- One row, pinned by the CHECK: there is one association per install and one
-- set of colours. `ON CONFLICT(id)` in brand.py relies on that pin, which is
-- also why there is no "which brand is current" question to get wrong.
--
-- Only the tokens that differ from apps/board/brand.py's FACTORY are stored, as
-- JSON. A snapshot of every token would mean that a token added later arrived
-- frozen at its old value for every install that had ever opened this screen.
--
-- `published_at` is NULL between a save and the commit that carries it to the
-- content repository — which is to say, whenever the git server was unreachable
-- when somebody pressed save. The screen reads it and offers to try again.
CREATE TABLE IF NOT EXISTS brand (
id INTEGER PRIMARY KEY CHECK (id = 1),
tokens_json TEXT NOT NULL DEFAULT '{}',
custom_css TEXT NOT NULL DEFAULT '',
logo_name TEXT,
favicon_name TEXT,
-- Cleared rather than reassigned when that member is erased: the colours
-- belong to the association, like an event in the calendar.
updated_by INTEGER REFERENCES members(id),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
published_at TEXT
);

View File

@ -733,3 +733,74 @@ input[type="file"] {
.cal__number { display: inline-block; margin-right: 0.5rem; }
.cal__add { display: inline; }
}
/* --- Gestión → Marca ---------------------------------------------------- */
/* Constrained in height rather than width: a wordmark is wide and a square
icon is not, and both have to sit in a bar 56px tall without pushing it
open. An admin who wants it bigger has the custom CSS box, and the
placeholder in that box is this very rule. */
.site-bar__logo { display: block; max-height: 36px; max-width: 240px; width: auto; }
.swatches {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
gap: 1rem;
margin: 0.75rem 0 1.25rem;
}
.swatch label { margin-bottom: 0.25rem; }
.swatch p { margin: 0.25rem 0 0; }
/* The input rule above gives every field width:100%, which on a colour picker
produces a swatch the width of the column. */
.swatch input[type="color"] {
width: 100%;
height: 2.75rem;
padding: 0.2rem;
cursor: pointer;
}
/* The preview block. Every colour inside it comes from a custom property, so
board.js can restyle the whole thing by setting six of them on this one
element — which is also what makes it an honest preview rather than a
drawing of one. */
.brand-preview {
background: var(--bg);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
overflow: hidden;
margin-bottom: 1.25rem;
}
.brand-preview__bar {
background: var(--surface);
border-bottom: 1px solid var(--border);
color: var(--brand);
font-weight: 700;
padding: 0.75rem 1rem;
}
.brand-preview__card {
background: var(--surface);
border: 1px solid var(--border-light);
border-radius: var(--radius-md);
color: var(--text);
margin: 1rem;
padding: 1rem;
}
.brand-preview__meta { color: var(--muted); font-size: 0.85rem; margin: 0 0 0.5rem; }
.brand-preview__card p:last-of-type { margin: 0 0 0.75rem; }
.brand-preview__btn {
display: inline-block;
background: var(--brand);
border-radius: 999px;
color: #fff;
font-weight: 600;
padding: 0.4rem 1rem;
}
.brand-current { max-height: 72px; max-width: 100%; width: auto; }
.brand-current--small { max-height: 48px; }
.brand-advanced { margin-top: 1.5rem; border-top: 1px solid var(--border-light); padding-top: 0.75rem; }
.brand-advanced summary { cursor: pointer; color: var(--subtle); }
.btn--danger { background: var(--danger); }
.btn--danger:hover { background: var(--danger); filter: brightness(0.9); }

View File

@ -149,9 +149,36 @@ document.addEventListener("submit", function (event) {
});
}
// --- the brand preview --------------------------------------------------
//
// Setting the custom properties on one element, from the colour pickers above
// it. A DOM write rather than a `style=""` attribute in the template, which
// is what makes it work under a policy with no 'unsafe-inline' — and it is
// also why the preview exists at all: the Marca screen itself is deliberately
// rendered in the factory colours, so this block is the only place an admin
// sees their own.
function brandPreview() {
var target = document.querySelector("[data-brand-preview-target]");
if (!target) { return; }
var pickers = document.querySelectorAll("[data-brand-preview] [data-token]");
function paint() {
Array.prototype.forEach.call(pickers, function (picker) {
target.style.setProperty("--" + picker.getAttribute("data-token"),
picker.value);
});
}
Array.prototype.forEach.call(pickers, function (picker) {
picker.addEventListener("input", paint);
});
paint();
}
document.addEventListener("DOMContentLoaded", function () {
Array.prototype.forEach.call(
document.querySelectorAll("textarea[data-markdown]"), toolbarFor);
brandPreview();
document.addEventListener("change", function (event) {
var input = event.target;

View File

@ -8,13 +8,33 @@
<meta name="robots" content="noindex, nofollow">
<title>{% block title %}Comunidad{% endblock %} — Viena Latina</title>
<link rel="stylesheet" href="{{ url_for('static', filename='board.css') }}">
{% block brand_css %}
{# After board.css, so the admin's colours win, and cache-busted by when
they were saved. A generated file rather than an inline <style> because
the CSP has no 'unsafe-inline' — an inline block would simply not apply,
without a word in the console. The Marca screen overrides this block
with nothing, so custom CSS that breaks the page cannot hide the page
that undoes it. #}
<link rel="stylesheet" href="{{ url_for('brand.stylesheet_file') }}?v={{ brand.stamp }}">
{% endblock %}
{% if brand.favicon_name %}
<link rel="icon" type="image/png"
href="{{ url_for('brand.picture', stored_name=brand.favicon_name) }}?v={{ brand.stamp }}">
{% endif %}
<script src="{{ url_for('static', filename='board.js') }}" defer></script>
</head>
<body>
<header class="site-bar">
<div class="site-bar__inner">
<a class="site-bar__brand" href="/"><span class="site-bar__brand-text">Viena Latina</span></a>
<a class="site-bar__brand" href="/">
{% if brand.logo_name %}
<img class="site-bar__logo" alt="Viena Latina"
src="{{ url_for('brand.picture', stored_name=brand.logo_name) }}?v={{ brand.stamp }}">
{% else %}
<span class="site-bar__brand-text">Viena Latina</span>
{% endif %}
</a>
{% if g.member %}
{# <details> rather than a button with a handler: the CSP has no
'unsafe-inline', so a menu that needs onclick="" is a menu that

View File

@ -0,0 +1,162 @@
{# Gestión → Marca: the colours, the logo and the favicon.
**This page deliberately does not load the generated stylesheet.** Every
other page in the members area does, and the free CSS box below can contain
anything — including `* { display: none }`. If that CSS applied here, the one
screen that can undo it would be the one screen you could not read. So the
block is overridden with nothing and this page is always in the factory
colours. The live preview below is where the admin sees their own.
The consequence is worth stating because it looks like an oversight: the
colours an admin picks do not show on the page where they pick them. #}
{% extends "base.html" %}
{% block title %}Marca{% endblock %}
{% block brand_css %}{% endblock %}
{% block main %}
<div class="feed-head">
<h1>Marca</h1>
<a class="linkish" href="{{ url_for('home.gestion') }}">Volver a Gestión</a>
</div>
<p class="muted">
Los colores, el logotipo y el icono de la pestaña, para las dos mitades del
sitio. El área privada cambia al guardar; vienalatina.com se reconstruye en
un par de minutos.
</p>
{% if state.updated_at and not state.published_at %}
<section class="panel panel--attention">
<div class="panel__head">
<h2>Pendiente de publicar</h2>
</div>
<p class="panel__row">
Lo de aquí está guardado, pero no ha llegado al sitio público: no se pudo
contactar con el servidor de git la última vez.
</p>
<form method="post" action="{{ url_for('brand.publish') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="btn" type="submit">Reintentar publicar en el sitio</button>
</form>
</section>
{% endif %}
{% for note in notes %}
<p class="flash flash--error">{{ note }}</p>
{% endfor %}
<form class="card" method="post" enctype="multipart/form-data"
action="{{ url_for('brand.edit') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<h2 class="section-title">Colores</h2>
<p class="muted small">
Seis colores. Los demás —los tonos claros y oscuros del principal— se
calculan a partir de él, para que no haya que acertar con cinco rojos
parecidos. Están en «Avanzado» si los quieres a mano.
</p>
{# A real colour picker, which every current browser draws natively: no
dependency, no script, and it works with a keyboard. The text beside each
one says where that colour shows up, because "--surface-soft" is not a
question an admin can answer. #}
<div class="swatches" data-brand-preview>
{% for name, label, where in simple %}
<div class="swatch">
<label for="token-{{ name }}">{{ label }}</label>
<input id="token-{{ name }}" name="token-{{ name }}" type="color"
data-token="{{ name }}" value="{{ state.tokens[name] }}">
<p class="muted small">{{ where }}</p>
</div>
{% endfor %}
</div>
{# Restyled by the pickers above, through board.js setting the custom
properties on this element. The DOM write is not an inline style
attribute in the HTML, which is why it works under the CSP. #}
<div class="brand-preview" data-brand-preview-target>
<div class="brand-preview__bar">Viena Latina</div>
<div class="brand-preview__card">
<p class="brand-preview__meta">Ana Pérez · hace dos horas</p>
<p>Así se verá una tarjeta del muro con estos colores.</p>
<span class="brand-preview__btn">Un botón</span>
</div>
</div>
<h2 class="section-title">Logotipo</h2>
<p class="muted small">
PNG, JPG o WebP. Aparece en la cabecera de las dos mitades del sitio y es
la imagen que sale al compartir un enlace que no tiene foto propia.
{% if state.logo_name %}Ahora hay uno puesto; si eliges otro, lo reemplaza.{% endif %}
</p>
{% if state.logo_name %}
<p><img class="brand-current"
src="{{ url_for('brand.picture', stored_name=state.logo_name) }}?v={{ state.stamp }}"
alt="El logotipo actual"></p>
{% endif %}
<input id="logo" name="logo" type="file" accept="image/png,image/jpeg,image/webp">
<h2 class="section-title">Icono de la pestaña</h2>
<p class="muted small">
PNG, y cuadrado: 32×32 o 180×180 van bien. Se sube aparte y no se saca del
logotipo — recortar un logotipo ancho a un cuadrado da un trozo de letra.
</p>
{% if state.favicon_name %}
<p><img class="brand-current brand-current--small"
src="{{ url_for('brand.picture', stored_name=state.favicon_name) }}?v={{ state.stamp }}"
alt="El icono actual"></p>
{% endif %}
<input id="favicon" name="favicon" type="file" accept="image/png">
<details class="brand-advanced">
<summary>Avanzado</summary>
<p class="muted small">
Para quien sepa CSS. Todo lo de aquí se aplica después de lo de arriba,
así que gana. Si algo sale mal, «Restaurar lo de fábrica» está al final
de esta página y esta página nunca carga este CSS, justamente para que
se pueda llegar a ese botón.
</p>
<h3 class="section-title">Los demás colores</h3>
<p class="muted small">
Déjalos en blanco para que se calculen desde el color principal
({{ derived|join(', ') }}) o queden como están de fábrica.
</p>
<div class="swatches">
{% for name in advanced %}
<div class="swatch">
<label for="token-{{ name }}"><span class="mono">--{{ name }}</span></label>
<input id="token-{{ name }}" name="token-{{ name }}" type="text"
value="{{ state.stored.get(name, '') }}"
placeholder="{{ state.tokens[name] }}"
pattern="^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$">
</div>
{% endfor %}
</div>
<h3 class="section-title">CSS propio</h3>
<p class="muted small">
Se añade al final de la hoja de estilos, en las dos mitades del sitio.
No puede contener «&lt;» ni «&gt;».
</p>
<textarea id="custom_css" name="custom_css" rows="10" class="mono"
placeholder=".site-bar__logo { max-height: 48px; }">{{ state.custom_css }}</textarea>
</details>
<button class="btn" type="submit">Guardar</button>
</form>
{% if state.customised %}
<form class="card" method="post" action="{{ url_for('brand.restore') }}"
data-confirm="Se vuelve a los colores originales y se borran el logotipo y el icono. ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<h2 class="section-title">Restaurar lo de fábrica</h2>
<p class="muted small">
Deja los colores como estaban al principio y quita el logotipo y el icono.
Esto funciona siempre, incluso si el CSS propio ha roto el resto del sitio.
</p>
<button class="btn btn--danger" type="submit">Restaurar lo de fábrica</button>
</form>
{% endif %}
{% endblock %}

View File

@ -53,6 +53,21 @@
</p>
</section>
<section class="panel">
<div class="panel__head">
<h2>Marca</h2>
<a class="linkish" href="{{ url_for('brand.edit') }}">Abrir</a>
</div>
{% if brand.updated_at and not brand.published_at %}
<p class="panel__row">Hay cambios guardados que no han llegado al sitio público.</p>
{% endif %}
<p class="muted small">
Los colores, el logotipo y el icono de la pestaña, para las dos mitades del
sitio. Con un apartado avanzado para quien sepa CSS, y un botón para
volver a lo de fábrica.
</p>
</section>
{% if counts.pending %}
<section class="panel panel--attention">
<div class="panel__head">

View File

@ -11,6 +11,7 @@ Gitea, and the tests that care about it stub the two network calls instead.
from __future__ import annotations
import hashlib
import sys
from pathlib import Path
@ -18,6 +19,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
from apps.board import gitea # noqa: E402
from apps.board.app import create_app # noqa: E402
from apps.board.db import connect # noqa: E402
@ -91,3 +93,60 @@ def post(client):
payload.setdefault("csrf_token", "token-for-tests")
return client.post(url, data=payload, **kwargs)
return _post
# --- the git server, as a dictionary --------------------------------------
#
# Shared because two features commit to the content repository now: the editor
# (test_content.py) and the brand (test_brand.py). What matters in both is the
# payload — which files, with which bytes, under whose name — and `requests` can
# be trusted to do HTTP.
class FakeRepo:
"""A repository in a dict, with shas that change when content does."""
def __init__(self):
self.files: dict[str, bytes] = {}
self.commits: list[str] = []
self.authors: list[dict] = []
self.reads = 0
@staticmethod
def _sha(data: bytes) -> str:
return hashlib.sha1(data).hexdigest()
def list_directory(self, path, token=None):
out = []
for name, data in self.files.items():
if name.startswith(path + "/") and "/" not in name[len(path) + 1:]:
out.append({"name": name.rsplit("/", 1)[1], "path": name,
"type": "file", "sha": self._sha(data)})
return out
def read_file(self, path, token=None):
self.reads += 1
if path not in self.files:
raise gitea.GiteaError("Ese archivo ya no existe.")
return self.files[path].decode("utf-8"), self._sha(self.files[path])
def write_file(self, path, data, message, token=None, sha=None, member=None):
if sha and self.files.get(path) is not None and self._sha(self.files[path]) != sha:
raise gitea.StaleFile("Alguien más guardó este archivo mientras lo editabas.")
self.files[path] = data
self.commits.append(message)
self.authors.append(gitea._identity(member))
return self._sha(data)
def delete_file(self, path, sha, message, token=None, member=None):
self.files.pop(path, None)
self.commits.append(message)
@pytest.fixture
def repo(monkeypatch):
fake = FakeRepo()
for name in ("list_directory", "read_file", "write_file", "delete_file"):
monkeypatch.setattr(gitea, name, getattr(fake, name))
return fake

View File

@ -0,0 +1,387 @@
"""The admin-editable look: colours, logo, favicon, custom CSS.
The first test in this file is the point of the phase. The brand colours were
two identical `:root` blocks in two stylesheets, with a comment saying *"If the
brand colours change, change them in both"* — an instruction, which is the
weakest kind of guarantee there is. `brand.FACTORY` is the one list now, and
this file fails the build if either stylesheet drifts from it.
"""
from __future__ import annotations
import io
import json
import re
from pathlib import Path
import pytest
from apps.board import brand
PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
GIF = b"GIF89a" + b"\x00" * 64
BOARD_CSS = Path(brand.__file__).resolve().parent / "static" / "board.css"
THEME_CSS = (Path(brand.__file__).resolve().parents[2]
/ "themes" / "vienalatina" / "assets" / "css" / "main.css")
def tokens_in(path: Path) -> dict:
"""The `--name: value` pairs from a stylesheet's first `:root` block."""
css = path.read_text(encoding="utf-8")
block = re.search(r":root\s*\{(.*?)\}", css, re.S)
assert block, f"{path.name} has no :root block"
return {name: value.strip().lower() for name, value in
re.findall(r"--([a-z-]+):\s*([^;]+);", block.group(1))}
# --- the one list ---------------------------------------------------------
@pytest.mark.parametrize("path", [BOARD_CSS, THEME_CSS], ids=["board", "theme"])
def test_the_stylesheet_agrees_with_the_factory_palette(path):
"""Both files keep their own `:root` — they are served by different things
and each has to stand alone — but neither may disagree with brand.py.
Only the names both sides share are compared: the theme has no `--danger`
and the members area has no `--accent` aliases, and neither absence is a
drift."""
declared = tokens_in(path)
shared = set(declared) & set(brand.FACTORY)
assert len(shared) > 8, f"{path.name}: only {len(shared)} tokens matched — is the block still there?"
for name in sorted(shared):
assert declared[name] == brand.FACTORY[name].lower(), (
f"{path.name}: --{name} is {declared[name]} and brand.FACTORY says "
f"{brand.FACTORY[name]}. One of the two is wrong."
)
# --- colour arithmetic ----------------------------------------------------
def test_the_three_shades_come_out_of_the_brand_colour():
"""Derived in HLS so the hue survives. A green brand must not produce the
pink tints that mixing #c0391c with white would."""
tokens = brand.resolve({"brand": "#1b5e20"})
assert tokens["brand"] == "#1b5e20"
for name in ("brand-dark", "brand-soft", "brand-softer"):
assert tokens[name] != brand.FACTORY[name], name
# Darker, then two tints, in that order.
assert (brand._luminance(tokens["brand-dark"])
< brand._luminance(tokens["brand"])
< brand._luminance(tokens["brand-soft"])
< brand._luminance(tokens["brand-softer"]))
def test_an_explicit_shade_stops_being_derived():
tokens = brand.resolve({"brand": "#1b5e20", "brand-dark": "#000000"})
assert tokens["brand-dark"] == "#000000"
def test_storing_nothing_leaves_the_factory_hexes_untouched():
"""Not "close to" the factory palette — the same strings. Deriving from an
unchanged brand colour would shift the three shades by a rounding error the
first time anybody opened the screen."""
assert brand.resolve({}) == brand.FACTORY
def test_contrast_matches_the_known_extremes():
assert round(brand.contrast("#ffffff", "#000000"), 1) == 21.0
assert round(brand.contrast("#777777", "#777777"), 1) == 1.0
def test_an_unreadable_pair_warns_and_a_readable_one_does_not():
assert brand.warnings(brand.FACTORY) == []
notes = brand.warnings(brand.resolve({"text": "#f2f2f2"}))
assert notes and "contraste" in notes[0]
# --- the form -------------------------------------------------------------
@pytest.fixture
def admin(make_member, sign_in):
member_id = make_member("admina", role="admin")
sign_in(member_id)
return member_id
# Arguments for the test client rather than fields of the form. Separated by
# name because the form has a field per token and the two would otherwise be
# posted together — `follow_redirects` as a form value is a quiet way for a
# test to assert against a redirect page it never followed.
CLIENT_ARGS = ("follow_redirects", "content_type")
def save(post, **fields):
"""Post the Marca form with every colour left blank but the ones given.
Blank rather than absent because that is what the real form sends: a text
field nobody filled in arrives as an empty string, and the handler has to
read that as "leave it at the factory value".
"""
sent = {name: fields.pop(name) for name in CLIENT_ARGS if name in fields}
data = {f"token-{name}": "" for name in brand.FACTORY}
data.update(fields)
return post("/comunidad/gestion/marca", data, **sent)
def test_only_admins_reach_it(client, post, make_member, sign_in):
for role in ("user", "moderator"):
sign_in(make_member(f"persona-{role}", role=role))
assert client.get("/comunidad/gestion/marca").status_code == 403
assert save(post, **{"token-brand": "#1b5e20"}).status_code == 403
assert post("/comunidad/gestion/marca/restaurar").status_code == 403
assert post("/comunidad/gestion/marca/publicar").status_code == 403
def test_a_colour_is_saved_and_served(client, post, admin):
save(post, **{"token-brand": "#1B5E20"})
css = client.get("/comunidad/marca.css")
assert css.mimetype == "text/css"
assert "--brand: #1b5e20;" in css.get_data(as_text=True)
# Lower-cased on the way in, so the same colour is one string in the row.
assert "#1B5E20" not in css.get_data(as_text=True)
def test_an_untouched_colour_is_not_written_at_all(client, db, post, admin):
"""Only differences are stored. A snapshot of all thirteen would freeze a
token added later at whatever this version thought it should be."""
save(post, **{"token-brand": brand.FACTORY["brand"], "token-text": "#111111"})
stored = json.loads(db.execute("SELECT tokens_json FROM brand").fetchone()[0])
assert stored == {"text": "#111111"}
def test_a_bad_colour_is_refused_field_by_field(client, db, post, admin):
for bad in ("red", "#xyz", "url(https://otro.sitio/x.png)", "#12345"):
response = save(post, **{"token-brand": bad}, follow_redirects=True)
assert "no es un color" in response.get_data(as_text=True), bad
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
def test_the_custom_css_is_last_so_it_wins(client, post, admin):
save(post, **{"token-brand": "#1b5e20", "custom_css": ".site-bar { height: 4rem; }"})
css = client.get("/comunidad/marca.css").get_data(as_text=True)
assert css.index(":root") < css.index(".site-bar")
def test_an_html_bracket_in_the_custom_css_is_refused(client, db, post, admin):
response = save(post, custom_css="</style><script>alert(1)</script>",
follow_redirects=True)
assert "no puede contener" in response.get_data(as_text=True)
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
def test_an_enormous_css_box_is_refused(client, db, post, admin):
response = save(post, custom_css="a{}" * 20_000, follow_redirects=True)
assert "caracteres" in response.get_data(as_text=True)
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
def test_the_screen_never_loads_the_custom_css(client, post, admin):
"""The reason an admin can always undo a mistake: `* { display: none }` in
the box breaks every page except this one."""
save(post, custom_css="* { display: none }")
page = client.get("/comunidad/gestion/marca").get_data(as_text=True)
other = client.get("/comunidad/gestion").get_data(as_text=True)
assert "marca.css" not in page
assert "marca.css" in other
assert "Restaurar lo de fábrica" in page
# --- the two pictures -----------------------------------------------------
def test_a_logo_is_sniffed_not_trusted(client, db, post, admin):
"""The same check as every other upload: the extension comes from the
bytes. A GIF called logo.png is a GIF."""
response = save(post, logo=(io.BytesIO(GIF), "logo.png"),
content_type="multipart/form-data", follow_redirects=True)
assert "es un gif" in response.get_data(as_text=True)
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
def test_a_png_logo_is_kept_and_served(app, client, db, post, admin):
save(post, logo=(io.BytesIO(PNG), "vienalatina.png"),
content_type="multipart/form-data")
name = db.execute("SELECT logo_name FROM brand").fetchone()["logo_name"]
assert name and name.endswith(".png")
with app.app_context():
from apps.board import uploads
assert uploads.directory().joinpath(name).exists()
# Public on purpose: it is in the <head> of the sign-in page.
client.get("/comunidad/logout")
assert client.get(f"/comunidad/marca/{name}").status_code == 200
def test_a_picture_that_is_not_the_current_one_is_not_served(client, db, post, admin):
save(post, logo=(io.BytesIO(PNG), "uno.png"), content_type="multipart/form-data")
first = db.execute("SELECT logo_name FROM brand").fetchone()["logo_name"]
save(post, logo=(io.BytesIO(PNG), "dos.png"), content_type="multipart/form-data")
assert client.get(f"/comunidad/marca/{first}").status_code == 404
def test_a_replaced_logo_goes_off_disk(app, client, db, post, admin):
save(post, logo=(io.BytesIO(PNG), "uno.png"), content_type="multipart/form-data")
first = db.execute("SELECT logo_name FROM brand").fetchone()["logo_name"]
save(post, logo=(io.BytesIO(PNG), "dos.png"), content_type="multipart/form-data")
with app.app_context():
from apps.board import uploads
assert not uploads.directory().joinpath(first).exists()
def test_the_favicon_is_png_only(client, db, post, admin):
"""ICO and SVG are both refused, for different reasons: the sniffer
identifies bytes by a prefix and an SVG is XML that can carry script."""
response = save(post, favicon=(io.BytesIO(GIF), "icono.gif"),
content_type="multipart/form-data", follow_redirects=True)
assert "hace falta png" in response.get_data(as_text=True)
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
def test_the_logo_and_the_favicon_reach_the_chrome(client, post, admin):
save(post, logo=(io.BytesIO(PNG), "logo.png"),
favicon=(io.BytesIO(PNG), "icono.png"),
content_type="multipart/form-data")
body = client.get("/comunidad/").get_data(as_text=True)
assert "site-bar__logo" in body
assert 'rel="icon"' in body
assert "site-bar__brand-text" not in body
# --- publishing to the public site ----------------------------------------
@pytest.fixture(autouse=True)
def unreachable(monkeypatch):
"""No test in this file talks to a real git server.
Autouse and not optional: every save tries to publish, so without this each
one would open a socket to git.vienalatina.com and wait for it to fail. The
tests that care about the commit ask for `repo` as well, whose patches are
applied after these and therefore win.
"""
def refuse(*args, **kwargs):
raise brand.gitea.GiteaError("No se pudo contactar con el servidor de git.")
for name in ("list_directory", "read_file", "write_file", "delete_file"):
monkeypatch.setattr(brand.gitea, name, refuse)
def test_the_commit_carries_the_colours_and_the_pictures(db, post, admin, repo):
save(post, **{"token-brand": "#1b5e20", "custom_css": ".x { color: red }"},
logo=(io.BytesIO(PNG), "vienalatina.png"),
favicon=(io.BytesIO(PNG), "icono.png"),
content_type="multipart/form-data")
assert set(repo.files) == {"data/brand.yaml",
"static/brand/logo.png",
"static/brand/favicon.png"}
yaml = repo.files["data/brand.yaml"].decode("utf-8")
assert ' brand: "#1b5e20"' in yaml
assert 'logo: "/brand/logo.png"' in yaml # the path Hugo serves it at
assert 'favicon: "/brand/favicon.png"' in yaml
assert "custom_css: |\n .x { color: red }" in yaml
# Only the differences, exactly as the stylesheet does it.
assert "surface:" not in yaml
assert db.execute("SELECT published_at FROM brand").fetchone()["published_at"]
def test_a_logo_in_another_format_does_not_leave_the_old_one_behind(post, admin, repo):
"""`static/brand/logo.png` and `logo.webp` would otherwise both sit in the
repository, deployed, with only one of them referenced."""
save(post, logo=(io.BytesIO(PNG), "uno.png"), content_type="multipart/form-data")
assert "static/brand/logo.png" in repo.files
webp = b"RIFF\x00\x00\x00\x00WEBP" + b"\x00" * 64
save(post, logo=(io.BytesIO(webp), "dos.webp"), content_type="multipart/form-data")
assert "static/brand/logo.webp" in repo.files
assert "static/brand/logo.png" not in repo.files
def test_a_save_survives_the_git_server_being_down(client, db, post, admin):
"""The order this is written in. SQLite first, so a change that does not
need git is not blocked by git — and the screen says the public site is a
step behind rather than pretending it is not."""
response = save(post, **{"token-brand": "#1b5e20"}, follow_redirects=True)
row = db.execute("SELECT tokens_json, published_at FROM brand").fetchone()
assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"}
assert row["published_at"] is None
assert "Pendiente de publicar" in response.get_data(as_text=True)
assert "--brand: #1b5e20;" in client.get("/comunidad/marca.css").get_data(as_text=True)
def test_the_retry_publishes_what_was_already_saved(db, post, admin, monkeypatch, repo):
"""What the *Reintentar publicar* button is for: the colours are in SQLite
and the commit never happened."""
def refuse(*args, **kwargs):
raise brand.gitea.GiteaError("caído")
# Only the write, and put it back by hand rather than with
# `monkeypatch.undo()` — which would also undo the `repo` fixture's own
# patches and leave the retry talking to the real git server.
working = brand.gitea.write_file
monkeypatch.setattr(brand.gitea, "write_file", refuse)
save(post, **{"token-brand": "#1b5e20"})
assert db.execute("SELECT published_at FROM brand").fetchone()["published_at"] is None
monkeypatch.setattr(brand.gitea, "write_file", working)
post("/comunidad/gestion/marca/publicar")
assert ' brand: "#1b5e20"' in repo.files["data/brand.yaml"].decode("utf-8")
assert db.execute("SELECT published_at FROM brand").fetchone()["published_at"]
# --- restoring ------------------------------------------------------------
def test_restoring_empties_the_row_and_the_disk(app, client, db, post, admin):
save(post, **{"token-brand": "#1b5e20"}, )
save(post, logo=(io.BytesIO(PNG), "logo.png"), content_type="multipart/form-data")
name = db.execute("SELECT logo_name FROM brand").fetchone()["logo_name"]
post("/comunidad/gestion/marca/restaurar")
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
with app.app_context():
from apps.board import uploads
assert not uploads.directory().joinpath(name).exists()
css = client.get("/comunidad/marca.css").get_data(as_text=True)
assert ":root" not in css # nothing to override any more
assert "site-bar__brand-text" in client.get("/comunidad/").get_data(as_text=True)
# --- erasure --------------------------------------------------------------
def test_erasing_the_admin_leaves_the_brand_standing(client, db, post, owner_id,
make_member, sign_in):
"""The colours belong to the association, like an event in the calendar.
An admin leaving is not a reason for the site to look like a default
install again."""
admin_id = make_member("admina", role="admin")
sign_in(admin_id)
save(post, **{"token-brand": "#1b5e20"})
sign_in(owner_id)
post(f"/comunidad/miembros/{admin_id}/eliminar")
row = db.execute("SELECT tokens_json, updated_by FROM brand").fetchone()
assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"}
assert row["updated_by"] is None

View File

@ -9,7 +9,6 @@ import the real translate.py and run its parser over what the editor wrote.
from __future__ import annotations
import hashlib
import importlib.util
import io
import sys
@ -18,6 +17,7 @@ from pathlib import Path
import pytest
from apps.board import content, gitea
from apps.board.tests.conftest import FakeRepo # noqa: F401 (used by the `repo` fixture)
REPO_ROOT = Path(__file__).resolve().parents[3]
@ -35,54 +35,6 @@ def _load_translate():
translate = _load_translate()
class FakeRepo:
"""A repository in a dict, with shas that change when content does."""
def __init__(self):
self.files: dict[str, bytes] = {}
self.commits: list[str] = []
self.authors: list[dict] = []
self.reads = 0
@staticmethod
def _sha(data: bytes) -> str:
return hashlib.sha1(data).hexdigest()
def list_directory(self, path, token=None):
out = []
for name, data in self.files.items():
if name.startswith(path + "/") and "/" not in name[len(path) + 1:]:
out.append({"name": name.rsplit("/", 1)[1], "path": name,
"type": "file", "sha": self._sha(data)})
return out
def read_file(self, path, token=None):
self.reads += 1
if path not in self.files:
raise gitea.GiteaError("Ese archivo ya no existe.")
return self.files[path].decode("utf-8"), self._sha(self.files[path])
def write_file(self, path, data, message, token=None, sha=None, member=None):
if sha and self.files.get(path) is not None and self._sha(self.files[path]) != sha:
raise gitea.StaleFile("Alguien más guardó este archivo mientras lo editabas.")
self.files[path] = data
self.commits.append(message)
self.authors.append(gitea._identity(member))
return self._sha(data)
def delete_file(self, path, sha, message, token=None, member=None):
self.files.pop(path, None)
self.commits.append(message)
@pytest.fixture
def repo(monkeypatch):
fake = FakeRepo()
for name in ("list_directory", "read_file", "write_file", "delete_file"):
monkeypatch.setattr(gitea, name, getattr(fake, name))
return fake
@pytest.fixture
def editor(db, make_member, sign_in):
"""An admin. The editor commits through the server's own content token

View File

@ -79,10 +79,13 @@ languages:
params:
# The picture a share card falls back on when a post or page has none, and the
# organisation's logo in the structured data. One path — /uploads/algo.png —
# and WhatsApp, Signal, Mastodon and Bluesky all start showing an image. Left
# empty until there is a logo to put here; a link then shares as title and
# description, which is what happens today.
# organisation's logo in the structured data.
#
# **The logo uploaded in Gestión → Marca is used first**, so this is now only
# for a site that wants a different share picture from its logo — a photo of
# the city, say. One path (/uploads/algo.png) and WhatsApp, Signal, Mastodon
# and Bluesky all start showing an image. Empty, with no logo either, means a
# link shares as title and description.
defaultImage: ""
# The organisation's profiles elsewhere, for `sameAs` in the Organization

View File

@ -1008,6 +1008,72 @@ Choosing a picture shows a thumbnail with its name and size before anything is
uploaded. That is the one reason `blob:` is in the `img-src` policy — a handle to
bytes already in the page, which reaches no network.
### 11.18 Marca: the admin owns the look
*Gestión* → **Marca**, admins only. Colours, a logo and a favicon for both
halves of the site, with an *Avanzado* fold holding every token as a text field
and a free CSS box.
**`apps/board/brand.py`'s `FACTORY` is the single source of truth for the
palette.** The two `:root` blocks — `themes/vienalatina/assets/css/main.css` and
`apps/board/static/board.css` — each still carry their own copy, because they are
served by different things and each has to stand alone; what changed is that
`apps/board/tests/test_brand.py` parses both and fails the build if either
disagrees with `FACTORY`. The comment that used to say *"If the brand colours
change, change them in both"* was an instruction, which is the weakest kind of
guarantee there is.
**One save, two destinations**, because the two halves cannot read the same
store:
| Where | What | Why |
|---|---|---|
| SQLite, table `brand`, one row | the tokens, the custom CSS, both pictures under `/data/uploads` | the members area must render when the git server is down |
| the content repository: `data/brand.yaml`, `static/brand/logo.*`, `static/brand/favicon.png` | the same values | the public site is files on disk and has no database |
**SQLite first, then the commits.** If Gitea is unreachable the change still
takes effect in the members area, `published_at` stays NULL, and the screen says
so with a *Reintentar publicar* button. The other order would let a git outage
block a change that does not need git. A colour therefore reaches
vienalatina.com on the next pipeline run — a couple of minutes — and the members
area immediately.
Three details worth knowing before changing any of it:
* **Only what differs from the factory is stored**, as JSON in one column. A
token added here later arrives with its default already in place for every
existing install, which a snapshot of all thirteen would not.
* **`--brand-dark`, `--brand-soft` and `--brand-softer` are worked out from
`--brand`** in HLS (hue and saturation kept, lightness moved), so an admin
picks one colour and gets a coherent set. Each can be overridden in
*Avanzado*. With no brand colour stored, the factory hexes are used verbatim —
deriving from an unchanged colour would shift the palette by a rounding error
the first time anybody opened the screen.
* **A WCAG contrast warning, not a refusal.** Text on background below 4.5:1,
or white on the brand colour below 3:1, is named with its ratio and saved
anyway. An admin may have a reason; what this prevents is shipping an
unreadable site without once being told.
**The Marca screen deliberately does not load the generated stylesheet.** Every
other page does. That is what keeps *Restaurar lo de fábrica* reachable after
somebody puts `* { display: none }` in the CSS box — and the reason the colours
an admin picks do not show on the page where they pick them. The live preview
block is where they see them, restyled by `board.js` setting the custom
properties on that one element (a DOM write, not an inline `style` attribute,
which is what makes it work under a policy with no `'unsafe-inline'`).
**No SVG and no ICO.** The logo takes PNG, JPG or WebP and the favicon PNG only,
both identified from their bytes by the same sniffer the wall uses. An SVG is XML
that can carry script and would be served from our own origin; ICO would be one
more branch in the sniffer for a format every current browser no longer needs.
The pictures are committed to stable paths, so saving a new logo replaces the
file instead of leaving every previous one deployed and unreferenced; a logo
saved in a different format has its predecessor deleted. `scripts/translate.py`
needs nothing — it walks `content/` only, and `data/` and `static/` are outside
it. A site with no `data/brand.yaml` builds byte-for-byte the HTML it built
before any of this existed, which is asserted by building both ways.
## 12. Make Gitea look like the site
Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its

View File

@ -7,6 +7,7 @@
{{ partial "seo-head.html" . }}
{{ $css := resources.Get "css/main.css" | minify | fingerprint }}
<link rel="stylesheet" href="{{ $css.RelPermalink }}" integrity="{{ $css.Data.Integrity }}">
{{ partial "brand-head.html" . }}
<link rel="canonical" href="{{ .Permalink }}">
{{ range .AlternativeOutputFormats -}}
<link rel="{{ .Rel }}" type="{{ .MediaType.Type }}" href="{{ .Permalink | safeURL }}">

View File

@ -0,0 +1,31 @@
{{/* The admin's colours and the favicon, from data/brand.yaml.
That file is written by the members area — Gestión → Marca commits it
through the contents API, the pipeline runs, and the colours arrive here on
the next build. The whole partial is inside a `with`, so a site with no
brand.yaml emits nothing at all and its HTML is byte-identical to before
this existed.
Built with resources.FromString rather than written into a <style> block:
the public site has no Content-Security-Policy of its own today, but the
members area does and this stylesheet is generated the same way on both
sides. Fingerprinted, which is what makes a colour change reach a browser
that already has the old file.
The favicon carries ?v= the stamp instead, because it is a static file
Caddy serves under its own name — replacing the picture does not change
the path. */}}
{{ with site.Data.brand }}
{{ $tokens := "" }}
{{ range $name, $value := .tokens }}{{ $tokens = printf "%s--%s:%s;" $tokens $name $value }}{{ end }}
{{ $sheet := "" }}
{{ with $tokens }}{{ $sheet = printf ":root{%s}" . }}{{ end }}
{{ with $.Site.Data.brand.custom_css }}{{ $sheet = printf "%s\n%s" $sheet . }}{{ end }}
{{ with $sheet }}
{{ $brand := resources.FromString "css/brand.css" . | minify | fingerprint }}
<link rel="stylesheet" href="{{ $brand.RelPermalink }}" integrity="{{ $brand.Data.Integrity }}">
{{ end }}
{{ with .favicon }}
<link rel="icon" type="image/png" href="{{ . }}?v={{ $.Site.Data.brand.stamp }}">
{{ end }}
{{ end }}

View File

@ -4,7 +4,21 @@
<header class="site-bar">
<div class="site-bar__inner">
<a class="site-bar__brand" href="{{ .Site.Home.Permalink }}" aria-label="Inicio">
{{/* The logo uploaded in Gestión → Marca, and the site's name in
letters when there is none. The alt text is the name either way,
so a reader who does not see the picture reads the same thing.
Read through two variables rather than as
`site.Data.brand.logo`, because on a site with no data/brand.yaml
that expression is a field lookup on nil and fails the build —
which is precisely the state every install starts in. */}}
{{ $logo := "" }}{{ $stamp := "0" }}
{{ with site.Data.brand }}{{ $logo = .logo }}{{ $stamp = .stamp }}{{ end }}
{{ with $logo }}
<img class="site-bar__logo" src="{{ . }}?v={{ $stamp }}" alt="{{ site.Title }}">
{{ else }}
<span class="site-bar__brand-text">{{ .Site.Title }}</span>
{{ end }}
</a>
<nav class="site-bar__nav" aria-label="Idioma">

View File

@ -10,15 +10,22 @@
renders raggedly in some readers and truncated in others. */}}
{{ $desc = trim ($desc | plainify | replaceRE "\\s+" " ") " " }}
{{/* The picture a share card shows. A page's own image when it has one, the
site default when it does not — `params.defaultImage` is empty until the
logo arrives, and a card with no picture is what happens meanwhile, which is
also what happens today. Absolute, because WhatsApp, Signal, Mastodon and
Bluesky all fetch it from outside and a relative path means nothing to
them. */}}
{{/* The picture a share card shows. A page's own image when it has one, and
otherwise the fallback: the logo uploaded in Gestión → Marca, or
`params.defaultImage` when there is no logo. The logo comes first because
it is the one somebody can change without the repository — and because
`defaultImage` only ever existed as the line to fill in once a logo
arrived. With neither, a card shows title and description and no picture,
which is what happened before either existed.
Absolute, because WhatsApp, Signal, Mastodon and Bluesky all fetch it from
outside and a relative path means nothing to them. */}}
{{ $brandLogo := "" }}
{{ with site.Data.brand }}{{ $brandLogo = .logo }}{{ end }}
{{ $fallback := or $brandLogo .Site.Params.defaultImage }}
{{ $image := "" }}
{{ with .Params.image }}{{ $image = . | absURL }}
{{ else }}{{ with .Site.Params.defaultImage }}{{ $image = . | absURL }}{{ end }}{{ end }}
{{ else }}{{ with $fallback }}{{ $image = . | absURL }}{{ end }}{{ end }}
<meta name="description" content="{{ $desc }}">
@ -123,6 +130,14 @@
<meta property="og:description" content="{{ $desc }}">
<meta property="og:url" content="{{ .Permalink }}">
<meta property="og:locale" content="{{ $locale }}">
{{/* The home page shared without a picture until there was one to use. Now
that an admin can upload a logo, the front page of the site is the last
place that should share as a bare link. */}}
{{ with $image }}
<meta property="og:image" content="{{ . }}">
<meta property="og:image:alt" content="{{ $.Site.Title }}">
<meta name="twitter:image" content="{{ . }}">
{{ end }}
{{ $org := dict
"@context" "https://schema.org"
@ -132,7 +147,10 @@
"description" .Site.Params.description
"areaServed" (dict "@type" "City" "name" "Wien" "addressCountry" "AT")
}}
{{ with .Site.Params.defaultImage }}{{ $org = merge $org (dict "logo" (. | absURL)) }}{{ end }}
{{/* The same fallback as the share card: the admin's logo, then the configured
default. This is the field a search engine uses to put a mark beside the
organisation's name, so it should be the logo somebody actually uploaded. */}}
{{ with $fallback }}{{ $org = merge $org (dict "logo" (. | absURL)) }}{{ end }}
{{ with .Site.Params.sameAs }}{{ $org = merge $org (dict "sameAs" .) }}{{ end }}
<script type="application/ld+json">{{ $org | jsonify (dict "indent" " ") | safeJS }}</script>