vienalatina/apps/board/media.py
Pablo Volenski 81d9fae4a9
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
2026-10-06 12:18:04 +00:00

105 lines
4.0 KiB
Python

"""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"))