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
418 lines
17 KiB
Python
418 lines
17 KiB
Python
"""What members propose for the public site, and who lets it through.
|
|
|
|
The whole of the curation policy, in three sentences. A member writes a post
|
|
here and it waits. A moderator or an admin reads it and either approves it —
|
|
which commits it to the site repository under the member's own name — or rejects
|
|
it with a reason the author can read. Moderators and admins do not queue: they
|
|
write in the editor (`content.py`) and their post is committed as they save it.
|
|
|
|
**Nothing in this module reaches git until somebody approves.** That is not a
|
|
convention, it is the reason the table exists: a commit to the content repository
|
|
*is* publication, because Gitea's webhook starts the translate → build → deploy
|
|
pipeline within seconds. A draft that lived in the repository with a "pending"
|
|
flag would already be on vienalatina.com in three languages.
|
|
|
|
Approval goes through `content.publish`, the same function the editor uses, so an
|
|
approved submission is byte-identical to a post written by a moderator and the
|
|
pipeline cannot tell the two apart. `gitea.write_file` takes an author per commit,
|
|
so git history names the member who wrote it, not the moderator who approved it.
|
|
|
|
There is deliberately no way to promote a thread from the wall into a
|
|
submission. Writing for the public is a separate act — somebody decided to
|
|
address strangers rather than the people they already know, and that decision is
|
|
the thing worth keeping visible.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import date as date_type
|
|
|
|
from flask import (Blueprint, abort, current_app, flash, g, redirect,
|
|
render_template, request, send_from_directory, url_for)
|
|
|
|
from . import activity, content, gitea, uploads
|
|
from .db import get_db
|
|
from .render import excerpt, to_html
|
|
from .security import is_at_least, login_required, moderator_required
|
|
|
|
bp = Blueprint("submissions", __name__)
|
|
|
|
TITLE_MAX = content.TITLE_MAX
|
|
BODY_MAX = content.BODY_MAX
|
|
|
|
# How many proposals one member may have waiting at once. Not a security limit:
|
|
# everyone here is a known member. It is a limit on how much unread work one
|
|
# person can put on the moderators before talking to them.
|
|
PENDING_MAX = 3
|
|
|
|
STATE_LABELS = {
|
|
"pending": "En revisión",
|
|
"approved": "Publicado",
|
|
"rejected": "Devuelto",
|
|
}
|
|
|
|
|
|
def may_moderate(member=None) -> bool:
|
|
member = member or g.member
|
|
return member is not None and is_at_least(member["role"], "moderator")
|
|
|
|
|
|
def pending_count() -> int:
|
|
"""For the badge in the navigation, and 0 for anyone who cannot act on it —
|
|
a member does not need to know how long the queue is."""
|
|
if not may_moderate():
|
|
return 0
|
|
return get_db().execute(
|
|
"SELECT COUNT(*) AS n FROM submissions WHERE state = 'pending'"
|
|
).fetchone()["n"]
|
|
|
|
|
|
def _load(submission_id: int):
|
|
row = get_db().execute(
|
|
"""SELECT s.*, m.display_name AS author, m.email AS author_email,
|
|
m.gitea_login AS author_login, m.profile_published AS author_published,
|
|
r.display_name AS reviewer
|
|
FROM submissions s
|
|
JOIN members m ON m.id = s.author_id
|
|
LEFT JOIN members r ON r.id = s.reviewed_by
|
|
WHERE s.id = ?""",
|
|
(submission_id,),
|
|
).fetchone()
|
|
if row is None:
|
|
abort(404)
|
|
return row
|
|
|
|
|
|
def _mine_or_403(row) -> None:
|
|
if row["author_id"] != g.member["id"]:
|
|
abort(403)
|
|
|
|
|
|
def _read_proposal() -> tuple[dict, list[str]]:
|
|
"""The same fields the editor asks for, minus the ones only a publisher
|
|
decides: the date is the day it is approved, and `manual_translation` is a
|
|
pipeline switch, not something to explain to a member."""
|
|
errors = []
|
|
fields = {
|
|
"title": request.form.get("title", "").strip()[:TITLE_MAX],
|
|
"body": request.form.get("body", "").strip()[:BODY_MAX],
|
|
"description": request.form.get("description", "").strip()[:300],
|
|
# The same three fields the editor asks for, read by the same function:
|
|
# a member's event and a moderator's have to produce the same post.
|
|
**content.read_event_fields(request.form, errors),
|
|
}
|
|
if not fields["title"]:
|
|
errors.append("El título no puede estar vacío.")
|
|
if not fields["body"]:
|
|
errors.append("El texto no puede estar vacío.")
|
|
return fields, errors
|
|
|
|
|
|
# --- the member's side ----------------------------------------------------
|
|
|
|
@bp.route("/publicaciones")
|
|
@login_required
|
|
def index():
|
|
"""One page for both sides of the queue.
|
|
|
|
A member sees what they proposed and what happened to it. A moderator sees
|
|
that plus everything waiting, because the first thing a moderator wants on
|
|
opening this section is the list of things to read.
|
|
"""
|
|
db = get_db()
|
|
mine = db.execute(
|
|
"""SELECT * FROM submissions WHERE author_id = ?
|
|
ORDER BY CASE state WHEN 'pending' THEN 0 ELSE 1 END, created_at DESC""",
|
|
(g.member["id"],),
|
|
).fetchall()
|
|
queue = []
|
|
if may_moderate():
|
|
queue = db.execute(
|
|
"""SELECT s.*, m.display_name AS author,
|
|
m.gitea_login AS author_login,
|
|
m.profile_published AS author_published
|
|
FROM submissions s JOIN members m ON m.id = s.author_id
|
|
WHERE s.state = 'pending' AND s.author_id != ?
|
|
ORDER BY s.created_at""",
|
|
(g.member["id"],),
|
|
).fetchall()
|
|
return render_template("submissions.html", mine=mine, queue=queue,
|
|
labels=STATE_LABELS, excerpt=excerpt,
|
|
can_moderate=may_moderate())
|
|
|
|
|
|
@bp.route("/publicaciones/nueva", methods=["GET", "POST"])
|
|
@login_required
|
|
def propose():
|
|
if may_moderate():
|
|
# Not a refusal: a moderator's post does not queue, so sending them
|
|
# through a form that would only wait for their own approval is a
|
|
# detour with nothing at the end of it.
|
|
return redirect(url_for("content.new", collection="post"))
|
|
|
|
if request.method == "GET":
|
|
return render_template("submission_form.html", item=None, fields=None)
|
|
|
|
fields, errors = _read_proposal()
|
|
waiting = get_db().execute(
|
|
"SELECT COUNT(*) AS n FROM submissions WHERE author_id = ? AND state = 'pending'",
|
|
(g.member["id"],),
|
|
).fetchone()["n"]
|
|
if waiting >= PENDING_MAX:
|
|
errors.append(
|
|
f"Ya tienes {waiting} propuestas en revisión. Espera a que las lean "
|
|
"antes de enviar otra."
|
|
)
|
|
staged = []
|
|
if not errors:
|
|
try:
|
|
staged = uploads.stage(request.files.getlist("picture"))
|
|
except uploads.RejectedUpload as exc:
|
|
errors.append(str(exc))
|
|
if errors:
|
|
return _back_to_form(None, fields, errors)
|
|
|
|
photo_name = _store_picture(staged)
|
|
get_db().execute(
|
|
"""INSERT INTO submissions
|
|
(author_id, title, body_md, description, photo_name,
|
|
event_date, event_time, event_location)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
|
|
(g.member["id"], fields["title"], fields["body"], fields["description"],
|
|
photo_name,
|
|
fields["event_date"], fields["event_time"], fields["event_location"]),
|
|
)
|
|
flash("Enviado. Un moderador lo leerá antes de publicarlo.", "ok")
|
|
return redirect(url_for("submissions.index"))
|
|
|
|
|
|
@bp.route("/publicaciones/<int:submission_id>", methods=["GET"])
|
|
@login_required
|
|
def show(submission_id: int):
|
|
"""The author reads their own; a moderator reads anybody's. Nobody else
|
|
reads any of it — an unapproved post is private writing."""
|
|
row = _load(submission_id)
|
|
if row["author_id"] != g.member["id"] and not may_moderate():
|
|
abort(403)
|
|
return render_template("submission.html", item=row, labels=STATE_LABELS,
|
|
body_html=to_html(row["body_md"]),
|
|
can_moderate=may_moderate(),
|
|
mine=row["author_id"] == g.member["id"])
|
|
|
|
|
|
@bp.route("/publicaciones/<int:submission_id>/editar", methods=["GET", "POST"])
|
|
@login_required
|
|
def edit(submission_id: int):
|
|
"""Only while it is waiting or has come back. Editing an approved one would
|
|
change nothing: the file is already in the repository, and the editor is
|
|
where a published post is changed."""
|
|
row = _load(submission_id)
|
|
_mine_or_403(row)
|
|
if row["state"] == "approved":
|
|
flash("Ya está publicado. Pide a un moderador que lo edite en el sitio.", "error")
|
|
return redirect(url_for("submissions.index"))
|
|
|
|
if request.method == "GET":
|
|
return render_template("submission_form.html", item=row,
|
|
fields={
|
|
"title": row["title"], "body": row["body_md"],
|
|
"description": row["description"],
|
|
"event_date": row["event_date"] or "",
|
|
"event_time": row["event_time"] or "",
|
|
"event_location": row["event_location"] or "",
|
|
})
|
|
|
|
fields, errors = _read_proposal()
|
|
staged = []
|
|
if not errors:
|
|
try:
|
|
staged = uploads.stage(request.files.getlist("picture"))
|
|
except uploads.RejectedUpload as exc:
|
|
errors.append(str(exc))
|
|
if errors:
|
|
return _back_to_form(row, fields, errors)
|
|
|
|
photo_name = row["photo_name"]
|
|
if staged:
|
|
if photo_name:
|
|
uploads.remove(photo_name)
|
|
photo_name = _store_picture(staged)
|
|
|
|
get_db().execute(
|
|
"""UPDATE submissions
|
|
SET title = ?, body_md = ?, description = ?,
|
|
photo_name = ?, event_date = ?, event_time = ?,
|
|
event_location = ?, state = 'pending', note = NULL,
|
|
reviewed_by = NULL, reviewed_at = NULL,
|
|
updated_at = datetime('now')
|
|
WHERE id = ?""",
|
|
(fields["title"], fields["body"], fields["description"],
|
|
photo_name, fields["event_date"],
|
|
fields["event_time"], fields["event_location"], submission_id),
|
|
)
|
|
# Back to pending on every edit, including one made after a rejection: a
|
|
# rejected post that has been rewritten is waiting again, and leaving it
|
|
# marked "devuelto" would hide it from the queue forever.
|
|
flash("Actualizado. Vuelve a estar en revisión.", "ok")
|
|
return redirect(url_for("submissions.index"))
|
|
|
|
|
|
@bp.route("/publicaciones/<int:submission_id>/retirar", methods=["POST"])
|
|
@login_required
|
|
def withdraw(submission_id: int):
|
|
row = _load(submission_id)
|
|
_mine_or_403(row)
|
|
if row["state"] == "approved":
|
|
abort(403)
|
|
get_db().execute("DELETE FROM submissions WHERE id = ?", (submission_id,))
|
|
if row["photo_name"]:
|
|
uploads.remove(row["photo_name"])
|
|
flash("Propuesta retirada.", "ok")
|
|
return redirect(url_for("submissions.index"))
|
|
|
|
|
|
@bp.route("/publicaciones/foto/<stored_name>")
|
|
@login_required
|
|
def photo(stored_name: str):
|
|
"""Behind the login and narrower than that: the author and the moderators.
|
|
|
|
A submission's picture is not published yet, and "any signed-in member" is
|
|
not the audience the author chose when they attached it.
|
|
"""
|
|
if not uploads.STORED_NAME.match(stored_name):
|
|
abort(404)
|
|
row = get_db().execute(
|
|
"SELECT author_id FROM submissions WHERE photo_name = ?", (stored_name,)
|
|
).fetchone()
|
|
if row is None:
|
|
abort(404)
|
|
if row["author_id"] != g.member["id"] and not may_moderate():
|
|
abort(404)
|
|
return send_from_directory(uploads.directory(), stored_name)
|
|
|
|
|
|
# --- the moderator's side -------------------------------------------------
|
|
|
|
@bp.route("/publicaciones/<int:submission_id>/aprobar", methods=["POST"])
|
|
@moderator_required
|
|
def approve(submission_id: int):
|
|
"""Commit it, under the author's name, and record where it landed."""
|
|
row = _load(submission_id)
|
|
if row["state"] == "approved":
|
|
flash("Esa propuesta ya estaba publicada.", "error")
|
|
return redirect(url_for("submissions.index"))
|
|
|
|
author = {"display_name": row["author"], "email": row["author_email"],
|
|
"gitea_login": row["author_login"],
|
|
# For the byline on the published page: it links to their profile
|
|
# only if they have one, so an approved post never carries a link
|
|
# to a 404.
|
|
"profile_published": row["author_published"]}
|
|
fields = {
|
|
"title": row["title"],
|
|
# The day it is published, not the day it was written: Hugo sorts by
|
|
# this and the URL carries it, so a proposal that waited a week should
|
|
# not arrive dated a week ago.
|
|
"date": date_type.today(),
|
|
"description": row["description"],
|
|
"image": "",
|
|
"manual_translation": False,
|
|
# Straight through: the event the member described is the event that
|
|
# gets published, with its own date rather than today's.
|
|
"event_date": row["event_date"] or "",
|
|
"event_time": row["event_time"] or "",
|
|
"event_location": row["event_location"] or "",
|
|
}
|
|
# Read the picture before the try, and catch only the error that means what
|
|
# it says. The first version wrapped everything in `except OSError`, which
|
|
# also catches PermissionError and every `requests` failure — so a git
|
|
# server refusing the token was reported as a missing photograph, on a page
|
|
# displaying that photograph. An except clause wide enough to catch the
|
|
# network is wide enough to lie.
|
|
picture = None
|
|
if row["photo_name"]:
|
|
try:
|
|
picture = (uploads.directory() / row["photo_name"]).read_bytes()
|
|
except FileNotFoundError:
|
|
current_app.logger.warning("submission %s: %s is not on disk",
|
|
submission_id, row["photo_name"])
|
|
flash("No se encontró la imagen en el disco. Pide al autor que la "
|
|
"vuelva a subir.", "error")
|
|
return redirect(url_for("submissions.show", submission_id=submission_id))
|
|
|
|
try:
|
|
if picture is not None:
|
|
fields["image"] = content.commit_picture(picture, row["photo_name"], author)
|
|
path = content.publish("post", fields, row["body_md"], author)
|
|
except gitea.GiteaError as exc:
|
|
flash(str(exc), "error")
|
|
return redirect(url_for("submissions.show", submission_id=submission_id))
|
|
|
|
get_db().execute(
|
|
"""UPDATE submissions
|
|
SET state = 'approved', note = NULL, reviewed_by = ?,
|
|
reviewed_at = datetime('now'), published_path = ?,
|
|
photo_name = NULL, updated_at = datetime('now')
|
|
WHERE id = ?""",
|
|
(g.member["id"], path, submission_id),
|
|
)
|
|
# The private copy goes now that the picture is in the repository: one file,
|
|
# in one place, and no orphan in /data/uploads that nothing will ever serve.
|
|
if 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")
|
|
return redirect(url_for("submissions.index"))
|
|
|
|
|
|
@bp.route("/publicaciones/<int:submission_id>/rechazar", methods=["POST"])
|
|
@moderator_required
|
|
def reject(submission_id: int):
|
|
"""A reason is required, and it is shown to the author.
|
|
|
|
Not politeness: without one the author has no idea whether to rewrite it,
|
|
shorten it or drop it, and the next thing they send has the same problem.
|
|
"""
|
|
row = _load(submission_id)
|
|
note = request.form.get("note", "").strip()[:1_000]
|
|
if not note:
|
|
flash("Escribe el motivo: el autor lo va a leer.", "error")
|
|
return redirect(url_for("submissions.show", submission_id=submission_id))
|
|
if row["state"] == "approved":
|
|
abort(403)
|
|
|
|
get_db().execute(
|
|
"""UPDATE submissions
|
|
SET state = 'rejected', note = ?, reviewed_by = ?,
|
|
reviewed_at = datetime('now'), updated_at = datetime('now')
|
|
WHERE 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")
|
|
return redirect(url_for("submissions.index"))
|
|
|
|
|
|
# --- helpers --------------------------------------------------------------
|
|
|
|
def _store_picture(staged: list[dict]) -> str | None:
|
|
"""Write the one picture to disk without an `attachments` row.
|
|
|
|
A submission carries at most one, and `attachments` insists a row belongs to
|
|
exactly one of a thread, a comment or a message. Giving it a fourth possible
|
|
parent would mean rebuilding that table again — so this follows what a
|
|
profile photo already does: a column on the row, a file in the same
|
|
directory, and `uploads.remove` when it goes.
|
|
"""
|
|
if not staged:
|
|
return None
|
|
item = staged[0]
|
|
(uploads.directory() / item["stored_name"]).write_bytes(item["data"])
|
|
return item["stored_name"]
|
|
|
|
|
|
def _back_to_form(item, fields, errors):
|
|
for message in errors:
|
|
flash(message, "error")
|
|
return render_template("submission_form.html", item=item, fields=fields), 400
|