Identidad, tipografías, y tres herramientas de administración

The second half of the superadministrator's job: not just who may do things, but
what they get to do that nobody else does.

**Identidad** is everything that used to be frozen in config.yaml — the name and
the one-line tagline in all three languages, the association's accounts
elsewhere, a public email, a city and street, a share picture and the footer
line. It commits data/site.yaml the way Marca commits data/brand.yaml.

Hugo cannot have config.yaml overridden by a data file, so the name and tagline
are read through two new partials that prefer the data file and fall back to the
config; every template showing either calls one, so they cannot drift. A site
with no data/site.yaml builds byte-for-byte what it built before — asserted by
building both ways and diffing with the stylesheet fingerprint normalised.

The contact fields are not decoration: they become ContactPoint and
PostalAddress in the Organization schema, which is what puts an association in a
local result rather than only a web one, and the social links become sameAs,
which is how an engine knows an Instagram account and this site are one body.

**Marca** grows a typeface and a roundness. Four system stacks — nothing
downloaded, which is deliberate and a GDPR matter — or an uploaded .woff2,
sniffed by its wOF2 signature, capped at 400 KB, named ahead of the old stack so
a font that fails to load leaves a readable site. The fold-out warning covers
missing accented glyphs, file size, synthesised bold, and licensing: a font is
software, a desktop licence is not a webfont licence, and that liability follows
the platform to every organisation it is installed for. SIL OFL and Apache-2.0
are named, with seven places to find them.

**Three tools.** Estado del sistema exercises the content token against the
repository rather than checking it is non-empty — "present" was never the
problem, a wrong scope broke publishing for three phases while looking fine —
and reports mail, backups, disk and every documented setting the container does
not have. It changes nothing on purpose. Registro de actividad records the dozen
acts that change who can do what; the actor is cleared and not cascaded on
erasure, and log() never raises, because an administrator who could not be
appointed because the note about it could not be saved is worse than a gap in
the notes. Biblioteca de medios lists every picture with the posts that use it
and, finally, shows the orphans — a picture whose post was deleted has stayed in
the repository, deployed and unreferenced, for the life of this site with no way
to see one.

Two bugs found by looking at the rendered pages rather than at the tests:

**Gestión had disappeared from the superadministrator's own navigation.**
base.html asked `g.member.role in ('owner', 'admin')`, right until a role
appeared above both. 622 tests passed while it was broken, because every one of
them signed in as an admin or below. The templates now call the same
`is_at_least` the handlers do, and test_navigation.py covers the tier above
admin — verified by reintroducing the tuple and watching it fail.

And the status screen counted the tombstone as a suspended member.

Migration 8 is plain ADD COLUMNs; `activity` and `site` are new tables, so
CREATE TABLE IF NOT EXISTS covers them with no step at all. The erase guard
caught both the moment they existed, which is that test doing its job.

627 tests pass. Hugo builds clean with the pipeline's flags, both with and
without the two data files.

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-06 12:18:04 +00:00
parent 1ff3522c56
commit 81d9fae4a9
No known key found for this signature in database
34 changed files with 2140 additions and 61 deletions

95
apps/board/activity.py Normal file
View File

@ -0,0 +1,95 @@
"""Who did what, for the superadministrator to read.
An audit trail is the natural companion to a role that can do everything: the
question "who made them an administrator?" has no other answer, and the moment
anybody asks it is exactly the moment nobody can remember.
**Deliberately not a general event store.** One row per act that changes who can
do what, or what the public sees. No page views, no successful sign-ins, no
"somebody opened Miembros" — a log that records everything is a log nobody
reads, and this one has to be readable by a person scrolling it once a month.
`log()` never raises. A failure to write the diary must not fail the thing being
recorded: an administrator who could not be appointed because the note about it
could not be saved is a worse outcome than a gap in the notes.
"""
from __future__ import annotations
from flask import Blueprint, current_app, g, render_template, request
from .db import get_db
from .security import superadmin_required
bp = Blueprint("activity", __name__)
PER_PAGE = 60
# action key -> the sentence a person reads. Built here rather than stored,
# because the stored key is what a later reader greps for and the wording is
# what changes. `{object}` is whatever the act was done to.
SENTENCES = {
"member.created": "dio de alta a {object}",
"member.invited": "envió una invitación a {object}",
"member.suspended": "suspendió a {object}",
"member.restored": "reactivó a {object}",
"member.erased": "eliminó a {object}",
"role.changed": "cambió el rol de {object}",
"chair.owner": "nombró responsable a {object}",
"chair.superadmin": "entregó la plataforma a {object}",
"submission.approved": "publicó la propuesta «{object}»",
"submission.rejected": "devolvió la propuesta «{object}»",
"content.published": "publicó «{object}»",
"content.deleted": "retiró «{object}»",
"brand.saved": "cambió el aspecto del sitio",
"brand.restored": "restauró el aspecto de fábrica",
"identity.saved": "cambió la identidad del sitio",
"media.deleted": "borró la imagen {object}",
}
def log(action: str, object_name: str = "", detail: str = "") -> None:
"""Record one act. Call it after the thing succeeded, never before.
Swallows everything on purpose — see the module docstring. The log line it
writes instead is what tells somebody the diary is broken.
"""
try:
get_db().execute(
"INSERT INTO activity (actor_id, action, object, detail) VALUES (?, ?, ?, ?)",
(g.member["id"] if getattr(g, "member", None) else None,
action, str(object_name)[:200], str(detail)[:400]),
)
except Exception: # pragma: no cover - defensive
current_app.logger.warning("could not write activity %r", action, exc_info=True)
@bp.route("/gestion/registro")
@superadmin_required
def index():
page = max(0, request.args.get("p", type=int) or 0)
rows = get_db().execute(
"""SELECT a.*, m.display_name AS actor, m.gitea_login AS actor_login
FROM activity a
LEFT JOIN members m ON m.id = a.actor_id
ORDER BY a.created_at DESC, a.id DESC
LIMIT ? OFFSET ?""",
(PER_PAGE + 1, page * PER_PAGE),
).fetchall()
# One more than a page, asked for so that "is there another page" is known
# without a second COUNT(*) over a table that only grows.
more = len(rows) > PER_PAGE
# The sentence is built here rather than in the template: Jinja's `format`
# filter is printf-style, so a `{object}` placeholder would have rendered
# literally — and an unknown action falling back to its own key is what
# makes a log written by an older version still readable.
entries = [{
"at": row["created_at"],
"actor": row["actor"],
"sentence": SENTENCES.get(row["action"], row["action"]).format(
object=row["object"] or "—"),
"detail": row["detail"],
} for row in rows[:PER_PAGE]]
return render_template("activity.html", rows=entries, page=page, more=more)

View File

@ -14,7 +14,7 @@ from flask import Flask, render_template, request
from werkzeug.middleware.proxy_fix import ProxyFix from werkzeug.middleware.proxy_fix import ProxyFix
from .db import TOMBSTONE_LOGIN, close_db, init_db from .db import TOMBSTONE_LOGIN, close_db, init_db
from .security import check_csrf, csrf_token from .security import check_csrf, csrf_token, is_at_least
URL_PREFIX = "/comunidad" URL_PREFIX = "/comunidad"
@ -94,11 +94,16 @@ def create_app(overrides: dict | None = None) -> Flask:
# restart, which is a confusing way to find out the variable is unset. # 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`).") raise RuntimeError("BOARD_SECRET_KEY is required (generate one with `openssl rand -hex 32`).")
from . import (auth, board, brand, content, events, home, members, from . import (activity, auth, board, brand, content, events, home,
messages, profiles, submissions, uploads) identity, media, members, messages, profiles, status,
submissions, uploads)
app.register_blueprint(auth.bp, url_prefix=URL_PREFIX) app.register_blueprint(auth.bp, url_prefix=URL_PREFIX)
app.register_blueprint(home.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(brand.bp, url_prefix=URL_PREFIX)
app.register_blueprint(identity.bp, url_prefix=URL_PREFIX)
app.register_blueprint(status.bp, url_prefix=URL_PREFIX)
app.register_blueprint(activity.bp, url_prefix=URL_PREFIX)
app.register_blueprint(media.bp, url_prefix=URL_PREFIX)
app.register_blueprint(submissions.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(events.bp, url_prefix=URL_PREFIX)
app.register_blueprint(members.bp, url_prefix=URL_PREFIX) app.register_blueprint(members.bp, url_prefix=URL_PREFIX)
@ -122,6 +127,11 @@ def create_app(overrides: dict | None = None) -> Flask:
# keeps the picker from offering a role the handler will refuse — with two # keeps the picker from offering a role the handler will refuse — with two
# levels above admin, a hardcoded list can only be right for one of them. # levels above admin, a hardcoded list can only be right for one of them.
app.jinja_env.globals["assignable_roles"] = members.assignable_roles app.jinja_env.globals["assignable_roles"] = members.assignable_roles
# The same predicate the handlers use. Templates had their own literal
# tuples until a tier appeared above them and Gestión quietly disappeared
# from the superadministrator's own navigation — the exact failure
# `is_at_least` was introduced to end on the Python side.
app.jinja_env.globals["is_at_least"] = is_at_least
@app.context_processor @app.context_processor
def _year(): def _year():
@ -134,6 +144,12 @@ def create_app(overrides: dict | None = None) -> Flask:
# that would save the query by deferring it. # that would save the query by deferring it.
return {"brand": brand.state()} return {"brand": brand.state()}
@app.context_processor
def _identity():
# Only Gestión draws it, so unlike `brand` this one is lazy: a function
# the template calls, costing nothing on the pages that never ask.
return {"identity": identity.current}
@app.context_processor @app.context_processor
def _badges(): def _badges():
# Lazily, as functions: base.html is rendered for signed-out pages and # Lazily, as functions: base.html is rendered for signed-out pages and

View File

@ -49,11 +49,12 @@ from __future__ import annotations
import colorsys import colorsys
import json import json
import re import re
import secrets
from flask import (Blueprint, Response, abort, current_app, flash, g, redirect, from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
render_template, request, send_from_directory, url_for) render_template, request, send_from_directory, url_for)
from . import gitea, uploads from . import activity, gitea, uploads
from .db import get_db from .db import get_db
from .security import superadmin_required from .security import superadmin_required
@ -105,6 +106,50 @@ DERIVED = {
HEX = re.compile(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$") HEX = re.compile(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
# --- the typeface ----------------------------------------------------------
#
# Four stacks of fonts that are already on the reader's machine, and nothing
# downloaded from anywhere. The site's freedom from Google Fonts is deliberate
# and a GDPR matter: a stylesheet that pulls a font from fonts.gstatic.com tells
# Google the IP address of everyone who reads this site, which is a disclosure
# an association cannot make on its visitors' behalf without asking them.
#
# A fifth option, `propia`, uses an uploaded .woff2 and falls back to the sans
# stack — so a font that fails to load leaves a readable site rather than a
# browser default.
TYPEFACES = {
"sans": ("Sans (la de ahora)",
'"Montserrat", -apple-system, BlinkMacSystemFont, "Segoe UI", '
'Roboto, "Helvetica Neue", Arial, sans-serif'),
"serif": ("Serif",
'Georgia, Cambria, "Times New Roman", Times, serif'),
"redonda": ("Redondeada",
'"Trebuchet MS", "Segoe UI", Verdana, sans-serif'),
"sistema": ("La del sistema",
'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif'),
}
DEFAULT_TYPEFACE = "sans"
FONT_STACK_FALLBACK = TYPEFACES["sans"][1]
# A .woff2 and nothing else. It is the web format — every browser in use takes
# it, it is the smallest, and it has a four-byte signature this can check
# without a parser. A .ttf or .otf would work in a browser and would also be
# two to five times the size for the same letters.
FONT_SIGNATURE = b"wOF2"
FONT_MAX_BYTES = 400_000
# How round everything is. One setting driving four tokens, because a site whose
# cards are round and whose buttons are square looks like two sites.
ROUNDNESS = {
"suave": ("Suave (la de ahora)", {"radius-xl": "18px", "radius-lg": "12px",
"radius-md": "8px", "radius-sm": "5px"}),
"recta": ("Recta", {"radius-xl": "0", "radius-lg": "0",
"radius-md": "0", "radius-sm": "0"}),
"redonda": ("Redonda", {"radius-xl": "28px", "radius-lg": "20px",
"radius-md": "14px", "radius-sm": "10px"}),
}
DEFAULT_ROUNDNESS = "suave"
# The free CSS box takes anything but these. `<` and `>` cannot appear in valid # 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 # 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 # stylesheet context in a consumer that mishandles it. Everything else is left
@ -236,25 +281,43 @@ def current() -> dict:
stored = {} stored = {}
if not isinstance(stored, dict): if not isinstance(stored, dict):
stored = {} stored = {}
def column(name):
return (row[name] if row else None) or None
typeface = column("typeface")
if typeface not in TYPEFACES and typeface != "propia":
typeface = DEFAULT_TYPEFACE
roundness = column("roundness")
if roundness not in ROUNDNESS:
roundness = DEFAULT_ROUNDNESS
return { return {
"stored": stored, "stored": stored,
"tokens": resolve(stored), "tokens": resolve(stored),
"custom_css": (row["custom_css"] if row else "") or "", "custom_css": (row["custom_css"] if row else "") or "",
"logo_name": row["logo_name"] if row else None, "logo_name": column("logo_name"),
"favicon_name": row["favicon_name"] if row else None, "favicon_name": column("favicon_name"),
"font_name": column("font_name"),
"typeface": typeface,
"roundness": roundness,
"updated_at": row["updated_at"] if row else None, "updated_at": row["updated_at"] if row else None,
"published_at": row["published_at"] if row else None, "published_at": row["published_at"] if row else None,
"stamp": _stamp(row["updated_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"] "customised": bool(stored or (row and (row["custom_css"] or row["logo_name"]
or row["favicon_name"]))), or row["favicon_name"]
or column("font_name")
or typeface != DEFAULT_TYPEFACE
or roundness != DEFAULT_ROUNDNESS))),
} }
def _blank() -> dict: def _blank() -> dict:
"""The factory look, as `current()` would describe it.""" """The factory look, as `current()` would describe it."""
return {"stored": {}, "tokens": dict(FACTORY), "custom_css": "", return {"stored": {}, "tokens": dict(FACTORY), "custom_css": "",
"logo_name": None, "favicon_name": None, "updated_at": None, "logo_name": None, "favicon_name": None, "font_name": None,
"published_at": None, "stamp": "0", "customised": False} "typeface": DEFAULT_TYPEFACE, "roundness": DEFAULT_ROUNDNESS,
"updated_at": None, "published_at": None, "stamp": "0",
"customised": False}
def state() -> dict: def state() -> dict:
@ -283,20 +346,74 @@ def _stamp(updated_at: str | None) -> str:
return re.sub(r"\D", "", updated_at or "") or "0" return re.sub(r"\D", "", updated_at or "") or "0"
def stylesheet(state: dict | None = None) -> str: def font_stack(state: dict) -> str | None:
"""The `:root` overrides and then the custom CSS, in that order. """The `font-family` the site should use, or None to leave it alone.
Only the tokens that differ from the factory are written, so the file reads None rather than the default string when nothing was chosen, so a site that
as what the admin changed, and an install that has changed nothing serves a has not touched this serves no font rule at all and the stylesheets stay
byte-identical to what they were.
An uploaded face is named first and the sans stack follows it: a font that
404s or arrives corrupt then leaves a readable site rather than whatever the
browser falls back to on its own.
"""
if state["typeface"] == "propia" and state["font_name"]:
return f'"VLPropia", {FONT_STACK_FALLBACK}'
if state["typeface"] in TYPEFACES and state["typeface"] != DEFAULT_TYPEFACE:
return TYPEFACES[state["typeface"]][1]
return None
def _radius_tokens(state: dict) -> dict:
"""The four radius values, or nothing when the roundness is the built-in."""
if state["roundness"] == DEFAULT_ROUNDNESS:
return {}
return ROUNDNESS[state["roundness"]][1]
def font_face(state: dict, url: str) -> str:
"""The `@font-face` for an uploaded typeface, at whatever URL serves it.
`font-display: swap` deliberately: the alternative shows nothing until the
file arrives, and a blank article on a slow phone is worse than an article
that changes typeface a moment after it appears.
"""
return ("@font-face {\n"
'\tfont-family: "VLPropia";\n'
f"\tsrc: url({url}) format('woff2');\n"
"\tfont-weight: 100 900;\n"
"\tfont-display: swap;\n"
"}\n")
def stylesheet(state: dict | None = None) -> str:
"""The `@font-face`, the `:root` overrides, then the custom CSS, in that
order.
Only what differs from the factory is written, so the file reads as what the
superadministrator changed, and an install that has changed nothing serves a
comment and no rules at all. comment and no rules at all.
""" """
state = state or current() state = state or current()
css = "/* Generado desde Gestión → Marca. No editar a mano. */\n"
if state["typeface"] == "propia" and state["font_name"]:
css += font_face(state, url_for("brand.picture",
stored_name=state["font_name"]))
lines = [f"\t--{name}: {value};" lines = [f"\t--{name}: {value};"
for name, value in state["tokens"].items() for name, value in state["tokens"].items()
if value != FACTORY[name]] if value != FACTORY[name]]
css = "/* Generado desde Gestión → Marca. No editar a mano. */\n" lines += [f"\t--{name}: {value};" for name, value in _radius_tokens(state).items()]
if lines: if lines:
css += ":root {\n" + "\n".join(lines) + "\n}\n" css += ":root {\n" + "\n".join(lines) + "\n}\n"
stack = font_stack(state)
if stack:
# On `body` rather than `:root`, because the rule it is overriding is on
# `body` and a custom property would need every rule to opt in.
css += f"body {{ font-family: {stack}; }}\n"
if state["custom_css"]: if state["custom_css"]:
# Last, so it wins over everything above it. That is the whole contract # Last, so it wins over everything above it. That is the whole contract
# of the advanced box. # of the advanced box.
@ -369,6 +486,52 @@ def _read_picture(field: str, allowed: tuple[str, ...], errors: list[str]):
return item return item
def _read_font(errors: list[str]):
"""The uploaded typeface, sniffed rather than trusted.
Not through `uploads.stage`, which knows about pictures: this needs its own
four-byte check and its own size limit. Same shape though, and the same
rule — the name on the file decides nothing.
A stored name that ends `.woff2` would not match `uploads.STORED_NAME`,
which allows three or four letters; `.wof` would be a lie. So the file is
stored as `.bin` and served with an explicit Content-Type, which is what the
browser reads anyway.
"""
upload = request.files.get("font")
if not upload or not upload.filename:
return None
data = upload.read()
if not data:
return None
if len(data) > FONT_MAX_BYTES:
errors.append(
f"La tipografía pesa {len(data) // 1024}KB y el máximo son "
f"{FONT_MAX_BYTES // 1024}KB. Subconjunta la fuente a latín y "
"latín extendido antes de subirla."
)
return None
if not data.startswith(FONT_SIGNATURE):
errors.append(
f"«{upload.filename[:60]}» no es un .woff2. Es el único formato que "
"se acepta: es el de la web, lo entienden todos los navegadores y "
"es el más pequeño."
)
return None
return {
"data": data,
"original_name": upload.filename[:200],
"stored_name": f"tipografia-{secrets.token_hex(6)}.bin",
}
def _read_choice(form, field: str, table: dict, default: str,
extra: tuple[str, ...] = ()) -> str:
"""One key from a table of our own, or the default. Never the raw value."""
choice = (form.get(field) or "").strip()
return choice if choice in table or choice in extra else default
# --- routes ---------------------------------------------------------------- # --- routes ----------------------------------------------------------------
@bp.route("/gestion/marca", methods=["GET", "POST"]) @bp.route("/gestion/marca", methods=["GET", "POST"])
@ -379,6 +542,7 @@ def edit():
return render_template("brand_form.html", state=state, return render_template("brand_form.html", state=state,
factory=FACTORY, simple=SIMPLE, factory=FACTORY, simple=SIMPLE,
derived=sorted(DERIVED), advanced=_advanced(), derived=sorted(DERIVED), advanced=_advanced(),
typefaces=TYPEFACES, roundness=ROUNDNESS,
notes=warnings(state["tokens"])) notes=warnings(state["tokens"]))
errors: list[str] = [] errors: list[str] = []
@ -386,18 +550,31 @@ def edit():
css = _read_css(request.form, errors) css = _read_css(request.form, errors)
logo = _read_picture("logo", LOGO_EXTENSIONS, errors) logo = _read_picture("logo", LOGO_EXTENSIONS, errors)
favicon = _read_picture("favicon", FAVICON_EXTENSIONS, errors) favicon = _read_picture("favicon", FAVICON_EXTENSIONS, errors)
font = _read_font(errors)
typeface = _read_choice(request.form, "typeface", TYPEFACES,
DEFAULT_TYPEFACE, extra=("propia",))
roundness = _read_choice(request.form, "roundness", ROUNDNESS, DEFAULT_ROUNDNESS)
if errors: if errors:
for message in errors: for message in errors:
flash(message, "error") flash(message, "error")
return redirect(url_for("brand.edit")) return redirect(url_for("brand.edit"))
state = current() state = current()
if typeface == "propia" and not (font or state["font_name"]):
# Chosen without ever uploading one. Refused rather than silently
# falling back, because the site would look unchanged and the setting
# would say otherwise.
flash("Para usar una tipografía propia hay que subir un archivo .woff2.",
"error")
return redirect(url_for("brand.edit"))
# Written before the commits: the members area must not depend on the git # Written before the commits: the members area must not depend on the git
# server being up to change its own colours. # server being up to change its own colours.
_store(stored, css, logo, favicon, state) _store(stored, css, logo, favicon, font, typeface, roundness, state)
for note in warnings(resolve(stored)): for note in warnings(resolve(stored)):
flash(note, "error") flash(note, "error")
activity.log("brand.saved")
if _publish(): if _publish():
flash("Guardado. El sitio público se reconstruye en un par de minutos.", "ok") flash("Guardado. El sitio público se reconstruye en un par de minutos.", "ok")
return redirect(url_for("brand.edit")) return redirect(url_for("brand.edit"))
@ -409,15 +586,19 @@ def _advanced() -> tuple:
return tuple(name for name in FACTORY if name not 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: def _store(stored: dict, css: str, logo, favicon, font, typeface: str,
"""The row, and the two pictures on disk. roundness: str, state: dict) -> None:
"""The row, and the three uploaded files on disk.
Files before the row, as `uploads.save` does it and for the same reason: a 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 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. future visit, while a file with no row is invisible.
""" """
names = {"logo_name": state["logo_name"], "favicon_name": state["favicon_name"]} names = {"logo_name": state["logo_name"],
for field, item in (("logo_name", logo), ("favicon_name", favicon)): "favicon_name": state["favicon_name"],
"font_name": state["font_name"]}
uploaded = (("logo_name", logo), ("favicon_name", favicon), ("font_name", font))
for field, item in uploaded:
if item is None: if item is None:
continue continue
uploads.directory().joinpath(item["stored_name"]).write_bytes(item["data"]) uploads.directory().joinpath(item["stored_name"]).write_bytes(item["data"])
@ -425,23 +606,28 @@ def _store(stored: dict, css: str, logo, favicon, state: dict) -> None:
get_db().execute( get_db().execute(
"""INSERT INTO brand (id, tokens_json, custom_css, logo_name, favicon_name, """INSERT INTO brand (id, tokens_json, custom_css, logo_name, favicon_name,
font_name, typeface, roundness,
updated_by, updated_at, published_at) updated_by, updated_at, published_at)
VALUES (1, ?, ?, ?, ?, ?, datetime('now'), NULL) VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), NULL)
ON CONFLICT(id) DO UPDATE SET ON CONFLICT(id) DO UPDATE SET
tokens_json = excluded.tokens_json, tokens_json = excluded.tokens_json,
custom_css = excluded.custom_css, custom_css = excluded.custom_css,
logo_name = excluded.logo_name, logo_name = excluded.logo_name,
favicon_name = excluded.favicon_name, favicon_name = excluded.favicon_name,
font_name = excluded.font_name,
typeface = excluded.typeface,
roundness = excluded.roundness,
updated_by = excluded.updated_by, updated_by = excluded.updated_by,
updated_at = excluded.updated_at, updated_at = excluded.updated_at,
published_at = NULL""", published_at = NULL""",
(json.dumps(stored, sort_keys=True), css, (json.dumps(stored, sort_keys=True), css,
names["logo_name"], names["favicon_name"], g.member["id"]), names["logo_name"], names["favicon_name"], names["font_name"],
typeface, roundness, g.member["id"]),
) )
# The old pictures, once nothing points at them. After the row, so a # The old files, once nothing points at them. After the row, so a rollback
# rollback cannot leave the row naming a file that has been deleted. # cannot leave the row naming a file that has been deleted.
for field, item in (("logo_name", logo), ("favicon_name", favicon)): for field, item in uploaded:
if item is not None and state[field] and state[field] != names[field]: if item is not None and state[field] and state[field] != names[field]:
uploads.remove(state[field]) uploads.remove(state[field])
@ -465,9 +651,10 @@ def restore():
""" """
state = current() state = current()
get_db().execute("DELETE FROM brand WHERE id = 1") get_db().execute("DELETE FROM brand WHERE id = 1")
for name in (state["logo_name"], state["favicon_name"]): for name in (state["logo_name"], state["favicon_name"], state["font_name"]):
if name: if name:
uploads.remove(name) uploads.remove(name)
activity.log("brand.restored")
flash("Restaurado lo de fábrica.", "ok") flash("Restaurado lo de fábrica.", "ok")
_publish() _publish()
return redirect(url_for("brand.edit")) return redirect(url_for("brand.edit"))
@ -498,8 +685,16 @@ def picture(stored_name: str):
if not uploads.STORED_NAME.match(stored_name): if not uploads.STORED_NAME.match(stored_name):
abort(404) abort(404)
state = current() state = current()
if stored_name not in (state["logo_name"], state["favicon_name"]): if stored_name not in (state["logo_name"], state["favicon_name"],
state["font_name"]):
abort(404) abort(404)
# The typeface is stored `.bin` — `.woff2` is five characters and
# `STORED_NAME` allows three or four — so its type is stated here rather
# than guessed from the name. A font served as application/octet-stream
# loads anyway, but says nothing true in a network panel.
if stored_name == state["font_name"]:
return send_from_directory(uploads.directory(), stored_name,
mimetype="font/woff2")
return send_from_directory(uploads.directory(), stored_name) return send_from_directory(uploads.directory(), stored_name)
@ -512,10 +707,15 @@ def _repo_path(stored_name: str, kind: str) -> str:
file instead of leaving every previous one in the repository, deployed and file instead of leaving every previous one in the repository, deployed and
unreferenced. unreferenced.
""" """
return f"{REPO_FOLDER}/{kind}.{stored_name.rsplit('.', 1)[-1]}" # The typeface is stored locally as `.bin` — see `_read_font` — but the
# repository is a web root, where the extension is what a reader's cache and
# a CDN go by. It lands as `.woff2`, which is what it is.
extension = "woff2" if kind == "font" else stored_name.rsplit(".", 1)[-1]
return f"{REPO_FOLDER}/{kind}.{extension}"
def _yaml(state: dict, logo: str | None, favicon: str | None) -> str: def _yaml(state: dict, logo: str | None, favicon: str | None,
font: str | None = None) -> str:
"""`data/brand.yaml`, written rather than dumped. """`data/brand.yaml`, written rather than dumped.
By hand because the values are known: colours matched against a hex By hand because the values are known: colours matched against a hex
@ -531,6 +731,14 @@ def _yaml(state: dict, logo: str | None, favicon: str | None) -> str:
for name, value in state["tokens"].items(): for name, value in state["tokens"].items():
if value != FACTORY[name]: if value != FACTORY[name]:
lines.append(f" {name}: \"{value}\"") lines.append(f" {name}: \"{value}\"")
for name, value in _radius_tokens(state).items():
lines.append(f" {name}: \"{value}\"")
stack = font_stack(state)
if stack:
# Single-quoted because every stack has double quotes inside it.
lines.append(f"font_stack: '{stack}'")
if font:
lines.append(f"font: \"/{font.removeprefix('static/')}\"")
if logo: if logo:
lines.append(f"logo: \"/{logo.removeprefix('static/')}\"") lines.append(f"logo: \"/{logo.removeprefix('static/')}\"")
if favicon: if favicon:
@ -561,21 +769,21 @@ def _publish() -> bool:
return False return False
try: try:
logo_path = favicon_path = None paths = {}
for kind, name in (("logo", state["logo_name"]), for kind, name in (("logo", state["logo_name"]),
("favicon", state["favicon_name"])): ("favicon", state["favicon_name"]),
("font", state["font_name"])):
if not name: if not name:
continue continue
path = _repo_path(name, kind) path = _repo_path(name, kind)
data = uploads.directory().joinpath(name).read_bytes() data = uploads.directory().joinpath(name).read_bytes()
_write(path, data, f"marca: {kind}", token) _write(path, data, f"marca: {kind}", token)
_tidy(kind, path, token) _tidy(kind, path, token)
if kind == "logo": paths[kind] = path
logo_path = path
else:
favicon_path = path
_write(DATA_FILE, _yaml(state, logo_path, favicon_path).encode("utf-8"), _write(DATA_FILE,
_yaml(state, paths.get("logo"), paths.get("favicon"),
paths.get("font")).encode("utf-8"),
"marca: colores", token) "marca: colores", token)
except (gitea.GiteaError, OSError) as exc: except (gitea.GiteaError, OSError) as exc:
current_app.logger.warning("brand publish failed: %s", exc) current_app.logger.warning("brand publish failed: %s", exc)

View File

@ -172,17 +172,22 @@ def _cache_read(path: str, sha: str):
def _cache_write(path: str, sha: str, fm: dict) -> None: def _cache_write(path: str, sha: str, fm: dict) -> None:
get_db().execute( get_db().execute(
"""INSERT INTO content_cache (path, sha, title, date, generated, """INSERT INTO content_cache (path, sha, title, date, generated, image,
event_date, event_time, event_location) event_date, event_time, event_location)
VALUES (?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(path) DO UPDATE SET ON CONFLICT(path) DO UPDATE SET
sha = excluded.sha, title = excluded.title, date = excluded.date, sha = excluded.sha, title = excluded.title, date = excluded.date,
generated = excluded.generated, generated = excluded.generated, image = excluded.image,
event_date = excluded.event_date, event_time = excluded.event_time, event_date = excluded.event_date, event_time = excluded.event_time,
event_location = excluded.event_location, event_location = excluded.event_location,
updated_at = datetime('now')""", updated_at = datetime('now')""",
(path, sha, str(fm.get("title", "")), str(fm.get("date", "")), (path, sha, str(fm.get("title", "")), str(fm.get("date", "")),
1 if fm.get("translated_from") else 0, 1 if fm.get("translated_from") else 0,
# Which picture this post carries, for the media library: without it,
# answering "does anything use this image?" means re-reading every
# post's frontmatter from the git server on every page view — the exact
# cost this cache exists to avoid.
str(fm.get("image", "") or ""),
# Cached for the private calendar, which shows public events beside the # Cached for the private calendar, which shows public events beside the
# internal ones and would otherwise read every post's frontmatter on # internal ones and would otherwise read every post's frontmatter on
# every page view to find out when they are. # every page view to find out when they are.

View File

@ -181,7 +181,8 @@ def gestion():
"SELECT COUNT(*) AS n FROM members WHERE active = 0 AND role != 'tombstone'" "SELECT COUNT(*) AS n FROM members WHERE active = 0 AND role != 'tombstone'"
).fetchone()["n"], ).fetchone()["n"],
"moderators": db.execute( "moderators": db.execute(
"SELECT COUNT(*) AS n FROM members WHERE role IN ('owner', 'admin', 'moderator')" "SELECT COUNT(*) AS n FROM members WHERE role IN "
"('superadmin', 'owner', 'admin', 'moderator')"
).fetchone()["n"], ).fetchone()["n"],
"pending": db.execute( "pending": db.execute(
"SELECT COUNT(*) AS n FROM submissions WHERE state = 'pending'").fetchone()["n"], "SELECT COUNT(*) AS n FROM submissions WHERE state = 'pending'").fetchone()["n"],

305
apps/board/identity.py Normal file
View File

@ -0,0 +1,305 @@
"""What the site is called, what it says it is, and where to find it.
Separate from `brand.py`, which is how the site *looks*, because the two have
different audiences and different failure modes: a wrong colour is ugly and a
wrong contact address is a message nobody receives. They are also published to
different files, so an organisation can change its tagline without touching its
palette.
Everything here used to live in `config.yaml`, which means it could only be
changed by somebody with the repository — the one thing this phase exists to
end. The same arrangement `brand.py` uses carries it: SQLite first for the
members area, then a commit of `data/site.yaml` for the public site, in that
order so a git outage never blocks a change that does not need git.
**Hugo cannot have `config.yaml` overridden by a data file**, so the name and
the tagline are read through `partials/site-name.html` and
`partials/site-tagline.html`, which prefer `site.Data.site` and fall back to the
config. Every template that shows either calls one of them, so the two cannot
drift — and a site with no `data/site.yaml` renders exactly what it rendered
before any of this existed.
"""
from __future__ import annotations
import json
import re
from flask import (Blueprint, current_app, flash, g, redirect,
render_template, request, url_for)
from . import activity, gitea
from .db import get_db
from .security import superadmin_required
bp = Blueprint("identity", __name__)
DATA_FILE = "data/site.yaml"
# The languages the site is built in, with the config.yaml values they fall back
# to. Written here rather than read from config.yaml because the members area
# does not parse the site's configuration — and because a fallback that silently
# follows a file somebody edits is a fallback nobody can predict.
LANGUAGES = (
("es", "Español", "Viena Latina",
"Comunidad latinoamericana en Viena — turismo, cultura, gastronomía, "
"comunidad y comercio."),
("de", "Deutsch", "Viena Latina",
"Lateinamerikanische Community in Wien — Tourismus, Kultur, Gastronomie, "
"Gemeinschaft und Handel."),
("pt-br", "Português (Brasil)", "Viena Latina",
"Comunidade latino-americana em Viena — turismo, cultura, gastronomia, "
"comunidade e comércio."),
)
# The networks offered, in the order they are drawn. A fixed list rather than a
# free "add a link" box: these become `sameAs` in the Organization schema, which
# is a claim that an account and this site are the same body — and a list of
# arbitrary URLs is not that claim, it is a bookmark bar.
NETWORKS = (
("instagram", "Instagram", "https://instagram.com/…"),
("facebook", "Facebook", "https://facebook.com/…"),
("whatsapp", "WhatsApp", "https://chat.whatsapp.com/…"),
("youtube", "YouTube", "https://youtube.com/@…"),
("mastodon", "Mastodon", "https://mastodon.social/@…"),
("bluesky", "Bluesky", "https://bsky.app/profile/…"),
)
NAME_MAX = 80
TAGLINE_MAX = 300
FOOTER_MAX = 200
# Same rule as a profile link, and for the same reason: `javascript:` in an href
# is a script running on vienalatina.com, and these are rendered in the footer of
# every page.
URL_RE = re.compile(r"^https?://[^\s<>\"']{3,300}$")
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s.]+\.[^@\s]{2,}$")
def _row():
return get_db().execute("SELECT * FROM site WHERE id = 1").fetchone()
def _loads(raw) -> dict:
try:
value = json.loads(raw or "{}")
except (TypeError, ValueError):
return {}
return value if isinstance(value, dict) else {}
def current() -> dict:
"""Everything the form and both halves of the site read.
Works with no row at all, which is every install until somebody opens the
screen — so the defaults here are the values `config.yaml` has today.
"""
row = _row()
names = _loads(row["names_json"] if row else None)
social = _loads(row["social_json"] if row else None)
languages = {}
for code, _label, name, tagline in LANGUAGES:
given = names.get(code) if isinstance(names.get(code), dict) else {}
languages[code] = {
"name": (given.get("name") or "").strip() or name,
"tagline": (given.get("tagline") or "").strip() or tagline,
# What was actually stored, for the form: a field showing the
# fallback as its value would save the fallback the first time
# anybody pressed the button, freezing it.
"stored_name": (given.get("name") or "").strip(),
"stored_tagline": (given.get("tagline") or "").strip(),
}
def column(name, default=""):
return ((row[name] if row else None) or default)
return {
"languages": languages,
"social": {key: social.get(key, "") for key, _, _ in NETWORKS},
"email": column("email"),
"phone": column("phone"),
"city": column("city"),
"street": column("street"),
"share_image": column("share_image"),
"footer_text": column("footer_text"),
"updated_at": row["updated_at"] if row else None,
"published_at": row["published_at"] if row else None,
"customised": row is not None,
}
def _read(form, errors: list[str]) -> dict:
"""The whole form, checked. Nothing here is written as it arrived."""
names = {}
for code, label, _name, _tagline in LANGUAGES:
name = (form.get(f"name-{code}") or "").strip()[:NAME_MAX]
tagline = (form.get(f"tagline-{code}") or "").strip()[:TAGLINE_MAX]
# One line, always: a tagline with a newline in it is an og:description
# that renders raggedly in some readers and truncated in others.
tagline = re.sub(r"\s+", " ", tagline)
if name or tagline:
names[code] = {"name": name, "tagline": tagline}
social = {}
for key, label, _placeholder in NETWORKS:
url = (form.get(f"social-{key}") or "").strip()
if not url:
continue
if not URL_RE.match(url):
errors.append(f"La dirección de {label} tiene que empezar por https://.")
continue
social[key] = url
email = (form.get("email") or "").strip()[:120]
if email and not EMAIL_RE.match(email):
errors.append("Ese correo de contacto no parece una dirección.")
email = ""
share = (form.get("share_image") or "").strip()
if share and not re.match(r"^/uploads/[A-Za-z0-9._-]+$", share):
errors.append("La imagen al compartir tiene que ser una de /uploads/.")
share = ""
return {
"names": names, "social": social, "email": email,
"phone": (form.get("phone") or "").strip()[:40],
"city": (form.get("city") or "").strip()[:80],
"street": (form.get("street") or "").strip()[:160],
"share_image": share,
"footer_text": (form.get("footer_text") or "").strip()[:FOOTER_MAX],
}
# --- routes ----------------------------------------------------------------
@bp.route("/gestion/identidad", methods=["GET", "POST"])
@superadmin_required
def edit():
if request.method == "GET":
return render_template("identity_form.html", state=current(),
languages=LANGUAGES, networks=NETWORKS)
errors: list[str] = []
fields = _read(request.form, errors)
if errors:
for message in errors:
flash(message, "error")
return redirect(url_for("identity.edit"))
get_db().execute(
"""INSERT INTO site (id, names_json, social_json, email, phone, city,
street, share_image, footer_text,
updated_by, updated_at, published_at)
VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), NULL)
ON CONFLICT(id) DO UPDATE SET
names_json = excluded.names_json,
social_json = excluded.social_json,
email = excluded.email, phone = excluded.phone,
city = excluded.city, street = excluded.street,
share_image = excluded.share_image,
footer_text = excluded.footer_text,
updated_by = excluded.updated_by,
updated_at = excluded.updated_at,
published_at = NULL""",
(json.dumps(fields["names"], sort_keys=True, ensure_ascii=False),
json.dumps(fields["social"], sort_keys=True), fields["email"],
fields["phone"], fields["city"], fields["street"],
fields["share_image"], fields["footer_text"], g.member["id"]),
)
activity.log("identity.saved")
if _publish():
flash("Guardado. El sitio público se reconstruye en un par de minutos.", "ok")
return redirect(url_for("identity.edit"))
@bp.route("/gestion/identidad/publicar", methods=["POST"])
@superadmin_required
def publish():
if _publish():
flash("Publicado. El sitio público se reconstruye en un par de minutos.", "ok")
return redirect(url_for("identity.edit"))
# --- the public site's copy ------------------------------------------------
def _quote(value: str) -> str:
"""A double-quoted YAML scalar. Backslashes and quotes are the only two
characters that can end one, and both are escapable inside it."""
return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"'
def yaml_for(state: dict) -> str:
"""`data/site.yaml`, written rather than dumped — the same trade `brand.py`
makes, for the same reason: PyYAML is not a dependency of the members area
and is not worth becoming one for thirty lines of output.
Only what was actually stored is written. A file repeating `config.yaml`'s
own values back at it would make the fallback meaningless and freeze the
defaults at whatever this version thought they were.
"""
lines = ["# Generado desde Gestión → Identidad en vienalatina.com/comunidad.",
"# No editar a mano: el próximo guardado lo sobrescribe."]
languages = {code: data for code, data in state["languages"].items()
if data["stored_name"] or data["stored_tagline"]}
if languages:
lines.append("languages:")
for code, data in languages.items():
lines.append(f" {code}:")
if data["stored_name"]:
lines.append(f" name: {_quote(data['stored_name'])}")
if data["stored_tagline"]:
lines.append(f" tagline: {_quote(data['stored_tagline'])}")
social = [url for url in state["social"].values() if url]
if social:
# A flat list, because `sameAs` is a list of URLs and the names of the
# networks are nowhere in the schema.
lines.append("sameAs:")
lines += [f" - {_quote(url)}" for url in social]
lines.append("social:")
for key, url in state["social"].items():
if url:
lines.append(f" {key}: {_quote(url)}")
for key in ("email", "phone", "city", "street", "share_image", "footer_text"):
if state[key]:
lines.append(f"{key}: {_quote(state[key])}")
return "\n".join(lines) + "\n"
def _publish() -> bool:
"""Commit the identity. True if it got there.
Returns False and says why rather than raising, exactly as `brand._publish`
does: the values are already saved here, and a superadministrator 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
# The contents API wants the current sha to replace a file and refuses one
# when creating, so the read comes first and a missing file is the normal
# case the first time. Same shape as `brand._write`.
try:
_, sha = gitea.read_file(DATA_FILE, token)
except gitea.GiteaError:
sha = None
try:
gitea.write_file(DATA_FILE, yaml_for(state).encode("utf-8"),
"identidad: datos del sitio", token, sha=sha)
except (gitea.GiteaError, OSError) as exc:
current_app.logger.warning("identity publish failed: %s", exc)
flash(f"Guardado aquí. El sitio público no se ha actualizado: {exc}", "error")
return False
get_db().execute("UPDATE site SET published_at = datetime('now') WHERE id = 1")
return True

104
apps/board/media.py Normal file
View File

@ -0,0 +1,104 @@
"""Biblioteca de medios — every picture the public site carries.
WordPress's Media Library, and the reason it earns a place here is narrower than
WordPress's: **nothing has ever been able to see an orphan.** A picture is
committed to `static/uploads/` when a post is written; delete the post and the
picture stays in the repository, deployed, referenced by nothing, for good.
There has been no way to list them, no way to notice, and no way to remove one
short of a commit by hand.
So this is a listing with one question answered per row — which posts use this —
and one action: delete the ones nobody uses.
**Open to administrators**, unlike the rest of Gestión's new screens. They are
the people who upload, so they are the people who should be able to see what
they have uploaded; and the worst an administrator can do here is remove a
picture from a post they could already have edited.
"""
from __future__ import annotations
from flask import (Blueprint, abort, flash, redirect, render_template, request,
url_for)
from . import activity, content, gitea
from .db import get_db
from .security import admin_required
bp = Blueprint("media", __name__)
FOLDER = content.UPLOAD_FOLDER # static/uploads
def _users() -> dict[str, list[str]]:
"""Which posts reference which picture, from the cache the listing fills.
From `content_cache.image` rather than by reading every post's frontmatter:
the whole point of that cache is that a page like this one costs one
directory request to the git server rather than one request per post.
A path appears in frontmatter as `/uploads/foto-abc.jpg`; the repository
calls it `static/uploads/foto-abc.jpg`. The basename is what both agree on.
"""
rows = get_db().execute(
"SELECT title, image FROM content_cache WHERE image IS NOT NULL AND image != ''"
).fetchall()
used: dict[str, list[str]] = {}
for row in rows:
used.setdefault(row["image"].rsplit("/", 1)[-1], []).append(row["title"])
return used
@bp.route("/gestion/medios")
@admin_required
def index():
used = _users()
try:
files = gitea.list_directory(FOLDER, gitea.content_token())
except (gitea.GiteaError, OSError) as exc:
flash(f"No se pudo leer la carpeta de imágenes: {exc}", "error")
files = []
items = []
for entry in files:
name = entry.get("name", "")
items.append({
"name": name,
"url": f"/uploads/{name}",
"sha": entry.get("sha", ""),
"size": (entry.get("size") or 0) // 1024,
"posts": used.get(name, []),
})
# Orphans first: they are the only rows anybody has to act on, and a
# listing sorted by name buries them among the ones doing their job.
items.sort(key=lambda item: (bool(item["posts"]), item["name"]))
return render_template("media.html", items=items,
orphans=sum(1 for i in items if not i["posts"]))
@bp.route("/gestion/medios/<name>/eliminar", methods=["POST"])
@admin_required
def delete(name: str):
"""Remove a picture nobody uses.
**Refuses one that is in use**, from the handler and not only by hiding the
button: deleting a referenced picture leaves a broken image on a published
page, which is worse than an orphan nobody sees.
"""
if "/" in name or name.startswith("."):
abort(404)
if _users().get(name):
flash("Esa imagen está en uso. Quítala del artículo primero.", "error")
return redirect(url_for("media.index"))
sha = (request.form.get("sha") or "").strip()
try:
gitea.delete_file(f"{FOLDER}/{name}", sha, f"medios: retirar {name}",
gitea.content_token())
except (gitea.GiteaError, OSError) as exc:
flash(f"No se pudo borrar: {exc}", "error")
return redirect(url_for("media.index"))
activity.log("media.deleted", name)
flash(f"{name} borrada. El sitio se reconstruye en un par de minutos.", "ok")
return redirect(url_for("media.index"))

View File

@ -30,7 +30,7 @@ import sqlite3
from flask import (Blueprint, Response, abort, current_app, flash, g, redirect, from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
render_template, request, url_for) render_template, request, url_for)
from . import auth, invites, mail, messages, profiles, uploads from . import activity, auth, invites, mail, messages, profiles, uploads
from .db import TOMBSTONE_LOGIN, get_db from .db import TOMBSTONE_LOGIN, get_db
from .render import to_html from .render import to_html
from .security import (admin_required, login_required, owner_required, from .security import (admin_required, login_required, owner_required,
@ -153,9 +153,15 @@ CLEARED_ON_ERASE = {
# admin who typed it in: the meeting still happens after they leave, so the # admin who typed it in: the meeting still happens after they leave, so the
# row stays and the name goes. # row stays and the name goes.
("events", "created_by"), ("events", "created_by"),
# Same for the colours and the logo. An admin leaving is not a reason for # Same for the colours and the logo. Whoever set them leaving is not a
# the site to go back to looking like a default install. # reason for the site to go back to looking like a default install.
("brand", "updated_by"), ("brand", "updated_by"),
("site", "updated_by"),
# That a role was changed is the association's record; whose name was on it
# is the erased person's data. The row stays, the name goes — which is also
# why the log is not a cascade: an audit trail that deletes itself when the
# person who triggered it leaves is not an audit trail.
("activity", "actor_id"),
} }
# Private correspondence is not reassigned to the tombstone, it goes. A thread # Private correspondence is not reassigned to the tombstone, it goes. A thread
@ -422,6 +428,8 @@ def new():
except mail.MailFailed: except mail.MailFailed:
invite_link, mail_problem = link, "failed" invite_link, mail_problem = link, "failed"
activity.log("member.created", display_name or login,
f"rol: {ROLE_LABELS[role]}")
return render_template("member_created.html", login=login, return render_template("member_created.html", login=login,
email=email, created=True, email=email, created=True,
invite_link=invite_link, mail_problem=mail_problem, invite_link=invite_link, mail_problem=mail_problem,
@ -463,6 +471,7 @@ def invite(member_id: int):
flash(f"No se pudo enviar el correo. Pásale este enlace: {link}", "error") flash(f"No se pudo enviar el correo. Pásale este enlace: {link}", "error")
return redirect(_page(target)) return redirect(_page(target))
activity.log("member.invited", target["display_name"], target["email"])
flash(f"Invitación enviada a {target['email']}.", "ok") flash(f"Invitación enviada a {target['email']}.", "ok")
return redirect(_page(target)) return redirect(_page(target))
@ -475,6 +484,8 @@ def set_active(member_id: int):
abort(403) abort(403)
active = 1 if request.form.get("active") == "1" else 0 active = 1 if request.form.get("active") == "1" else 0
get_db().execute("UPDATE members SET active = ? WHERE id = ?", (active, member_id)) get_db().execute("UPDATE members SET active = ? WHERE id = ?", (active, member_id))
activity.log("member.restored" if active else "member.suspended",
target["display_name"])
flash(f"{target['display_name']}: acceso {'restaurado' if active else 'suspendido'}.", "ok") flash(f"{target['display_name']}: acceso {'restaurado' if active else 'suspendido'}.", "ok")
return redirect(_page(target)) return redirect(_page(target))
@ -499,6 +510,8 @@ def set_role(member_id: int):
if not may_create(g.member["role"], role): if not may_create(g.member["role"], role):
abort(403) abort(403)
get_db().execute("UPDATE members SET role = ? WHERE id = ?", (role, member_id)) get_db().execute("UPDATE members SET role = ? WHERE id = ?", (role, member_id))
activity.log("role.changed", target["display_name"],
f"{ROLE_LABELS[target['role']]} → {ROLE_LABELS[role]}")
flash(f"{target['display_name']} ahora es {ROLE_LABELS[role].lower()}.", "ok") flash(f"{target['display_name']} ahora es {ROLE_LABELS[role].lower()}.", "ok")
return redirect(_page(target)) return redirect(_page(target))
@ -513,6 +526,7 @@ def transfer(member_id: int):
flash("Solo puedes nombrar responsable a un miembro activo.", "error") flash("Solo puedes nombrar responsable a un miembro activo.", "error")
return redirect(_page(target)) return redirect(_page(target))
transfer_ownership(get_db(), g.member["id"], target["id"], "owner") transfer_ownership(get_db(), g.member["id"], target["id"], "owner")
activity.log("chair.owner", target["display_name"])
flash(f"{target['display_name']} es ahora el responsable.", "ok") flash(f"{target['display_name']} es ahora el responsable.", "ok")
return redirect(_page(target)) return redirect(_page(target))
@ -532,6 +546,7 @@ def transfer_platform(member_id: int):
flash("Solo puedes entregar la plataforma a un administrador activo.", "error") flash("Solo puedes entregar la plataforma a un administrador activo.", "error")
return redirect(_page(target)) return redirect(_page(target))
transfer_ownership(get_db(), g.member["id"], target["id"], "superadmin") transfer_ownership(get_db(), g.member["id"], target["id"], "superadmin")
activity.log("chair.superadmin", target["display_name"])
flash(f"{target['display_name']} es ahora el superadministrador. " flash(f"{target['display_name']} es ahora el superadministrador. "
"Tú eres administrador.", "ok") "Tú eres administrador.", "ok")
return redirect(_page(target)) return redirect(_page(target))
@ -550,6 +565,9 @@ def erase(member_id: int):
# rows back, and nothing can put the pictures back. # rows back, and nothing can put the pictures back.
for stored_name in erase_member(get_db(), member_id): for stored_name in erase_member(get_db(), member_id):
uploads.remove(stored_name) uploads.remove(stored_name)
# After the transaction: a row recording an erasure that rolled back is a
# worse record than no row.
activity.log("member.erased", target["display_name"])
flash(f"{target['display_name']} eliminado. Sus mensajes quedan como «Miembro eliminado».", "ok") flash(f"{target['display_name']} eliminado. Sus mensajes quedan como «Miembro eliminado».", "ok")
return redirect(url_for("members.index")) return redirect(url_for("members.index"))

View File

@ -313,6 +313,31 @@ def _a_superadmin_above_the_owner(db: sqlite3.Connection) -> None:
raise RuntimeError(f"migration left dangling references: {broken}") raise RuntimeError(f"migration left dangling references: {broken}")
def _room_for_identity_and_a_typeface(db: sqlite3.Connection) -> None:
"""Columns for the style half's new settings and for the media library.
Plain ADD COLUMNs — none of these is in a CHECK, an index or a foreign key,
which is what separates this from steps 1, 4 and 7.
`content_cache.image` is what turns "which post uses this picture?" into a
query. Without it the media library would re-read every post's frontmatter
from the git server on every page view, which is the exact cost that cache
was built to avoid.
The three new tables — `activity`, `site`, and nothing else — need no step
at all: `CREATE TABLE IF NOT EXISTS` in schema.sql runs before these and
creates them on any database that lacks them.
"""
for table, columns in (("brand", ("typeface", "font_name", "roundness")),
("content_cache", ("image",))):
existing = _columns(db, table)
if not existing:
continue
for column in columns:
if column not in existing:
db.execute(f"ALTER TABLE {table} ADD COLUMN {column} TEXT")
# (number, description, function). The number is the value written to # (number, description, function). The number is the value written to
# user_version once the step succeeds. # user_version once the step succeeds.
STEPS = [ STEPS = [
@ -323,6 +348,8 @@ STEPS = [
(5, "events carry a date of their own", _rooms_for_a_date_of_its_own), (5, "events carry a date of their own", _rooms_for_a_date_of_its_own),
(6, "there are no categories any more", _no_more_categories), (6, "there are no categories any more", _no_more_categories),
(7, "a superadministrator above the responsable", _a_superadmin_above_the_owner), (7, "a superadministrator above the responsable", _a_superadmin_above_the_owner),
(8, "room for the identity, a typeface and the media library",
_room_for_identity_and_a_typeface),
] ]

View File

@ -352,9 +352,70 @@ CREATE TABLE IF NOT EXISTS brand (
custom_css TEXT NOT NULL DEFAULT '', custom_css TEXT NOT NULL DEFAULT '',
logo_name TEXT, logo_name TEXT,
favicon_name TEXT, favicon_name TEXT,
-- A key from brand.TYPEFACES, or 'propia' when `font_name` holds an uploaded
-- .woff2. Null means the one the site was built with.
typeface TEXT,
font_name TEXT,
-- A key from brand.ROUNDNESS. One setting driving four radius tokens: a site
-- whose cards are round and whose buttons are square looks like two sites.
roundness TEXT,
-- Cleared rather than reassigned when that member is erased: the colours -- Cleared rather than reassigned when that member is erased: the colours
-- belong to the association, like an event in the calendar. -- belong to the association, like an event in the calendar.
updated_by INTEGER REFERENCES members(id), updated_by INTEGER REFERENCES members(id),
updated_at TEXT NOT NULL DEFAULT (datetime('now')), updated_at TEXT NOT NULL DEFAULT (datetime('now')),
published_at TEXT published_at TEXT
); );
-- What somebody did, for the superadministrator to read.
--
-- An audit trail is the natural companion to a role that can do everything: the
-- question "who made them an administrator?" has no other answer, and asking it
-- after the fact is exactly when nobody can remember.
--
-- `actor_id` is cleared and not cascaded when that member is erased. That a
-- role was changed is the association's record; whose name was on it is the
-- erased person's data, and the two can be separated.
--
-- Deliberately not a general event store. One row per act that changes who can
-- do what, or what the public sees — not page views, not sign-ins that worked.
CREATE TABLE IF NOT EXISTS activity (
id INTEGER PRIMARY KEY,
actor_id INTEGER REFERENCES members(id),
-- A short stable key: 'role.changed', 'member.erased', 'brand.saved'. Stable
-- because it is what a later reader greps for; short because the sentence a
-- person reads is built from it in the template, not stored here in Spanish.
action TEXT NOT NULL,
-- What it was done to, as a display name or a title. A copy on purpose: the
-- row it names may be gone, and "erased Miembro eliminado" is not a record.
object TEXT NOT NULL DEFAULT '',
detail TEXT NOT NULL DEFAULT '',
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS activity_recent ON activity(created_at DESC);
-- The site's identity, as opposed to its look: what it is called, what it says
-- it is, where to find it. One row, pinned like `brand`.
--
-- Separate from `brand` because the two have different audiences and different
-- failure modes: a wrong colour is ugly, a wrong contact address is a message
-- nobody receives. They are also published to different files.
CREATE TABLE IF NOT EXISTS site (
id INTEGER PRIMARY KEY CHECK (id = 1),
-- {"es": {"name": …, "tagline": …}, "de": …}: per language, because the
-- tagline is prose and prose is not the same in three languages.
names_json TEXT NOT NULL DEFAULT '{}',
-- {"instagram": "https://…", …} → `sameAs` in the Organization schema, which
-- is how a search or answer engine knows an account and this site are one
-- body.
social_json TEXT NOT NULL DEFAULT '{}',
email TEXT NOT NULL DEFAULT '',
phone TEXT NOT NULL DEFAULT '',
city TEXT NOT NULL DEFAULT '',
street TEXT NOT NULL DEFAULT '',
share_image TEXT NOT NULL DEFAULT '',
footer_text TEXT NOT NULL DEFAULT '',
updated_by INTEGER REFERENCES members(id),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
published_at TEXT
);

View File

@ -816,3 +816,66 @@ input[type="file"] {
.btn--danger { background: var(--danger); } .btn--danger { background: var(--danger); }
.btn--danger:hover { background: var(--danger); filter: brightness(0.9); } .btn--danger:hover { background: var(--danger); filter: brightness(0.9); }
/* --- the typeface picker ------------------------------------------------ */
/* Each option shown in the face it offers. Classes rather than a style
attribute on the label, because the Content-Security-Policy has no
'unsafe-inline' and style-src falls under default-src: an inline style here
is dropped and all four options render identically, which is a picker that
tells you nothing. The stacks are the ones in brand.TYPEFACES. */
.face { font-size: 1.05rem; }
.face--sans { font-family: "Montserrat", -apple-system, BlinkMacSystemFont,
"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; }
.face--serif { font-family: Georgia, Cambria, "Times New Roman", Times, serif; }
.face--redonda { font-family: "Trebuchet MS", "Segoe UI", Verdana, sans-serif; }
.face--sistema { font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; }
/* The font warning. One line closed, which is the point: it is four paragraphs
nobody needs until the moment they are uploading a typeface. */
.brand-warning {
margin: 0.75rem 0 1.5rem;
border: 1px solid var(--border-light);
border-radius: var(--radius-md);
padding: 0.6rem 0.9rem;
background: var(--surface-soft);
}
.brand-warning summary { cursor: pointer; font-weight: 600; font-size: 0.9rem; }
.brand-warning p { font-size: 0.9rem; color: var(--muted); margin: 0.75rem 0 0; }
.brand-warning p:last-child { margin-bottom: 0.25rem; }
/* --- the media library -------------------------------------------------- */
.media-grid {
list-style: none;
margin: 1rem 0 0;
padding: 0;
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 1rem;
}
.media-item {
background: var(--surface);
border: 1px solid var(--border-light);
border-radius: var(--radius-lg);
padding: 0.75rem;
}
/* Orphans are the only rows anybody has to act on, so they say so twice: first
in the order (they sort to the top) and then in the colour. */
.media-item--orphan { border-color: var(--brand); background: var(--brand-softer); }
.media-item img {
display: block;
width: 100%;
height: 120px;
object-fit: cover;
border-radius: var(--radius-md);
background: var(--surface-soft);
}
.media-item p { margin: 0.4rem 0 0; word-break: break-all; }
.media-item form { margin-top: 0.5rem; }
/* --- the status screen -------------------------------------------------- */
.tag--ok { background: #e4f2e4; color: #1b5e20; }
.tag--warn { background: var(--brand-soft); color: var(--brand-dark); }
.tag--bad { background: #f6dcdc; color: var(--danger); }

191
apps/board/status.py Normal file
View File

@ -0,0 +1,191 @@
"""Estado del sistema — what is actually true of this server right now.
WordPress calls it Site Health. It earns its place here for a specific reason:
**every outage in this project has been a configuration fact that was invisible
until somebody hit it.** A `CONTENT_TOKEN` with the wrong scope looked exactly
like a working one until an editor pressed save and got a 500. Mail was
unconfigured for a week while invitations were "sent". The settings were right
in `.env.example` and absent from the container.
So this page asks the questions nobody thinks to ask, and asks them of the
running system rather than of a file:
* the content token is **exercised**, not merely checked for emptiness — the
single most valuable line here, because "present" was never the problem
* the mail host is resolved and connected to
* the newest backup, with its age and size
* free disk, which is the one that ends everything at once
* every setting `.env.example` documents that the container does not have
**It changes nothing.** No buttons, no fixes, no restarts — a page that answers
questions. That is deliberate: a diagnostic screen that can also act is a screen
somebody uses to act without reading, and the actions here are the ones with the
longest reach on the box.
"""
from __future__ import annotations
import os
import shutil
import smtplib
import socket
from datetime import datetime, timezone
from pathlib import Path
from flask import Blueprint, current_app, render_template
from . import gitea, mail, uploads
from .db import get_db
from .security import superadmin_required
bp = Blueprint("status", __name__)
# Where deploy-board.sh puts them. Read-only, and missing is an answer.
BACKUP_DIR = "/srv/board/backups"
# Settings whose absence turns a feature off rather than breaking the app. The
# names are the ones in infra/board/.env.example; the sentence is what stops
# working. Checked against os.environ because the container cannot read
# /srv/board/.env — compose substitutes it in and the file never arrives.
EXPECTED = (
("BOARD_SECRET_KEY", "las sesiones (sin esto la app no arranca)"),
("CONTENT_TOKEN", "publicar en el sitio: el editor y la marca"),
("MAIL_HOST", "invitaciones y recuperar contraseña"),
("MAIL_USER", "autenticarse en el servidor de correo"),
("MAIL_PASSWORD", "autenticarse en el servidor de correo"),
("BOARD_OWNER", "sembrar al superadministrador en el primer arranque"),
("GITEA_URL", "hablar con el servidor de git"),
("CONTENT_REPO", "saber en qué repositorio se publica"),
)
def _ok(label, detail=""):
return {"state": "ok", "label": label, "detail": detail}
def _warn(label, detail=""):
return {"state": "warn", "label": label, "detail": detail}
def _bad(label, detail=""):
return {"state": "bad", "label": label, "detail": detail}
def _content_token() -> dict:
"""Not "is it set" — "does it work".
A token with `admin` scope and no `repository` scope is present, non-empty,
and cannot write a single file; that exact configuration broke publishing
for three phases while every check anybody thought to run said it was fine.
So this one reads the content directory through the API and reports what
came back.
"""
try:
token = gitea.content_token()
except gitea.GiteaError as exc:
return _bad("No hay token para publicar", str(exc))
which = "CONTENT_TOKEN" if os.environ.get("CONTENT_TOKEN") else "GITEA_ADMIN_TOKEN"
try:
gitea.list_directory("content/post", token)
except gitea.GiteaError as exc:
return _bad(f"El token ({which}) no puede leer el repositorio", str(exc))
except OSError as exc:
return _warn("No se pudo contactar con el servidor de git", str(exc))
if which == "GITEA_ADMIN_TOKEN":
return _warn(
"Publicando con el token de administración",
"Funciona, pero ese token puede modificar cualquier cuenta del "
"servidor de git. Crea uno con permiso de repositorio y ponlo en "
"CONTENT_TOKEN.")
return _ok("El token de publicación funciona", f"{which}, con acceso de lectura")
def _mail() -> dict:
if not mail.configured():
return _warn("Sin correo saliente",
"Nadie puede ser invitado ni recuperar su contraseña.")
host = current_app.config["MAIL_HOST"]
port = int(current_app.config["MAIL_PORT"] or 587)
try:
with smtplib.SMTP(host, port, timeout=5) as server:
server.ehlo()
except (OSError, smtplib.SMTPException) as exc:
return _bad(f"{host}:{port} no responde", str(exc))
return _ok(f"{host}:{port} responde", "La conexión se abre; no se envía nada.")
def _backups() -> dict:
folder = Path(BACKUP_DIR)
if not folder.is_dir():
return _warn("No hay carpeta de copias", f"{BACKUP_DIR} no existe.")
files = sorted(folder.glob("board-*.db.gz"), key=lambda f: f.stat().st_mtime)
if not files:
return _bad("Ninguna copia de seguridad", f"{BACKUP_DIR} está vacía.")
newest = files[-1]
age = datetime.now(timezone.utc) - datetime.fromtimestamp(
newest.stat().st_mtime, timezone.utc)
size = newest.stat().st_size // 1024
detail = f"{newest.name}, {size} KB, {len(files)} en total"
if age.days >= 2:
return _warn(f"La copia más reciente tiene {age.days} días", detail)
return _ok("Copia reciente", detail)
def _disk() -> dict:
"""The one that ends everything at once, and silently: SQLite cannot write,
uploads fail, and the log that would say so cannot be written either."""
# Through `uploads.directory()`, which creates it: asking statvfs about a
# path that does not exist raises, and "the uploads folder has not been made
# yet" is not a disk problem.
usage = shutil.disk_usage(uploads.directory())
free_mb = usage.free // (1024 * 1024)
detail = f"{free_mb} MB libres de {usage.total // (1024 * 1024)} MB"
if free_mb < 200:
return _bad("Queda muy poco disco", detail)
if free_mb < 1000:
return _warn("Queda poco disco", detail)
return _ok("Disco suficiente", detail)
def _settings() -> dict:
missing = [(name, why) for name, why in EXPECTED if not os.environ.get(name)]
if not missing:
return _ok("Todos los ajustes esperados están puestos")
return _warn(
f"{len(missing)} ajuste{'s' if len(missing) > 1 else ''} sin poner",
"; ".join(f"{name} — {why}" for name, why in missing))
def _counts() -> dict:
db = get_db()
one = lambda sql: db.execute(sql).fetchone()[0] # noqa: E731
return {
"members": one("SELECT COUNT(*) FROM members WHERE role != 'tombstone'"),
"admins": one("SELECT COUNT(*) FROM members WHERE role IN "
"('superadmin', 'owner', 'admin', 'moderator')"),
# `role != 'tombstone'` because the row erased members are reassigned
# to is inactive by construction and is not a suspended person.
"suspended": one("SELECT COUNT(*) FROM members "
"WHERE active = 0 AND role != 'tombstone'"),
"threads": one("SELECT COUNT(*) FROM threads WHERE deleted_at IS NULL"),
"pending": one("SELECT COUNT(*) FROM submissions WHERE state = 'pending'"),
"events": one("SELECT COUNT(*) FROM events"),
"posts": one("SELECT COUNT(*) FROM content_cache WHERE generated = 0"),
}
@bp.route("/gestion/estado")
@superadmin_required
def index():
checks = [
("Publicar en el sitio", _content_token()),
("Correo saliente", _mail()),
("Copias de seguridad", _backups()),
("Disco", _disk()),
("Ajustes del contenedor", _settings()),
]
return render_template("status.html", checks=checks, counts=_counts(),
worst=min((c[1]["state"] for c in checks),
key=["bad", "warn", "ok"].index))

View File

@ -30,7 +30,7 @@ from datetime import date as date_type
from flask import (Blueprint, abort, current_app, flash, g, redirect, from flask import (Blueprint, abort, current_app, flash, g, redirect,
render_template, request, send_from_directory, url_for) render_template, request, send_from_directory, url_for)
from . import content, gitea, uploads from . import activity, content, gitea, uploads
from .db import get_db from .db import get_db
from .render import excerpt, to_html from .render import excerpt, to_html
from .security import is_at_least, login_required, moderator_required from .security import is_at_least, login_required, moderator_required
@ -360,6 +360,7 @@ def approve(submission_id: int):
# in one place, and no orphan in /data/uploads that nothing will ever serve. # in one place, and no orphan in /data/uploads that nothing will ever serve.
if row["photo_name"]: if row["photo_name"]:
uploads.remove(row["photo_name"]) uploads.remove(row["photo_name"])
activity.log("submission.approved", row["title"], f"de {row['author']}")
flash(f"Publicado «{row['title']}». La traducción tarda un par de minutos.", "ok") flash(f"Publicado «{row['title']}». La traducción tarda un par de minutos.", "ok")
return redirect(url_for("submissions.index")) return redirect(url_for("submissions.index"))
@ -387,6 +388,7 @@ def reject(submission_id: int):
WHERE id = ?""", WHERE id = ?""",
(note, g.member["id"], submission_id), (note, g.member["id"], submission_id),
) )
activity.log("submission.rejected", row["title"], f"de {row['author']}")
flash("Devuelto al autor con tu motivo.", "ok") flash("Devuelto al autor con tu motivo.", "ok")
return redirect(url_for("submissions.index")) return redirect(url_for("submissions.index"))

View File

@ -0,0 +1,51 @@
{# Gestión → Registro de actividad. Read-only by construction: there is nothing
here to press, because an audit trail you can edit is not one. #}
{% extends "base.html" %}
{% block title %}Registro{% endblock %}
{% block main %}
<div class="feed-head">
<h1>Registro de actividad</h1>
<a class="linkish" href="{{ url_for('home.gestion') }}">Volver a Gestión</a>
</div>
<p class="muted">
Lo que se ha hecho que cambia quién puede hacer qué, o qué ve el público. No
están las visitas ni los inicios de sesión correctos: un registro que lo
apunta todo es un registro que nadie lee.
</p>
{% if not rows %}
<p class="muted">Todavía no hay nada apuntado.</p>
{% else %}
<table class="table">
<thead><tr><th>Cuándo</th><th>Quién</th><th>Qué</th></tr></thead>
<tbody>
{% for row in rows %}
<tr>
<td class="mono small">{{ row.at }}</td>
<td>
{# A name that is simply gone, rather than a tombstone: the row stays
when somebody is erased and the name does not, which is the whole
arrangement. #}
{{ row.actor or 'Alguien que ya no está' }}
</td>
<td>
{{ row.sentence }}
{% if row.detail %}<span class="muted small"> · {{ row.detail }}</span>{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="actions">
{% if page > 0 %}
<a class="linkish" href="{{ url_for('activity.index', p=page - 1) }}">← Más reciente</a>
{% endif %}
{% if more %}
<a class="linkish" href="{{ url_for('activity.index', p=page + 1) }}">Más antiguo →</a>
{% endif %}
</div>
{% endif %}
{% endblock %}

View File

@ -80,7 +80,7 @@
<a href="{{ url_for('submissions.index') }}">Publicaciones{% set waiting = pending_review() %}{% if waiting %} <span class="tag">{{ waiting }}</span>{% endif %}</a> <a href="{{ url_for('submissions.index') }}">Publicaciones{% set waiting = pending_review() %}{% if waiting %} <span class="tag">{{ waiting }}</span>{% endif %}</a>
</li> </li>
<li><a href="{{ url_for('events.month') }}">Calendario</a></li> <li><a href="{{ url_for('events.month') }}">Calendario</a></li>
{% if g.member.role in ('owner', 'admin') %} {% if is_at_least(g.member.role, 'admin') %}
<li><a href="{{ url_for('home.gestion') }}">Gestión</a></li> <li><a href="{{ url_for('home.gestion') }}">Gestión</a></li>
{% endif %} {% endif %}
</ul> </ul>

View File

@ -108,6 +108,97 @@
{% endif %} {% endif %}
<input id="favicon" name="favicon" type="file" accept="image/png"> <input id="favicon" name="favicon" type="file" accept="image/png">
<h2 class="section-title">Tipografía</h2>
<p class="muted small">
Las cuatro primeras ya están en el ordenador de quien lee: no se descarga
nada de ningún sitio. Eso es a propósito — una hoja de estilos que pide una
fuente a Google le cuenta a Google la dirección IP de todo el que entra, y
eso no se puede consentir en nombre de quien visita la página.
</p>
<div class="choices">
{% for key, (label, stack) in typefaces.items() %}
<label class="choice">
<input type="radio" name="typeface" value="{{ key }}"
{{ 'checked' if state.typeface == key }}>
{# The class, not a style attribute: `default-src 'self'` covers
style-src, so an inline style on this label would be dropped and
every option would look identical. The four classes are in
board.css beside the form rules. #}
<span class="face face--{{ key }}">{{ label }}</span>
</label>
{% endfor %}
<label class="choice">
<input type="radio" name="typeface" value="propia"
{{ 'checked' if state.typeface == 'propia' }}>
Propia (subida aquí)
</label>
</div>
{% if state.font_name %}
<p class="muted small">Ya hay una tipografía subida. Si eliges otra, la sustituye.</p>
{% endif %}
<label for="font">Archivo .woff2 <span class="muted small">(sólo para «Propia»)</span></label>
<input id="font" name="font" type="file" accept=".woff2,font/woff2">
{# Closed by default and one line tall, as asked. Everything in it is a way
this goes wrong in practice rather than in theory. #}
<details class="brand-warning">
<summary>Antes de subir una tipografía, lee esto</summary>
<p><strong>Lo que hace una fuente mala.</strong> Una tipografía sin
<span class="mono">ñ á ü ç ã</span> dibuja esas letras con otra distinta, así
que el español y el portugués salen visiblemente remendados — y nadie te
avisa. Un archivo de 2 MB retrasa cada página en un móvil. Una fuente de
titulares puesta a 16px no se lee.</p>
<p><strong>Cómo hacerlo bien.</strong> Sube un solo archivo, el peso normal:
la negrita y la cursiva las fabrica el navegador a partir de él, lo cual
está bien para un sitio con logotipo y mal para textos largos. Subconjunta
la fuente a latín y latín extendido-A. Que no pase de unos 100 KB. Sólo
<span class="mono">.woff2</span>: es el formato de la web, lo entienden
todos los navegadores y es el que este formulario comprueba por su firma,
no por el nombre del archivo. Antes de guardar, mira cómo quedan
<span class="mono">ñ á ü ç ã</span> en la vista previa de arriba.</p>
<p><strong>La licencia, que es lo único de aquí que cuesta dinero.</strong>
Una tipografía es software, y una licencia de escritorio no es una licencia
web: servir desde tu propio servidor una fuente que compraste para el
ordenador suele incumplirla, y esa responsabilidad viaja con la plataforma
a cada organización donde la instales. Busca
<strong>SIL OFL</strong> o <strong>Apache 2.0</strong>: las dos permiten
alojarla uno mismo y redistribuirla.</p>
<p><strong>Dónde buscarlas sin riesgo.</strong>
<a href="https://fonts.google.com/" rel="nofollow noopener">Google Fonts</a>
(descargándolas, no enlazándolas, por lo del párrafo primero),
<a href="https://fontsource.org/" rel="nofollow noopener">Fontsource</a>
(las mismas familias ya empaquetadas en <span class="mono">.woff2</span>),
<a href="https://www.fontsquirrel.com/" rel="nofollow noopener">Font Squirrel</a>,
<a href="https://www.theleagueofmoveabletype.com/" rel="nofollow noopener">The League of Moveable Type</a>,
<a href="https://velvetyne.fr/" rel="nofollow noopener">Velvetyne</a>,
<a href="https://open-foundry.com/" rel="nofollow noopener">Open Foundry</a> y
<a href="https://usemodify.com/" rel="nofollow noopener">Use &amp; Modify</a>.
Comprueba la licencia del archivo que te has descargado, no la de la página
desde la que llegaste a él.</p>
</details>
<h2 class="section-title">Esquinas</h2>
<p class="muted small">
Lo redondeadas que son las tarjetas, los botones y las fotos. Un solo ajuste
para todo: un sitio con tarjetas redondas y botones cuadrados parece dos
sitios.
</p>
<div class="choices">
{% for key, (label, values) in roundness.items() %}
<label class="choice">
<input type="radio" name="roundness" value="{{ key }}"
{{ 'checked' if state.roundness == key }}>
{{ label }}
</label>
{% endfor %}
</div>
<details class="brand-advanced"> <details class="brand-advanced">
<summary>Avanzado</summary> <summary>Avanzado</summary>

View File

@ -53,6 +53,17 @@
</p> </p>
</section> </section>
<section class="panel">
<div class="panel__head">
<h2>Biblioteca de medios</h2>
<a class="linkish" href="{{ url_for('media.index') }}">Abrir</a>
</div>
<p class="muted small">
Todas las imágenes del sitio público y qué artículo usa cada una. Las que
no usa nadie —de artículos que se borraron— se pueden quitar desde ahí.
</p>
</section>
{% if g.member.role == 'superadmin' %} {% if g.member.role == 'superadmin' %}
<section class="panel"> <section class="panel">
<div class="panel__head"> <div class="panel__head">
@ -68,6 +79,42 @@
volver a lo de fábrica. volver a lo de fábrica.
</p> </p>
</section> </section>
<section class="panel">
<div class="panel__head">
<h2>Identidad</h2>
<a class="linkish" href="{{ url_for('identity.edit') }}">Abrir</a>
</div>
{% set site = identity() %}{% if site.updated_at and not site.published_at %}
<p class="panel__row">Hay cambios guardados que no han llegado al sitio público.</p>
{% endif %}
<p class="muted small">
El nombre y el lema en los tres idiomas, los perfiles de la asociación en
otros sitios, el contacto y el pie de página.
</p>
</section>
<section class="panel">
<div class="panel__head">
<h2>Estado del sistema</h2>
<a class="linkish" href="{{ url_for('status.index') }}">Abrir</a>
</div>
<p class="muted small">
Si el token para publicar funciona de verdad, si el correo sale, cuándo fue
la última copia de seguridad y cuánto disco queda. No cambia nada: responde.
</p>
</section>
<section class="panel">
<div class="panel__head">
<h2>Registro de actividad</h2>
<a class="linkish" href="{{ url_for('activity.index') }}">Abrir</a>
</div>
<p class="muted small">
Quién cambió un rol, aprobó una publicación, tocó el aspecto del sitio o
eliminó a alguien.
</p>
</section>
{% endif %} {% endif %}
{% if counts.pending %} {% if counts.pending %}

View File

@ -0,0 +1,112 @@
{# Gestión → Identidad: what the site is called and where to find it.
Everything here used to be in config.yaml, which meant it could only be
changed by somebody with the repository. The fields show their current value
as a placeholder rather than as a value, deliberately: a form prefilled with
the fallback saves the fallback the first time anybody presses the button,
and the default is frozen from then on. #}
{% extends "base.html" %}
{% block title %}Identidad{% endblock %}
{% block main %}
<div class="feed-head">
<h1>Identidad</h1>
<a class="linkish" href="{{ url_for('home.gestion') }}">Volver a Gestión</a>
</div>
<p class="muted">
Cómo se llama el sitio, qué dice que es y dónde encontrarlo. Lo de aquí
alimenta también los datos estructurados: es lo que lee un buscador —o una IA
que responde preguntas— para saber que esta asociación y esas cuentas son el
mismo cuerpo.
</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">
Guardado aquí, 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('identity.publish') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<button class="btn" type="submit">Reintentar publicar</button>
</form>
</section>
{% endif %}
<form class="card" method="post" action="{{ url_for('identity.edit') }}">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<h2 class="section-title">Nombre y lema</h2>
<p class="muted small">
Uno por idioma. El lema es la frase que sale al compartir un enlace, la que
describe al sitio en los buscadores y la primera línea de
<span class="mono">llms.txt</span>. Déjalo vacío para no cambiar lo que hay.
</p>
{% for code, label, _name, _tagline in languages %}
<fieldset class="fieldset">
<legend>{{ label }}</legend>
<label for="name-{{ code }}">Nombre</label>
<input id="name-{{ code }}" name="name-{{ code }}" type="text" maxlength="80"
value="{{ state.languages[code].stored_name }}"
placeholder="{{ state.languages[code].name }}">
<label for="tagline-{{ code }}">Lema</label>
<textarea id="tagline-{{ code }}" name="tagline-{{ code }}" rows="2"
maxlength="300"
placeholder="{{ state.languages[code].tagline }}">{{ state.languages[code].stored_tagline }}</textarea>
</fieldset>
{% endfor %}
<h2 class="section-title">Perfiles</h2>
<p class="muted small">
Las cuentas de la asociación en otros sitios. Salen en el pie de página y
como <span class="mono">sameAs</span> en los datos estructurados, que es
como un buscador sabe que esa cuenta de Instagram y esta web son lo mismo.
</p>
{% for key, label, placeholder in networks %}
<label for="social-{{ key }}">{{ label }}</label>
<input id="social-{{ key }}" name="social-{{ key }}" type="url" maxlength="300"
value="{{ state.social[key] }}" placeholder="{{ placeholder }}">
{% endfor %}
<h2 class="section-title">Contacto y lugar</h2>
<p class="muted small">
Público, y pensado para que lo lea una persona tanto como un buscador: una
dirección y una ciudad son lo que pone a una asociación en un resultado
local y no sólo en uno web.
</p>
<label for="email">Correo público</label>
<input id="email" name="email" type="email" maxlength="120" value="{{ state.email }}"
placeholder="hola@vienalatina.com">
<label for="phone">Teléfono <span class="muted small">(opcional)</span></label>
<input id="phone" name="phone" type="text" maxlength="40" value="{{ state.phone }}">
<label for="city">Ciudad</label>
<input id="city" name="city" type="text" maxlength="80" value="{{ state.city }}"
placeholder="Wien">
<label for="street">Calle <span class="muted small">(opcional)</span></label>
<input id="street" name="street" type="text" maxlength="160" value="{{ state.street }}">
<h2 class="section-title">Al compartir, y el pie</h2>
<label for="share_image">Imagen por defecto <span class="muted small">(opcional)</span></label>
<input id="share_image" name="share_image" type="text" maxlength="200"
value="{{ state.share_image }}" placeholder="/uploads/algo.png">
<p class="muted small">
La que sale al compartir un artículo que no tiene foto propia. Si la dejas
vacía se usa el logotipo, que casi siempre es lo que quieres: esto es para
cuando prefieres otra cosa —una foto de la ciudad, por ejemplo.
</p>
<label for="footer_text">Texto del pie <span class="muted small">(opcional)</span></label>
<input id="footer_text" name="footer_text" type="text" maxlength="200"
value="{{ state.footer_text }}">
<p class="muted small">Si lo dejas vacío, el pie pone el nombre y el año.</p>
<button class="btn" type="submit">Guardar</button>
</form>
{% endblock %}

View File

@ -0,0 +1,47 @@
{# Gestión → Biblioteca de medios.
Orphans first, because they are the only rows anybody has to act on: a
listing sorted by name buries them among the pictures doing their job, which
is how they went unnoticed for the life of the site. #}
{% extends "base.html" %}
{% block title %}Medios{% endblock %}
{% block main %}
<div class="feed-head">
<h1>Biblioteca de medios</h1>
<a class="linkish" href="{{ url_for('home.gestion') }}">Volver a Gestión</a>
</div>
<p class="muted">
Todas las imágenes que lleva el sitio público, y qué artículo usa cada una.
{% if orphans %}
<strong>{{ orphans }} no la usa nadie</strong>: se subieron con un artículo que
luego se borró, y siguen ahí ocupando sitio.
{% endif %}
</p>
{% if not items %}
<p class="muted">No hay imágenes todavía.</p>
{% else %}
<ul class="media-grid">
{% for item in items %}
<li class="media-item {{ 'media-item--orphan' if not item.posts }}">
<img src="{{ item.url }}" alt="" loading="lazy">
<p class="mono small">{{ item.name }}</p>
<p class="muted small">{{ item.size }} KB</p>
{% if item.posts %}
<p class="muted small">{{ item.posts|join(', ') }}</p>
{% else %}
<p class="muted small">No la usa ningún artículo.</p>
<form method="post" action="{{ url_for('media.delete', name=item.name) }}"
data-confirm="Se borrará {{ item.name }} del repositorio. ¿Seguro?">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<input type="hidden" name="sha" value="{{ item.sha }}">
<button class="linkish linkish--danger" type="submit">Borrar</button>
</form>
{% endif %}
</li>
{% endfor %}
</ul>
{% endif %}
{% endblock %}

View File

@ -19,7 +19,7 @@
cannot offer a role that comes back 403. #} cannot offer a role that comes back 403. #}
{% set is_super = me.role == 'superadmin' %} {% set is_super = me.role == 'superadmin' %}
{% set is_chair = me.role in ('superadmin', 'owner') %} {% set is_chair = me.role in ('superadmin', 'owner') %}
{% set is_admin = me.role in ('superadmin', 'owner', 'admin') %} {% set is_admin = is_at_least(me.role, 'admin') %}
{% set can_assign = assignable_roles(me.role) %} {% set can_assign = assignable_roles(me.role) %}
{% block main %} {% block main %}

View File

@ -2,7 +2,7 @@
{% block title %}Miembros{% endblock %} {% block title %}Miembros{% endblock %}
{% set me = g.member %} {% set me = g.member %}
{% set is_admin = me.role in ('owner', 'admin') %} {% set is_admin = is_at_least(me.role, 'admin') %}
{% block main %} {% block main %}
<div class="feed-head"> <div class="feed-head">

View File

@ -0,0 +1,49 @@
{# Gestión → Estado del sistema.
Nothing on this page changes anything, deliberately: a diagnostic screen that
can also act is a screen somebody uses to act without reading, and the actions
it would offer are the ones with the longest reach on this box. #}
{% extends "base.html" %}
{% block title %}Estado{% endblock %}
{% block main %}
<div class="feed-head">
<h1>Estado del sistema</h1>
<a class="linkish" href="{{ url_for('home.gestion') }}">Volver a Gestión</a>
</div>
<p class="muted">
Lo que es verdad del servidor ahora mismo, preguntado al sistema y no a un
archivo. Esta página no cambia nada: sólo responde.
</p>
{% if worst == 'ok' %}
<p class="flash flash--ok">Todo responde.</p>
{% endif %}
{% for title, check in checks %}
<section class="panel panel--{{ 'attention' if check.state != 'ok' }}">
<div class="panel__head">
<h2>{{ title }}</h2>
<span class="tag tag--{{ check.state }}">
{{ {'ok': 'Bien', 'warn': 'Atención', 'bad': 'Mal'}[check.state] }}
</span>
</div>
<p class="panel__row">{{ check.label }}</p>
{% if check.detail %}<p class="muted small">{{ check.detail }}</p>{% endif %}
</section>
{% endfor %}
<section class="panel">
<div class="panel__head"><h2>Cuántas cosas hay</h2></div>
<p class="panel__row">
{{ counts.members }} miembros · {{ counts.admins }} con algún cargo
{% if counts.suspended %} · {{ counts.suspended }} suspendido{{ '' if counts.suspended == 1 else 's' }}{% endif %}
</p>
<p class="panel__row">
{{ counts.posts }} artículos publicados · {{ counts.threads }} hilos en el muro ·
{{ counts.events }} eventos en el calendario
{% if counts.pending %} · {{ counts.pending }} propuesta{{ '' if counts.pending == 1 else 's' }} esperando{% endif %}
</p>
</section>
{% endblock %}

View File

@ -393,3 +393,116 @@ def test_erasing_whoever_set_the_brand_leaves_it_standing(client, db, post, admi
row = db.execute("SELECT tokens_json, updated_by FROM brand").fetchone() row = db.execute("SELECT tokens_json, updated_by FROM brand").fetchone()
assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"} assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"}
assert row["updated_by"] is None assert row["updated_by"] is None
# --- the typeface and the corners -----------------------------------------
WOFF2 = b"wOF2" + b"\x00" * 200
TTF = b"\x00\x01\x00\x00" + b"\x00" * 200
def test_a_preset_typeface_reaches_the_stylesheet(client, post, admin):
save(post, typeface="serif")
css = client.get("/comunidad/marca.css").get_data(as_text=True)
assert "body { font-family: Georgia" in css
assert "@font-face" not in css # nothing is downloaded for a preset
def test_the_default_typeface_writes_no_rule_at_all(client, post, admin):
"""An install that has not touched this serves what it always served."""
save(post, typeface="sans")
css = client.get("/comunidad/marca.css").get_data(as_text=True)
assert "font-family" not in css
def test_a_font_that_is_not_a_woff2_is_refused(client, db, post, admin):
"""By its signature, not its name — the same rule every other upload here
follows. A .ttf renders fine in a browser and is two to five times the size
for the same letters."""
response = save(post, typeface="propia", font=(io.BytesIO(TTF), "bonita.woff2"),
content_type="multipart/form-data", follow_redirects=True)
assert "no es un .woff2" in response.get_data(as_text=True)
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
def test_an_enormous_font_is_refused(client, db, post, admin):
big = b"wOF2" + b"\x00" * 500_000
response = save(post, typeface="propia", font=(io.BytesIO(big), "gorda.woff2"),
content_type="multipart/form-data", follow_redirects=True)
assert "Subconjunta" in response.get_data(as_text=True)
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
def test_choosing_propia_without_a_file_is_refused(client, db, post, admin):
"""Rather than falling back silently: the site would look unchanged and the
setting would say otherwise."""
response = save(post, typeface="propia", follow_redirects=True)
assert "hay que subir un archivo" in response.get_data(as_text=True)
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
def test_an_uploaded_font_is_declared_served_and_falls_back(client, db, post, admin):
save(post, typeface="propia", font=(io.BytesIO(WOFF2), "bonita.woff2"),
content_type="multipart/form-data")
name = db.execute("SELECT font_name FROM brand").fetchone()["font_name"]
css = client.get("/comunidad/marca.css").get_data(as_text=True)
assert "@font-face" in css and name in css
# Named first, with the old stack behind it: a font that 404s or arrives
# corrupt must leave a readable site, not a browser default.
assert 'body { font-family: "VLPropia", "Montserrat"' in css
served = client.get(f"/comunidad/marca/{name}")
assert served.status_code == 200
assert served.mimetype == "font/woff2"
def test_roundness_writes_the_four_radius_tokens(client, post, admin):
save(post, roundness="recta")
css = client.get("/comunidad/marca.css").get_data(as_text=True)
for token in ("--radius-xl", "--radius-lg", "--radius-md", "--radius-sm"):
assert f"{token}: 0;" in css, token
def test_a_made_up_choice_falls_back_rather_than_being_stored(client, db, post, admin):
"""Both pickers read a key from a table in this module, never the value that
arrived."""
save(post, typeface="../../etc/passwd", roundness="DROP TABLE brand")
row = db.execute("SELECT typeface, roundness FROM brand").fetchone()
assert (row["typeface"], row["roundness"]) == ("sans", "suave")
def test_restoring_takes_the_font_with_it(app, client, db, post, admin):
save(post, typeface="propia", font=(io.BytesIO(WOFF2), "bonita.woff2"),
content_type="multipart/form-data")
name = db.execute("SELECT font_name FROM brand").fetchone()["font_name"]
post("/comunidad/gestion/marca/restaurar")
with app.app_context():
from apps.board import uploads
assert not uploads.directory().joinpath(name).exists()
assert "font-family" not in client.get("/comunidad/marca.css").get_data(as_text=True)
def test_the_font_and_the_radii_reach_the_public_site(db, post, admin, repo):
save(post, typeface="propia", roundness="redonda",
font=(io.BytesIO(WOFF2), "bonita.woff2"),
content_type="multipart/form-data")
assert "static/brand/font.woff2" in repo.files
yaml = repo.files["data/brand.yaml"].decode("utf-8")
assert 'font: "/brand/font.woff2"' in yaml
assert "font_stack: '\"VLPropia\"" in yaml
assert ' radius-xl: "28px"' in yaml

View File

@ -217,3 +217,40 @@ def test_signing_in_sets_the_hint_and_signing_out_clears_it(client, db, post, ma
signed_out = post("/comunidad/logout") signed_out = post("/comunidad/logout")
assert any("vl_sesion=;" in header or "vl_sesion=\"\"" in header assert any("vl_sesion=;" in header or "vl_sesion=\"\"" in header
for header in signed_out.headers.get_all("Set-Cookie")) for header in signed_out.headers.get_all("Set-Cookie"))
# --- the tier above admin -------------------------------------------------
def test_the_superadmin_sees_gestion(nav, superadmin_id):
"""The regression this file exists for, one tier higher.
`base.html` asked `g.member.role in ('owner', 'admin')`, which was right
until a role appeared above both — and then Gestión vanished from the
navigation of the one account that owns every screen on it. 622 tests
passed while it was broken, because every one of them signed in as an
admin or below.
"""
body = nav(superadmin_id)
assert "Gestión" in body
assert "/comunidad/gestion" in body
@pytest.mark.parametrize("role", ["superadmin", "owner", "admin"])
def test_gestion_opens_for_every_role_that_can_see_it(role, client, db,
superadmin_id, make_member,
sign_in):
"""Seeing the link and reaching the page are two different checks, and a
role that passes one and fails the other is the worst of both."""
member_id = superadmin_id if role == "superadmin" else make_member("x", role=role)
sign_in(member_id)
assert client.get("/comunidad/gestion").status_code == 200
def test_the_public_strip_offers_gestion_to_the_superadmin(client, superadmin_id,
sign_in):
"""`sesion.json` draws the bar on vienalatina.com from its own list, so it
is a second place the same rule can be got wrong."""
sign_in(superadmin_id)
labels = [s["label"] for s in
client.get("/comunidad/sesion.json").get_json()["sections"]]
assert "Gestión" in labels

View File

@ -0,0 +1,260 @@
"""The three screens the superadministrator gets, and the identity half.
Grouped in one file because they are one phase and share one question: who may
open this, and does it tell the truth about the running system.
"""
from __future__ import annotations
import json
import pytest
from apps.board import activity, identity
SCREENS = {
"/comunidad/gestion/identidad": "superadmin",
"/comunidad/gestion/estado": "superadmin",
"/comunidad/gestion/registro": "superadmin",
"/comunidad/gestion/medios": "admin",
}
@pytest.fixture
def boss(superadmin_id, sign_in):
sign_in(superadmin_id)
return superadmin_id
@pytest.mark.parametrize("url", sorted(SCREENS))
def test_every_screen_opens_for_the_superadmin(client, boss, url, repo):
assert client.get(url).status_code == 200
@pytest.mark.parametrize("url,needs", sorted(SCREENS.items()))
def test_each_screen_refuses_the_roles_below_it(client, make_member, sign_in,
url, needs, repo):
"""Medios is open to admins — they are the people who upload, and the worst
an admin can do there is remove a picture from a post they could already
have edited. The other three are the platform's."""
# Everything above the rank passes too, which is what `is_at_least` means.
allowed = {"superadmin": set(), "admin": {"admin", "owner"}}[needs]
for role in ("user", "moderator", "admin", "owner"):
sign_in(make_member(f"persona-{role}", role=role))
expected = 200 if role in allowed else 403
assert client.get(url).status_code == expected, (url, role)
# --- identity -------------------------------------------------------------
def test_the_identity_round_trips_all_three_languages(client, db, post, boss, repo):
post("/comunidad/gestion/identidad", {
"name-es": "Viena Latina", "tagline-es": "La comunidad en Viena.",
"name-de": "Wien Latina", "tagline-de": "Die Community in Wien.",
"tagline-pt-br": "A comunidade em Viena.",
"social-instagram": "https://instagram.com/vienalatina",
"email": "hola@vienalatina.com", "city": "Wien",
"footer_text": "Asociación Viena Latina",
})
body = client.get("/comunidad/gestion/identidad").get_data(as_text=True)
for value in ("Wien Latina", "Die Community in Wien.",
"A comunidade em Viena.", "https://instagram.com/vienalatina",
"hola@vienalatina.com", "Asociación Viena Latina"):
assert value in body, value
def test_an_untouched_language_is_not_written_at_all(client, db, post, boss, repo):
"""A file repeating config.yaml's own values back at it would make the
fallback meaningless and freeze today's defaults for good."""
post("/comunidad/gestion/identidad", {"tagline-es": "Sólo esto."})
names = json.loads(db.execute("SELECT names_json FROM site").fetchone()[0])
assert names == {"es": {"name": "", "tagline": "Sólo esto."}}
yaml = repo.files["data/site.yaml"].decode("utf-8")
assert "de:" not in yaml and "pt-br:" not in yaml
def test_a_social_link_that_is_not_https_is_refused(client, db, post, boss, repo):
"""These render in the footer of every public page. `javascript:` in an href
is a script running on vienalatina.com."""
response = post("/comunidad/gestion/identidad",
{"social-instagram": "javascript:alert(1)"},
follow_redirects=True)
assert "tiene que empezar por https" in response.get_data(as_text=True)
assert db.execute("SELECT COUNT(*) AS n FROM site").fetchone()["n"] == 0
def test_a_tagline_is_flattened_to_one_line(client, db, post, boss, repo):
"""A newline inside og:description is a share card that renders raggedly in
some readers and truncated in others."""
post("/comunidad/gestion/identidad", {"tagline-es": "Una línea.\n\nY otra."})
names = json.loads(db.execute("SELECT names_json FROM site").fetchone()[0])
assert names["es"]["tagline"] == "Una línea. Y otra."
def test_the_yaml_is_what_hugo_reads(client, post, boss, repo):
post("/comunidad/gestion/identidad", {
"name-es": "Viena Latina", "tagline-es": "La comunidad.",
"social-instagram": "https://instagram.com/vl",
"social-bluesky": "https://bsky.app/profile/vl",
"email": "hola@vienalatina.com", "city": "Wien",
})
yaml = repo.files["data/site.yaml"].decode("utf-8")
assert ' name: "Viena Latina"' in yaml
assert ' tagline: "La comunidad."' in yaml
# sameAs is a flat list of URLs: the names of the networks appear nowhere in
# the schema, only the addresses.
assert 'sameAs:\n - "https://instagram.com/vl"' in yaml
assert 'email: "hola@vienalatina.com"' in yaml
def test_a_quote_in_a_name_cannot_break_the_file(client, post, boss, repo):
post("/comunidad/gestion/identidad", {"name-es": 'Viena "La" Latina\\'})
yaml = repo.files["data/site.yaml"].decode("utf-8")
assert r'name: "Viena \"La\" Latina\\"' in yaml
# --- the activity log -----------------------------------------------------
def test_the_acts_that_change_power_are_recorded(client, db, post, boss, make_member):
maria = make_member("maria")
post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"})
post(f"/comunidad/miembros/{maria}/estado", {"active": "0"})
rows = db.execute(
"SELECT action, object, detail FROM activity ORDER BY id").fetchall()
assert [(r["action"], r["object"]) for r in rows] == [
("role.changed", "Maria"), ("member.suspended", "Maria")]
assert "Miembro → Moderador" in rows[0]["detail"]
def test_the_log_survives_the_person_who_wrote_it(client, db, post, boss, make_member):
"""The row stays and the name goes. That a role was changed is the
association's record; whose name was on it is the erased person's data."""
admin_id = make_member("admina", role="admin")
maria = make_member("maria")
sign_in_as = client.session_transaction
with sign_in_as() as session:
session["member_id"] = admin_id
session["csrf"] = "token-for-tests"
post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"})
with sign_in_as() as session:
session["member_id"] = boss
post(f"/comunidad/miembros/{admin_id}/eliminar")
rows = db.execute("SELECT actor_id, action FROM activity "
"WHERE action = 'role.changed'").fetchall()
assert len(rows) == 1
assert rows[0]["actor_id"] is None
def test_a_broken_log_does_not_break_the_thing_it_records(app, db, boss,
make_member, monkeypatch):
"""An administrator who could not be appointed because the note about it
could not be saved is a worse outcome than a gap in the notes."""
with app.test_request_context():
monkeypatch.setattr(activity, "get_db",
lambda: (_ for _ in ()).throw(RuntimeError("no")))
activity.log("role.changed", "Maria") # must not raise
def test_the_registro_reads_as_sentences(client, db, post, boss, make_member):
maria = make_member("maria")
post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"})
body = client.get("/comunidad/gestion/registro").get_data(as_text=True)
assert "cambió el rol de Maria" in body
# --- the media library ----------------------------------------------------
def test_an_orphan_is_named_as_one_and_a_used_picture_is_not(client, db, boss, repo):
repo.files["static/uploads/usada-aaaaaa.jpg"] = b"\xff\xd8\xff"
repo.files["static/uploads/huerfana-bbbbbb.jpg"] = b"\xff\xd8\xff"
db.execute("""INSERT INTO content_cache (path, sha, title, date, image)
VALUES ('content/post/x.es.md', 'a', 'Un artículo', '2026-01-01',
'/uploads/usada-aaaaaa.jpg')""")
body = client.get("/comunidad/gestion/medios").get_data(as_text=True)
assert "1 no la usa nadie" in body
assert "Un artículo" in body
# And the orphan is first, because it is the only row anybody has to act on.
assert body.index("huerfana-bbbbbb") < body.index("usada-aaaaaa")
def test_a_picture_in_use_cannot_be_deleted(client, db, post, boss, repo):
repo.files["static/uploads/usada-aaaaaa.jpg"] = b"\xff\xd8\xff"
db.execute("""INSERT INTO content_cache (path, sha, title, date, image)
VALUES ('content/post/x.es.md', 'a', 'Un artículo', '2026-01-01',
'/uploads/usada-aaaaaa.jpg')""")
response = post("/comunidad/gestion/medios/usada-aaaaaa.jpg/eliminar",
follow_redirects=True)
assert "está en uso" in response.get_data(as_text=True)
assert "static/uploads/usada-aaaaaa.jpg" in repo.files
def test_an_orphan_is_deleted_and_logged(client, db, post, boss, repo):
repo.files["static/uploads/huerfana-bbbbbb.jpg"] = b"\xff\xd8\xff"
post("/comunidad/gestion/medios/huerfana-bbbbbb.jpg/eliminar",
{"sha": repo._sha(b"\xff\xd8\xff")})
assert "static/uploads/huerfana-bbbbbb.jpg" not in repo.files
assert db.execute("SELECT action, object FROM activity").fetchone()["object"] == \
"huerfana-bbbbbb.jpg"
def test_the_editor_records_which_picture_a_post_uses(client, repo, db, post,
superadmin_id, sign_in):
"""Which is what makes "does anything use this?" a query rather than a
re-read of every post's frontmatter from the git server.
The cache is filled by the listing rather than by the write — it is keyed on
the sha the git server reports — so opening Contenido is the step that puts
the row there."""
sign_in(superadmin_id)
post("/comunidad/contenido/post/nuevo",
{"title": "Con foto", "body": "Texto.", "date": "2026-10-03",
"image": "/uploads/foto-abcdef.jpg"})
client.get("/comunidad/contenido/post")
row = db.execute("SELECT image FROM content_cache").fetchone()
assert row["image"] == "/uploads/foto-abcdef.jpg"
# --- the status screen ----------------------------------------------------
def test_the_status_screen_says_when_the_token_cannot_write(client, boss, monkeypatch):
""""Present" was never the problem. A token with the wrong scope is
non-empty, looks fine, and cannot write a single file — which is exactly the
configuration that broke publishing for three phases."""
from apps.board import gitea, status
monkeypatch.setattr(status.gitea, "list_directory",
lambda *a, **k: (_ for _ in ()).throw(
gitea.GiteaError("403: sin permiso de repositorio")))
body = client.get("/comunidad/gestion/estado").get_data(as_text=True)
assert "no puede leer el repositorio" in body
assert "sin permiso de repositorio" in body
def test_the_status_screen_counts_what_is_there(client, db, boss, make_member, repo):
make_member("maria")
make_member("luisa", role="moderator")
body = client.get("/comunidad/gestion/estado").get_data(as_text=True)
assert "3 miembros" in body # the superadministrator and the two
assert "2 con algún cargo" in body # superadministrator + moderator

View File

@ -1045,7 +1045,7 @@ 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 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. bytes already in the page, which reaches no network.
### 11.18 Marca: the admin owns the look ### 11.18 Marca: the superadministrator owns the look
*Gestión* → **Marca**, admins only. Colours, a logo and a favicon for both *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 halves of the site, with an *Avanzado* fold holding every token as a text field
@ -1099,6 +1099,21 @@ 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, 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'`). which is what makes it work under a policy with no `'unsafe-inline'`).
**A typeface and the corners.** Four system-font stacks — nothing is downloaded
from anywhere, which is deliberate and a GDPR matter: a stylesheet that pulls a
font from fonts.gstatic.com tells Google the IP address of everyone who reads
the site. A fifth option takes an uploaded `.woff2`, self-hosted, sniffed by its
`wOF2` signature and capped at 400 KB; it is named ahead of the old stack in the
`font-family`, so a font that fails to load leaves a readable site rather than a
browser default. The screen carries a fold-out warning about missing accented
glyphs, file size, synthesised bold — and about **licensing**, which is the part
with a real cost: a font is software, a desktop licence is not a webfont
licence, and that liability follows the platform to every organisation it is
installed for. SIL OFL and Apache-2.0 are the safe ones.
Roundness is one setting driving all four `--radius-*` tokens, because a site
whose cards are round and whose buttons are square looks like two sites.
**No SVG and no ICO.** The logo takes PNG, JPG or WebP and the favicon PNG only, **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 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 that can carry script and would be served from our own origin; ICO would be one
@ -1111,6 +1126,37 @@ needs nothing — it walks `content/` only, and `data/` and `static/` are outsid
it. A site with no `data/brand.yaml` builds byte-for-byte the HTML it built 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. before any of this existed, which is asserted by building both ways.
### 11.18b Identidad — what the site is called and where to find it
*Gestión* → **Identidad**, superadministrator only. The name and the one-line
tagline **in the three languages**, the association's accounts elsewhere, a
public email, a city and street, a default share picture and the footer line.
All of it used to be `config.yaml`, which meant it could only be changed by
somebody with the repository — the thing this phase exists to end. Same
architecture as Marca: SQLite first for the members area, then a commit of
`data/site.yaml`, so a git outage never blocks a change that does not need git.
**Hugo cannot have `config.yaml` overridden by a data file.** The name and
tagline are therefore read through `partials/site-name.html` and
`site-tagline.html`, which prefer `site.Data.site` and fall back to the config —
and every template that shows either calls one of them, so the two cannot drift.
A site with no `data/site.yaml` builds byte-for-byte what it built before, which
is asserted by building both ways.
**Only what was actually set is written.** A file repeating the config's own
values back at it would make the fallback meaningless and freeze today's
defaults for good, so the form shows them as placeholders rather than as values
— a prefilled form saves the fallback the first time anybody presses the button.
The contact fields are not decoration: they become `ContactPoint` and
`PostalAddress` in the `Organization` schema, which is what puts an association
in a *local* search result rather than only a web one. The social links become
`sameAs`, which is how a search or answer engine knows an Instagram account and
this site are the same body. Both are checked on the way in — a link must be
`https://`, because these render in the footer of every public page and
`javascript:` in an `href` is a script running on vienalatina.com.
### 11.19 The chrome on a phone ### 11.19 The chrome on a phone
**The public menu opens from a ☰ below 768px**, and above it is the horizontal **The public menu opens from a ☰ below 768px**, and above it is the horizontal
@ -1147,6 +1193,43 @@ In the members area the navigation **wraps** on a phone rather than scrolling:
six sections over two lines shows all six, where a swipe strip would have left six sections over two lines shows all six, where a swipe strip would have left
Calendario and Gestión off the right edge with nothing to say they were there. Calendario and Gestión off the right edge with nothing to say they were there.
### 11.20 The three admin tools
**Estado del sistema** (superadministrator). WordPress's Site Health, and it
earns its place for a specific reason: every outage in this project has been a
configuration fact invisible until somebody hit it. It asks the running system
rather than a file — the content token is **exercised** against the repository
rather than checked for emptiness, which is the single most valuable line on the
page, because "present" was never the problem; the mail host is connected to;
the newest backup is named with its age and size; free disk is reported; and
every setting `.env.example` documents that the container does not have is
listed with what stops working without it. **It changes nothing**, deliberately:
a diagnostic screen that can also act is one somebody uses to act without
reading.
**Registro de actividad** (superadministrator). Who changed a role, approved or
returned a proposal, touched the look or the identity, suspended or erased
somebody. Deliberately not a general event store — no page views, no successful
sign-ins; a log that records everything is a log nobody reads. `activity.log()`
never raises: an administrator who could not be appointed because the note about
it could not be saved is a worse outcome than a gap in the notes. On erasure the
actor is **cleared and not cascaded** — that a role was changed is the
association's record, whose name was on it is the erased person's data.
**Biblioteca de medios** (administrators and above). Every picture the public
site carries, with the posts that use each. **Orphans are the point**: a picture
is committed when a post is written, and deleting the post leaves it in the
repository, deployed, referenced by nothing, for good — there has never been a
way to see one. They sort to the top and are the only rows with a delete button;
a picture in use is refused by the handler and not merely hidden, because a
broken image on a published page is worse than an orphan nobody sees. It reads
`content_cache.image`, which is what makes "does anything use this?" a query
rather than a re-read of every post's frontmatter on every page view.
Open to administrators, unlike the other two, because they are the people who
upload — and the worst an administrator can do here is remove a picture from a
post they could already have edited.
## 12. Make Gitea look like the site ## 12. Make Gitea look like the site
Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its

View File

@ -4041,3 +4041,14 @@ a.notif-card__message:hover {
.agenda__day--busy { display: block; } .agenda__day--busy { display: block; }
.agenda__number { display: inline-block; margin-right: 8px; } .agenda__number { display: inline-block; margin-right: 8px; }
} }
/* The association's accounts elsewhere, in the footer. Set in
Gestión → Identidad; absent entirely on a site that has set none. */
.site-foot__social {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 14px;
margin-bottom: 10px;
font-size: 0.85rem;
}

View File

@ -3,7 +3,7 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{ if not .IsHome }}{{ .Title }} — {{ end }}{{ .Site.Title }}</title> <title>{{ if not .IsHome }}{{ .Title }} — {{ end }}{{ partial "site-name.html" . }}</title>
{{ partial "seo-head.html" . }} {{ partial "seo-head.html" . }}
{{ $css := resources.Get "css/main.css" | minify | fingerprint }} {{ $css := resources.Get "css/main.css" | minify | fingerprint }}
<link rel="stylesheet" href="{{ $css.RelPermalink }}" integrity="{{ $css.Data.Integrity }}"> <link rel="stylesheet" href="{{ $css.RelPermalink }}" integrity="{{ $css.Data.Integrity }}">

View File

@ -19,7 +19,17 @@
{{ $tokens := "" }} {{ $tokens := "" }}
{{ range $name, $value := .tokens }}{{ $tokens = printf "%s--%s:%s;" $tokens $name $value }}{{ end }} {{ range $name, $value := .tokens }}{{ $tokens = printf "%s--%s:%s;" $tokens $name $value }}{{ end }}
{{ $sheet := "" }} {{ $sheet := "" }}
{{ with $tokens }}{{ $sheet = printf ":root{%s}" . }}{{ end }} {{/* The uploaded typeface first, so the @font-face is declared before anything
asks for the family. `font-display: swap` deliberately: the alternative
shows nothing until the file arrives, and a blank article on a slow phone
is worse than one that changes typeface a moment after it appears. */}}
{{ with .font }}
{{ $sheet = printf "@font-face{font-family:\"VLPropia\";src:url(%s) format('woff2');font-weight:100 900;font-display:swap}" . }}
{{ end }}
{{ with $tokens }}{{ $sheet = printf "%s:root{%s}" $sheet . }}{{ end }}
{{/* On `body`, because that is where main.css sets the stack and a custom
property would need every rule to opt in. */}}
{{ with .font_stack }}{{ $sheet = printf "%sbody{font-family:%s}" $sheet . }}{{ end }}
{{ with $.Site.Data.brand.custom_css }}{{ $sheet = printf "%s\n%s" $sheet . }}{{ end }} {{ with $.Site.Data.brand.custom_css }}{{ $sheet = printf "%s\n%s" $sheet . }}{{ end }}
{{ with $sheet }} {{ with $sheet }}
{{ $brand := resources.FromString "css/brand.css" . | minify | fingerprint }} {{ $brand := resources.FromString "css/brand.css" . | minify | fingerprint }}

View File

@ -8,5 +8,21 @@
{{ end }} {{ end }}
</nav> </nav>
{{ end }} {{ end }}
<p>{{ .Site.Title }} &copy; {{ now.Format "2006" }}</p> {{/* The association's accounts elsewhere. Read through a variable for the
same reason as the name — a field lookup on nil fails the build on a
site that has not set any. `rel="me"` is what lets Mastodon verify a
link back, and costs nothing on the others. */}}
{{ $social := dict }}
{{ with site.Data.site }}{{ with .social }}{{ $social = . }}{{ end }}{{ end }}
{{ with $social }}
<nav class="site-foot__social" aria-label="Redes">
{{ range $name, $url := . }}
<a href="{{ $url }}" rel="me nofollow noopener">{{ $name | title }}</a>
{{ end }}
</nav>
{{ end }}
{{ $footer := "" }}
{{ with site.Data.site }}{{ $footer = .footer_text }}{{ end }}
<p>{{ with $footer }}{{ . }}{{ else }}{{ partial "site-name.html" $ }} &copy; {{ now.Format "2006" }}{{ end }}</p>
</footer> </footer>

View File

@ -15,9 +15,10 @@
{{ $logo := "" }}{{ $stamp := "0" }} {{ $logo := "" }}{{ $stamp := "0" }}
{{ with site.Data.brand }}{{ $logo = .logo }}{{ $stamp = .stamp }}{{ end }} {{ with site.Data.brand }}{{ $logo = .logo }}{{ $stamp = .stamp }}{{ end }}
{{ with $logo }} {{ with $logo }}
<img class="site-bar__logo" src="{{ . }}?v={{ $stamp }}" alt="{{ site.Title }}"> <img class="site-bar__logo" src="{{ . }}?v={{ $stamp }}"
alt="{{ partial "site-name.html" $ }}">
{{ else }} {{ else }}
<span class="site-bar__brand-text">{{ .Site.Title }}</span> <span class="site-bar__brand-text">{{ partial "site-name.html" . }}</span>
{{ end }} {{ end }}
</a> </a>

View File

@ -4,7 +4,7 @@
{{ $localeMap := .Site.Params.localeMap }} {{ $localeMap := .Site.Params.localeMap }}
{{ $locale := index $localeMap .Language.Lang | default "es_ES" }} {{ $locale := index $localeMap .Language.Lang | default "es_ES" }}
{{ $desc := "" }} {{ $desc := "" }}
{{ if .IsPage }}{{ $desc = .Description | default (.Summary | plainify | truncate 200) }}{{ else }}{{ $desc = .Site.Params.description }}{{ end }} {{ if .IsPage }}{{ $desc = .Description | default (.Summary | plainify | truncate 200) }}{{ else }}{{ $desc = partial "site-tagline.html" . }}{{ end }}
{{/* One line, always. A summary pulled out of the body arrives with the line {{/* One line, always. A summary pulled out of the body arrives with the line
breaks the prose had, and a newline inside og:description is a card that breaks the prose had, and a newline inside og:description is a card that
renders raggedly in some readers and truncated in others. */}} renders raggedly in some readers and truncated in others. */}}
@ -20,9 +20,13 @@
Absolute, because WhatsApp, Signal, Mastodon and Bluesky all fetch it from Absolute, because WhatsApp, Signal, Mastodon and Bluesky all fetch it from
outside and a relative path means nothing to them. */}} outside and a relative path means nothing to them. */}}
{{ $brandLogo := "" }} {{ $brandLogo := "" }}{{ $chosen := "" }}
{{ with site.Data.brand }}{{ $brandLogo = .logo }}{{ end }} {{ with site.Data.brand }}{{ $brandLogo = .logo }}{{ end }}
{{ $fallback := or $brandLogo .Site.Params.defaultImage }} {{ with site.Data.site }}{{ $chosen = .share_image }}{{ end }}
{{/* The picture chosen in Identidad wins over the logo, which wins over the
one in config.yaml: most sites want their logo and the field exists for the
ones that want something else. */}}
{{ $fallback := or $chosen (or $brandLogo .Site.Params.defaultImage) }}
{{ $image := "" }} {{ $image := "" }}
{{ with .Params.image }}{{ $image = . | absURL }} {{ with .Params.image }}{{ $image = . | absURL }}
{{ else }}{{ with $fallback }}{{ $image = . | absURL }}{{ end }}{{ end }} {{ else }}{{ with $fallback }}{{ $image = . | absURL }}{{ end }}{{ end }}
@ -42,7 +46,7 @@
{{ if and .IsPage (eq .Section "post") }} {{ if and .IsPage (eq .Section "post") }}
{{/* ---- Article ---- */}} {{/* ---- Article ---- */}}
<meta property="og:type" content="article"> <meta property="og:type" content="article">
<meta property="og:site_name" content="{{ .Site.Title }}"> <meta property="og:site_name" content="{{ partial "site-name.html" . }}">
<meta property="og:title" content="{{ .Title }}"> <meta property="og:title" content="{{ .Title }}">
<meta property="og:description" content="{{ $desc }}"> <meta property="og:description" content="{{ $desc }}">
<meta property="og:url" content="{{ .Permalink }}"> <meta property="og:url" content="{{ .Permalink }}">
@ -124,8 +128,8 @@
{{ else if .IsHome }} {{ else if .IsHome }}
{{/* ---- Home ---- */}} {{/* ---- Home ---- */}}
<meta property="og:type" content="website"> <meta property="og:type" content="website">
<meta property="og:site_name" content="{{ .Site.Title }}"> <meta property="og:site_name" content="{{ partial "site-name.html" . }}">
<meta property="og:title" content="{{ .Site.Title }}"> <meta property="og:title" content="{{ partial "site-name.html" . }}">
<meta property="og:description" content="{{ $desc }}"> <meta property="og:description" content="{{ $desc }}">
<meta property="og:url" content="{{ .Permalink }}"> <meta property="og:url" content="{{ .Permalink }}">
<meta property="og:locale" content="{{ $locale }}"> <meta property="og:locale" content="{{ $locale }}">
@ -138,14 +142,33 @@
<meta name="twitter:image" content="{{ . }}"> <meta name="twitter:image" content="{{ . }}">
{{ end }} {{ end }}
{{/* The organisation, as a search or answer engine reads it. Everything
overridable lives in Gestión → Identidad; `areaServed` stays here because a
city is a fact about this association and not a setting. */}}
{{ $org := dict {{ $org := dict
"@context" "https://schema.org" "@context" "https://schema.org"
"@type" "Organization" "@type" "Organization"
"name" .Site.Title "name" (partial "site-name.html" .)
"url" .Site.Home.Permalink "url" .Site.Home.Permalink
"description" .Site.Params.description "description" (partial "site-tagline.html" .)
"areaServed" (dict "@type" "City" "name" "Wien" "addressCountry" "AT") "areaServed" (dict "@type" "City" "name" "Wien" "addressCountry" "AT")
}} }}
{{ with site.Data.site }}
{{/* sameAs is how an engine knows an Instagram account and this site are one
body — the single highest-value field here for being found at all. */}}
{{ with .sameAs }}{{ $org = merge $org (dict "sameAs" .) }}{{ end }}
{{ with .email }}
{{ $org = merge $org (dict "contactPoint" (dict
"@type" "ContactPoint" "contactType" "general" "email" .)) }}
{{ end }}
{{ if or .city .street }}
{{ $address := dict "@type" "PostalAddress" "addressCountry" "AT" }}
{{ with .city }}{{ $address = merge $address (dict "addressLocality" .) }}{{ end }}
{{ with .street }}{{ $address = merge $address (dict "streetAddress" .) }}{{ end }}
{{ with .phone }}{{ $org = merge $org (dict "telephone" .) }}{{ end }}
{{ $org = merge $org (dict "address" $address) }}
{{ end }}
{{ end }}
{{/* The same fallback as the share card: the admin's logo, then the configured {{/* 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 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. */}} organisation's name, so it should be the logo somebody actually uploaded. */}}
@ -184,7 +207,7 @@
document about the organisation rather than an article, hence WebPage document about the organisation rather than an article, hence WebPage
rather than BlogPosting, and no author: a page is the site speaking. */}} rather than BlogPosting, and no author: a page is the site speaking. */}}
<meta property="og:type" content="website"> <meta property="og:type" content="website">
<meta property="og:site_name" content="{{ .Site.Title }}"> <meta property="og:site_name" content="{{ partial "site-name.html" . }}">
<meta property="og:title" content="{{ .Title }}"> <meta property="og:title" content="{{ .Title }}">
<meta property="og:description" content="{{ $desc }}"> <meta property="og:description" content="{{ $desc }}">
<meta property="og:url" content="{{ .Permalink }}"> <meta property="og:url" content="{{ .Permalink }}">

View File

@ -0,0 +1,20 @@
{{- /* The site's name, from Gestión → Identidad when it has been set there and
from config.yaml when it has not.
Hugo cannot have `config.yaml` overridden by a data file, so this partial
is the override: every template that shows the name calls it, and the two
sources cannot drift. A site with no data/site.yaml renders exactly what it
rendered before any of this existed.
Read through a variable rather than as site.Data.site.languages.<lang>.name,
because on a site with no data file that chain is a field lookup on nil and
fails the build — which is the state every install starts in. */ -}}
{{- $name := site.Title -}}
{{- with site.Data.site -}}
{{- with .languages -}}
{{- with index . $.Site.Language.Lang -}}
{{- with .name }}{{ $name = . }}{{ end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- $name -}}

View File

@ -0,0 +1,12 @@
{{- /* The one-line description of the site, from Gestión → Identidad or from
config.yaml. See site-name.html for why it is a partial and why it reads
through a variable. */ -}}
{{- $tagline := site.Params.description -}}
{{- with site.Data.site -}}
{{- with .languages -}}
{{- with index . $.Site.Language.Lang -}}
{{- with .tagline }}{{ $tagline = . }}{{ end -}}
{{- end -}}
{{- end -}}
{{- end -}}
{{- $tagline -}}