Compare commits
10 Commits
028b7f3269
...
1be18989ed
| Author | SHA1 | Date | |
|---|---|---|---|
| 1be18989ed | |||
| 7e70004e7b | |||
| 91aa0c9a9e | |||
| 440ed45ca5 | |||
|
|
1e1113ed53 | ||
| 076d16aa7a | |||
|
|
5e8ee5ad20 | ||
| c3a7d8fb89 | |||
|
|
8608e71c7e | ||
|
|
4e82f66d08 |
@ -13,7 +13,7 @@ from datetime import datetime, timezone
|
||||
from flask import Flask, render_template, request
|
||||
from werkzeug.middleware.proxy_fix import ProxyFix
|
||||
|
||||
from .db import close_db, init_db
|
||||
from .db import TOMBSTONE_LOGIN, close_db, init_db
|
||||
from .security import check_csrf, csrf_token
|
||||
|
||||
URL_PREFIX = "/comunidad"
|
||||
@ -94,11 +94,13 @@ def create_app(overrides: dict | None = None) -> Flask:
|
||||
# restart, which is a confusing way to find out the variable is unset.
|
||||
raise RuntimeError("BOARD_SECRET_KEY is required (generate one with `openssl rand -hex 32`).")
|
||||
|
||||
from . import (auth, board, content, home, members, messages, profiles,
|
||||
submissions, uploads)
|
||||
from . import (auth, board, brand, content, events, home, members,
|
||||
messages, profiles, submissions, uploads)
|
||||
app.register_blueprint(auth.bp, url_prefix=URL_PREFIX)
|
||||
app.register_blueprint(home.bp, url_prefix=URL_PREFIX)
|
||||
app.register_blueprint(brand.bp, url_prefix=URL_PREFIX)
|
||||
app.register_blueprint(submissions.bp, url_prefix=URL_PREFIX)
|
||||
app.register_blueprint(events.bp, url_prefix=URL_PREFIX)
|
||||
app.register_blueprint(members.bp, url_prefix=URL_PREFIX)
|
||||
app.register_blueprint(content.bp, url_prefix=URL_PREFIX)
|
||||
app.register_blueprint(uploads.bp, url_prefix=URL_PREFIX)
|
||||
@ -113,11 +115,21 @@ def create_app(overrides: dict | None = None) -> Flask:
|
||||
app.teardown_appcontext(close_db)
|
||||
app.jinja_env.globals["csrf_token"] = csrf_token
|
||||
app.jinja_env.globals["url_prefix"] = URL_PREFIX
|
||||
# For _person.html: the one login with no page behind it. A literal in the
|
||||
# template would be the same string written twice, in two languages.
|
||||
app.jinja_env.globals["tombstone_login"] = TOMBSTONE_LOGIN
|
||||
|
||||
@app.context_processor
|
||||
def _year():
|
||||
return {"current_year": datetime.now(timezone.utc).year}
|
||||
|
||||
@app.context_processor
|
||||
def _brand():
|
||||
# Not lazy, unlike the badges below: base.html draws the stylesheet
|
||||
# link, the logo and the favicon on every page, so there is no render
|
||||
# that would save the query by deferring it.
|
||||
return {"brand": brand.state()}
|
||||
|
||||
@app.context_processor
|
||||
def _badges():
|
||||
# Lazily, as functions: base.html is rendered for signed-out pages and
|
||||
|
||||
613
apps/board/brand.py
Normal file
613
apps/board/brand.py
Normal file
@ -0,0 +1,613 @@
|
||||
"""The look of both halves of the site, owned by the admin rather than by me.
|
||||
|
||||
Until this existed, the brand colours were two identical `:root` blocks — one in
|
||||
`themes/vienalatina/assets/css/main.css`, one in `apps/board/static/board.css` —
|
||||
with a comment in the second saying *"If the brand colours change, change them
|
||||
in both."* There was no logo anywhere and no favicon in either `<head>`. Every
|
||||
one of those is a change only somebody with the repository could make.
|
||||
|
||||
**The dictionary below is now the single source of truth for the palette**, and
|
||||
`apps/board/tests/test_brand.py` parses both stylesheets and fails if either
|
||||
drifts from it. That is what retires the comment: not by merging the two files —
|
||||
they are served by different things and each has to stand on its own — but by
|
||||
making a divergence fail the build instead of going unnoticed for a month.
|
||||
|
||||
### The two destinations
|
||||
|
||||
One form, saved to two places, because the two halves cannot read the same
|
||||
store:
|
||||
|
||||
* **SQLite**, for the members area, which must render correctly when the git
|
||||
server is unreachable — the same rule the private calendar follows.
|
||||
* **Git** (`data/brand.yaml` and `static/brand/…`), for the public site, which
|
||||
is files on disk built by Hugo and has no database to read.
|
||||
|
||||
SQLite is written first and the commits follow. If Gitea is down the change
|
||||
still takes effect here, the row keeps `published_at` NULL, and the screen says
|
||||
so with a button to try the publish again. The other order would let a git
|
||||
outage block a change that does not need git.
|
||||
|
||||
### Why the custom CSS is a file and not a `<style>`
|
||||
|
||||
The Content-Security-Policy in `app.py` has no `'unsafe-inline'`, so an inline
|
||||
style block is not an error anybody sees — the browser ignores it and the colours
|
||||
simply do not apply. Both halves therefore serve a generated stylesheet:
|
||||
`/comunidad/marca.css` here, a fingerprinted `resources.FromString` on the
|
||||
public site.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import colorsys
|
||||
import json
|
||||
import re
|
||||
|
||||
from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
|
||||
render_template, request, send_from_directory, url_for)
|
||||
|
||||
from . import gitea, uploads
|
||||
from .db import get_db
|
||||
from .security import admin_required
|
||||
|
||||
bp = Blueprint("brand", __name__)
|
||||
|
||||
# Every token, with the value it has had since the site was built. Copied from
|
||||
# the two `:root` blocks, which the test above holds to this.
|
||||
FACTORY = {
|
||||
"brand": "#c0391c",
|
||||
"brand-dark": "#9a2a0f",
|
||||
"brand-soft": "#fbe2db",
|
||||
"brand-softer": "#fdf1ed",
|
||||
"bg": "#f8f3ef",
|
||||
"surface": "#ffffff",
|
||||
"surface-soft": "#f2ebe6",
|
||||
"border": "#c2a89f",
|
||||
"border-light": "#e0cec8",
|
||||
"text": "#1a0d09",
|
||||
"muted": "#5c3d37",
|
||||
"subtle": "#9a7870",
|
||||
"danger": "#a11b1b",
|
||||
}
|
||||
|
||||
# The six on the easy form, in the order they are drawn, with what each one is
|
||||
# for in words an admin can act on. Six rather than thirteen because the other
|
||||
# seven are shades of these, and a form of thirteen colour pickers is a form
|
||||
# nobody finishes.
|
||||
SIMPLE = (
|
||||
("brand", "Color principal", "Botones, enlaces y la barra de arriba."),
|
||||
("bg", "Fondo", "El color de la página detrás de todo."),
|
||||
("surface", "Tarjetas", "El fondo de las tarjetas y los formularios."),
|
||||
("text", "Texto", "El color de las letras."),
|
||||
("muted", "Texto secundario", "Fechas, autores y notas al pie."),
|
||||
("border", "Líneas", "Bordes y separadores."),
|
||||
)
|
||||
|
||||
# Shades worked out from `brand` when they are not given explicitly. The factory
|
||||
# palette has exactly this relationship, so an admin who picks one colour gets a
|
||||
# coherent set rather than one red button on an orange background.
|
||||
#
|
||||
# Each entry is the lightness the shade gets: a multiplier of the brand's own
|
||||
# for the dark one, an absolute value for the two tints. Hue and saturation are
|
||||
# kept, which is what makes them read as the same colour.
|
||||
DERIVED = {
|
||||
"brand-dark": ("scale", 0.75),
|
||||
"brand-soft": ("set", 0.92),
|
||||
"brand-softer": ("set", 0.96),
|
||||
}
|
||||
|
||||
HEX = re.compile(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")
|
||||
|
||||
# The free CSS box takes anything but these. `<` and `>` cannot appear in valid
|
||||
# CSS outside a string, and they are the two characters that could end the
|
||||
# stylesheet context in a consumer that mishandles it. Everything else is left
|
||||
# alone on purpose: the point of the box is that an admin who knows CSS is not
|
||||
# second-guessed.
|
||||
CSS_FORBIDDEN = ("<", ">")
|
||||
CSS_MAX = 20_000
|
||||
|
||||
LOGO_EXTENSIONS = ("png", "jpg", "webp")
|
||||
FAVICON_EXTENSIONS = ("png",)
|
||||
|
||||
# Where the two pictures land in the content repository. Stable paths, so saving
|
||||
# twice replaces the file rather than leaving the old one behind.
|
||||
REPO_FOLDER = "static/brand"
|
||||
DATA_FILE = "data/brand.yaml"
|
||||
|
||||
|
||||
# --- colour arithmetic, all of it from the standard library ----------------
|
||||
|
||||
def _rgb(value: str) -> tuple[float, float, float]:
|
||||
text = value.lstrip("#")
|
||||
if len(text) == 3:
|
||||
text = "".join(c * 2 for c in text)
|
||||
return tuple(int(text[i:i + 2], 16) / 255 for i in (0, 2, 4))
|
||||
|
||||
|
||||
def _hex(rgb: tuple[float, float, float]) -> str:
|
||||
return "#" + "".join(f"{round(max(0.0, min(1.0, c)) * 255):02x}" for c in rgb)
|
||||
|
||||
|
||||
def shade(value: str, token: str) -> str:
|
||||
"""One of the three brand shades, from the brand colour.
|
||||
|
||||
In HLS rather than by multiplying the channels: scaling RGB towards white
|
||||
washes the hue out, and the result of mixing #c0391c with white is pink
|
||||
rather than the warm tint the design uses.
|
||||
"""
|
||||
how, amount = DERIVED[token]
|
||||
hue, lightness, saturation = colorsys.rgb_to_hls(*_rgb(value))
|
||||
lightness = lightness * amount if how == "scale" else amount
|
||||
return _hex(colorsys.hls_to_rgb(hue, lightness, saturation))
|
||||
|
||||
|
||||
def _luminance(value: str) -> float:
|
||||
"""WCAG 2.1 relative luminance."""
|
||||
def channel(c: float) -> float:
|
||||
return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
|
||||
red, green, blue = (channel(c) for c in _rgb(value))
|
||||
return 0.2126 * red + 0.7152 * green + 0.0722 * blue
|
||||
|
||||
|
||||
def contrast(a: str, b: str) -> float:
|
||||
"""The WCAG contrast ratio between two colours, 1.0 to 21.0."""
|
||||
first, second = _luminance(a), _luminance(b)
|
||||
lighter, darker = max(first, second), min(first, second)
|
||||
return (lighter + 0.05) / (darker + 0.05)
|
||||
|
||||
|
||||
# What has to be readable, and the ratio WCAG asks for. Body text is 4.5:1;
|
||||
# 3:1 is the rule for large text and for the edge of a control, which is what a
|
||||
# button in the brand colour is.
|
||||
PAIRS = (
|
||||
("text", "bg", 4.5, "el texto sobre el fondo"),
|
||||
("text", "surface", 4.5, "el texto sobre las tarjetas"),
|
||||
("muted", "surface", 4.5, "el texto secundario sobre las tarjetas"),
|
||||
)
|
||||
|
||||
|
||||
def warnings(tokens: dict) -> list[str]:
|
||||
"""Pairs that are hard to read, named with their ratio.
|
||||
|
||||
A warning and not a refusal. An admin may have a reason, and a form that
|
||||
argues is a form people work around; what this prevents is somebody
|
||||
shipping an unreadable site without once being told.
|
||||
"""
|
||||
notes = []
|
||||
for first, second, needed, description in PAIRS:
|
||||
ratio = contrast(tokens[first], tokens[second])
|
||||
if ratio < needed:
|
||||
notes.append(
|
||||
f"Poco contraste en {description}: {ratio:.1f}:1, y hacen falta "
|
||||
f"{needed}:1. Se guarda igual, pero costará leerlo."
|
||||
)
|
||||
white = contrast("#ffffff", tokens["brand"])
|
||||
if white < 3.0:
|
||||
notes.append(
|
||||
f"El texto blanco sobre el color principal queda en {white:.1f}:1 "
|
||||
"(hacen falta 3:1). Los botones costarán de leer."
|
||||
)
|
||||
return notes
|
||||
|
||||
|
||||
# --- the stored row --------------------------------------------------------
|
||||
|
||||
def _row():
|
||||
return get_db().execute("SELECT * FROM brand WHERE id = 1").fetchone()
|
||||
|
||||
|
||||
def resolve(stored: dict) -> dict:
|
||||
"""Every token's value, given what has been stored.
|
||||
|
||||
Only differences from the factory are stored, which has two consequences
|
||||
worth the arrangement: a token added here later arrives with its default
|
||||
already in place for every existing install, and an admin who has changed
|
||||
one colour has one row of JSON rather than a snapshot of thirteen.
|
||||
|
||||
The three shades are derived from `brand` **only when a brand colour has
|
||||
been stored**. Without one the factory hexes are used verbatim, so saving
|
||||
nothing cannot quietly shift the palette by a rounding error.
|
||||
"""
|
||||
tokens = dict(FACTORY)
|
||||
tokens.update({k: v for k, v in stored.items() if k in FACTORY and v})
|
||||
if stored.get("brand"):
|
||||
for token in DERIVED:
|
||||
if not stored.get(token):
|
||||
tokens[token] = shade(stored["brand"], token)
|
||||
return tokens
|
||||
|
||||
|
||||
def current() -> dict:
|
||||
"""What both the form and the stylesheet read. Works with no row at all."""
|
||||
row = _row()
|
||||
try:
|
||||
stored = json.loads(row["tokens_json"]) if row else {}
|
||||
except (TypeError, ValueError):
|
||||
# A row we cannot parse must not take the site down. Factory colours
|
||||
# and a line in the log is the right failure here.
|
||||
current_app.logger.warning("brand.tokens_json is not readable; using factory")
|
||||
stored = {}
|
||||
if not isinstance(stored, dict):
|
||||
stored = {}
|
||||
return {
|
||||
"stored": stored,
|
||||
"tokens": resolve(stored),
|
||||
"custom_css": (row["custom_css"] if row else "") or "",
|
||||
"logo_name": row["logo_name"] if row else None,
|
||||
"favicon_name": row["favicon_name"] if row else None,
|
||||
"updated_at": row["updated_at"] if row else None,
|
||||
"published_at": row["published_at"] if row else None,
|
||||
"stamp": _stamp(row["updated_at"] if row else None),
|
||||
"customised": bool(stored or (row and (row["custom_css"] or row["logo_name"]
|
||||
or row["favicon_name"]))),
|
||||
}
|
||||
|
||||
|
||||
def _blank() -> dict:
|
||||
"""The factory look, as `current()` would describe it."""
|
||||
return {"stored": {}, "tokens": dict(FACTORY), "custom_css": "",
|
||||
"logo_name": None, "favicon_name": None, "updated_at": None,
|
||||
"published_at": None, "stamp": "0", "customised": False}
|
||||
|
||||
|
||||
def state() -> dict:
|
||||
"""`current()`, once per request, and never raising.
|
||||
|
||||
`base.html` asks for this on every page, the error pages included — and on a
|
||||
500 the thing that broke may well be the database. A page in the factory
|
||||
colours is still a page; a second traceback inside the error handler is not.
|
||||
"""
|
||||
if "brand_state" not in g:
|
||||
try:
|
||||
g.brand_state = current()
|
||||
except Exception: # pragma: no cover - defensive
|
||||
current_app.logger.warning("brand unreadable, using factory", exc_info=True)
|
||||
g.brand_state = _blank()
|
||||
return g.brand_state
|
||||
|
||||
|
||||
def _stamp(updated_at: str | None) -> str:
|
||||
"""A cache-buster safe to put in a query string.
|
||||
|
||||
`updated_at` is SQLite's `datetime('now')` — spaces and colons — and both
|
||||
halves of the site paste this into a URL, so the digits alone are what
|
||||
travels.
|
||||
"""
|
||||
return re.sub(r"\D", "", updated_at or "") or "0"
|
||||
|
||||
|
||||
def stylesheet(state: dict | None = None) -> str:
|
||||
"""The `:root` overrides and then the custom CSS, in that order.
|
||||
|
||||
Only the tokens that differ from the factory are written, so the file reads
|
||||
as what the admin changed, and an install that has changed nothing serves a
|
||||
comment and no rules at all.
|
||||
"""
|
||||
state = state or current()
|
||||
lines = [f"\t--{name}: {value};"
|
||||
for name, value in state["tokens"].items()
|
||||
if value != FACTORY[name]]
|
||||
css = "/* Generado desde Gestión → Marca. No editar a mano. */\n"
|
||||
if lines:
|
||||
css += ":root {\n" + "\n".join(lines) + "\n}\n"
|
||||
if state["custom_css"]:
|
||||
# Last, so it wins over everything above it. That is the whole contract
|
||||
# of the advanced box.
|
||||
css += "\n/* CSS propio */\n" + state["custom_css"] + "\n"
|
||||
return css
|
||||
|
||||
|
||||
# --- reading the form ------------------------------------------------------
|
||||
|
||||
def _read_tokens(form, errors: list[str]) -> dict:
|
||||
"""Only what differs from the factory, and only if it is a colour.
|
||||
|
||||
A colour field is not a place to accept arbitrary CSS: `url(...)` in a
|
||||
custom property is a request to another server on every page view, and
|
||||
there is a whole textarea below for people who want to write CSS.
|
||||
"""
|
||||
stored = {}
|
||||
for name in FACTORY:
|
||||
raw = (form.get(f"token-{name}") or "").strip().lower()
|
||||
if not raw:
|
||||
continue
|
||||
if not HEX.match(raw):
|
||||
errors.append(f"«{raw}» no es un color. Usa la forma #rrggbb.")
|
||||
continue
|
||||
if raw != FACTORY[name].lower():
|
||||
stored[name] = raw
|
||||
return stored
|
||||
|
||||
|
||||
def _read_css(form, errors: list[str]) -> str:
|
||||
css = (form.get("custom_css") or "").strip()
|
||||
if len(css) > CSS_MAX:
|
||||
errors.append(f"El CSS propio no puede pasar de {CSS_MAX // 1000}.000 caracteres.")
|
||||
return ""
|
||||
for character in CSS_FORBIDDEN:
|
||||
if character in css:
|
||||
errors.append(
|
||||
f"El CSS propio no puede contener «{character}». "
|
||||
"Eso no aparece en CSS válido y sí en una etiqueta HTML."
|
||||
)
|
||||
return ""
|
||||
return css
|
||||
|
||||
|
||||
def _read_picture(field: str, allowed: tuple[str, ...], errors: list[str]):
|
||||
"""One staged picture, or None if nothing was chosen.
|
||||
|
||||
`uploads.stage` does the work that matters — it reads the bytes and decides
|
||||
the extension from them rather than from the name — so a GIF called
|
||||
`logo.png` is refused here by the same code that refuses it on the wall.
|
||||
"""
|
||||
upload = request.files.get(field)
|
||||
if not upload or not upload.filename:
|
||||
return None
|
||||
try:
|
||||
staged = uploads.stage([upload])
|
||||
except uploads.RejectedUpload as exc:
|
||||
errors.append(str(exc))
|
||||
return None
|
||||
if not staged:
|
||||
return None
|
||||
item = staged[0]
|
||||
extension = item["stored_name"].rsplit(".", 1)[-1]
|
||||
if extension not in allowed:
|
||||
errors.append(
|
||||
f"«{item['original_name']}» es un {extension}. "
|
||||
f"Aquí hace falta {' o '.join(allowed)}."
|
||||
)
|
||||
return None
|
||||
return item
|
||||
|
||||
|
||||
# --- routes ----------------------------------------------------------------
|
||||
|
||||
@bp.route("/gestion/marca", methods=["GET", "POST"])
|
||||
@admin_required
|
||||
def edit():
|
||||
if request.method == "GET":
|
||||
state = current()
|
||||
return render_template("brand_form.html", state=state,
|
||||
factory=FACTORY, simple=SIMPLE,
|
||||
derived=sorted(DERIVED), advanced=_advanced(),
|
||||
notes=warnings(state["tokens"]))
|
||||
|
||||
errors: list[str] = []
|
||||
stored = _read_tokens(request.form, errors)
|
||||
css = _read_css(request.form, errors)
|
||||
logo = _read_picture("logo", LOGO_EXTENSIONS, errors)
|
||||
favicon = _read_picture("favicon", FAVICON_EXTENSIONS, errors)
|
||||
if errors:
|
||||
for message in errors:
|
||||
flash(message, "error")
|
||||
return redirect(url_for("brand.edit"))
|
||||
|
||||
state = current()
|
||||
# Written before the commits: the members area must not depend on the git
|
||||
# server being up to change its own colours.
|
||||
_store(stored, css, logo, favicon, state)
|
||||
for note in warnings(resolve(stored)):
|
||||
flash(note, "error")
|
||||
|
||||
if _publish():
|
||||
flash("Guardado. El sitio público se reconstruye en un par de minutos.", "ok")
|
||||
return redirect(url_for("brand.edit"))
|
||||
|
||||
|
||||
def _advanced() -> tuple:
|
||||
"""Every token the easy form does not offer, for the fold-out."""
|
||||
simple = {name for name, _, _ in SIMPLE}
|
||||
return tuple(name for name in FACTORY if name not in simple)
|
||||
|
||||
|
||||
def _store(stored: dict, css: str, logo, favicon, state: dict) -> None:
|
||||
"""The row, and the two pictures on disk.
|
||||
|
||||
Files before the row, as `uploads.save` does it and for the same reason: a
|
||||
row naming a file that is not there renders as a broken image on every
|
||||
future visit, while a file with no row is invisible.
|
||||
"""
|
||||
names = {"logo_name": state["logo_name"], "favicon_name": state["favicon_name"]}
|
||||
for field, item in (("logo_name", logo), ("favicon_name", favicon)):
|
||||
if item is None:
|
||||
continue
|
||||
uploads.directory().joinpath(item["stored_name"]).write_bytes(item["data"])
|
||||
names[field] = item["stored_name"]
|
||||
|
||||
get_db().execute(
|
||||
"""INSERT INTO brand (id, tokens_json, custom_css, logo_name, favicon_name,
|
||||
updated_by, updated_at, published_at)
|
||||
VALUES (1, ?, ?, ?, ?, ?, datetime('now'), NULL)
|
||||
ON CONFLICT(id) DO UPDATE SET
|
||||
tokens_json = excluded.tokens_json,
|
||||
custom_css = excluded.custom_css,
|
||||
logo_name = excluded.logo_name,
|
||||
favicon_name = excluded.favicon_name,
|
||||
updated_by = excluded.updated_by,
|
||||
updated_at = excluded.updated_at,
|
||||
published_at = NULL""",
|
||||
(json.dumps(stored, sort_keys=True), css,
|
||||
names["logo_name"], names["favicon_name"], g.member["id"]),
|
||||
)
|
||||
|
||||
# The old pictures, once nothing points at them. After the row, so a
|
||||
# rollback cannot leave the row naming a file that has been deleted.
|
||||
for field, item in (("logo_name", logo), ("favicon_name", favicon)):
|
||||
if item is not None and state[field] and state[field] != names[field]:
|
||||
uploads.remove(state[field])
|
||||
|
||||
|
||||
@bp.route("/gestion/marca/publicar", methods=["POST"])
|
||||
@admin_required
|
||||
def publish():
|
||||
"""Try the commits again after the git server was unreachable."""
|
||||
if _publish():
|
||||
flash("Publicado. El sitio público se reconstruye en un par de minutos.", "ok")
|
||||
return redirect(url_for("brand.edit"))
|
||||
|
||||
|
||||
@bp.route("/gestion/marca/restaurar", methods=["POST"])
|
||||
@admin_required
|
||||
def restore():
|
||||
"""Back to the colours the site was built with.
|
||||
|
||||
Reachable even when the custom CSS has broken every other page, because the
|
||||
Marca screen deliberately does not load it — see `brand_form.html`.
|
||||
"""
|
||||
state = current()
|
||||
get_db().execute("DELETE FROM brand WHERE id = 1")
|
||||
for name in (state["logo_name"], state["favicon_name"]):
|
||||
if name:
|
||||
uploads.remove(name)
|
||||
flash("Restaurado lo de fábrica.", "ok")
|
||||
_publish()
|
||||
return redirect(url_for("brand.edit"))
|
||||
|
||||
|
||||
@bp.route("/marca.css")
|
||||
def stylesheet_file():
|
||||
"""Loaded by every page in the members area, after board.css.
|
||||
|
||||
No login: it carries no private data, and the sign-in page should look like
|
||||
the site it signs you in to. Cached hard and busted by `?v=`, which is why
|
||||
`base.html` appends the stamp.
|
||||
"""
|
||||
response = Response(stylesheet(), mimetype="text/css")
|
||||
response.headers["Cache-Control"] = "public, max-age=31536000, immutable"
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/marca/<stored_name>")
|
||||
def picture(stored_name: str):
|
||||
"""The logo and the favicon, for the members area.
|
||||
|
||||
Its own route rather than `uploads.serve`, which is behind the login: these
|
||||
two are public by definition, and one of them is in the `<head>` of the
|
||||
sign-in page. Only the current pair is served — an old logo stops being
|
||||
reachable the moment it is replaced, which is also when the file goes.
|
||||
"""
|
||||
if not uploads.STORED_NAME.match(stored_name):
|
||||
abort(404)
|
||||
state = current()
|
||||
if stored_name not in (state["logo_name"], state["favicon_name"]):
|
||||
abort(404)
|
||||
return send_from_directory(uploads.directory(), stored_name)
|
||||
|
||||
|
||||
# --- the public site's copy ------------------------------------------------
|
||||
|
||||
def _repo_path(stored_name: str, kind: str) -> str:
|
||||
"""A stable path per picture: `static/brand/logo.png`.
|
||||
|
||||
Stable rather than the stored name so that saving a new logo replaces the
|
||||
file instead of leaving every previous one in the repository, deployed and
|
||||
unreferenced.
|
||||
"""
|
||||
return f"{REPO_FOLDER}/{kind}.{stored_name.rsplit('.', 1)[-1]}"
|
||||
|
||||
|
||||
def _yaml(state: dict, logo: str | None, favicon: str | None) -> str:
|
||||
"""`data/brand.yaml`, written rather than dumped.
|
||||
|
||||
By hand because the values are known: colours matched against a hex
|
||||
pattern, a stamp of digits, two paths this module built, and one block of
|
||||
CSS that goes in as a literal block scalar so nothing in it needs quoting.
|
||||
PyYAML is not a dependency of the members area and is not worth becoming
|
||||
one for twenty lines of output.
|
||||
"""
|
||||
lines = ["# Generado desde Gestión → Marca en vienalatina.com/comunidad.",
|
||||
"# No editar a mano: el próximo guardado lo sobrescribe.",
|
||||
f"stamp: \"{state['stamp']}\"",
|
||||
"tokens:"]
|
||||
for name, value in state["tokens"].items():
|
||||
if value != FACTORY[name]:
|
||||
lines.append(f" {name}: \"{value}\"")
|
||||
if logo:
|
||||
lines.append(f"logo: \"/{logo.removeprefix('static/')}\"")
|
||||
if favicon:
|
||||
lines.append(f"favicon: \"/{favicon.removeprefix('static/')}\"")
|
||||
if state["custom_css"]:
|
||||
lines.append("custom_css: |")
|
||||
lines += [f" {line}" for line in state["custom_css"].splitlines()]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def _publish() -> bool:
|
||||
"""Commit the brand into the content repository. True if it got there.
|
||||
|
||||
Four commits at most, because the contents API writes one file per request.
|
||||
That is the same trade `content.commit_picture` makes: the git trees API
|
||||
would batch them, at the cost of noticeably more code to get wrong, for a
|
||||
benefit nobody sees beyond one fewer pipeline run.
|
||||
|
||||
Returns False and says why rather than raising: the colours are already
|
||||
saved here, and an admin whose change took effect in the members area needs
|
||||
to know the public site is a step behind, not to meet a traceback.
|
||||
"""
|
||||
state = current()
|
||||
try:
|
||||
token = gitea.content_token()
|
||||
except gitea.GiteaError as exc:
|
||||
flash(f"Guardado aquí. El sitio público no se ha actualizado: {exc}", "error")
|
||||
return False
|
||||
|
||||
try:
|
||||
logo_path = favicon_path = None
|
||||
for kind, name in (("logo", state["logo_name"]),
|
||||
("favicon", state["favicon_name"])):
|
||||
if not name:
|
||||
continue
|
||||
path = _repo_path(name, kind)
|
||||
data = uploads.directory().joinpath(name).read_bytes()
|
||||
_write(path, data, f"marca: {kind}", token)
|
||||
_tidy(kind, path, token)
|
||||
if kind == "logo":
|
||||
logo_path = path
|
||||
else:
|
||||
favicon_path = path
|
||||
|
||||
_write(DATA_FILE, _yaml(state, logo_path, favicon_path).encode("utf-8"),
|
||||
"marca: colores", token)
|
||||
except (gitea.GiteaError, OSError) as exc:
|
||||
current_app.logger.warning("brand publish failed: %s", exc)
|
||||
flash(f"Guardado aquí. El sitio público no se ha actualizado: {exc}", "error")
|
||||
return False
|
||||
|
||||
get_db().execute(
|
||||
"UPDATE brand SET published_at = datetime('now') WHERE id = 1")
|
||||
return True
|
||||
|
||||
|
||||
def _write(path: str, data: bytes, message: str, token: str) -> None:
|
||||
"""Create or update, whichever this file needs.
|
||||
|
||||
The contents API wants the current sha to replace a file and refuses one
|
||||
when creating, so the read comes first. A missing file is the normal case
|
||||
the first time.
|
||||
"""
|
||||
try:
|
||||
_, sha = gitea.read_file(path, token)
|
||||
except gitea.GiteaError:
|
||||
sha = None
|
||||
gitea.write_file(path, data, message, token, sha=sha)
|
||||
|
||||
|
||||
def _tidy(kind: str, keep: str, token: str) -> None:
|
||||
"""Remove a previous picture of the same kind with another extension.
|
||||
|
||||
A logo saved as a PNG and then as a WebP would otherwise leave
|
||||
`static/brand/logo.png` in the repository for good — deployed, unreferenced
|
||||
and confusing to the next person who looks. Failure here is logged and
|
||||
swallowed: the new logo is already committed, and a leftover file is not a
|
||||
reason to tell the admin their change did not work.
|
||||
"""
|
||||
try:
|
||||
for item in gitea.list_directory(REPO_FOLDER, token):
|
||||
name = item.get("name", "")
|
||||
path = f"{REPO_FOLDER}/{name}"
|
||||
if path != keep and name.rsplit(".", 1)[0] == kind:
|
||||
gitea.delete_file(path, item.get("sha", ""),
|
||||
f"marca: retirar {name}", token)
|
||||
except (gitea.GiteaError, OSError) as exc:
|
||||
current_app.logger.info("brand tidy-up skipped: %s", exc)
|
||||
@ -59,7 +59,12 @@ COLLECTIONS = {
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORIES = ["Turismo", "Cultura", "Gastronomía", "Comunidad", "Comercio"]
|
||||
# The one category that changes what a post *is* rather than what it is about:
|
||||
# tick it and the post needs a date of its own, appears in the agenda, renders
|
||||
# with the date and the place at the top, and offers an .ics.
|
||||
EVENT_CATEGORY = "Evento"
|
||||
|
||||
CATEGORIES = ["Evento", "Turismo", "Cultura", "Gastronomía", "Comunidad", "Comercio"]
|
||||
|
||||
UPLOAD_FOLDER = "static/uploads"
|
||||
|
||||
@ -80,6 +85,10 @@ AUTHOR_URL = re.compile(r"^/[A-Za-z0-9][A-Za-z0-9._-]{0,38}$")
|
||||
# names when it hangs under it.
|
||||
PAGE_BASENAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$")
|
||||
|
||||
# 24-hour, because every reader of this site is in one city and half of them
|
||||
# learned to read a clock in a country that writes it this way.
|
||||
EVENT_TIME = re.compile(r"^([01][0-9]|2[0-3]):[0-5][0-9]$")
|
||||
|
||||
|
||||
# --- the contract with translate.py --------------------------------------
|
||||
|
||||
@ -129,6 +138,16 @@ def frontmatter_for(collection: str, form: dict) -> dict:
|
||||
fields["faq"] = form["faq"]
|
||||
if form.get("image_alt"):
|
||||
fields["image_alt"] = form["image_alt"]
|
||||
if collection == "post" and form.get("event_date"):
|
||||
fields["event_date"] = form["event_date"]
|
||||
if form.get("event_time"):
|
||||
fields["event_time"] = form["event_time"]
|
||||
if form.get("event_location"):
|
||||
fields["event_location"] = form["event_location"]
|
||||
# Hugo builds one output per format listed here, so only an event gets
|
||||
# an .ics file beside its page. Written by this code and never by a
|
||||
# person: it is a build instruction, not something to explain in a form.
|
||||
fields["outputs"] = ["HTML", "ics"]
|
||||
if collection == "post":
|
||||
if form["categories"]:
|
||||
fields["categories"] = form["categories"]
|
||||
@ -162,14 +181,22 @@ def _cache_read(path: str, sha: str):
|
||||
|
||||
def _cache_write(path: str, sha: str, fm: dict) -> None:
|
||||
get_db().execute(
|
||||
"""INSERT INTO content_cache (path, sha, title, date, categories, generated)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
"""INSERT INTO content_cache (path, sha, title, date, categories, generated,
|
||||
event_date, event_time, event_location)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(path) DO UPDATE SET
|
||||
sha = excluded.sha, title = excluded.title, date = excluded.date,
|
||||
categories = excluded.categories, generated = excluded.generated,
|
||||
event_date = excluded.event_date, event_time = excluded.event_time,
|
||||
event_location = excluded.event_location,
|
||||
updated_at = datetime('now')""",
|
||||
(path, sha, str(fm.get("title", "")), str(fm.get("date", "")),
|
||||
", ".join(fm.get("categories") or []), 1 if fm.get("translated_from") else 0),
|
||||
", ".join(fm.get("categories") or []), 1 if fm.get("translated_from") else 0,
|
||||
# Cached for the private calendar, which shows public events beside the
|
||||
# internal ones and would otherwise read every post's frontmatter on
|
||||
# every page view to find out when they are.
|
||||
str(fm.get("event_date", "") or ""), str(fm.get("event_time", "") or ""),
|
||||
str(fm.get("event_location", "") or "")),
|
||||
)
|
||||
|
||||
|
||||
@ -197,6 +224,9 @@ def listing(collection: str) -> list[dict]:
|
||||
"name": name, "path": path, "sha": sha,
|
||||
"title": row["title"] or name,
|
||||
"date": row["date"], "categories": row["categories"],
|
||||
"event_date": row["event_date"] or "",
|
||||
"event_time": row["event_time"] or "",
|
||||
"event_location": row["event_location"] or "",
|
||||
})
|
||||
|
||||
items.sort(key=lambda item: (item["date"], item["name"]), reverse=True)
|
||||
@ -247,11 +277,6 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]:
|
||||
|
||||
categories = [c for c in request.form.getlist("categories") if c in CATEGORIES]
|
||||
|
||||
# Carried through the form as hidden fields, the way the date and the image
|
||||
# path are: they belong to the document being edited, not to whoever is
|
||||
# editing it, so saving a correction must not re-sign the post. Checked on
|
||||
# the way back in because a hidden field is only a convention — the URL has
|
||||
# to be a path on this site and nothing else.
|
||||
# A page's place in the menu. `parent` is another page's basename — the one
|
||||
# translate.py uses to pair siblings, so a parent chosen once holds in all
|
||||
# three languages — and the menu is built from these, not from a list in
|
||||
@ -269,9 +294,19 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]:
|
||||
# separator is dropped rather than published half-formed. They are rendered
|
||||
# on the page and as FAQPage structured data, which is the shape an answer
|
||||
# engine quotes most readily.
|
||||
# When a post is an event, it has a date of its own. The post's `date` above
|
||||
# is when it was announced — often weeks earlier, and the thing Hugo sorts
|
||||
# the blog by — so the two cannot be the same field.
|
||||
event = read_event_fields(request.form, categories, errors)
|
||||
|
||||
faq = clean_faq(request.form.get("faq", ""))
|
||||
image_alt = request.form.get("image_alt", "").strip()[:200]
|
||||
|
||||
# Carried through the form as hidden fields, the way the date and the image
|
||||
# path are: they belong to the document being edited, not to whoever is
|
||||
# editing it, so saving a correction must not re-sign the post. Checked on
|
||||
# the way back in because a hidden field is only a convention — the URL has
|
||||
# to be a path on this site and nothing else.
|
||||
author = request.form.get("author", "").strip()[:80]
|
||||
author_url = request.form.get("author_url", "").strip()
|
||||
if author_url and not AUTHOR_URL.match(author_url):
|
||||
@ -294,6 +329,7 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]:
|
||||
"author": author, "author_url": author_url,
|
||||
"parent": parent, "weight": weight,
|
||||
"faq": faq, "image_alt": image_alt,
|
||||
**event,
|
||||
}
|
||||
return fields, body, errors
|
||||
|
||||
@ -332,6 +368,40 @@ def commit_picture(data: bytes, filename: str, author=None) -> str:
|
||||
return f"/uploads/{name}"
|
||||
|
||||
|
||||
def read_event_fields(form, categories: list[str], errors: list[str]) -> dict:
|
||||
"""The three fields that come with the Evento category.
|
||||
|
||||
Shared by the editor and by a member's proposal, so a post written by a
|
||||
moderator and one approved from the queue carry the same frontmatter. The
|
||||
date is required and the other two are not: an event with no time is an
|
||||
all-day event, and one with no place is a mistake somebody can fix later
|
||||
rather than a reason to refuse the whole post.
|
||||
|
||||
Returns empty strings when the category is absent, so an ordinary article
|
||||
never carries empty event lines in its frontmatter.
|
||||
"""
|
||||
if EVENT_CATEGORY not in categories:
|
||||
return {"event_date": "", "event_time": "", "event_location": ""}
|
||||
|
||||
raw = form.get("event_date", "").strip()
|
||||
try:
|
||||
event_date = datetime.strptime(raw, "%Y-%m-%d").date().isoformat()
|
||||
except ValueError:
|
||||
event_date = ""
|
||||
errors.append("Un evento necesita fecha, con el formato AAAA-MM-DD.")
|
||||
|
||||
event_time = form.get("event_time", "").strip()
|
||||
if event_time and not EVENT_TIME.match(event_time):
|
||||
event_time = ""
|
||||
errors.append("La hora debe ser HH:MM, de 00:00 a 23:59.")
|
||||
|
||||
return {
|
||||
"event_date": event_date,
|
||||
"event_time": event_time,
|
||||
"event_location": form.get("event_location", "").strip()[:200],
|
||||
}
|
||||
|
||||
|
||||
def clean_faq(raw: str) -> list[str]:
|
||||
"""`pregunta|respuesta` per line, kept only when both halves are there.
|
||||
|
||||
@ -492,6 +562,9 @@ def edit(collection: str, name: str):
|
||||
"weight": fm.get("weight", ""),
|
||||
"faq": "\n".join(fm.get("faq") or []),
|
||||
"image_alt": fm.get("image_alt", ""),
|
||||
"event_date": str(fm.get("event_date", "") or ""),
|
||||
"event_time": str(fm.get("event_time", "") or ""),
|
||||
"event_location": fm.get("event_location", ""),
|
||||
}
|
||||
return render_template("content_form.html", collection=collection, meta=meta,
|
||||
categories=CATEGORIES, item={"name": name, "sha": sha},
|
||||
@ -562,6 +635,36 @@ def preview(collection: str):
|
||||
preview_html=to_html(body))
|
||||
|
||||
|
||||
def public_events() -> list[dict]:
|
||||
"""The published events, for the private calendar to show beside its own.
|
||||
|
||||
Reads the same cache the editor's listing fills, so this costs one directory
|
||||
request and nothing more for files that have not changed. The permalink is
|
||||
rebuilt from the filename rather than stored: `YYYY-MM-DD-slug.es.md` is the
|
||||
contract translate.py and Hugo's `permalinks` both already rely on.
|
||||
"""
|
||||
events = []
|
||||
for item in listing("post"):
|
||||
if not item["event_date"]:
|
||||
continue
|
||||
# `2026-10-24-feria.es.md` → /2026/10/24/feria/, the shape config.yaml's
|
||||
# `permalinks` sets for this section.
|
||||
parts = item["name"].removesuffix(".es.md").split("-", 3)
|
||||
if len(parts) == 4 and parts[0].isdigit():
|
||||
url = f"/{parts[0]}/{parts[1]}/{parts[2]}/{parts[3]}/"
|
||||
else:
|
||||
url = ""
|
||||
events.append({
|
||||
"title": item["title"],
|
||||
"starts_on": item["event_date"],
|
||||
"starts_at": item["event_time"],
|
||||
"location": item["event_location"],
|
||||
"url": url,
|
||||
"public": True,
|
||||
})
|
||||
return events
|
||||
|
||||
|
||||
def possible_parents(collection: str, exclude: str = "") -> list[dict]:
|
||||
"""The pages a page may hang under, for the select in the form.
|
||||
|
||||
|
||||
329
apps/board/events.py
Normal file
329
apps/board/events.py
Normal file
@ -0,0 +1,329 @@
|
||||
"""The private calendar.
|
||||
|
||||
What the association is doing and when, for the people inside: a meeting, a
|
||||
rehearsal, a visit somewhere. Admins write them, every member reads them, and
|
||||
nothing here is ever published — no Open Graph, no sitemap, nothing written to
|
||||
/var/www. That is the whole difference between this and a post in the Evento
|
||||
category, and it is why the two live in different places rather than behind a
|
||||
flag on one.
|
||||
|
||||
**The public events appear here too**, marked as public and linking to the site,
|
||||
because a member should have one place to look rather than two. They come from
|
||||
`content.public_events`, which reads the cache the editor's listing already
|
||||
fills — so a month view costs one directory request to the git server, not one
|
||||
per post. When that server cannot be reached the private events still render and
|
||||
the page says the public ones are missing, rather than failing whole.
|
||||
|
||||
The month grid is built with Python's own `calendar` module. There is no
|
||||
JavaScript here and no date arithmetic of mine to get wrong: the standard
|
||||
library has known which day of the week the first of the month falls on since
|
||||
1991.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
|
||||
from flask import (Blueprint, Response, abort, flash, g, redirect,
|
||||
render_template, request, url_for)
|
||||
|
||||
from . import content, gitea, uploads
|
||||
from .db import get_db
|
||||
from .render import to_html
|
||||
from .security import admin_required, login_required
|
||||
|
||||
bp = Blueprint("events", __name__)
|
||||
|
||||
TITLE_MAX = 140
|
||||
BODY_MAX = 20_000
|
||||
LOCATION_MAX = 200
|
||||
|
||||
MONTH = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$")
|
||||
TIME = re.compile(r"^([01][0-9]|2[0-3]):[0-5][0-9]$")
|
||||
|
||||
MONTH_NAMES = ["enero", "febrero", "marzo", "abril", "mayo", "junio", "julio",
|
||||
"agosto", "septiembre", "octubre", "noviembre", "diciembre"]
|
||||
WEEKDAYS = ["lun", "mar", "mié", "jue", "vie", "sáb", "dom"]
|
||||
|
||||
|
||||
def month_label(year: int, month: int) -> str:
|
||||
return f"{MONTH_NAMES[month - 1]} {year}"
|
||||
|
||||
|
||||
def shift(year: int, month: int, by: int) -> tuple[int, int]:
|
||||
"""The month `by` months away. Written out rather than reached for a
|
||||
library: twelve months is modular arithmetic, and dateutil is a dependency."""
|
||||
index = (year * 12 + month - 1) + by
|
||||
return index // 12, index % 12 + 1
|
||||
|
||||
|
||||
def _requested_month() -> tuple[int, int]:
|
||||
"""`?mes=2026-10`, or the month we are in. A malformed one is today's rather
|
||||
than a 400: a calendar that refuses to draw because a query string was
|
||||
mistyped is worse than one that shows now."""
|
||||
match = MONTH.match(request.args.get("mes", ""))
|
||||
if match:
|
||||
return int(match.group(1)), int(match.group(2))
|
||||
today = date.today()
|
||||
return today.year, today.month
|
||||
|
||||
|
||||
def private_events(first: str, last: str) -> list[dict]:
|
||||
rows = get_db().execute(
|
||||
"""SELECT e.*, m.display_name AS author
|
||||
FROM events e LEFT JOIN members m ON m.id = e.created_by
|
||||
WHERE e.starts_on BETWEEN ? AND ?
|
||||
ORDER BY e.starts_on, COALESCE(e.starts_at, '99:99')""",
|
||||
(first, last),
|
||||
).fetchall()
|
||||
return [{
|
||||
"id": row["id"],
|
||||
"title": row["title"],
|
||||
"starts_on": row["starts_on"],
|
||||
"starts_at": row["starts_at"] or "",
|
||||
"location": row["location"] or "",
|
||||
"url": url_for("events.show", event_id=row["id"]),
|
||||
"public": False,
|
||||
} for row in rows]
|
||||
|
||||
|
||||
@bp.route("/calendario")
|
||||
@login_required
|
||||
def month():
|
||||
year, number = _requested_month()
|
||||
days_in_month = calendar.monthrange(year, number)[1]
|
||||
first = f"{year:04d}-{number:02d}-01"
|
||||
last = f"{year:04d}-{number:02d}-{days_in_month:02d}"
|
||||
|
||||
events = private_events(first, last)
|
||||
|
||||
# The public ones, from the site. A git server that is unreachable must not
|
||||
# take the private calendar down with it — it is the half that only exists
|
||||
# here.
|
||||
public_missing = False
|
||||
try:
|
||||
events += [item for item in content.public_events()
|
||||
if first <= item["starts_on"] <= last]
|
||||
except gitea.GiteaError:
|
||||
public_missing = True
|
||||
|
||||
by_day: dict[int, list] = {}
|
||||
for item in sorted(events, key=lambda e: (e["starts_on"], e["starts_at"] or "99:99")):
|
||||
by_day.setdefault(int(item["starts_on"][8:10]), []).append(item)
|
||||
|
||||
previous_year, previous_month = shift(year, number, -1)
|
||||
next_year, next_month = shift(year, number, 1)
|
||||
today = date.today()
|
||||
|
||||
return render_template(
|
||||
"calendar.html",
|
||||
weeks=calendar.Calendar(firstweekday=0).monthdayscalendar(year, number),
|
||||
weekdays=WEEKDAYS,
|
||||
by_day=by_day,
|
||||
label=month_label(year, number),
|
||||
month_key=f"{year:04d}-{number:02d}",
|
||||
previous=f"{previous_year:04d}-{previous_month:02d}",
|
||||
next=f"{next_year:04d}-{next_month:02d}",
|
||||
this_month=f"{today.year:04d}-{today.month:02d}",
|
||||
today=today.day if (today.year, today.month) == (year, number) else 0,
|
||||
public_missing=public_missing,
|
||||
may_edit=g.member["role"] in ("owner", "admin"),
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/calendario/<int:event_id>")
|
||||
@login_required
|
||||
def show(event_id: int):
|
||||
row = _load(event_id)
|
||||
return render_template("event.html", event=row,
|
||||
body_html=to_html(row["body_md"] or ""),
|
||||
when=_spoken_date(row["starts_on"]),
|
||||
may_edit=g.member["role"] in ("owner", "admin"))
|
||||
|
||||
|
||||
@bp.route("/calendario/<int:event_id>.ics")
|
||||
@login_required
|
||||
def ics(event_id: int):
|
||||
"""The same courtesy the public events get, behind the login.
|
||||
|
||||
Hand-written rather than through a library for the same reason the rest of
|
||||
this app is: it is fifteen lines of a format that has not changed since
|
||||
1998, and the alternative is a dependency to track for them.
|
||||
"""
|
||||
row = _load(event_id)
|
||||
start = row["starts_on"].replace("-", "")
|
||||
if row["starts_at"]:
|
||||
when = f"DTSTART;TZID=Europe/Vienna:{start}T{row['starts_at'].replace(':', '')}00"
|
||||
else:
|
||||
when = f"DTSTART;VALUE=DATE:{start}"
|
||||
|
||||
def escaped(text: str) -> str:
|
||||
return re.sub(r"([,;\\])", r"\\\1", (text or "").replace("\n", " "))
|
||||
|
||||
lines = [
|
||||
"BEGIN:VCALENDAR", "VERSION:2.0",
|
||||
"PRODID:-//Viena Latina//calendario//ES", "CALSCALE:GREGORIAN",
|
||||
"BEGIN:VEVENT",
|
||||
# Stable and unique, so adding it twice updates one entry rather than
|
||||
# making two.
|
||||
f"UID:evento-{row['id']}@vienalatina.com",
|
||||
f"DTSTAMP:{datetime.utcnow().strftime('%Y%m%dT%H%M%SZ')}",
|
||||
when,
|
||||
f"SUMMARY:{escaped(row['title'])}",
|
||||
]
|
||||
if row["location"]:
|
||||
lines.append(f"LOCATION:{escaped(row['location'])}")
|
||||
if row["body_md"]:
|
||||
lines.append(f"DESCRIPTION:{escaped(row['body_md'])[:500]}")
|
||||
lines += ["END:VEVENT", "END:VCALENDAR"]
|
||||
|
||||
return Response(
|
||||
"\r\n".join(lines) + "\r\n",
|
||||
mimetype="text/calendar",
|
||||
headers={"Content-Disposition":
|
||||
f'attachment; filename="evento-{row["id"]}.ics"'},
|
||||
)
|
||||
|
||||
|
||||
# --- writing them, which only admins do -----------------------------------
|
||||
|
||||
@bp.route("/calendario/nuevo", methods=["GET", "POST"])
|
||||
@admin_required
|
||||
def new():
|
||||
if request.method == "GET":
|
||||
return render_template("event_form.html", event=None,
|
||||
suggested=request.args.get("dia", ""))
|
||||
|
||||
fields, errors = _read_form()
|
||||
if errors:
|
||||
return _back(None, fields, errors)
|
||||
|
||||
photo_name = _store_picture()
|
||||
cursor = get_db().execute(
|
||||
"""INSERT INTO events (title, body_md, starts_on, starts_at, location,
|
||||
photo_name, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)""",
|
||||
(fields["title"], fields["body"], fields["starts_on"], fields["starts_at"],
|
||||
fields["location"], photo_name, g.member["id"]),
|
||||
)
|
||||
flash("Evento añadido al calendario.", "ok")
|
||||
return redirect(url_for("events.show", event_id=cursor.lastrowid))
|
||||
|
||||
|
||||
@bp.route("/calendario/<int:event_id>/editar", methods=["GET", "POST"])
|
||||
@admin_required
|
||||
def edit(event_id: int):
|
||||
row = _load(event_id)
|
||||
if request.method == "GET":
|
||||
return render_template("event_form.html", event=row, suggested="")
|
||||
|
||||
fields, errors = _read_form()
|
||||
if errors:
|
||||
return _back(row, fields, errors)
|
||||
|
||||
photo_name = row["photo_name"]
|
||||
staged = _store_picture()
|
||||
if staged:
|
||||
if photo_name:
|
||||
uploads.remove(photo_name)
|
||||
photo_name = staged
|
||||
|
||||
get_db().execute(
|
||||
"""UPDATE events SET title = ?, body_md = ?, starts_on = ?, starts_at = ?,
|
||||
location = ?, photo_name = ?, updated_at = datetime('now')
|
||||
WHERE id = ?""",
|
||||
(fields["title"], fields["body"], fields["starts_on"], fields["starts_at"],
|
||||
fields["location"], photo_name, event_id),
|
||||
)
|
||||
flash("Evento actualizado.", "ok")
|
||||
return redirect(url_for("events.show", event_id=event_id))
|
||||
|
||||
|
||||
@bp.route("/calendario/<int:event_id>/eliminar", methods=["POST"])
|
||||
@admin_required
|
||||
def delete(event_id: int):
|
||||
row = _load(event_id)
|
||||
get_db().execute("DELETE FROM events WHERE id = ?", (event_id,))
|
||||
if row["photo_name"]:
|
||||
uploads.remove(row["photo_name"])
|
||||
flash(f"«{row['title']}» ya no está en el calendario.", "ok")
|
||||
return redirect(url_for("events.month", mes=row["starts_on"][:7]))
|
||||
|
||||
|
||||
@bp.route("/calendario/foto/<stored_name>")
|
||||
@login_required
|
||||
def photo(stored_name: str):
|
||||
"""Behind the login, like the calendar it belongs to."""
|
||||
if not uploads.STORED_NAME.match(stored_name):
|
||||
abort(404)
|
||||
row = get_db().execute(
|
||||
"SELECT 1 FROM events WHERE photo_name = ?", (stored_name,)).fetchone()
|
||||
if row is None:
|
||||
abort(404)
|
||||
from flask import send_from_directory
|
||||
return send_from_directory(uploads.directory(), stored_name)
|
||||
|
||||
|
||||
# --- helpers --------------------------------------------------------------
|
||||
|
||||
def _load(event_id: int):
|
||||
row = get_db().execute("SELECT * FROM events WHERE id = ?", (event_id,)).fetchone()
|
||||
if row is None:
|
||||
abort(404)
|
||||
return row
|
||||
|
||||
|
||||
def _spoken_date(stamp: str) -> str:
|
||||
when = datetime.strptime(stamp, "%Y-%m-%d").date()
|
||||
return f"{when.day} de {MONTH_NAMES[when.month - 1]} de {when.year}"
|
||||
|
||||
|
||||
def _read_form() -> tuple[dict, list[str]]:
|
||||
errors = []
|
||||
fields = {
|
||||
"title": request.form.get("title", "").strip()[:TITLE_MAX],
|
||||
"body": request.form.get("body", "").strip()[:BODY_MAX],
|
||||
"location": request.form.get("location", "").strip()[:LOCATION_MAX],
|
||||
"starts_on": "",
|
||||
"starts_at": "",
|
||||
}
|
||||
if not fields["title"]:
|
||||
errors.append("El evento necesita un título.")
|
||||
|
||||
try:
|
||||
fields["starts_on"] = datetime.strptime(
|
||||
request.form.get("starts_on", "").strip(), "%Y-%m-%d").date().isoformat()
|
||||
except ValueError:
|
||||
errors.append("La fecha debe tener el formato AAAA-MM-DD.")
|
||||
|
||||
at = request.form.get("starts_at", "").strip()
|
||||
if at and not TIME.match(at):
|
||||
errors.append("La hora debe ser HH:MM, de 00:00 a 23:59.")
|
||||
else:
|
||||
fields["starts_at"] = at or None
|
||||
|
||||
return fields, errors
|
||||
|
||||
|
||||
def _store_picture():
|
||||
"""One picture, on disk beside the rest, with no `attachments` row — the same
|
||||
arrangement a profile photo and a proposal's picture already use."""
|
||||
try:
|
||||
staged = uploads.stage(request.files.getlist("picture"))
|
||||
except uploads.RejectedUpload as exc:
|
||||
flash(str(exc), "error")
|
||||
return None
|
||||
if not staged:
|
||||
return None
|
||||
item = staged[0]
|
||||
uploads.directory().joinpath(item["stored_name"]).write_bytes(item["data"])
|
||||
return item["stored_name"]
|
||||
|
||||
|
||||
def _back(event, fields, errors):
|
||||
for message in errors:
|
||||
flash(message, "error")
|
||||
return render_template("event_form.html", event=event, fields=fields,
|
||||
suggested=""), 400
|
||||
@ -218,12 +218,25 @@ def _content_request(method: str, url: str, token: str, **kwargs):
|
||||
Hence the message: the thing to check is the token's scope, and it should
|
||||
say so on the screen rather than in a traceback nobody reads.
|
||||
"""
|
||||
try:
|
||||
response = requests.request(
|
||||
method, url,
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=TIMEOUT,
|
||||
**kwargs,
|
||||
)
|
||||
except requests.RequestException as exc:
|
||||
# The network is a failure mode of this module, not of its callers.
|
||||
# `requests` raises its own exceptions, which inherit from OSError and so
|
||||
# are not GiteaError — so a caller that handles GiteaError carefully, as
|
||||
# the calendar does to keep working while the git server is down, would
|
||||
# still have been taken out by a refused connection. Translated here, at
|
||||
# the one place that touches the wire.
|
||||
current_app.logger.warning("gitea unreachable: %s", exc)
|
||||
raise GiteaError(
|
||||
"No se pudo contactar con el servidor de git. Vuelve a intentarlo "
|
||||
"en un momento."
|
||||
) from exc
|
||||
if response.status_code in (401, 403):
|
||||
raise GiteaError(
|
||||
"El servidor de git rechazó el token del editor. Comprueba que "
|
||||
|
||||
@ -122,8 +122,9 @@ def session_state():
|
||||
sections = [
|
||||
{"label": "Inicio", "url": url_for("home.index")},
|
||||
{"label": "Muro", "url": url_for("board.threads")},
|
||||
{"label": "Privados", "url": url_for("messages.inbox")},
|
||||
{"label": "Miembros", "url": url_for("members.index")},
|
||||
{"label": "Publicaciones", "url": url_for("submissions.index")},
|
||||
{"label": "Calendario", "url": url_for("events.month")},
|
||||
]
|
||||
if g.member["role"] in ("owner", "admin"):
|
||||
sections.append({"label": "Gestión", "url": url_for("home.gestion")})
|
||||
|
||||
@ -27,8 +27,9 @@ import sqlite3
|
||||
from flask import (Blueprint, Response, abort, current_app, flash, g, redirect,
|
||||
render_template, request, url_for)
|
||||
|
||||
from . import auth, invites, mail, profiles, uploads
|
||||
from . import auth, invites, mail, messages, profiles, uploads
|
||||
from .db import TOMBSTONE_LOGIN, get_db
|
||||
from .render import to_html
|
||||
from .security import admin_required, login_required, owner_required
|
||||
|
||||
bp = Blueprint("members", __name__)
|
||||
@ -108,7 +109,16 @@ REASSIGNED_ON_ERASE = {
|
||||
# Removing the picture itself means deleting the post it is attached to.
|
||||
("attachments", "uploaded_by"),
|
||||
}
|
||||
CLEARED_ON_ERASE = {("members", "created_by")}
|
||||
CLEARED_ON_ERASE = {
|
||||
("members", "created_by"),
|
||||
# An event in the private calendar belongs to the association, not to the
|
||||
# admin who typed it in: the meeting still happens after they leave, so the
|
||||
# row stays and the name goes.
|
||||
("events", "created_by"),
|
||||
# Same for the colours and the logo. An admin leaving is not a reason for
|
||||
# the site to go back to looking like a default install.
|
||||
("brand", "updated_by"),
|
||||
}
|
||||
|
||||
# Private correspondence is not reassigned to the tombstone, it goes. A thread
|
||||
# outlives its author because other people replied and the conversation would
|
||||
@ -218,23 +228,91 @@ def _load(member_id: int):
|
||||
return row
|
||||
|
||||
|
||||
def _page(target) -> str:
|
||||
"""Back to the person whose page the button was on.
|
||||
|
||||
The admin controls used to sit on the cards, so every one of them sent the
|
||||
admin back to the directory. They are on the person's page now, and landing
|
||||
on the page you just changed — with the flash above it — is the difference
|
||||
between seeing that it worked and going to look for it.
|
||||
"""
|
||||
return url_for("members.show", login=target["gitea_login"])
|
||||
|
||||
|
||||
@bp.route("/miembros")
|
||||
@login_required
|
||||
def index():
|
||||
"""The directory, and the way into every private conversation.
|
||||
|
||||
Faces and names, and nothing else on a card: this is a section of the site
|
||||
now, not an admin screen, and everything about one person — their page,
|
||||
their messages, and the admin controls — is on their own page one click
|
||||
away.
|
||||
|
||||
**Sorted by who wrote to you, first.** That is what makes a directory work
|
||||
as the entrance to private messages: without it, the person waiting for an
|
||||
answer is wherever the alphabet put them. The role order comes second, so a
|
||||
page with nothing unread looks exactly as it did before.
|
||||
"""
|
||||
rows = get_db().execute(
|
||||
"""SELECT m.*, c.display_name AS creator,
|
||||
f"""SELECT m.*, c.display_name AS creator,
|
||||
(SELECT COUNT(*) FROM threads t
|
||||
WHERE t.author_id = m.id AND t.deleted_at IS NULL) AS posts
|
||||
WHERE t.author_id = m.id AND t.deleted_at IS NULL) AS posts,
|
||||
({messages.unread_sql()}) AS unread
|
||||
FROM members m
|
||||
LEFT JOIN members c ON c.id = m.created_by
|
||||
WHERE m.role != 'tombstone'
|
||||
ORDER BY CASE m.role WHEN 'owner' THEN 0 WHEN 'admin' THEN 1
|
||||
ORDER BY CASE WHEN unread > 0 THEN 0 ELSE 1 END,
|
||||
CASE m.role WHEN 'owner' THEN 0 WHEN 'admin' THEN 1
|
||||
WHEN 'moderator' THEN 2 ELSE 3 END,
|
||||
m.display_name COLLATE NOCASE"""
|
||||
m.display_name COLLATE NOCASE""",
|
||||
{"me": g.member["id"]},
|
||||
).fetchall()
|
||||
return render_template("members.html", members=rows, labels=ROLE_LABELS)
|
||||
|
||||
|
||||
@bp.route("/miembro/<login>")
|
||||
@login_required
|
||||
def show(login: str):
|
||||
"""One person: who they are, and everything between you and them.
|
||||
|
||||
Keyed on the login rather than the row id so the address matches the public
|
||||
one — `/comunidad/miembro/maria` beside `vienalatina.com/maria` — and so a
|
||||
link written by hand is guessable.
|
||||
|
||||
Suspended members are shown rather than hidden: they are in the directory,
|
||||
an admin needs to reach their controls to reactivate them, and a page that
|
||||
404s for somebody visible one click earlier is its own small mystery. What
|
||||
they do not get is a write box — see the template.
|
||||
"""
|
||||
member = get_db().execute(
|
||||
"""SELECT m.*, c.display_name AS creator FROM members m
|
||||
LEFT JOIN members c ON c.id = m.created_by
|
||||
WHERE m.gitea_login = ? COLLATE NOCASE AND m.role != 'tombstone'""",
|
||||
(login,),
|
||||
).fetchone()
|
||||
if member is None:
|
||||
abort(404)
|
||||
|
||||
mine = member["id"] == g.member["id"]
|
||||
# Nothing to read, nothing to mark read, and no conversation with yourself.
|
||||
talk = ({"messages": [], "images": {}, "blocked": False} if mine
|
||||
else messages.history(member["id"]))
|
||||
try:
|
||||
links = json.loads(member["links"] or "[]")
|
||||
except ValueError:
|
||||
# A profile whose links column is unreadable still has a page. Half a
|
||||
# page with a traceback in the log is better than none with one on
|
||||
# screen.
|
||||
links = []
|
||||
|
||||
return render_template(
|
||||
"member.html", member=member, labels=ROLE_LABELS, is_me=mine,
|
||||
messages=talk["messages"], images=talk["images"], blocked=talk["blocked"],
|
||||
links=links, bio_html=to_html(member["bio"] or ""), to_html=to_html,
|
||||
)
|
||||
|
||||
|
||||
@bp.route("/miembros/nuevo", methods=["GET", "POST"])
|
||||
@admin_required
|
||||
def new():
|
||||
@ -332,7 +410,7 @@ def invite(member_id: int):
|
||||
target = _load(member_id)
|
||||
if not target["email"]:
|
||||
flash(f"{target['display_name']} no tiene correo. Añádelo primero.", "error")
|
||||
return redirect(url_for("members.index"))
|
||||
return redirect(_page(target))
|
||||
if not target["active"] or target["role"] == "tombstone":
|
||||
abort(403)
|
||||
|
||||
@ -345,10 +423,10 @@ def invite(member_id: int):
|
||||
# did not work.
|
||||
current_app.logger.warning("Invite mail to %s failed: %s", target["email"], exc)
|
||||
flash(f"No se pudo enviar el correo. Pásale este enlace: {link}", "error")
|
||||
return redirect(url_for("members.index"))
|
||||
return redirect(_page(target))
|
||||
|
||||
flash(f"Invitación enviada a {target['email']}.", "ok")
|
||||
return redirect(url_for("members.index"))
|
||||
return redirect(_page(target))
|
||||
|
||||
|
||||
@bp.route("/miembros/<int:member_id>/estado", methods=["POST"])
|
||||
@ -360,7 +438,7 @@ def set_active(member_id: int):
|
||||
active = 1 if request.form.get("active") == "1" else 0
|
||||
get_db().execute("UPDATE members SET active = ? WHERE id = ?", (active, member_id))
|
||||
flash(f"{target['display_name']}: acceso {'restaurado' if active else 'suspendido'}.", "ok")
|
||||
return redirect(url_for("members.index"))
|
||||
return redirect(_page(target))
|
||||
|
||||
|
||||
@bp.route("/miembros/<int:member_id>/rol", methods=["POST"])
|
||||
@ -384,7 +462,7 @@ def set_role(member_id: int):
|
||||
abort(403)
|
||||
get_db().execute("UPDATE members SET role = ? WHERE id = ?", (role, member_id))
|
||||
flash(f"{target['display_name']} ahora es {ROLE_LABELS[role].lower()}.", "ok")
|
||||
return redirect(url_for("members.index"))
|
||||
return redirect(_page(target))
|
||||
|
||||
|
||||
@bp.route("/miembros/<int:member_id>/transferir", methods=["POST"])
|
||||
@ -393,10 +471,10 @@ def transfer(member_id: int):
|
||||
target = _load(member_id)
|
||||
if target["role"] != "admin" or not target["active"]:
|
||||
flash("Solo puedes transferir la titularidad a un administrador activo.", "error")
|
||||
return redirect(url_for("members.index"))
|
||||
return redirect(_page(target))
|
||||
transfer_ownership(get_db(), g.member["id"], target["id"])
|
||||
flash(f"{target['display_name']} es ahora el responsable. Tú eres administrador.", "ok")
|
||||
return redirect(url_for("members.index"))
|
||||
return redirect(_page(target))
|
||||
|
||||
|
||||
@bp.route("/miembros/<int:member_id>/eliminar", methods=["POST"])
|
||||
|
||||
@ -1,9 +1,19 @@
|
||||
"""Private messages between two members.
|
||||
|
||||
An inbox, not a chat. Each conversation has exactly two people, each keeps
|
||||
their own unread mark, and either can block the other — after which neither can
|
||||
write. That symmetry is deliberate: a block that silences only one side is a
|
||||
one-way megaphone, which is worse than having no block at all.
|
||||
Not a chat, and — since the sections were rearranged — not an inbox either.
|
||||
Each conversation has exactly two people, each keeps their own unread mark, and
|
||||
either can block the other, after which neither can write. That symmetry is
|
||||
deliberate: a block that silences only one side is a one-way megaphone, which is
|
||||
worse than having no block at all.
|
||||
|
||||
**Where the messages are shown moved; where the rules live did not.** The
|
||||
conversation is read on the other person's page (`members.show`), because
|
||||
writing to somebody is something you do to a person and not in a separate
|
||||
mailbox. This module still owns every rule about it — who may read a
|
||||
conversation, what counts as having read it, when the conversation comes into
|
||||
being, and who may write to whom — and hands the page its contents through
|
||||
`history()`. The routes that remain are the ones that *change* something: a
|
||||
message sent, a block set or lifted.
|
||||
|
||||
Every rule here is enforced in the handler, not only in the template. A hidden
|
||||
button is a courtesy to somebody using the site normally; it is not a rule, and
|
||||
@ -12,12 +22,10 @@ the difference matters most for exactly the person a block exists to stop.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import (Blueprint, abort, flash, g, redirect, render_template,
|
||||
request, url_for)
|
||||
from flask import Blueprint, abort, flash, g, redirect, request, url_for
|
||||
|
||||
from . import uploads
|
||||
from .db import TOMBSTONE_LOGIN, get_db
|
||||
from .render import to_html
|
||||
from .db import get_db
|
||||
from .security import login_required
|
||||
|
||||
bp = Blueprint("messages", __name__)
|
||||
@ -87,121 +95,51 @@ def unread_count() -> int:
|
||||
).fetchone()["n"]
|
||||
|
||||
|
||||
# --- routes ---------------------------------------------------------------
|
||||
def unread_sql(me: str = ":me", other: str = "m.id") -> str:
|
||||
"""How many unread messages the signed-in member has from `other`.
|
||||
|
||||
@bp.route("/privados")
|
||||
@login_required
|
||||
def inbox():
|
||||
rows = get_db().execute(
|
||||
"""SELECT c.id,
|
||||
other.display_name AS other_name,
|
||||
other.id AS other_id,
|
||||
other.gitea_login AS other_login,
|
||||
other.profile_published AS other_published,
|
||||
(SELECT body_md FROM messages
|
||||
WHERE conversation_id = c.id AND deleted_at IS NULL
|
||||
ORDER BY created_at DESC LIMIT 1) AS last_body,
|
||||
(SELECT created_at FROM messages
|
||||
WHERE conversation_id = c.id AND deleted_at IS NULL
|
||||
ORDER BY created_at DESC LIMIT 1) AS last_at,
|
||||
(SELECT COUNT(*) FROM messages m
|
||||
WHERE m.conversation_id = c.id AND m.author_id != mine.member_id
|
||||
AND m.deleted_at IS NULL
|
||||
AND (mine.last_read_at IS NULL OR m.created_at > mine.last_read_at)
|
||||
) AS unread
|
||||
FROM conversations c
|
||||
A string rather than a function because its one caller is the directory
|
||||
query in `members.index`, which needs the number per row and sorts on it —
|
||||
one query that answers for everybody, rather than one query per face on the
|
||||
page. The two parameters are SQL fragments chosen by this module, never by a
|
||||
request.
|
||||
|
||||
`author_id = other` is what makes it unread *from them*: a member's own
|
||||
messages are not unread, and without that clause looking at your own card
|
||||
would count everything you have ever written.
|
||||
"""
|
||||
return f"""
|
||||
SELECT COUNT(*) FROM messages msg
|
||||
JOIN conversation_members mine
|
||||
ON mine.conversation_id = c.id AND mine.member_id = :me
|
||||
ON mine.conversation_id = msg.conversation_id AND mine.member_id = {me}
|
||||
JOIN conversation_members theirs
|
||||
ON theirs.conversation_id = c.id AND theirs.member_id != :me
|
||||
JOIN members other ON other.id = theirs.member_id
|
||||
ORDER BY last_at DESC NULLS LAST""",
|
||||
{"me": g.member["id"]},
|
||||
).fetchall()
|
||||
|
||||
# Anyone you could start writing to: every active member but yourself, the
|
||||
# tombstone, and anyone either of you has blocked.
|
||||
people = get_db().execute(
|
||||
"""SELECT m.id, m.display_name FROM members m
|
||||
WHERE m.id != :me AND m.active = 1
|
||||
AND m.role != 'tombstone'
|
||||
AND m.gitea_login != :ghost
|
||||
AND NOT EXISTS (SELECT 1 FROM blocks
|
||||
WHERE (blocker_id = :me AND blocked_id = m.id)
|
||||
OR (blocker_id = m.id AND blocked_id = :me))
|
||||
ORDER BY m.display_name COLLATE NOCASE""",
|
||||
{"me": g.member["id"], "ghost": TOMBSTONE_LOGIN},
|
||||
).fetchall()
|
||||
|
||||
return render_template("inbox.html", conversations=rows, people=people,
|
||||
excerpt=lambda text: (text or "")[:120])
|
||||
|
||||
|
||||
@bp.route("/privados/con")
|
||||
@login_required
|
||||
def pick():
|
||||
"""The select posts here as a plain GET and is sent on to the conversation.
|
||||
|
||||
A form cannot put its own value into a path, and rewriting the action with
|
||||
JavaScript is not available: the Content-Security-Policy has no
|
||||
'unsafe-inline', so an inline handler is ignored without a word. One tiny
|
||||
redirect avoids the whole question.
|
||||
ON theirs.conversation_id = msg.conversation_id AND theirs.member_id = {other}
|
||||
WHERE msg.author_id = {other}
|
||||
AND {other} != {me}
|
||||
AND msg.deleted_at IS NULL
|
||||
AND (mine.last_read_at IS NULL OR msg.created_at > mine.last_read_at)
|
||||
"""
|
||||
return redirect(url_for("messages.talk",
|
||||
member_id=request.args.get("member_id", type=int) or 0))
|
||||
|
||||
|
||||
@bp.route("/privados/con/<int:member_id>", methods=["GET", "POST"])
|
||||
@login_required
|
||||
def talk(member_id: int):
|
||||
"""One page for a conversation, whether or not it exists yet.
|
||||
def history(other_id: int) -> dict:
|
||||
"""The conversation with `other_id`, and the fact of having read it.
|
||||
|
||||
There used to be an "Abrir conversación" step that created an empty
|
||||
conversation and sent you to it. It bought nothing — you still had to type
|
||||
a message afterwards — and it littered the inbox with rows saying "Sin
|
||||
mensajes todavía" for people nobody had actually written to. The
|
||||
conversation is now created by the first message, not by looking at
|
||||
somebody's name.
|
||||
Called by the member page, which renders it. Reading is a side effect on
|
||||
purpose: opening somebody's page *is* opening the conversation, there is no
|
||||
second step any more, and so there is no moment at which the messages are on
|
||||
screen and still counted as unread.
|
||||
|
||||
Creates nothing. A conversation comes into being with the first message
|
||||
(`talk` below), so looking at a page is not enough to put a row in the
|
||||
database — which is what kept the old inbox free of entries saying "no
|
||||
messages yet" for people nobody had written to.
|
||||
"""
|
||||
if member_id == g.member["id"]:
|
||||
abort(400)
|
||||
other = get_db().execute(
|
||||
"""SELECT * FROM members
|
||||
WHERE id = ? AND active = 1 AND role != 'tombstone'""",
|
||||
(member_id,),
|
||||
).fetchone()
|
||||
if other is None:
|
||||
abort(404)
|
||||
blocked = blocked_between(g.member["id"], member_id)
|
||||
if blocked and request.method == "POST":
|
||||
abort(403)
|
||||
|
||||
db = get_db()
|
||||
conversation_id = existing_conversation(member_id)
|
||||
|
||||
if request.method == "POST":
|
||||
body = request.form.get("body", "").strip()[:BODY_MAX]
|
||||
try:
|
||||
staged = uploads.stage(request.files.getlist("pictures"))
|
||||
except uploads.RejectedUpload as exc:
|
||||
flash(str(exc), "error")
|
||||
return redirect(url_for("messages.talk", member_id=member_id))
|
||||
if not body and not staged:
|
||||
flash("Escribe algo o adjunta una imagen.", "error")
|
||||
return redirect(url_for("messages.talk", member_id=member_id))
|
||||
|
||||
# Only now does the conversation come into being.
|
||||
blocked = blocked_between(g.member["id"], other_id)
|
||||
conversation_id = existing_conversation(other_id)
|
||||
if conversation_id is None:
|
||||
conversation_id = conversation_with(member_id)
|
||||
cursor = db.execute(
|
||||
"INSERT INTO messages (conversation_id, author_id, body_md) VALUES (?, ?, ?)",
|
||||
(conversation_id, g.member["id"], body),
|
||||
)
|
||||
uploads.save(staged, g.member["id"], message_id=cursor.lastrowid)
|
||||
return redirect(url_for("messages.talk", member_id=member_id) + "#final")
|
||||
return {"messages": [], "images": {}, "blocked": blocked}
|
||||
|
||||
rows = []
|
||||
if conversation_id is not None:
|
||||
rows = db.execute(
|
||||
"""SELECT m.*, a.display_name AS author,
|
||||
a.gitea_login AS author_login,
|
||||
@ -216,12 +154,89 @@ def talk(member_id: int):
|
||||
WHERE conversation_id = ? AND member_id = ?""",
|
||||
(conversation_id, g.member["id"]),
|
||||
)
|
||||
return {
|
||||
"messages": rows,
|
||||
"images": uploads.for_messages([row["id"] for row in rows]),
|
||||
"blocked": blocked,
|
||||
}
|
||||
|
||||
return render_template(
|
||||
"conversation.html", other=other, messages=rows, to_html=to_html,
|
||||
images=uploads.for_messages([row["id"] for row in rows]),
|
||||
blocked=blocked,
|
||||
|
||||
def _back_to(member_row, anchor: str = "") -> str:
|
||||
return url_for("members.show", login=member_row["gitea_login"]) + anchor
|
||||
|
||||
|
||||
# --- routes ---------------------------------------------------------------
|
||||
|
||||
@bp.route("/privados")
|
||||
@login_required
|
||||
def inbox():
|
||||
"""Kept as a redirect, not deleted.
|
||||
|
||||
This was the *Privados* section until the people became the section. The
|
||||
route stays because members have the address in their history and admins
|
||||
have it written down, and a bookmark that lands on the directory is a
|
||||
bookmark that still works.
|
||||
"""
|
||||
return redirect(url_for("members.index"))
|
||||
|
||||
|
||||
@bp.route("/privados/con/<int:member_id>")
|
||||
@login_required
|
||||
def talk_redirect(member_id: int):
|
||||
"""The old per-conversation address, pointed at the person's page.
|
||||
|
||||
By id, because that is what the old links carry; everything written from now
|
||||
on uses the login, which is the same address as their public page.
|
||||
"""
|
||||
other = get_db().execute(
|
||||
"SELECT gitea_login FROM members WHERE id = ? AND role != 'tombstone'",
|
||||
(member_id,),
|
||||
).fetchone()
|
||||
if other is None:
|
||||
abort(404)
|
||||
return redirect(url_for("members.show", login=other["gitea_login"]))
|
||||
|
||||
|
||||
@bp.route("/privados/con/<int:member_id>", methods=["POST"])
|
||||
@login_required
|
||||
def talk(member_id: int):
|
||||
"""Send one message. The reading half is `history()`, on the member page.
|
||||
|
||||
POST only. There used to be a GET here rendering the whole conversation;
|
||||
that page is now the person's page, and leaving a GET behind would have
|
||||
meant two addresses rendering the same thing, drifting apart.
|
||||
"""
|
||||
if member_id == g.member["id"]:
|
||||
abort(400)
|
||||
db = get_db()
|
||||
other = db.execute(
|
||||
"""SELECT * FROM members
|
||||
WHERE id = ? AND active = 1 AND role != 'tombstone'""",
|
||||
(member_id,),
|
||||
).fetchone()
|
||||
if other is None:
|
||||
abort(404)
|
||||
if blocked_between(g.member["id"], member_id):
|
||||
abort(403)
|
||||
|
||||
body = request.form.get("body", "").strip()[:BODY_MAX]
|
||||
try:
|
||||
staged = uploads.stage(request.files.getlist("pictures"))
|
||||
except uploads.RejectedUpload as exc:
|
||||
flash(str(exc), "error")
|
||||
return redirect(_back_to(other))
|
||||
if not body and not staged:
|
||||
flash("Escribe algo o adjunta una imagen.", "error")
|
||||
return redirect(_back_to(other))
|
||||
|
||||
# Only now does the conversation come into being.
|
||||
conversation_id = existing_conversation(member_id) or conversation_with(member_id)
|
||||
cursor = db.execute(
|
||||
"INSERT INTO messages (conversation_id, author_id, body_md) VALUES (?, ?, ?)",
|
||||
(conversation_id, g.member["id"], body),
|
||||
)
|
||||
uploads.save(staged, g.member["id"], message_id=cursor.lastrowid)
|
||||
return redirect(_back_to(other, "#final"))
|
||||
|
||||
|
||||
@bp.route("/privados/bloquear/<int:member_id>", methods=["POST"])
|
||||
@ -229,13 +244,18 @@ def talk(member_id: int):
|
||||
def block(member_id: int):
|
||||
if member_id == g.member["id"]:
|
||||
abort(400)
|
||||
other = get_db().execute(
|
||||
"SELECT * FROM members WHERE id = ? AND role != 'tombstone'", (member_id,)
|
||||
).fetchone()
|
||||
if other is None:
|
||||
abort(404)
|
||||
get_db().execute(
|
||||
"""INSERT INTO blocks (blocker_id, blocked_id) VALUES (?, ?)
|
||||
ON CONFLICT DO NOTHING""",
|
||||
(g.member["id"], member_id),
|
||||
)
|
||||
flash("Bloqueado. Ninguno de los dos puede escribir al otro.", "ok")
|
||||
return redirect(url_for("messages.inbox"))
|
||||
return redirect(_back_to(other))
|
||||
|
||||
|
||||
@bp.route("/privados/desbloquear/<int:member_id>", methods=["POST"])
|
||||
@ -243,7 +263,12 @@ def block(member_id: int):
|
||||
def unblock(member_id: int):
|
||||
"""Only your own block. Removing somebody else's would let the blocked
|
||||
person undo the thing that was done to protect against them."""
|
||||
other = get_db().execute(
|
||||
"SELECT * FROM members WHERE id = ? AND role != 'tombstone'", (member_id,)
|
||||
).fetchone()
|
||||
if other is None:
|
||||
abort(404)
|
||||
get_db().execute("DELETE FROM blocks WHERE blocker_id = ? AND blocked_id = ?",
|
||||
(g.member["id"], member_id))
|
||||
flash("Desbloqueado.", "ok")
|
||||
return redirect(url_for("messages.inbox"))
|
||||
return redirect(_back_to(other))
|
||||
|
||||
@ -206,6 +206,32 @@ def _members_can_moderate(db: sqlite3.Connection) -> None:
|
||||
if broken:
|
||||
raise RuntimeError(f"migration left dangling references: {broken}")
|
||||
|
||||
def _rooms_for_a_date_of_its_own(db: sqlite3.Connection) -> None:
|
||||
"""Somewhere to keep an event's date, in the two tables that already exist.
|
||||
|
||||
Plain ADD COLUMNs, nothing like the rebuilds in steps 1 and 4 — neither
|
||||
table has a CHECK in the way.
|
||||
|
||||
`submissions` needs them because a member can propose an event, and the date
|
||||
has to survive in the queue until a moderator approves it. `content_cache`
|
||||
needs them because the private calendar shows public events beside internal
|
||||
ones, and reading every post's frontmatter on every page view to find their
|
||||
dates is exactly what that cache exists to avoid.
|
||||
"""
|
||||
for table in ("submissions", "content_cache"):
|
||||
existing = _columns(db, table)
|
||||
if not existing:
|
||||
# No such table in this database. `init_db` runs schema.sql before
|
||||
# these steps, so on a real server both tables are always there;
|
||||
# skipping rather than failing keeps a step from depending on how
|
||||
# much of the schema a given database happens to have, which is the
|
||||
# property that lets these run against any vintage.
|
||||
continue
|
||||
for column in ("event_date", "event_time", "event_location"):
|
||||
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
|
||||
# user_version once the step succeeds.
|
||||
STEPS = [
|
||||
@ -213,6 +239,7 @@ STEPS = [
|
||||
(2, "members keep their own password", _members_own_their_passwords),
|
||||
(3, "members can have a public page", _members_get_a_public_page),
|
||||
(4, "members can be moderators", _members_can_moderate),
|
||||
(5, "events carry a date of their own", _rooms_for_a_date_of_its_own),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@ -246,6 +246,12 @@ CREATE TABLE IF NOT EXISTS submissions (
|
||||
body_md TEXT NOT NULL,
|
||||
description TEXT NOT NULL DEFAULT '',
|
||||
categories TEXT NOT NULL DEFAULT '', -- comma-separated, as content_cache
|
||||
-- Set only when the proposal carries the Evento category. The event's own
|
||||
-- date, which is not the day it is published: a member announcing a concert
|
||||
-- three weeks out is the normal case.
|
||||
event_date TEXT,
|
||||
event_time TEXT,
|
||||
event_location TEXT,
|
||||
photo_name TEXT,
|
||||
state TEXT NOT NULL DEFAULT 'pending'
|
||||
CHECK (state IN ('pending', 'approved', 'rejected')),
|
||||
@ -292,3 +298,56 @@ CREATE UNIQUE INDEX IF NOT EXISTS reactions_one_per_thread
|
||||
ON reactions(member_id, thread_id) WHERE thread_id IS NOT NULL;
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS reactions_one_per_comment
|
||||
ON reactions(member_id, comment_id) WHERE comment_id IS NOT NULL;
|
||||
|
||||
-- The private calendar.
|
||||
--
|
||||
-- Events the association puts on for its members: a meeting, a rehearsal, a
|
||||
-- visit somewhere. Written by admins, read by every member, and never published
|
||||
-- — nothing here reaches /var/www, the sitemap or a share card, which is the
|
||||
-- difference between this table and a post with the Evento category.
|
||||
--
|
||||
-- `starts_on` and `starts_at` are kept apart rather than as one timestamp
|
||||
-- because an event with no time is an ordinary thing ("the whole Saturday") and
|
||||
-- a timestamp cannot say so without inventing midnight.
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
id INTEGER PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
body_md TEXT NOT NULL DEFAULT '',
|
||||
starts_on TEXT NOT NULL, -- YYYY-MM-DD
|
||||
starts_at TEXT, -- HH:MM, or null for all day
|
||||
location TEXT NOT NULL DEFAULT '',
|
||||
photo_name TEXT,
|
||||
-- Cleared rather than reassigned when that member is erased: the event
|
||||
-- belongs to the association, not to whoever typed it in.
|
||||
created_by INTEGER REFERENCES members(id),
|
||||
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
updated_at TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS events_month ON events(starts_on);
|
||||
|
||||
-- The look of the site, as the admin set it.
|
||||
--
|
||||
-- One row, pinned by the CHECK: there is one association per install and one
|
||||
-- set of colours. `ON CONFLICT(id)` in brand.py relies on that pin, which is
|
||||
-- also why there is no "which brand is current" question to get wrong.
|
||||
--
|
||||
-- Only the tokens that differ from apps/board/brand.py's FACTORY are stored, as
|
||||
-- JSON. A snapshot of every token would mean that a token added later arrived
|
||||
-- frozen at its old value for every install that had ever opened this screen.
|
||||
--
|
||||
-- `published_at` is NULL between a save and the commit that carries it to the
|
||||
-- content repository — which is to say, whenever the git server was unreachable
|
||||
-- when somebody pressed save. The screen reads it and offers to try again.
|
||||
CREATE TABLE IF NOT EXISTS brand (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||
tokens_json TEXT NOT NULL DEFAULT '{}',
|
||||
custom_css TEXT NOT NULL DEFAULT '',
|
||||
logo_name TEXT,
|
||||
favicon_name TEXT,
|
||||
-- Cleared rather than reassigned when that member is erased: the colours
|
||||
-- belong to the association, like an event in the calendar.
|
||||
updated_by INTEGER REFERENCES members(id),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
|
||||
published_at TEXT
|
||||
);
|
||||
|
||||
@ -180,8 +180,22 @@ label { display: block; margin: 1rem 0 0.35rem; font-weight: 600; font-size: 0.9
|
||||
label.check { display: flex; align-items: center; gap: 0.5rem; font-weight: 400; }
|
||||
label.check input { margin: 0; }
|
||||
|
||||
input[type="text"], input[type="email"], input[type="date"],
|
||||
input:not([type]), select, textarea {
|
||||
/* Everything a person types in, named by what it is NOT.
|
||||
*
|
||||
* This was a list — text, email, date and inputs with no type at all — and a
|
||||
* list of accepted types is wrong the moment somebody adds one. It was: the
|
||||
* password box on the sign-in page was a browser default sitting under a
|
||||
* full-width username box, because `password` was never added, and so was the
|
||||
* number box for a page's order. Nothing errors; the form just looks unfinished
|
||||
* in a way only a person looking at it can catch.
|
||||
*
|
||||
* The controls below are excluded because they are not text boxes and would be
|
||||
* disfigured by this: a checkbox, a radio, a file picker (styled separately),
|
||||
* and the button-like types. Anything else — password, number, url, search,
|
||||
* tel, whatever arrives next — is a field somebody types in and gets the same
|
||||
* box without this rule having to be edited again. */
|
||||
input:not([type="checkbox"]):not([type="radio"]):not([type="file"]):not([type="submit"]):not([type="button"]):not([type="reset"]):not([type="image"]):not([type="hidden"]),
|
||||
select, textarea {
|
||||
width: 100%;
|
||||
padding: 0.6rem 0.75rem;
|
||||
border: 1px solid var(--border-light);
|
||||
@ -189,7 +203,7 @@ input:not([type]), select, textarea {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
}
|
||||
input[type="checkbox"] { width: auto; }
|
||||
input[type="checkbox"], input[type="radio"] { width: auto; }
|
||||
textarea { resize: vertical; line-height: 1.55; }
|
||||
|
||||
:focus-visible { outline: 2px solid var(--brand); outline-offset: 2px; }
|
||||
@ -207,6 +221,16 @@ textarea { resize: vertical; line-height: 1.55; }
|
||||
}
|
||||
.btn:hover { background: var(--brand-dark); }
|
||||
|
||||
/* A button sitting straight in a card, rather than in an .actions row, still
|
||||
* needs air above it. Five of them did not have any — the one under the "escribir
|
||||
* a" picker was flush against the select — because the space every other form
|
||||
* has comes from .actions, not from the button.
|
||||
*
|
||||
* Matching .actions' own margin so the two look the same, and a direct-child
|
||||
* selector so a button inside .actions is never given both: it is a child of the
|
||||
* row, not of the card. */
|
||||
.card > .btn { margin-top: 1.25rem; }
|
||||
|
||||
.linkish {
|
||||
background: none;
|
||||
border: 0;
|
||||
@ -487,9 +511,26 @@ input[type="file"] {
|
||||
border: 1px solid var(--border-light);
|
||||
border-radius: var(--radius-lg);
|
||||
box-shadow: var(--shadow-sm);
|
||||
padding: 1rem;
|
||||
/* No padding of its own: the whole card is one link, and the padding lives
|
||||
on the anchor so that a click an eighth of an inch from the name still
|
||||
opens the page. */
|
||||
padding: 0;
|
||||
}
|
||||
.person-card--off { opacity: 0.55; }
|
||||
.person-card__link {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 1rem;
|
||||
border-radius: var(--radius-lg);
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
.person-card__link:hover,
|
||||
.person-card__link:focus-visible {
|
||||
background: var(--brand-softer);
|
||||
}
|
||||
.person-card__link:hover .person-card__name { color: var(--brand-dark); }
|
||||
.person-card__head { display: flex; align-items: center; gap: 0.75rem; }
|
||||
.person-card__photo {
|
||||
width: 56px;
|
||||
@ -508,22 +549,44 @@ input[type="file"] {
|
||||
font-size: 1.4rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
.person-card__who { min-width: 0; } /* so a long name wraps instead of pushing */
|
||||
.person-card__name { margin: 0; font-size: 1.05rem; }
|
||||
/* min-width so a long name wraps instead of pushing the card wider; the spans
|
||||
are blocks because the name and the line under it are two lines, and a card
|
||||
this small does not need a heading element to say so. */
|
||||
.person-card__who { display: block; min-width: 0; }
|
||||
.person-card__who > span { display: block; }
|
||||
.person-card__name { margin: 0; font-size: 1.05rem; font-weight: 600; }
|
||||
.person-card__name .muted { font-weight: 400; }
|
||||
.person-card__who p { margin: 0.15rem 0 0; }
|
||||
.person-card__bio {
|
||||
margin: 0.75rem 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 0.9rem;
|
||||
|
||||
/* --- one person's page ------------------------------------------------- */
|
||||
|
||||
.person-head { display: flex; align-items: flex-start; gap: 1rem; }
|
||||
.person-head__photo {
|
||||
width: 88px;
|
||||
height: 88px;
|
||||
flex: 0 0 88px;
|
||||
border-radius: 50%;
|
||||
object-fit: cover;
|
||||
border: 1px solid var(--border-light);
|
||||
}
|
||||
.person-card__foot {
|
||||
.person-head__photo--none {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.75rem;
|
||||
margin-top: 0.75rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--brand-soft);
|
||||
color: var(--brand-dark);
|
||||
font-size: 2rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
.person-card__admin { margin-top: 0.75rem; border-top: 1px solid var(--border-light); padding-top: 0.5rem; }
|
||||
.person-head__who { min-width: 0; }
|
||||
.person-head__who > :first-child { margin-top: 0; }
|
||||
.person-head__links { margin: 0.5rem 0 0; padding-left: 1.1rem; }
|
||||
.person-head__foot { margin: 0.75rem 0 0; }
|
||||
.section-title { margin: 1.5rem 0 0.25rem; font-size: 1.1rem; }
|
||||
.person-block { margin-top: 1.25rem; }
|
||||
.person-block summary { cursor: pointer; color: var(--subtle); font-size: 0.85rem; }
|
||||
.person-block p { margin: 0.5rem 0; }
|
||||
|
||||
.person-card__admin { margin-top: 1.25rem; border-top: 1px solid var(--border-light); padding-top: 0.5rem; }
|
||||
.person-card__admin summary {
|
||||
cursor: pointer;
|
||||
color: var(--subtle);
|
||||
@ -597,3 +660,147 @@ input[type="file"] {
|
||||
color: var(--subtle);
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* --- the private calendar ---------------------------------------------- */
|
||||
|
||||
.cal-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
margin-bottom: 0.35rem;
|
||||
}
|
||||
.cal-bar__today { text-align: center; margin: 0 0 1rem; }
|
||||
|
||||
.cal {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
table-layout: fixed;
|
||||
}
|
||||
.cal th {
|
||||
padding: 0.4rem;
|
||||
font-size: 0.72rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
color: var(--muted);
|
||||
text-align: left;
|
||||
}
|
||||
.cal__day, .cal__pad {
|
||||
vertical-align: top;
|
||||
height: 92px;
|
||||
padding: 0.35rem;
|
||||
border: 1px solid var(--border-light);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--surface);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.cal__pad { background: transparent; border-color: transparent; }
|
||||
.cal__day--today { border-color: var(--brand); background: var(--brand-softer); }
|
||||
.cal__number { color: var(--subtle); font-weight: 700; }
|
||||
|
||||
.cal__event {
|
||||
display: block;
|
||||
margin-top: 0.25rem;
|
||||
color: var(--brand-dark);
|
||||
text-decoration: none;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.cal__event:hover { text-decoration: underline; }
|
||||
.cal__event time { font-weight: 700; }
|
||||
/* A public event is the association speaking to everybody; an internal one is
|
||||
not. The distinction has to survive a glance. */
|
||||
.cal__event--public { color: var(--muted); }
|
||||
|
||||
.cal__add {
|
||||
display: none;
|
||||
float: right;
|
||||
color: var(--subtle);
|
||||
text-decoration: none;
|
||||
font-weight: 700;
|
||||
}
|
||||
.cal__day:hover .cal__add { display: inline; }
|
||||
.cal__add:hover { color: var(--brand); }
|
||||
|
||||
.event-facts p { margin: 0 0 0.25rem; }
|
||||
|
||||
/* Seven columns of nothing is what a month grid is on a phone. */
|
||||
@media (max-width: 640px) {
|
||||
.cal, .cal tbody, .cal tr, .cal td { display: block; width: auto; }
|
||||
.cal thead { display: none; }
|
||||
.cal__pad { display: none; }
|
||||
.cal__day { height: auto; margin-bottom: 0.4rem; }
|
||||
.cal__day:not(:has(.cal__event)) { display: none; }
|
||||
.cal__number { display: inline-block; margin-right: 0.5rem; }
|
||||
.cal__add { display: inline; }
|
||||
}
|
||||
|
||||
/* --- Gestión → Marca ---------------------------------------------------- */
|
||||
|
||||
/* Constrained in height rather than width: a wordmark is wide and a square
|
||||
icon is not, and both have to sit in a bar 56px tall without pushing it
|
||||
open. An admin who wants it bigger has the custom CSS box, and the
|
||||
placeholder in that box is this very rule. */
|
||||
.site-bar__logo { display: block; max-height: 36px; max-width: 240px; width: auto; }
|
||||
|
||||
.swatches {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(190px, 1fr));
|
||||
gap: 1rem;
|
||||
margin: 0.75rem 0 1.25rem;
|
||||
}
|
||||
.swatch label { margin-bottom: 0.25rem; }
|
||||
.swatch p { margin: 0.25rem 0 0; }
|
||||
/* The input rule above gives every field width:100%, which on a colour picker
|
||||
produces a swatch the width of the column. */
|
||||
.swatch input[type="color"] {
|
||||
width: 100%;
|
||||
height: 2.75rem;
|
||||
padding: 0.2rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* The preview block. Every colour inside it comes from a custom property, so
|
||||
board.js can restyle the whole thing by setting six of them on this one
|
||||
element — which is also what makes it an honest preview rather than a
|
||||
drawing of one. */
|
||||
.brand-preview {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-lg);
|
||||
overflow: hidden;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
.brand-preview__bar {
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--border);
|
||||
color: var(--brand);
|
||||
font-weight: 700;
|
||||
padding: 0.75rem 1rem;
|
||||
}
|
||||
.brand-preview__card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border-light);
|
||||
border-radius: var(--radius-md);
|
||||
color: var(--text);
|
||||
margin: 1rem;
|
||||
padding: 1rem;
|
||||
}
|
||||
.brand-preview__meta { color: var(--muted); font-size: 0.85rem; margin: 0 0 0.5rem; }
|
||||
.brand-preview__card p:last-of-type { margin: 0 0 0.75rem; }
|
||||
.brand-preview__btn {
|
||||
display: inline-block;
|
||||
background: var(--brand);
|
||||
border-radius: 999px;
|
||||
color: #fff;
|
||||
font-weight: 600;
|
||||
padding: 0.4rem 1rem;
|
||||
}
|
||||
|
||||
.brand-current { max-height: 72px; max-width: 100%; width: auto; }
|
||||
.brand-current--small { max-height: 48px; }
|
||||
|
||||
.brand-advanced { margin-top: 1.5rem; border-top: 1px solid var(--border-light); padding-top: 0.75rem; }
|
||||
.brand-advanced summary { cursor: pointer; color: var(--subtle); }
|
||||
|
||||
.btn--danger { background: var(--danger); }
|
||||
.btn--danger:hover { background: var(--danger); filter: brightness(0.9); }
|
||||
|
||||
@ -149,9 +149,36 @@ document.addEventListener("submit", function (event) {
|
||||
});
|
||||
}
|
||||
|
||||
// --- the brand preview --------------------------------------------------
|
||||
//
|
||||
// Setting the custom properties on one element, from the colour pickers above
|
||||
// it. A DOM write rather than a `style=""` attribute in the template, which
|
||||
// is what makes it work under a policy with no 'unsafe-inline' — and it is
|
||||
// also why the preview exists at all: the Marca screen itself is deliberately
|
||||
// rendered in the factory colours, so this block is the only place an admin
|
||||
// sees their own.
|
||||
function brandPreview() {
|
||||
var target = document.querySelector("[data-brand-preview-target]");
|
||||
if (!target) { return; }
|
||||
var pickers = document.querySelectorAll("[data-brand-preview] [data-token]");
|
||||
|
||||
function paint() {
|
||||
Array.prototype.forEach.call(pickers, function (picker) {
|
||||
target.style.setProperty("--" + picker.getAttribute("data-token"),
|
||||
picker.value);
|
||||
});
|
||||
}
|
||||
|
||||
Array.prototype.forEach.call(pickers, function (picker) {
|
||||
picker.addEventListener("input", paint);
|
||||
});
|
||||
paint();
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
Array.prototype.forEach.call(
|
||||
document.querySelectorAll("textarea[data-markdown]"), toolbarFor);
|
||||
brandPreview();
|
||||
|
||||
document.addEventListener("change", function (event) {
|
||||
var input = event.target;
|
||||
|
||||
@ -92,14 +92,18 @@ 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."""
|
||||
categories = [c for c in request.form.getlist("categories")
|
||||
if c in content.CATEGORIES]
|
||||
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],
|
||||
"categories": [c for c in request.form.getlist("categories")
|
||||
if c in content.CATEGORIES],
|
||||
"categories": categories,
|
||||
# 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, categories, errors),
|
||||
}
|
||||
errors = []
|
||||
if not fields["title"]:
|
||||
errors.append("El título no puede estar vacío.")
|
||||
if not fields["body"]:
|
||||
@ -175,10 +179,12 @@ def propose():
|
||||
photo_name = _store_picture(staged)
|
||||
get_db().execute(
|
||||
"""INSERT INTO submissions
|
||||
(author_id, title, body_md, description, categories, photo_name)
|
||||
VALUES (?, ?, ?, ?, ?, ?)""",
|
||||
(author_id, title, body_md, description, categories, photo_name,
|
||||
event_date, event_time, event_location)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)""",
|
||||
(g.member["id"], fields["title"], fields["body"], fields["description"],
|
||||
", ".join(fields["categories"]), photo_name),
|
||||
", ".join(fields["categories"]), 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"))
|
||||
@ -217,6 +223,9 @@ def edit(submission_id: int):
|
||||
"description": row["description"],
|
||||
"categories": [c.strip() for c in
|
||||
(row["categories"] or "").split(",") if c.strip()],
|
||||
"event_date": row["event_date"] or "",
|
||||
"event_time": row["event_time"] or "",
|
||||
"event_location": row["event_location"] or "",
|
||||
})
|
||||
|
||||
fields, errors = _read_proposal()
|
||||
@ -238,12 +247,14 @@ def edit(submission_id: int):
|
||||
get_db().execute(
|
||||
"""UPDATE submissions
|
||||
SET title = ?, body_md = ?, description = ?, categories = ?,
|
||||
photo_name = ?, state = 'pending', note = NULL,
|
||||
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"],
|
||||
", ".join(fields["categories"]), photo_name, submission_id),
|
||||
", ".join(fields["categories"]), 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
|
||||
@ -313,6 +324,11 @@ def approve(submission_id: int):
|
||||
"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
|
||||
|
||||
@ -1,12 +1,20 @@
|
||||
{# A member's name, as a link to their page when they have one.
|
||||
{# A member's name, as a link to their page inside the members area.
|
||||
|
||||
The rule is in one place because it is easy to get wrong in two directions:
|
||||
a name that never links makes the profiles invisible, and a name that always
|
||||
links sends people to a 404 for everybody who has not published theirs. So
|
||||
every screen calls this, and none of them has to remember. #}
|
||||
{% macro person(name, login=None, published=False) %}
|
||||
{%- if published and login -%}
|
||||
<a class="who-link" href="{{ url_for('profiles_public.show', name=login) }}">{{ name }}</a>
|
||||
It used to link to their *public* page, and only when they had published one
|
||||
— which meant most names on the wall were plain text, and there was no way to
|
||||
get from somebody's post to writing to them. Every template that calls this
|
||||
is behind the login, so the link now goes to /comunidad/miembro/<usuario>,
|
||||
which exists for every member: who they are, what the two of you have written
|
||||
each other, and a link out to their public page when they have published one.
|
||||
|
||||
The rule stays in one place because it is easy to get wrong in two
|
||||
directions: a name that never links makes the people invisible, and a name
|
||||
that always links sends somebody to a 404. The one name with no page is the
|
||||
tombstone that an erased member's writing is reassigned to — it is not a
|
||||
person and has nothing to show. #}
|
||||
{% macro person(name, login=None) %}
|
||||
{%- if login and login != tombstone_login -%}
|
||||
<a class="who-link" href="{{ url_for('members.show', login=login) }}">{{ name }}</a>
|
||||
{%- else -%}
|
||||
{{ name }}
|
||||
{%- endif -%}
|
||||
|
||||
@ -8,13 +8,33 @@
|
||||
<meta name="robots" content="noindex, nofollow">
|
||||
<title>{% block title %}Comunidad{% endblock %} — Viena Latina</title>
|
||||
<link rel="stylesheet" href="{{ url_for('static', filename='board.css') }}">
|
||||
{% block brand_css %}
|
||||
{# After board.css, so the admin's colours win, and cache-busted by when
|
||||
they were saved. A generated file rather than an inline <style> because
|
||||
the CSP has no 'unsafe-inline' — an inline block would simply not apply,
|
||||
without a word in the console. The Marca screen overrides this block
|
||||
with nothing, so custom CSS that breaks the page cannot hide the page
|
||||
that undoes it. #}
|
||||
<link rel="stylesheet" href="{{ url_for('brand.stylesheet_file') }}?v={{ brand.stamp }}">
|
||||
{% endblock %}
|
||||
{% if brand.favicon_name %}
|
||||
<link rel="icon" type="image/png"
|
||||
href="{{ url_for('brand.picture', stored_name=brand.favicon_name) }}?v={{ brand.stamp }}">
|
||||
{% endif %}
|
||||
<script src="{{ url_for('static', filename='board.js') }}" defer></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header class="site-bar">
|
||||
<div class="site-bar__inner">
|
||||
<a class="site-bar__brand" href="/"><span class="site-bar__brand-text">Viena Latina</span></a>
|
||||
<a class="site-bar__brand" href="/">
|
||||
{% if brand.logo_name %}
|
||||
<img class="site-bar__logo" alt="Viena Latina"
|
||||
src="{{ url_for('brand.picture', stored_name=brand.logo_name) }}?v={{ brand.stamp }}">
|
||||
{% else %}
|
||||
<span class="site-bar__brand-text">Viena Latina</span>
|
||||
{% endif %}
|
||||
</a>
|
||||
{% if g.member %}
|
||||
{# <details> rather than a button with a handler: the CSP has no
|
||||
'unsafe-inline', so a menu that needs onclick="" is a menu that
|
||||
@ -36,23 +56,30 @@
|
||||
|
||||
{% if g.member %}
|
||||
<nav class="site-bar__pages" aria-label="Secciones">
|
||||
{# Five entries, and four of them are the same for everybody. The role
|
||||
{# Six entries, and five of them are the same for everybody. The role
|
||||
only decides whether Gestión is there — it used to decide three of
|
||||
them, which is how an ordinary member ended up signing in to a wall
|
||||
and a member list with their own profile and their own private
|
||||
messages hidden from them. Account items are in the corner menu
|
||||
above, because "Mi perfil" is not a section of the site. #}
|
||||
above, because "Mi perfil" is not a section of the site.
|
||||
|
||||
*Privados* used to be here, holding a list of conversations. The
|
||||
people are the section now and the messages live on each person's
|
||||
page, so the unread badge hangs on Miembros: it is the only thing
|
||||
left that tells a member somebody wrote to them, which is why it is
|
||||
also repeated on the card of whoever wrote. #}
|
||||
<ul class="page-nav">
|
||||
<li><a href="{{ url_for('home.index') }}">Inicio</a></li>
|
||||
<li><a href="{{ url_for('board.threads') }}">Muro</a></li>
|
||||
<li>
|
||||
<a href="{{ url_for('messages.inbox') }}">Privados{% set unread = unread_private() %}{% if unread %} <span class="tag">{{ unread }}</span>{% endif %}</a>
|
||||
<a href="{{ url_for('members.index') }}">Miembros{% set unread = unread_private() %}{% if unread %} <span class="tag">{{ unread }}</span>{% endif %}</a>
|
||||
</li>
|
||||
<li>
|
||||
{# The badge counts what is waiting for a moderator, so for
|
||||
anybody else the function returns 0 and nothing is drawn. #}
|
||||
<a href="{{ url_for('submissions.index') }}">Publicaciones{% set waiting = pending_review() %}{% if waiting %} <span class="tag">{{ waiting }}</span>{% endif %}</a>
|
||||
</li>
|
||||
<li><a href="{{ url_for('events.month') }}">Calendario</a></li>
|
||||
{% if g.member.role in ('owner', 'admin') %}
|
||||
<li><a href="{{ url_for('home.gestion') }}">Gestión</a></li>
|
||||
{% endif %}
|
||||
@ -74,7 +101,6 @@
|
||||
|
||||
<footer class="site-foot">
|
||||
<a href="/">Ir al sitio público</a>
|
||||
{% if g.member %} · <a href="{{ url_for('members.index') }}">Miembros</a>{% endif %}
|
||||
<div class="site-foot__legal">Viena Latina © {{ current_year }} · Área privada</div>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
162
apps/board/templates/brand_form.html
Normal file
162
apps/board/templates/brand_form.html
Normal file
@ -0,0 +1,162 @@
|
||||
{# Gestión → Marca: the colours, the logo and the favicon.
|
||||
|
||||
**This page deliberately does not load the generated stylesheet.** Every
|
||||
other page in the members area does, and the free CSS box below can contain
|
||||
anything — including `* { display: none }`. If that CSS applied here, the one
|
||||
screen that can undo it would be the one screen you could not read. So the
|
||||
block is overridden with nothing and this page is always in the factory
|
||||
colours. The live preview below is where the admin sees their own.
|
||||
|
||||
The consequence is worth stating because it looks like an oversight: the
|
||||
colours an admin picks do not show on the page where they pick them. #}
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Marca{% endblock %}
|
||||
{% block brand_css %}{% endblock %}
|
||||
|
||||
{% block main %}
|
||||
<div class="feed-head">
|
||||
<h1>Marca</h1>
|
||||
<a class="linkish" href="{{ url_for('home.gestion') }}">Volver a Gestión</a>
|
||||
</div>
|
||||
|
||||
<p class="muted">
|
||||
Los colores, el logotipo y el icono de la pestaña, para las dos mitades del
|
||||
sitio. El área privada cambia al guardar; vienalatina.com se reconstruye en
|
||||
un par de minutos.
|
||||
</p>
|
||||
|
||||
{% if state.updated_at and not state.published_at %}
|
||||
<section class="panel panel--attention">
|
||||
<div class="panel__head">
|
||||
<h2>Pendiente de publicar</h2>
|
||||
</div>
|
||||
<p class="panel__row">
|
||||
Lo de aquí está guardado, pero no ha llegado al sitio público: no se pudo
|
||||
contactar con el servidor de git la última vez.
|
||||
</p>
|
||||
<form method="post" action="{{ url_for('brand.publish') }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button class="btn" type="submit">Reintentar publicar en el sitio</button>
|
||||
</form>
|
||||
</section>
|
||||
{% endif %}
|
||||
|
||||
{% for note in notes %}
|
||||
<p class="flash flash--error">{{ note }}</p>
|
||||
{% endfor %}
|
||||
|
||||
<form class="card" method="post" enctype="multipart/form-data"
|
||||
action="{{ url_for('brand.edit') }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
|
||||
<h2 class="section-title">Colores</h2>
|
||||
<p class="muted small">
|
||||
Seis colores. Los demás —los tonos claros y oscuros del principal— se
|
||||
calculan a partir de él, para que no haya que acertar con cinco rojos
|
||||
parecidos. Están en «Avanzado» si los quieres a mano.
|
||||
</p>
|
||||
|
||||
{# A real colour picker, which every current browser draws natively: no
|
||||
dependency, no script, and it works with a keyboard. The text beside each
|
||||
one says where that colour shows up, because "--surface-soft" is not a
|
||||
question an admin can answer. #}
|
||||
<div class="swatches" data-brand-preview>
|
||||
{% for name, label, where in simple %}
|
||||
<div class="swatch">
|
||||
<label for="token-{{ name }}">{{ label }}</label>
|
||||
<input id="token-{{ name }}" name="token-{{ name }}" type="color"
|
||||
data-token="{{ name }}" value="{{ state.tokens[name] }}">
|
||||
<p class="muted small">{{ where }}</p>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
{# Restyled by the pickers above, through board.js setting the custom
|
||||
properties on this element. The DOM write is not an inline style
|
||||
attribute in the HTML, which is why it works under the CSP. #}
|
||||
<div class="brand-preview" data-brand-preview-target>
|
||||
<div class="brand-preview__bar">Viena Latina</div>
|
||||
<div class="brand-preview__card">
|
||||
<p class="brand-preview__meta">Ana Pérez · hace dos horas</p>
|
||||
<p>Así se verá una tarjeta del muro con estos colores.</p>
|
||||
<span class="brand-preview__btn">Un botón</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2 class="section-title">Logotipo</h2>
|
||||
<p class="muted small">
|
||||
PNG, JPG o WebP. Aparece en la cabecera de las dos mitades del sitio y es
|
||||
la imagen que sale al compartir un enlace que no tiene foto propia.
|
||||
{% if state.logo_name %}Ahora hay uno puesto; si eliges otro, lo reemplaza.{% endif %}
|
||||
</p>
|
||||
{% if state.logo_name %}
|
||||
<p><img class="brand-current"
|
||||
src="{{ url_for('brand.picture', stored_name=state.logo_name) }}?v={{ state.stamp }}"
|
||||
alt="El logotipo actual"></p>
|
||||
{% endif %}
|
||||
<input id="logo" name="logo" type="file" accept="image/png,image/jpeg,image/webp">
|
||||
|
||||
<h2 class="section-title">Icono de la pestaña</h2>
|
||||
<p class="muted small">
|
||||
PNG, y cuadrado: 32×32 o 180×180 van bien. Se sube aparte y no se saca del
|
||||
logotipo — recortar un logotipo ancho a un cuadrado da un trozo de letra.
|
||||
</p>
|
||||
{% if state.favicon_name %}
|
||||
<p><img class="brand-current brand-current--small"
|
||||
src="{{ url_for('brand.picture', stored_name=state.favicon_name) }}?v={{ state.stamp }}"
|
||||
alt="El icono actual"></p>
|
||||
{% endif %}
|
||||
<input id="favicon" name="favicon" type="file" accept="image/png">
|
||||
|
||||
<details class="brand-advanced">
|
||||
<summary>Avanzado</summary>
|
||||
|
||||
<p class="muted small">
|
||||
Para quien sepa CSS. Todo lo de aquí se aplica después de lo de arriba,
|
||||
así que gana. Si algo sale mal, «Restaurar lo de fábrica» está al final
|
||||
de esta página y esta página nunca carga este CSS, justamente para que
|
||||
se pueda llegar a ese botón.
|
||||
</p>
|
||||
|
||||
<h3 class="section-title">Los demás colores</h3>
|
||||
<p class="muted small">
|
||||
Déjalos en blanco para que se calculen desde el color principal
|
||||
({{ derived|join(', ') }}) o queden como están de fábrica.
|
||||
</p>
|
||||
<div class="swatches">
|
||||
{% for name in advanced %}
|
||||
<div class="swatch">
|
||||
<label for="token-{{ name }}"><span class="mono">--{{ name }}</span></label>
|
||||
<input id="token-{{ name }}" name="token-{{ name }}" type="text"
|
||||
value="{{ state.stored.get(name, '') }}"
|
||||
placeholder="{{ state.tokens[name] }}"
|
||||
pattern="^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$">
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<h3 class="section-title">CSS propio</h3>
|
||||
<p class="muted small">
|
||||
Se añade al final de la hoja de estilos, en las dos mitades del sitio.
|
||||
No puede contener «<» ni «>».
|
||||
</p>
|
||||
<textarea id="custom_css" name="custom_css" rows="10" class="mono"
|
||||
placeholder=".site-bar__logo { max-height: 48px; }">{{ state.custom_css }}</textarea>
|
||||
</details>
|
||||
|
||||
<button class="btn" type="submit">Guardar</button>
|
||||
</form>
|
||||
|
||||
{% if state.customised %}
|
||||
<form class="card" method="post" action="{{ url_for('brand.restore') }}"
|
||||
data-confirm="Se vuelve a los colores originales y se borran el logotipo y el icono. ¿Seguro?">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<h2 class="section-title">Restaurar lo de fábrica</h2>
|
||||
<p class="muted small">
|
||||
Deja los colores como estaban al principio y quita el logotipo y el icono.
|
||||
Esto funciona siempre, incluso si el CSS propio ha roto el resto del sitio.
|
||||
</p>
|
||||
<button class="btn btn--danger" type="submit">Restaurar lo de fábrica</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
68
apps/board/templates/calendar.html
Normal file
68
apps/board/templates/calendar.html
Normal file
@ -0,0 +1,68 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Calendario{% endblock %}
|
||||
|
||||
{% block main %}
|
||||
<div class="feed-head">
|
||||
<h1>Calendario</h1>
|
||||
{% if may_edit %}
|
||||
<a class="btn" href="{{ url_for('events.new') }}">Añadir evento</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if public_missing %}
|
||||
<p class="flash flash--error">
|
||||
No se pudo leer la agenda pública del servidor de git, así que aquí abajo
|
||||
faltan los eventos del sitio. Los internos están todos.
|
||||
</p>
|
||||
{% endif %}
|
||||
|
||||
<nav class="cal-bar" aria-label="Mes">
|
||||
<a class="linkish" href="{{ url_for('events.month', mes=previous) }}">← Anterior</a>
|
||||
<strong>{{ label }}</strong>
|
||||
<a class="linkish" href="{{ url_for('events.month', mes=next) }}">Siguiente →</a>
|
||||
</nav>
|
||||
<p class="muted small cal-bar__today">
|
||||
<a href="{{ url_for('events.month', mes=this_month) }}">Ir a este mes</a>
|
||||
</p>
|
||||
|
||||
<table class="cal">
|
||||
<thead>
|
||||
<tr>{% for day in weekdays %}<th scope="col">{{ day }}</th>{% endfor %}</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for week in weeks %}
|
||||
<tr>
|
||||
{% for day in week %}
|
||||
{# calendar.monthdayscalendar pads the first and last weeks with
|
||||
zeroes, which are days belonging to the neighbouring months. #}
|
||||
{% if day == 0 %}
|
||||
<td class="cal__pad"></td>
|
||||
{% else %}
|
||||
<td class="cal__day {{ 'cal__day--today' if day == today }}">
|
||||
<span class="cal__number">{{ day }}</span>
|
||||
{% for item in by_day.get(day, []) %}
|
||||
<a class="cal__event {{ 'cal__event--public' if item.public }}"
|
||||
href="{{ item.url }}">
|
||||
{% if item.starts_at %}<time>{{ item.starts_at }}</time> {% endif %}{{ item.title }}
|
||||
{% if item.public %}<span class="tag tag--quiet">público</span>{% endif %}
|
||||
</a>
|
||||
{% endfor %}
|
||||
{% if may_edit %}
|
||||
{# The day is carried into the form, so adding something to the
|
||||
24th starts with the 24th already filled in. #}
|
||||
<a class="cal__add" title="Añadir evento este día"
|
||||
href="{{ url_for('events.new', dia='%s-%02d'|format(month_key, day)) }}">+</a>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<p class="muted small">
|
||||
Los eventos marcados <span class="tag tag--quiet">público</span> están en
|
||||
vienalatina.com y los ve cualquiera. Los demás sólo se ven desde aquí.
|
||||
</p>
|
||||
{% endblock %}
|
||||
@ -77,6 +77,30 @@
|
||||
{% endfor %}
|
||||
</fieldset>
|
||||
|
||||
{# An event's own date, which is not the day the post goes up. Shown whenever
|
||||
a post can be written: ticking Evento above is what makes these required,
|
||||
checked on the server rather than hidden and shown with a script. #}
|
||||
<fieldset class="fieldset">
|
||||
<legend>Si es un evento</legend>
|
||||
<p class="muted small">
|
||||
Marca <strong>Evento</strong> arriba y rellena al menos la fecha. El
|
||||
evento aparecerá en la agenda del sitio y se podrá añadir al
|
||||
calendario del móvil.
|
||||
</p>
|
||||
|
||||
<label for="event_date">Fecha del evento</label>
|
||||
<input id="event_date" name="event_date" type="date" value="{{ f.event_date or '' }}">
|
||||
|
||||
<label for="event_time">Hora <span class="muted small">(opcional)</span></label>
|
||||
<input id="event_time" name="event_time" type="time" value="{{ f.event_time or '' }}">
|
||||
<p class="muted small">Déjala vacía si dura todo el día.</p>
|
||||
|
||||
<label for="event_location">Lugar <span class="muted small">(opcional)</span></label>
|
||||
<input id="event_location" name="event_location" maxlength="200"
|
||||
value="{{ f.event_location or '' }}">
|
||||
<p class="muted small">Dónde es: el sitio, la calle, el barrio.</p>
|
||||
</fieldset>
|
||||
|
||||
<label for="description">Resumen</label>
|
||||
<textarea id="description" name="description" rows="2">{{ f.description or '' }}</textarea>
|
||||
<p class="muted small">
|
||||
|
||||
@ -1,54 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
{% from "_person.html" import person %}
|
||||
{% from "_attachments.html" import attachments %}
|
||||
{% block title %}{{ other.display_name }}{% endblock %}
|
||||
|
||||
{% block main %}
|
||||
<div class="feed-head">
|
||||
<h1>{{ person(other.display_name, other.gitea_login, other.profile_published) }}</h1>
|
||||
<a class="linkish" href="{{ url_for('messages.inbox') }}">Volver</a>
|
||||
</div>
|
||||
|
||||
{% for m in messages %}
|
||||
<article class="card card--comment">
|
||||
<div class="card__meta">
|
||||
<span>{{ person(m.author, m.author_login, m.author_published) }}</span> · <time>{{ m.created_at }}</time>
|
||||
</div>
|
||||
<div class="prose">{{ to_html(m.body_md) }}</div>
|
||||
{{ attachments(images.get(m.id, [])) }}
|
||||
</article>
|
||||
{% else %}
|
||||
<p class="muted">Todavía no os habéis escrito. Empieza abajo.</p>
|
||||
{% endfor %}
|
||||
|
||||
<span id="final"></span>
|
||||
|
||||
{% if blocked %}
|
||||
<p class="muted">
|
||||
Hay un bloqueo entre vosotros, así que ninguno de los dos puede escribir.
|
||||
</p>
|
||||
<form method="post" action="{{ url_for('messages.unblock', member_id=other.id) }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button class="linkish" type="submit">Quitar mi bloqueo</button>
|
||||
</form>
|
||||
<p class="muted small">
|
||||
Si el bloqueo lo puso la otra persona, esto no lo quita.
|
||||
</p>
|
||||
{% else %}
|
||||
{# Always on this page, under the history. There is no separate step to "open"
|
||||
a conversation: arriving at somebody's name is opening it, and nothing is
|
||||
created in the database until the first message is actually sent. #}
|
||||
<form class="card" method="post" enctype="multipart/form-data"
|
||||
action="{{ url_for('messages.talk', member_id=other.id) }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<label for="body">Mensaje</label>
|
||||
<textarea id="body" data-markdown name="body" rows="4" autofocus
|
||||
placeholder="Se puede usar Markdown: **negrita**, listas, enlaces."></textarea>
|
||||
|
||||
<label for="pictures">Imágenes <span class="muted small">(opcional)</span></label>
|
||||
<input id="pictures" name="pictures" type="file" multiple accept="image/*">
|
||||
|
||||
<button class="btn" type="submit">Enviar</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
41
apps/board/templates/event.html
Normal file
41
apps/board/templates/event.html
Normal file
@ -0,0 +1,41 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}{{ event.title }}{% endblock %}
|
||||
|
||||
{% block main %}
|
||||
<div class="feed-head">
|
||||
<h1>{{ event.title }}</h1>
|
||||
<a class="linkish" href="{{ url_for('events.month', mes=event.starts_on[:7]) }}">Volver al calendario</a>
|
||||
</div>
|
||||
|
||||
<article class="card">
|
||||
<div class="event-facts">
|
||||
<p><strong>{{ when }}</strong>{% if event.starts_at %} · {{ event.starts_at }}{% endif %}</p>
|
||||
{% if event.location %}<p class="muted">{{ event.location }}</p>{% endif %}
|
||||
</div>
|
||||
|
||||
{% if event.photo_name %}
|
||||
<img class="attachment" src="{{ url_for('events.photo', stored_name=event.photo_name) }}"
|
||||
alt="{{ event.title }}">
|
||||
{% endif %}
|
||||
|
||||
{% if event.body_md %}<div class="prose">{{ body_html }}</div>{% endif %}
|
||||
|
||||
<div class="actions actions--row">
|
||||
<a class="btn" href="{{ url_for('events.ics', event_id=event.id) }}">Añadir a mi calendario</a>
|
||||
{% if may_edit %}
|
||||
<a class="linkish" href="{{ url_for('events.edit', event_id=event.id) }}">Editar</a>
|
||||
<form method="post" action="{{ url_for('events.delete', event_id=event.id) }}"
|
||||
data-confirm="Se quitará «{{ event.title }}» del calendario. ¿Seguro?">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button class="linkish linkish--danger" type="submit">Eliminar</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
</article>
|
||||
|
||||
<p class="muted small">
|
||||
Este evento sólo se ve desde el área de miembros. Para anunciar algo a todo
|
||||
el mundo, usa <a href="{{ url_for('submissions.index') }}">Publicaciones</a>
|
||||
con la categoría «Evento».
|
||||
</p>
|
||||
{% endblock %}
|
||||
50
apps/board/templates/event_form.html
Normal file
50
apps/board/templates/event_form.html
Normal file
@ -0,0 +1,50 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}{{ 'Editar evento' if event else 'Nuevo evento' }}{% endblock %}
|
||||
|
||||
{% set f = fields or event %}
|
||||
|
||||
{% block main %}
|
||||
<div class="feed-head">
|
||||
<h1>{{ 'Editar evento' if event else 'Nuevo evento' }}</h1>
|
||||
</div>
|
||||
|
||||
<p class="muted">
|
||||
Esto va al calendario de la comunidad, que sólo ven los miembros. No sale al
|
||||
sitio público ni se comparte fuera.
|
||||
</p>
|
||||
|
||||
<form class="card" method="post" enctype="multipart/form-data"
|
||||
action="{{ url_for('events.edit', event_id=event.id) if event else url_for('events.new') }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
|
||||
<label for="title">Título</label>
|
||||
<input id="title" name="title" maxlength="140" required
|
||||
value="{{ f.title if f else '' }}">
|
||||
|
||||
<label for="starts_on">Fecha</label>
|
||||
<input id="starts_on" name="starts_on" type="date" required
|
||||
value="{{ (f.starts_on if f else '') or suggested }}">
|
||||
|
||||
<label for="starts_at">Hora <span class="muted small">(opcional)</span></label>
|
||||
<input id="starts_at" name="starts_at" type="time" value="{{ (f.starts_at if f else '') or '' }}">
|
||||
<p class="muted small">Déjala vacía si dura todo el día.</p>
|
||||
|
||||
<label for="location">Lugar <span class="muted small">(opcional)</span></label>
|
||||
<input id="location" name="location" maxlength="200" value="{{ (f.location if f else '') or '' }}">
|
||||
|
||||
<label for="body">Detalles <span class="muted small">(opcional)</span></label>
|
||||
<textarea id="body" name="body" rows="8" data-markdown
|
||||
placeholder="Qué llevar, cómo llegar, a quién avisar.">{{ (f.body_md if event and not fields else (f.body if f else '')) or '' }}</textarea>
|
||||
|
||||
<label for="picture">Imagen <span class="muted small">(opcional)</span></label>
|
||||
<input id="picture" name="picture" type="file" accept="image/*">
|
||||
{% if event and event.photo_name %}
|
||||
<p class="muted small">Ya tiene una. Subir otra la reemplaza.</p>
|
||||
{% endif %}
|
||||
|
||||
<div class="actions">
|
||||
<button class="btn" type="submit">Guardar</button>
|
||||
<a class="linkish" href="{{ url_for('events.month') }}">Cancelar</a>
|
||||
</div>
|
||||
</form>
|
||||
{% endblock %}
|
||||
@ -15,14 +15,16 @@
|
||||
<section class="panel">
|
||||
<div class="panel__head">
|
||||
<h2>Miembros</h2>
|
||||
<a class="linkish" href="{{ url_for('members.index') }}">Abrir</a>
|
||||
<a class="linkish" href="{{ url_for('members.new') }}">Dar de alta</a>
|
||||
</div>
|
||||
<p class="panel__row">
|
||||
{{ counts.members }} en total · {{ counts.moderators }} pueden moderar
|
||||
{% if counts.suspended %} · {{ counts.suspended }} suspendido{{ '' if counts.suspended == 1 else 's' }}{% endif %}
|
||||
</p>
|
||||
<p class="muted small">
|
||||
Dar de alta, invitar de nuevo, cambiar el rol, suspender y eliminar.
|
||||
El directorio está en <a href="{{ url_for('members.index') }}">Miembros</a>,
|
||||
que ahora es una sección como las demás. Invitar de nuevo, cambiar el rol,
|
||||
suspender y eliminar están en la ficha de cada persona.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@ -51,6 +53,21 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel__head">
|
||||
<h2>Marca</h2>
|
||||
<a class="linkish" href="{{ url_for('brand.edit') }}">Abrir</a>
|
||||
</div>
|
||||
{% if brand.updated_at and not brand.published_at %}
|
||||
<p class="panel__row">Hay cambios guardados que no han llegado al sitio público.</p>
|
||||
{% endif %}
|
||||
<p class="muted small">
|
||||
Los colores, el logotipo y el icono de la pestaña, para las dos mitades del
|
||||
sitio. Con un apartado avanzado para quien sepa CSS, y un botón para
|
||||
volver a lo de fábrica.
|
||||
</p>
|
||||
</section>
|
||||
|
||||
{% if counts.pending %}
|
||||
<section class="panel panel--attention">
|
||||
<div class="panel__head">
|
||||
|
||||
@ -19,7 +19,7 @@
|
||||
{% for item in queue %}
|
||||
<p class="panel__row">
|
||||
<a href="{{ url_for('submissions.show', submission_id=item.id) }}">{{ item.title }}</a>
|
||||
<span class="muted small">{{ person(item.author, item.author_login, item.author_published) }} · {{ item.created_at }}</span>
|
||||
<span class="muted small">{{ person(item.author, item.author_login) }} · {{ item.created_at }}</span>
|
||||
</p>
|
||||
{% endfor %}
|
||||
</section>
|
||||
@ -28,14 +28,14 @@
|
||||
<section class="panel">
|
||||
<div class="panel__head">
|
||||
<h2>Privados</h2>
|
||||
<a class="linkish" href="{{ url_for('messages.inbox') }}">Todos</a>
|
||||
<a class="linkish" href="{{ url_for('members.index') }}">Miembros</a>
|
||||
</div>
|
||||
{% if not conversations %}
|
||||
<p class="muted">Todavía no tienes conversaciones. Escribe a alguien desde Privados.</p>
|
||||
<p class="muted">Todavía no tienes conversaciones. Abre la ficha de alguien en Miembros y escríbele.</p>
|
||||
{% endif %}
|
||||
{% for c in conversations %}
|
||||
<p class="panel__row">
|
||||
<a href="{{ url_for('messages.talk', member_id=c.other_id) }}">{{ c.other_name }}</a>
|
||||
<a href="{{ url_for('members.show', login=c.other_login) }}">{{ c.other_name }}</a>
|
||||
{% if c.unread %}<span class="tag">{{ c.unread }}</span>{% endif %}
|
||||
{% if c.last_at %}<span class="muted small">{{ c.last_at }}</span>{% endif %}
|
||||
</p>
|
||||
@ -53,7 +53,7 @@
|
||||
{% for t in threads %}
|
||||
<p class="panel__row">
|
||||
<a href="{{ url_for('board.thread', thread_id=t.id) }}">{{ t.title }}</a>
|
||||
<span class="muted small">{{ person(t.author, t.author_login, t.author_published) }} · {{ t.replies }} respuesta{{ '' if t.replies == 1 else 's' }}</span>
|
||||
<span class="muted small">{{ person(t.author, t.author_login) }} · {{ t.replies }} respuesta{{ '' if t.replies == 1 else 's' }}</span>
|
||||
</p>
|
||||
{% endfor %}
|
||||
</section>
|
||||
|
||||
@ -1,44 +0,0 @@
|
||||
{% extends "base.html" %}
|
||||
{% block title %}Privados{% endblock %}
|
||||
|
||||
{% block main %}
|
||||
<div class="feed-head">
|
||||
<h1>Mensajes privados</h1>
|
||||
</div>
|
||||
|
||||
{% if people %}
|
||||
{# GET, not POST: choosing somebody to write to is navigation, not a change.
|
||||
It also means no conversation is created just because a name was picked. #}
|
||||
<form class="card" method="get" action="{{ url_for('messages.pick') }}">
|
||||
<label for="para">Escribir a</label>
|
||||
<select id="para" name="member_id">
|
||||
{% for person in people %}
|
||||
<option value="{{ person.id }}">{{ person.display_name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<button class="btn" type="submit">Escribir</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% if not conversations %}
|
||||
<p class="muted">Todavía no tienes conversaciones privadas.</p>
|
||||
{% endif %}
|
||||
|
||||
{% for c in conversations %}
|
||||
<article class="card">
|
||||
<a class="card__title" href="{{ url_for('messages.talk', member_id=c.other_id) }}">
|
||||
{{ c.other_name }}
|
||||
{% if c.unread %}<span class="tag">{{ c.unread }}</span>{% endif %}
|
||||
</a>
|
||||
<p class="muted small">{{ excerpt(c.last_body) or 'Sin mensajes todavía.' }}</p>
|
||||
<div class="card__meta">
|
||||
{% if c.last_at %}<time>{{ c.last_at }}</time>{% endif %}
|
||||
<form method="post" action="{{ url_for('messages.block', member_id=c.other_id) }}"
|
||||
data-confirm="Al bloquear a {{ c.other_name }} ninguno de los dos podrá escribir al otro. ¿Seguro?">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button class="linkish linkish--danger" type="submit">Bloquear</button>
|
||||
</form>
|
||||
</div>
|
||||
</article>
|
||||
{% endfor %}
|
||||
{% endblock %}
|
||||
204
apps/board/templates/member.html
Normal file
204
apps/board/templates/member.html
Normal file
@ -0,0 +1,204 @@
|
||||
{# One person's page inside the members area.
|
||||
|
||||
Three things in one place, in the order somebody actually wants them: who
|
||||
this is, what you have said to each other, and — for an admin — what can be
|
||||
done about them. It replaces two screens, `conversation.html` and the
|
||||
`<details>` block that used to be on every card in the directory.
|
||||
|
||||
The private half is the reason this page exists and the reason it is behind
|
||||
the login. Their *public* page is a separate thing they publish themselves,
|
||||
linked below when they have. #}
|
||||
{% extends "base.html" %}
|
||||
{% from "_person.html" import person %}
|
||||
{% from "_attachments.html" import attachments %}
|
||||
{% block title %}{{ member.display_name }}{% endblock %}
|
||||
|
||||
{% set me = g.member %}
|
||||
{% set is_owner = me.role == 'owner' %}
|
||||
{% set is_admin = me.role in ('owner', 'admin') %}
|
||||
|
||||
{% block main %}
|
||||
<div class="feed-head">
|
||||
<h1>{{ member.display_name }}{% if is_me %} <span class="muted small">(tú)</span>{% endif %}</h1>
|
||||
<a class="linkish" href="{{ url_for('members.index') }}">Todos los miembros</a>
|
||||
</div>
|
||||
|
||||
<section class="card person-head">
|
||||
{% if member.photo_name %}
|
||||
<img class="person-head__photo"
|
||||
src="{{ url_for('profiles.member_photo', stored_name=member.photo_name) }}"
|
||||
alt="">
|
||||
{% else %}
|
||||
<span class="person-head__photo person-head__photo--none" aria-hidden="true">
|
||||
{{ member.display_name[:1]|upper }}
|
||||
</span>
|
||||
{% endif %}
|
||||
|
||||
<div class="person-head__who">
|
||||
<p class="muted small">
|
||||
<span class="mono">{{ member.gitea_login }}</span> · {{ labels[member.role] }}
|
||||
{% if not member.active %} · Suspendido{% endif %}
|
||||
</p>
|
||||
|
||||
{% if member.bio %}<div class="prose">{{ bio_html }}</div>{% endif %}
|
||||
|
||||
{% if links %}
|
||||
<ul class="person-head__links">
|
||||
{% for link in links %}
|
||||
{# nofollow noopener as on the public page: these are addresses a
|
||||
member typed, and this page is no safer a place to vouch for them. #}
|
||||
<li><a href="{{ link.url }}" rel="nofollow noopener">{{ link.label or link.url }}</a></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
|
||||
<p class="person-head__foot">
|
||||
{% if member.profile_published %}
|
||||
<a class="linkish" href="{{ url_for('profiles_public.show', name=member.gitea_login) }}">Su página pública</a>
|
||||
{% elif is_me %}
|
||||
<a class="linkish" href="{{ url_for('profiles.edit') }}">Editar mi perfil</a>
|
||||
{% else %}
|
||||
<span class="muted small">No ha publicado una página pública.</span>
|
||||
{% endif %}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{% if is_me %}
|
||||
{# No conversation with yourself, and nothing to mark read. Your own private
|
||||
messages are each on the page of the person you had them with, which is the
|
||||
whole arrangement. #}
|
||||
<p class="muted">
|
||||
Esta es tu ficha, tal como la ven los demás. Para escribir a alguien, abre su
|
||||
ficha desde <a href="{{ url_for('members.index') }}">Miembros</a>.
|
||||
</p>
|
||||
{% else %}
|
||||
|
||||
<h2 class="section-title">Conversación privada</h2>
|
||||
<p class="muted small">
|
||||
Sólo vosotros dos podéis leer esto.
|
||||
</p>
|
||||
|
||||
{% for m in messages %}
|
||||
<article class="card card--comment">
|
||||
<div class="card__meta">
|
||||
<span>{{ person(m.author, m.author_login) }}</span> · <time>{{ m.created_at }}</time>
|
||||
</div>
|
||||
<div class="prose">{{ to_html(m.body_md) }}</div>
|
||||
{{ attachments(images.get(m.id, [])) }}
|
||||
</article>
|
||||
{% else %}
|
||||
<p class="muted">Todavía no os habéis escrito. Empieza abajo.</p>
|
||||
{% endfor %}
|
||||
|
||||
<span id="final"></span>
|
||||
|
||||
{% if blocked %}
|
||||
<p class="muted">
|
||||
Hay un bloqueo entre vosotros, así que ninguno de los dos puede escribir.
|
||||
</p>
|
||||
<form method="post" action="{{ url_for('messages.unblock', member_id=member.id) }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button class="linkish" type="submit">Quitar mi bloqueo</button>
|
||||
</form>
|
||||
<p class="muted small">
|
||||
Si el bloqueo lo puso la otra persona, esto no lo quita.
|
||||
</p>
|
||||
{% elif not member.active %}
|
||||
{# The handler refuses a message to a suspended member, so the box is not drawn
|
||||
for one. Said plainly rather than left as a missing form. #}
|
||||
<p class="muted">
|
||||
{{ member.display_name }} tiene el acceso suspendido y no puede recibir mensajes.
|
||||
</p>
|
||||
{% else %}
|
||||
<form class="card" method="post" enctype="multipart/form-data"
|
||||
action="{{ url_for('messages.talk', member_id=member.id) }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<label for="body">Mensaje</label>
|
||||
<textarea id="body" data-markdown name="body" rows="4"
|
||||
placeholder="Se puede usar Markdown: **negrita**, listas, enlaces."></textarea>
|
||||
|
||||
<label for="pictures">Imágenes <span class="muted small">(opcional)</span></label>
|
||||
<input id="pictures" name="pictures" type="file" multiple accept="image/*">
|
||||
|
||||
<button class="btn" type="submit">Enviar</button>
|
||||
</form>
|
||||
|
||||
<details class="person-block">
|
||||
<summary>Bloquear a {{ member.display_name }}</summary>
|
||||
<p class="muted small">
|
||||
Un bloqueo va en los dos sentidos: ninguno de los dos podrá escribir al
|
||||
otro. Lo puedes quitar cuando quieras, pero sólo el tuyo.
|
||||
</p>
|
||||
<form method="post" action="{{ url_for('messages.block', member_id=member.id) }}"
|
||||
data-confirm="Ninguno de los dos podrá escribir al otro. ¿Seguro?">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button class="linkish linkish--danger" type="submit">Bloquear</button>
|
||||
</form>
|
||||
</details>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
|
||||
{% if is_admin and member.role != 'owner' and not is_me %}
|
||||
{# Moved here from the directory cards. A <details>, not a script: the CSP has
|
||||
no 'unsafe-inline'. Every button is still checked in its handler — this block
|
||||
being hidden from a moderator is a courtesy, not the rule. #}
|
||||
<details class="person-card__admin">
|
||||
<summary>Gestionar</summary>
|
||||
<div class="person-card__actions">
|
||||
<form method="post" action="{{ url_for('members.set_active', member_id=member.id) }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<input type="hidden" name="active" value="{{ 0 if member.active else 1 }}">
|
||||
<button class="linkish" type="submit">{{ 'Suspender' if member.active else 'Reactivar' }}</button>
|
||||
</form>
|
||||
|
||||
{# Any admin can re-send, not just the owner: the usual reason somebody
|
||||
needs this is that the admin who added them made the account by hand,
|
||||
and waiting for the owner defeats the point. Hidden without an
|
||||
address, because the handler would refuse. #}
|
||||
{% if member.email and member.active %}
|
||||
<form method="post" action="{{ url_for('members.invite', member_id=member.id) }}"
|
||||
data-confirm="Se enviará un enlace nuevo a {{ member.email }} y el anterior dejará de servir. ¿Seguro?">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button class="linkish" type="submit">Enviar invitación</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% if is_owner or member.role != 'admin' %}
|
||||
<form class="inline-form" method="post"
|
||||
action="{{ url_for('members.set_role', member_id=member.id) }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<label class="sr-only" for="role">Rol de {{ member.display_name }}</label>
|
||||
<select id="role" name="role">
|
||||
<option value="user" {{ 'selected' if member.role == 'user' }}>Miembro</option>
|
||||
<option value="moderator" {{ 'selected' if member.role == 'moderator' }}>Moderador</option>
|
||||
{% if is_owner %}
|
||||
<option value="admin" {{ 'selected' if member.role == 'admin' }}>Administrador</option>
|
||||
{% endif %}
|
||||
</select>
|
||||
<button class="linkish" type="submit">Cambiar rol</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% if is_owner %}
|
||||
{% if member.role == 'admin' and member.active %}
|
||||
<form method="post" action="{{ url_for('members.transfer', member_id=member.id) }}"
|
||||
data-confirm="Vas a dejar de ser el responsable y {{ member.display_name }} pasará a serlo. ¿Seguro?">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button class="linkish" type="submit">Transferir titularidad</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
<form method="post" action="{{ url_for('members.erase', member_id=member.id) }}"
|
||||
data-confirm="Se borrarán sus datos personales. Sus mensajes quedarán como «Miembro eliminado». ¿Seguro?">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button class="linkish linkish--danger" type="submit">Eliminar</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% if member.email %}<p class="muted small">{{ member.email }}</p>{% endif %}
|
||||
{% if member.creator %}<p class="muted small">Dado de alta por {{ member.creator }}.</p>{% endif %}
|
||||
</div>
|
||||
</details>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@ -1,9 +1,7 @@
|
||||
{% extends "base.html" %}
|
||||
{% from "_person.html" import person %}
|
||||
{% block title %}Miembros{% endblock %}
|
||||
|
||||
{% set me = g.member %}
|
||||
{% set is_owner = me.role == 'owner' %}
|
||||
{% set is_admin = me.role in ('owner', 'admin') %}
|
||||
|
||||
{% block main %}
|
||||
@ -14,15 +12,20 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{# People, not rows. This was a five-column table whose last column held four
|
||||
forms, which is how the actions ended up wrapping on top of each other in a
|
||||
column two inches wide. A card has room for a face and somewhere to write
|
||||
from, and the admin controls fold away into a <details> so that the page is
|
||||
a directory first and a control panel second. #}
|
||||
<p class="muted">
|
||||
Abre la ficha de alguien para escribirle en privado y leer lo que os habéis
|
||||
escrito. Los mensajes privados viven en la ficha de cada persona; no hay
|
||||
bandeja aparte.
|
||||
</p>
|
||||
|
||||
{# Faces and names, and the whole card is the link. This was a page of cards
|
||||
each carrying a bio, a couple of links and a fold-out admin panel — four
|
||||
things to read per person, on a page whose job is to let you find one. All of
|
||||
that is on the person's own page now. #}
|
||||
<ul class="people">
|
||||
{% for m in members %}
|
||||
<li class="person-card {{ '' if m.active else 'person-card--off' }}">
|
||||
<div class="person-card__head">
|
||||
<a class="person-card__link" href="{{ url_for('members.show', login=m.gitea_login) }}">
|
||||
{% if m.photo_name %}
|
||||
<img class="person-card__photo"
|
||||
src="{{ url_for('profiles.member_photo', stored_name=m.photo_name) }}"
|
||||
@ -35,96 +38,26 @@
|
||||
</span>
|
||||
{% endif %}
|
||||
|
||||
<div class="person-card__who">
|
||||
<h2 class="person-card__name">
|
||||
{{ person(m.display_name, m.gitea_login, m.profile_published) }}
|
||||
<span class="person-card__who">
|
||||
<span class="person-card__name">
|
||||
{{ m.display_name }}
|
||||
{% if m.id == me.id %}<span class="muted small">(tú)</span>{% endif %}
|
||||
</h2>
|
||||
{% if m.unread %}
|
||||
{# Who wrote, not just that somebody did — and the cards are
|
||||
sorted so this one is at the top of the page. #}
|
||||
<span class="tag" aria-label="{{ m.unread }} sin leer">{{ m.unread }}</span>
|
||||
{% endif %}
|
||||
</span>
|
||||
{# The username is shown to everyone: it is not a secret, it is
|
||||
their address — vienalatina.com/<usuario> — and somebody
|
||||
looking for a person's page needs to know how it is spelled.
|
||||
The email stays inside the admin block. #}
|
||||
<p class="muted small">
|
||||
The email stays on their page, inside the admin block. #}
|
||||
<span class="muted small">
|
||||
<span class="mono">{{ m.gitea_login }}</span> · {{ labels[m.role] }}
|
||||
{% if not m.active %} · Suspendido{% endif %}
|
||||
{% if m.posts %} · {{ m.posts }} en el muro{% endif %}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if m.bio %}<p class="person-card__bio">{{ m.bio.split('\n')[0][:160] }}</p>{% endif %}
|
||||
|
||||
<div class="person-card__foot">
|
||||
{% if m.id != me.id and m.active %}
|
||||
<a class="linkish" href="{{ url_for('messages.talk', member_id=m.id) }}">Escribir</a>
|
||||
{% endif %}
|
||||
{% if m.profile_published %}
|
||||
<a class="linkish" href="{{ url_for('profiles_public.show', name=m.gitea_login) }}">Su página</a>
|
||||
{% elif m.id == me.id %}
|
||||
<a class="linkish" href="{{ url_for('profiles.edit') }}">Editar mi perfil</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if is_admin and m.role != 'owner' %}
|
||||
{# A <details>, not a script: the CSP has no 'unsafe-inline'. Closed by
|
||||
default, so the directory reads as a directory. #}
|
||||
<details class="person-card__admin">
|
||||
<summary>Gestionar</summary>
|
||||
<div class="person-card__actions">
|
||||
<form method="post" action="{{ url_for('members.set_active', member_id=m.id) }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<input type="hidden" name="active" value="{{ 0 if m.active else 1 }}">
|
||||
<button class="linkish" type="submit">{{ 'Suspender' if m.active else 'Reactivar' }}</button>
|
||||
</form>
|
||||
|
||||
{# Any admin can re-send, not just the owner: the usual reason
|
||||
somebody needs this is that the admin who added them made the
|
||||
account by hand, and waiting for the owner defeats the point.
|
||||
Hidden without an address, because the handler would refuse. #}
|
||||
{% if m.email and m.active %}
|
||||
<form method="post" action="{{ url_for('members.invite', member_id=m.id) }}"
|
||||
data-confirm="Se enviará un enlace nuevo a {{ m.email }} y el anterior dejará de servir. ¿Seguro?">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button class="linkish" type="submit">Enviar invitación</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% if is_owner or m.role != 'admin' %}
|
||||
<form class="inline-form" method="post"
|
||||
action="{{ url_for('members.set_role', member_id=m.id) }}">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<label class="sr-only" for="role-{{ m.id }}">Rol de {{ m.display_name }}</label>
|
||||
<select id="role-{{ m.id }}" name="role">
|
||||
<option value="user" {{ 'selected' if m.role == 'user' }}>Miembro</option>
|
||||
<option value="moderator" {{ 'selected' if m.role == 'moderator' }}>Moderador</option>
|
||||
{% if is_owner %}
|
||||
<option value="admin" {{ 'selected' if m.role == 'admin' }}>Administrador</option>
|
||||
{% endif %}
|
||||
</select>
|
||||
<button class="linkish" type="submit">Cambiar rol</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% if is_owner %}
|
||||
{% if m.role == 'admin' and m.active %}
|
||||
<form method="post" action="{{ url_for('members.transfer', member_id=m.id) }}"
|
||||
data-confirm="Vas a dejar de ser el responsable y {{ m.display_name }} pasará a serlo. ¿Seguro?">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button class="linkish" type="submit">Transferir titularidad</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
<form method="post" action="{{ url_for('members.erase', member_id=m.id) }}"
|
||||
data-confirm="Se borrarán sus datos personales. Sus mensajes quedarán como «Miembro eliminado». ¿Seguro?">
|
||||
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
|
||||
<button class="linkish linkish--danger" type="submit">Eliminar</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% if m.email %}<p class="muted small">{{ m.email }}</p>{% endif %}
|
||||
</div>
|
||||
</details>
|
||||
{% endif %}
|
||||
</span>
|
||||
</span>
|
||||
</a>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
@ -132,9 +65,9 @@
|
||||
{% if is_admin %}
|
||||
<p class="muted small">
|
||||
Hay un solo responsable. El responsable da de alta administradores; los
|
||||
administradores dan de alta miembros y moderadores. Nadie puede suspender ni
|
||||
degradar al responsable: para dejar el cargo hay que transferirlo a un
|
||||
administrador.
|
||||
administradores dan de alta miembros y moderadores. Suspender, cambiar el rol,
|
||||
reenviar la invitación y eliminar están en la ficha de cada persona, bajo
|
||||
«Gestionar».
|
||||
</p>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
@ -11,7 +11,7 @@
|
||||
<article class="card">
|
||||
<div class="card__meta">
|
||||
<span class="tag tag--{{ item.state }}">{{ labels[item.state] }}</span>
|
||||
<span>{{ person(item.author, item.author_login, item.author_published) }}</span> · <time>{{ item.created_at }}</time>
|
||||
<span>{{ person(item.author, item.author_login) }}</span> · <time>{{ item.created_at }}</time>
|
||||
{% if item.categories %} · <span>{{ item.categories }}</span>{% endif %}
|
||||
</div>
|
||||
{% if item.description %}<p class="muted">{{ item.description }}</p>{% endif %}
|
||||
|
||||
@ -35,6 +35,30 @@
|
||||
{% endfor %}
|
||||
</fieldset>
|
||||
|
||||
{# An event's own date, which is not the day the post goes up. Shown whenever
|
||||
a post can be written: ticking Evento above is what makes these required,
|
||||
checked on the server rather than hidden and shown with a script. #}
|
||||
<fieldset class="fieldset">
|
||||
<legend>Si es un evento</legend>
|
||||
<p class="muted small">
|
||||
Marca <strong>Evento</strong> arriba y rellena al menos la fecha. El
|
||||
evento aparecerá en la agenda del sitio y se podrá añadir al
|
||||
calendario del móvil.
|
||||
</p>
|
||||
|
||||
<label for="event_date">Fecha del evento</label>
|
||||
<input id="event_date" name="event_date" type="date" value="{{ fields.event_date or '' }}">
|
||||
|
||||
<label for="event_time">Hora <span class="muted small">(opcional)</span></label>
|
||||
<input id="event_time" name="event_time" type="time" value="{{ fields.event_time or '' }}">
|
||||
<p class="muted small">Déjala vacía si dura todo el día.</p>
|
||||
|
||||
<label for="event_location">Lugar <span class="muted small">(opcional)</span></label>
|
||||
<input id="event_location" name="event_location" maxlength="200"
|
||||
value="{{ fields.event_location or '' }}">
|
||||
<p class="muted small">Dónde es: el sitio, la calle, el barrio.</p>
|
||||
</fieldset>
|
||||
|
||||
<label for="body">Texto</label>
|
||||
<textarea id="body" data-markdown name="body" rows="16" required
|
||||
placeholder="Se puede usar Markdown: **negrita**, ## títulos, listas, enlaces.">{{ fields.body if fields else '' }}</textarea>
|
||||
|
||||
@ -36,7 +36,7 @@
|
||||
{% for item in queue %}
|
||||
<article class="card">
|
||||
<div class="card__meta">
|
||||
<span>{{ person(item.author, item.author_login, item.author_published) }}</span> · <time>{{ item.created_at }}</time>
|
||||
<span>{{ person(item.author, item.author_login) }}</span> · <time>{{ item.created_at }}</time>
|
||||
</div>
|
||||
<h3 class="card__title">
|
||||
<a href="{{ url_for('submissions.show', submission_id=item.id) }}">{{ item.title }}</a>
|
||||
|
||||
@ -9,7 +9,7 @@
|
||||
<div class="card__meta">
|
||||
{% if thread.pinned %}<span class="tag">Fijado</span>{% endif %}
|
||||
{% if thread.locked %}<span class="tag tag--quiet">Cerrado</span>{% endif %}
|
||||
<span>{{ person(author.display_name, author.gitea_login, author.profile_published) }}</span> · <time>{{ thread.created_at }}</time>
|
||||
<span>{{ person(author.display_name, author.gitea_login) }}</span> · <time>{{ thread.created_at }}</time>
|
||||
{% if thread.edited_at %}<span class="muted small">(editado)</span>{% endif %}
|
||||
</div>
|
||||
<h1 class="card__title">{{ thread.title }}</h1>
|
||||
@ -51,7 +51,7 @@
|
||||
{% for c in comments %}
|
||||
<article class="card card--comment" id="c{{ c.id }}">
|
||||
<div class="card__meta">
|
||||
<span>{{ person(c.author, c.author_login, c.author_published) }}</span> · <time>{{ c.created_at }}</time>
|
||||
<span>{{ person(c.author, c.author_login) }}</span> · <time>{{ c.created_at }}</time>
|
||||
{% if c.edited_at %}<span class="muted small">(editado)</span>{% endif %}
|
||||
</div>
|
||||
<div class="prose">{{ to_html(c.body_md) }}</div>
|
||||
|
||||
@ -20,7 +20,7 @@
|
||||
<div class="card__meta">
|
||||
{% if t.pinned %}<span class="tag">Fijado</span>{% endif %}
|
||||
{% if t.locked %}<span class="tag tag--quiet">Cerrado</span>{% endif %}
|
||||
<span>{{ person(t.author, t.author_login, t.author_published) }}</span> · <time>{{ t.created_at }}</time>
|
||||
<span>{{ person(t.author, t.author_login) }}</span> · <time>{{ t.created_at }}</time>
|
||||
</div>
|
||||
<h2 class="card__title">
|
||||
<a href="{{ url_for('board.thread', thread_id=t.id) }}">{{ t.title }}</a>
|
||||
|
||||
@ -11,6 +11,7 @@ Gitea, and the tests that care about it stub the two network calls instead.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
@ -18,6 +19,7 @@ import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
|
||||
|
||||
from apps.board import gitea # noqa: E402
|
||||
from apps.board.app import create_app # noqa: E402
|
||||
from apps.board.db import connect # noqa: E402
|
||||
|
||||
@ -91,3 +93,60 @@ def post(client):
|
||||
payload.setdefault("csrf_token", "token-for-tests")
|
||||
return client.post(url, data=payload, **kwargs)
|
||||
return _post
|
||||
|
||||
|
||||
# --- the git server, as a dictionary --------------------------------------
|
||||
#
|
||||
# Shared because two features commit to the content repository now: the editor
|
||||
# (test_content.py) and the brand (test_brand.py). What matters in both is the
|
||||
# payload — which files, with which bytes, under whose name — and `requests` can
|
||||
# be trusted to do HTTP.
|
||||
|
||||
class FakeRepo:
|
||||
"""A repository in a dict, with shas that change when content does."""
|
||||
|
||||
def __init__(self):
|
||||
self.files: dict[str, bytes] = {}
|
||||
self.commits: list[str] = []
|
||||
self.authors: list[dict] = []
|
||||
self.reads = 0
|
||||
|
||||
@staticmethod
|
||||
def _sha(data: bytes) -> str:
|
||||
return hashlib.sha1(data).hexdigest()
|
||||
|
||||
def list_directory(self, path, token=None):
|
||||
out = []
|
||||
for name, data in self.files.items():
|
||||
if name.startswith(path + "/") and "/" not in name[len(path) + 1:]:
|
||||
out.append({"name": name.rsplit("/", 1)[1], "path": name,
|
||||
"type": "file", "sha": self._sha(data)})
|
||||
return out
|
||||
|
||||
def read_file(self, path, token=None):
|
||||
self.reads += 1
|
||||
if path not in self.files:
|
||||
raise gitea.GiteaError("Ese archivo ya no existe.")
|
||||
return self.files[path].decode("utf-8"), self._sha(self.files[path])
|
||||
|
||||
def write_file(self, path, data, message, token=None, sha=None, member=None):
|
||||
if sha and self.files.get(path) is not None and self._sha(self.files[path]) != sha:
|
||||
raise gitea.StaleFile("Alguien más guardó este archivo mientras lo editabas.")
|
||||
self.files[path] = data
|
||||
self.commits.append(message)
|
||||
self.authors.append(gitea._identity(member))
|
||||
return self._sha(data)
|
||||
|
||||
def delete_file(self, path, sha, message, token=None, member=None):
|
||||
self.files.pop(path, None)
|
||||
self.commits.append(message)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo(monkeypatch):
|
||||
fake = FakeRepo()
|
||||
for name in ("list_directory", "read_file", "write_file", "delete_file"):
|
||||
monkeypatch.setattr(gitea, name, getattr(fake, name))
|
||||
return fake
|
||||
|
||||
|
||||
|
||||
387
apps/board/tests/test_brand.py
Normal file
387
apps/board/tests/test_brand.py
Normal file
@ -0,0 +1,387 @@
|
||||
"""The admin-editable look: colours, logo, favicon, custom CSS.
|
||||
|
||||
The first test in this file is the point of the phase. The brand colours were
|
||||
two identical `:root` blocks in two stylesheets, with a comment saying *"If the
|
||||
brand colours change, change them in both"* — an instruction, which is the
|
||||
weakest kind of guarantee there is. `brand.FACTORY` is the one list now, and
|
||||
this file fails the build if either stylesheet drifts from it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.board import brand
|
||||
|
||||
PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
|
||||
GIF = b"GIF89a" + b"\x00" * 64
|
||||
|
||||
BOARD_CSS = Path(brand.__file__).resolve().parent / "static" / "board.css"
|
||||
THEME_CSS = (Path(brand.__file__).resolve().parents[2]
|
||||
/ "themes" / "vienalatina" / "assets" / "css" / "main.css")
|
||||
|
||||
|
||||
def tokens_in(path: Path) -> dict:
|
||||
"""The `--name: value` pairs from a stylesheet's first `:root` block."""
|
||||
css = path.read_text(encoding="utf-8")
|
||||
block = re.search(r":root\s*\{(.*?)\}", css, re.S)
|
||||
assert block, f"{path.name} has no :root block"
|
||||
return {name: value.strip().lower() for name, value in
|
||||
re.findall(r"--([a-z-]+):\s*([^;]+);", block.group(1))}
|
||||
|
||||
|
||||
# --- the one list ---------------------------------------------------------
|
||||
|
||||
@pytest.mark.parametrize("path", [BOARD_CSS, THEME_CSS], ids=["board", "theme"])
|
||||
def test_the_stylesheet_agrees_with_the_factory_palette(path):
|
||||
"""Both files keep their own `:root` — they are served by different things
|
||||
and each has to stand alone — but neither may disagree with brand.py.
|
||||
|
||||
Only the names both sides share are compared: the theme has no `--danger`
|
||||
and the members area has no `--accent` aliases, and neither absence is a
|
||||
drift."""
|
||||
declared = tokens_in(path)
|
||||
shared = set(declared) & set(brand.FACTORY)
|
||||
assert len(shared) > 8, f"{path.name}: only {len(shared)} tokens matched — is the block still there?"
|
||||
for name in sorted(shared):
|
||||
assert declared[name] == brand.FACTORY[name].lower(), (
|
||||
f"{path.name}: --{name} is {declared[name]} and brand.FACTORY says "
|
||||
f"{brand.FACTORY[name]}. One of the two is wrong."
|
||||
)
|
||||
|
||||
|
||||
# --- colour arithmetic ----------------------------------------------------
|
||||
|
||||
def test_the_three_shades_come_out_of_the_brand_colour():
|
||||
"""Derived in HLS so the hue survives. A green brand must not produce the
|
||||
pink tints that mixing #c0391c with white would."""
|
||||
tokens = brand.resolve({"brand": "#1b5e20"})
|
||||
|
||||
assert tokens["brand"] == "#1b5e20"
|
||||
for name in ("brand-dark", "brand-soft", "brand-softer"):
|
||||
assert tokens[name] != brand.FACTORY[name], name
|
||||
# Darker, then two tints, in that order.
|
||||
assert (brand._luminance(tokens["brand-dark"])
|
||||
< brand._luminance(tokens["brand"])
|
||||
< brand._luminance(tokens["brand-soft"])
|
||||
< brand._luminance(tokens["brand-softer"]))
|
||||
|
||||
|
||||
def test_an_explicit_shade_stops_being_derived():
|
||||
tokens = brand.resolve({"brand": "#1b5e20", "brand-dark": "#000000"})
|
||||
assert tokens["brand-dark"] == "#000000"
|
||||
|
||||
|
||||
def test_storing_nothing_leaves_the_factory_hexes_untouched():
|
||||
"""Not "close to" the factory palette — the same strings. Deriving from an
|
||||
unchanged brand colour would shift the three shades by a rounding error the
|
||||
first time anybody opened the screen."""
|
||||
assert brand.resolve({}) == brand.FACTORY
|
||||
|
||||
|
||||
def test_contrast_matches_the_known_extremes():
|
||||
assert round(brand.contrast("#ffffff", "#000000"), 1) == 21.0
|
||||
assert round(brand.contrast("#777777", "#777777"), 1) == 1.0
|
||||
|
||||
|
||||
def test_an_unreadable_pair_warns_and_a_readable_one_does_not():
|
||||
assert brand.warnings(brand.FACTORY) == []
|
||||
|
||||
notes = brand.warnings(brand.resolve({"text": "#f2f2f2"}))
|
||||
assert notes and "contraste" in notes[0]
|
||||
|
||||
|
||||
# --- the form -------------------------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def admin(make_member, sign_in):
|
||||
member_id = make_member("admina", role="admin")
|
||||
sign_in(member_id)
|
||||
return member_id
|
||||
|
||||
|
||||
# Arguments for the test client rather than fields of the form. Separated by
|
||||
# name because the form has a field per token and the two would otherwise be
|
||||
# posted together — `follow_redirects` as a form value is a quiet way for a
|
||||
# test to assert against a redirect page it never followed.
|
||||
CLIENT_ARGS = ("follow_redirects", "content_type")
|
||||
|
||||
|
||||
def save(post, **fields):
|
||||
"""Post the Marca form with every colour left blank but the ones given.
|
||||
|
||||
Blank rather than absent because that is what the real form sends: a text
|
||||
field nobody filled in arrives as an empty string, and the handler has to
|
||||
read that as "leave it at the factory value".
|
||||
"""
|
||||
sent = {name: fields.pop(name) for name in CLIENT_ARGS if name in fields}
|
||||
data = {f"token-{name}": "" for name in brand.FACTORY}
|
||||
data.update(fields)
|
||||
return post("/comunidad/gestion/marca", data, **sent)
|
||||
|
||||
|
||||
def test_only_admins_reach_it(client, post, make_member, sign_in):
|
||||
for role in ("user", "moderator"):
|
||||
sign_in(make_member(f"persona-{role}", role=role))
|
||||
assert client.get("/comunidad/gestion/marca").status_code == 403
|
||||
assert save(post, **{"token-brand": "#1b5e20"}).status_code == 403
|
||||
assert post("/comunidad/gestion/marca/restaurar").status_code == 403
|
||||
assert post("/comunidad/gestion/marca/publicar").status_code == 403
|
||||
|
||||
|
||||
def test_a_colour_is_saved_and_served(client, post, admin):
|
||||
save(post, **{"token-brand": "#1B5E20"})
|
||||
|
||||
css = client.get("/comunidad/marca.css")
|
||||
|
||||
assert css.mimetype == "text/css"
|
||||
assert "--brand: #1b5e20;" in css.get_data(as_text=True)
|
||||
# Lower-cased on the way in, so the same colour is one string in the row.
|
||||
assert "#1B5E20" not in css.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_an_untouched_colour_is_not_written_at_all(client, db, post, admin):
|
||||
"""Only differences are stored. A snapshot of all thirteen would freeze a
|
||||
token added later at whatever this version thought it should be."""
|
||||
save(post, **{"token-brand": brand.FACTORY["brand"], "token-text": "#111111"})
|
||||
|
||||
stored = json.loads(db.execute("SELECT tokens_json FROM brand").fetchone()[0])
|
||||
|
||||
assert stored == {"text": "#111111"}
|
||||
|
||||
|
||||
def test_a_bad_colour_is_refused_field_by_field(client, db, post, admin):
|
||||
for bad in ("red", "#xyz", "url(https://otro.sitio/x.png)", "#12345"):
|
||||
response = save(post, **{"token-brand": bad}, follow_redirects=True)
|
||||
assert "no es un color" in response.get_data(as_text=True), bad
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
|
||||
|
||||
|
||||
def test_the_custom_css_is_last_so_it_wins(client, post, admin):
|
||||
save(post, **{"token-brand": "#1b5e20", "custom_css": ".site-bar { height: 4rem; }"})
|
||||
|
||||
css = client.get("/comunidad/marca.css").get_data(as_text=True)
|
||||
|
||||
assert css.index(":root") < css.index(".site-bar")
|
||||
|
||||
|
||||
def test_an_html_bracket_in_the_custom_css_is_refused(client, db, post, admin):
|
||||
response = save(post, custom_css="</style><script>alert(1)</script>",
|
||||
follow_redirects=True)
|
||||
|
||||
assert "no puede contener" in response.get_data(as_text=True)
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
|
||||
|
||||
|
||||
def test_an_enormous_css_box_is_refused(client, db, post, admin):
|
||||
response = save(post, custom_css="a{}" * 20_000, follow_redirects=True)
|
||||
|
||||
assert "caracteres" in response.get_data(as_text=True)
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
|
||||
|
||||
|
||||
def test_the_screen_never_loads_the_custom_css(client, post, admin):
|
||||
"""The reason an admin can always undo a mistake: `* { display: none }` in
|
||||
the box breaks every page except this one."""
|
||||
save(post, custom_css="* { display: none }")
|
||||
|
||||
page = client.get("/comunidad/gestion/marca").get_data(as_text=True)
|
||||
other = client.get("/comunidad/gestion").get_data(as_text=True)
|
||||
|
||||
assert "marca.css" not in page
|
||||
assert "marca.css" in other
|
||||
assert "Restaurar lo de fábrica" in page
|
||||
|
||||
|
||||
# --- the two pictures -----------------------------------------------------
|
||||
|
||||
def test_a_logo_is_sniffed_not_trusted(client, db, post, admin):
|
||||
"""The same check as every other upload: the extension comes from the
|
||||
bytes. A GIF called logo.png is a GIF."""
|
||||
response = save(post, logo=(io.BytesIO(GIF), "logo.png"),
|
||||
content_type="multipart/form-data", follow_redirects=True)
|
||||
|
||||
assert "es un gif" in response.get_data(as_text=True)
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
|
||||
|
||||
|
||||
def test_a_png_logo_is_kept_and_served(app, client, db, post, admin):
|
||||
save(post, logo=(io.BytesIO(PNG), "vienalatina.png"),
|
||||
content_type="multipart/form-data")
|
||||
|
||||
name = db.execute("SELECT logo_name FROM brand").fetchone()["logo_name"]
|
||||
assert name and name.endswith(".png")
|
||||
with app.app_context():
|
||||
from apps.board import uploads
|
||||
assert uploads.directory().joinpath(name).exists()
|
||||
|
||||
# Public on purpose: it is in the <head> of the sign-in page.
|
||||
client.get("/comunidad/logout")
|
||||
assert client.get(f"/comunidad/marca/{name}").status_code == 200
|
||||
|
||||
|
||||
def test_a_picture_that_is_not_the_current_one_is_not_served(client, db, post, admin):
|
||||
save(post, logo=(io.BytesIO(PNG), "uno.png"), content_type="multipart/form-data")
|
||||
first = db.execute("SELECT logo_name FROM brand").fetchone()["logo_name"]
|
||||
|
||||
save(post, logo=(io.BytesIO(PNG), "dos.png"), content_type="multipart/form-data")
|
||||
|
||||
assert client.get(f"/comunidad/marca/{first}").status_code == 404
|
||||
|
||||
|
||||
def test_a_replaced_logo_goes_off_disk(app, client, db, post, admin):
|
||||
save(post, logo=(io.BytesIO(PNG), "uno.png"), content_type="multipart/form-data")
|
||||
first = db.execute("SELECT logo_name FROM brand").fetchone()["logo_name"]
|
||||
|
||||
save(post, logo=(io.BytesIO(PNG), "dos.png"), content_type="multipart/form-data")
|
||||
|
||||
with app.app_context():
|
||||
from apps.board import uploads
|
||||
assert not uploads.directory().joinpath(first).exists()
|
||||
|
||||
|
||||
def test_the_favicon_is_png_only(client, db, post, admin):
|
||||
"""ICO and SVG are both refused, for different reasons: the sniffer
|
||||
identifies bytes by a prefix and an SVG is XML that can carry script."""
|
||||
response = save(post, favicon=(io.BytesIO(GIF), "icono.gif"),
|
||||
content_type="multipart/form-data", follow_redirects=True)
|
||||
|
||||
assert "hace falta png" in response.get_data(as_text=True)
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
|
||||
|
||||
|
||||
def test_the_logo_and_the_favicon_reach_the_chrome(client, post, admin):
|
||||
save(post, logo=(io.BytesIO(PNG), "logo.png"),
|
||||
favicon=(io.BytesIO(PNG), "icono.png"),
|
||||
content_type="multipart/form-data")
|
||||
|
||||
body = client.get("/comunidad/").get_data(as_text=True)
|
||||
|
||||
assert "site-bar__logo" in body
|
||||
assert 'rel="icon"' in body
|
||||
assert "site-bar__brand-text" not in body
|
||||
|
||||
|
||||
# --- publishing to the public site ----------------------------------------
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def unreachable(monkeypatch):
|
||||
"""No test in this file talks to a real git server.
|
||||
|
||||
Autouse and not optional: every save tries to publish, so without this each
|
||||
one would open a socket to git.vienalatina.com and wait for it to fail. The
|
||||
tests that care about the commit ask for `repo` as well, whose patches are
|
||||
applied after these and therefore win.
|
||||
"""
|
||||
def refuse(*args, **kwargs):
|
||||
raise brand.gitea.GiteaError("No se pudo contactar con el servidor de git.")
|
||||
for name in ("list_directory", "read_file", "write_file", "delete_file"):
|
||||
monkeypatch.setattr(brand.gitea, name, refuse)
|
||||
|
||||
|
||||
def test_the_commit_carries_the_colours_and_the_pictures(db, post, admin, repo):
|
||||
save(post, **{"token-brand": "#1b5e20", "custom_css": ".x { color: red }"},
|
||||
logo=(io.BytesIO(PNG), "vienalatina.png"),
|
||||
favicon=(io.BytesIO(PNG), "icono.png"),
|
||||
content_type="multipart/form-data")
|
||||
|
||||
assert set(repo.files) == {"data/brand.yaml",
|
||||
"static/brand/logo.png",
|
||||
"static/brand/favicon.png"}
|
||||
yaml = repo.files["data/brand.yaml"].decode("utf-8")
|
||||
assert ' brand: "#1b5e20"' in yaml
|
||||
assert 'logo: "/brand/logo.png"' in yaml # the path Hugo serves it at
|
||||
assert 'favicon: "/brand/favicon.png"' in yaml
|
||||
assert "custom_css: |\n .x { color: red }" in yaml
|
||||
# Only the differences, exactly as the stylesheet does it.
|
||||
assert "surface:" not in yaml
|
||||
assert db.execute("SELECT published_at FROM brand").fetchone()["published_at"]
|
||||
|
||||
|
||||
def test_a_logo_in_another_format_does_not_leave_the_old_one_behind(post, admin, repo):
|
||||
"""`static/brand/logo.png` and `logo.webp` would otherwise both sit in the
|
||||
repository, deployed, with only one of them referenced."""
|
||||
save(post, logo=(io.BytesIO(PNG), "uno.png"), content_type="multipart/form-data")
|
||||
assert "static/brand/logo.png" in repo.files
|
||||
|
||||
webp = b"RIFF\x00\x00\x00\x00WEBP" + b"\x00" * 64
|
||||
save(post, logo=(io.BytesIO(webp), "dos.webp"), content_type="multipart/form-data")
|
||||
|
||||
assert "static/brand/logo.webp" in repo.files
|
||||
assert "static/brand/logo.png" not in repo.files
|
||||
|
||||
|
||||
def test_a_save_survives_the_git_server_being_down(client, db, post, admin):
|
||||
"""The order this is written in. SQLite first, so a change that does not
|
||||
need git is not blocked by git — and the screen says the public site is a
|
||||
step behind rather than pretending it is not."""
|
||||
response = save(post, **{"token-brand": "#1b5e20"}, follow_redirects=True)
|
||||
|
||||
row = db.execute("SELECT tokens_json, published_at FROM brand").fetchone()
|
||||
assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"}
|
||||
assert row["published_at"] is None
|
||||
assert "Pendiente de publicar" in response.get_data(as_text=True)
|
||||
assert "--brand: #1b5e20;" in client.get("/comunidad/marca.css").get_data(as_text=True)
|
||||
|
||||
|
||||
def test_the_retry_publishes_what_was_already_saved(db, post, admin, monkeypatch, repo):
|
||||
"""What the *Reintentar publicar* button is for: the colours are in SQLite
|
||||
and the commit never happened."""
|
||||
def refuse(*args, **kwargs):
|
||||
raise brand.gitea.GiteaError("caído")
|
||||
|
||||
# Only the write, and put it back by hand rather than with
|
||||
# `monkeypatch.undo()` — which would also undo the `repo` fixture's own
|
||||
# patches and leave the retry talking to the real git server.
|
||||
working = brand.gitea.write_file
|
||||
monkeypatch.setattr(brand.gitea, "write_file", refuse)
|
||||
save(post, **{"token-brand": "#1b5e20"})
|
||||
assert db.execute("SELECT published_at FROM brand").fetchone()["published_at"] is None
|
||||
|
||||
monkeypatch.setattr(brand.gitea, "write_file", working)
|
||||
post("/comunidad/gestion/marca/publicar")
|
||||
|
||||
assert ' brand: "#1b5e20"' in repo.files["data/brand.yaml"].decode("utf-8")
|
||||
assert db.execute("SELECT published_at FROM brand").fetchone()["published_at"]
|
||||
|
||||
|
||||
# --- restoring ------------------------------------------------------------
|
||||
|
||||
def test_restoring_empties_the_row_and_the_disk(app, client, db, post, admin):
|
||||
save(post, **{"token-brand": "#1b5e20"}, )
|
||||
save(post, logo=(io.BytesIO(PNG), "logo.png"), content_type="multipart/form-data")
|
||||
name = db.execute("SELECT logo_name FROM brand").fetchone()["logo_name"]
|
||||
|
||||
post("/comunidad/gestion/marca/restaurar")
|
||||
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0
|
||||
with app.app_context():
|
||||
from apps.board import uploads
|
||||
assert not uploads.directory().joinpath(name).exists()
|
||||
css = client.get("/comunidad/marca.css").get_data(as_text=True)
|
||||
assert ":root" not in css # nothing to override any more
|
||||
assert "site-bar__brand-text" in client.get("/comunidad/").get_data(as_text=True)
|
||||
|
||||
|
||||
# --- erasure --------------------------------------------------------------
|
||||
|
||||
def test_erasing_the_admin_leaves_the_brand_standing(client, db, post, owner_id,
|
||||
make_member, sign_in):
|
||||
"""The colours belong to the association, like an event in the calendar.
|
||||
An admin leaving is not a reason for the site to look like a default
|
||||
install again."""
|
||||
admin_id = make_member("admina", role="admin")
|
||||
sign_in(admin_id)
|
||||
save(post, **{"token-brand": "#1b5e20"})
|
||||
|
||||
sign_in(owner_id)
|
||||
post(f"/comunidad/miembros/{admin_id}/eliminar")
|
||||
|
||||
row = db.execute("SELECT tokens_json, updated_by FROM brand").fetchone()
|
||||
assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"}
|
||||
assert row["updated_by"] is None
|
||||
@ -9,7 +9,6 @@ import the real translate.py and run its parser over what the editor wrote.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import io
|
||||
import sys
|
||||
@ -18,6 +17,7 @@ from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from apps.board import content, gitea
|
||||
from apps.board.tests.conftest import FakeRepo # noqa: F401 (used by the `repo` fixture)
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[3]
|
||||
|
||||
@ -35,54 +35,6 @@ def _load_translate():
|
||||
translate = _load_translate()
|
||||
|
||||
|
||||
class FakeRepo:
|
||||
"""A repository in a dict, with shas that change when content does."""
|
||||
|
||||
def __init__(self):
|
||||
self.files: dict[str, bytes] = {}
|
||||
self.commits: list[str] = []
|
||||
self.authors: list[dict] = []
|
||||
self.reads = 0
|
||||
|
||||
@staticmethod
|
||||
def _sha(data: bytes) -> str:
|
||||
return hashlib.sha1(data).hexdigest()
|
||||
|
||||
def list_directory(self, path, token=None):
|
||||
out = []
|
||||
for name, data in self.files.items():
|
||||
if name.startswith(path + "/") and "/" not in name[len(path) + 1:]:
|
||||
out.append({"name": name.rsplit("/", 1)[1], "path": name,
|
||||
"type": "file", "sha": self._sha(data)})
|
||||
return out
|
||||
|
||||
def read_file(self, path, token=None):
|
||||
self.reads += 1
|
||||
if path not in self.files:
|
||||
raise gitea.GiteaError("Ese archivo ya no existe.")
|
||||
return self.files[path].decode("utf-8"), self._sha(self.files[path])
|
||||
|
||||
def write_file(self, path, data, message, token=None, sha=None, member=None):
|
||||
if sha and self.files.get(path) is not None and self._sha(self.files[path]) != sha:
|
||||
raise gitea.StaleFile("Alguien más guardó este archivo mientras lo editabas.")
|
||||
self.files[path] = data
|
||||
self.commits.append(message)
|
||||
self.authors.append(gitea._identity(member))
|
||||
return self._sha(data)
|
||||
|
||||
def delete_file(self, path, sha, message, token=None, member=None):
|
||||
self.files.pop(path, None)
|
||||
self.commits.append(message)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo(monkeypatch):
|
||||
fake = FakeRepo()
|
||||
for name in ("list_directory", "read_file", "write_file", "delete_file"):
|
||||
monkeypatch.setattr(gitea, name, getattr(fake, name))
|
||||
return fake
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def editor(db, make_member, sign_in):
|
||||
"""An admin. The editor commits through the server's own content token
|
||||
@ -599,3 +551,79 @@ def test_a_parent_that_has_been_deleted_is_kept_and_named(repo, editor, client):
|
||||
|
||||
assert 'value="borrada" selected' in body
|
||||
assert "no encontrada" in body
|
||||
|
||||
|
||||
# --- events, which are posts with a date of their own ---------------------
|
||||
|
||||
def test_an_event_carries_its_own_date_and_an_ics(repo, editor, post):
|
||||
"""The post's `date` is when it was announced; `event_date` is when it
|
||||
happens, and the two are weeks apart in the normal case."""
|
||||
import yaml
|
||||
post("/comunidad/contenido/post/nuevo",
|
||||
{"title": "Feria de otoño", "body": "Ven.", "date": "2026-10-03",
|
||||
"categories": ["Evento", "Comunidad"], "event_date": "2026-10-24",
|
||||
"event_time": "18:30", "event_location": "Plaza de Ottakring"})
|
||||
|
||||
path, = repo.files
|
||||
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
|
||||
assert front["date"].isoformat() == "2026-10-03"
|
||||
assert front["event_date"] == "2026-10-24"
|
||||
assert front["event_time"] == "18:30"
|
||||
assert front["event_location"] == "Plaza de Ottakring"
|
||||
# Hugo builds an .ics only for pages that ask for one.
|
||||
assert front["outputs"] == ["HTML", "ics"]
|
||||
|
||||
|
||||
def test_the_evento_category_without_a_date_is_refused(repo, editor, post):
|
||||
response = post("/comunidad/contenido/post/nuevo",
|
||||
{"title": "Algún día", "body": "Texto.", "date": "2026-10-03",
|
||||
"categories": ["Evento"]})
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "necesita fecha" in response.get_data(as_text=True)
|
||||
assert repo.files == {}
|
||||
|
||||
|
||||
def test_a_nonsense_hour_is_refused(repo, editor, post):
|
||||
response = post("/comunidad/contenido/post/nuevo",
|
||||
{"title": "Feria", "body": "Texto.", "date": "2026-10-03",
|
||||
"categories": ["Evento"], "event_date": "2026-10-24",
|
||||
"event_time": "25:99"})
|
||||
|
||||
assert response.status_code == 400
|
||||
assert repo.files == {}
|
||||
|
||||
|
||||
def test_an_ordinary_post_carries_no_event_lines(repo, editor, post):
|
||||
"""Rather than three empty keys for somebody to wonder about."""
|
||||
import yaml
|
||||
post("/comunidad/contenido/post/nuevo",
|
||||
{"title": "Un artículo", "body": "Texto.", "date": "2026-10-03",
|
||||
"categories": ["Cultura"], "event_date": "2026-10-24"})
|
||||
|
||||
path, = repo.files
|
||||
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
|
||||
for key in ("event_date", "event_time", "event_location", "outputs"):
|
||||
assert key not in front, key
|
||||
|
||||
|
||||
def test_an_event_keeps_its_date_when_edited(repo, editor, post, client):
|
||||
import yaml
|
||||
repo.files["content/post/2026-10-03-feria.es.md"] = (
|
||||
"---\ntitle: Feria\ndate: 2026-10-03\nlang: es\nmanual_translation: false\n"
|
||||
"event_date: '2026-10-24'\nevent_time: '18:30'\n"
|
||||
"event_location: La plaza\ncategories:\n- Evento\n---\n\nVen.\n").encode("utf-8")
|
||||
|
||||
body = client.get("/comunidad/contenido/post/editar/2026-10-03-feria.es.md").get_data(as_text=True)
|
||||
assert 'value="2026-10-24"' in body
|
||||
assert 'value="18:30"' in body
|
||||
|
||||
post("/comunidad/contenido/post/editar/2026-10-03-feria.es.md",
|
||||
{"title": "Feria", "body": "Ven pronto.", "date": "2026-10-03",
|
||||
"categories": ["Evento"], "event_date": "2026-10-24",
|
||||
"event_time": "18:30", "event_location": "La plaza",
|
||||
"sha": repo._sha(repo.files["content/post/2026-10-03-feria.es.md"])})
|
||||
|
||||
front = yaml.safe_load(
|
||||
repo.files["content/post/2026-10-03-feria.es.md"].decode().split("---")[1])
|
||||
assert front["event_date"] == "2026-10-24"
|
||||
|
||||
231
apps/board/tests/test_events.py
Normal file
231
apps/board/tests/test_events.py
Normal file
@ -0,0 +1,231 @@
|
||||
"""Two calendars that must not be confused with each other.
|
||||
|
||||
The public one is posts with the Evento category: published, translated,
|
||||
indexed, shareable. The private one is rows in this database: admins write them,
|
||||
members read them, and nothing about them reaches the public site. Most of what
|
||||
is worth testing here is that boundary, and the handful of date rules that are
|
||||
easy to get subtly wrong and hard to notice.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.board import events, gitea
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def quiet_gitea(monkeypatch):
|
||||
"""The private calendar asks the git server for the published events. These
|
||||
tests are about the private half, so it answers with nothing."""
|
||||
monkeypatch.setattr(gitea, "list_directory", lambda *a, **k: [])
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def an_event(post, owner_id, sign_in, quiet_gitea):
|
||||
def _add(title="Asamblea", starts_on="2026-10-24", **extra):
|
||||
sign_in(owner_id)
|
||||
data = {"title": title, "starts_on": starts_on}
|
||||
data.update(extra)
|
||||
post("/comunidad/calendario/nuevo", data)
|
||||
return title
|
||||
return _add
|
||||
|
||||
|
||||
# --- who writes, who reads ------------------------------------------------
|
||||
|
||||
def test_an_admin_adds_an_event_and_every_member_sees_it(
|
||||
client, an_event, make_member, sign_in):
|
||||
an_event()
|
||||
|
||||
sign_in(make_member("maria"))
|
||||
page = client.get("/comunidad/calendario?mes=2026-10").get_data(as_text=True)
|
||||
|
||||
assert "Asamblea" in page
|
||||
assert "cal__add" not in page # no + on the days
|
||||
assert "Añadir evento" not in page # and no button
|
||||
|
||||
|
||||
def test_a_member_cannot_reach_the_form_or_the_handler(client, post, make_member, sign_in):
|
||||
sign_in(make_member("maria"))
|
||||
|
||||
assert client.get("/comunidad/calendario/nuevo").status_code == 403
|
||||
assert post("/comunidad/calendario/nuevo",
|
||||
{"title": "Mío", "starts_on": "2026-10-24"}).status_code == 403
|
||||
|
||||
|
||||
def test_a_moderator_cannot_either(client, make_member, sign_in):
|
||||
"""Moderating what the public reads is not the same as putting something in
|
||||
the association's diary."""
|
||||
sign_in(make_member("luisa", role="moderator"))
|
||||
assert client.get("/comunidad/calendario/nuevo").status_code == 403
|
||||
|
||||
|
||||
def test_the_calendar_itself_is_behind_the_login(client):
|
||||
response = client.get("/comunidad/calendario")
|
||||
assert response.status_code == 302
|
||||
assert "/login" in response.headers["Location"]
|
||||
|
||||
|
||||
# --- the month -----------------------------------------------------------
|
||||
|
||||
def test_the_month_shows_its_own_events_and_not_the_neighbours(
|
||||
client, an_event, owner_id, sign_in):
|
||||
an_event("Asamblea", "2026-10-24")
|
||||
an_event("Ensayo", "2026-11-03")
|
||||
|
||||
sign_in(owner_id)
|
||||
october = client.get("/comunidad/calendario?mes=2026-10").get_data(as_text=True)
|
||||
|
||||
assert "Asamblea" in october
|
||||
assert "Ensayo" not in october
|
||||
|
||||
|
||||
def test_the_arrows_cross_the_year(client, an_event, owner_id, sign_in):
|
||||
sign_in(owner_id)
|
||||
page = client.get("/comunidad/calendario?mes=2026-12").get_data(as_text=True)
|
||||
|
||||
assert "mes=2027-01" in page
|
||||
assert "mes=2026-11" in page
|
||||
|
||||
|
||||
def test_shifting_months_wraps_properly():
|
||||
assert events.shift(2026, 12, 1) == (2027, 1)
|
||||
assert events.shift(2026, 1, -1) == (2025, 12)
|
||||
assert events.shift(2026, 6, 0) == (2026, 6)
|
||||
|
||||
|
||||
def test_a_mistyped_month_shows_today_rather_than_an_error(
|
||||
client, owner_id, sign_in, quiet_gitea):
|
||||
"""A calendar that refuses to draw because a query string was mistyped is
|
||||
worse than one that shows now."""
|
||||
sign_in(owner_id)
|
||||
today = date.today()
|
||||
|
||||
page = client.get("/comunidad/calendario?mes=pumpkin")
|
||||
|
||||
assert page.status_code == 200
|
||||
assert events.month_label(today.year, today.month) in page.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_february_in_a_leap_year_has_twenty_nine_days(client, owner_id, sign_in, quiet_gitea):
|
||||
sign_in(owner_id)
|
||||
page = client.get("/comunidad/calendario?mes=2028-02").get_data(as_text=True)
|
||||
assert ">29<" in page
|
||||
assert ">30<" not in page
|
||||
|
||||
|
||||
# --- what the git server does to this ------------------------------------
|
||||
|
||||
def test_the_private_events_survive_a_git_server_that_is_down(
|
||||
client, post, owner_id, sign_in, monkeypatch):
|
||||
"""The half that only exists here must not be taken down by the half that
|
||||
does not. A refused connection reaches this module as a GiteaError because
|
||||
gitea.py translates it — before that it was a bare OSError and this page
|
||||
would have 500ed."""
|
||||
import requests
|
||||
sign_in(owner_id)
|
||||
post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"})
|
||||
|
||||
def refuse(*args, **kwargs):
|
||||
raise requests.ConnectionError("nobody home")
|
||||
monkeypatch.setattr(gitea.requests, "request", refuse)
|
||||
|
||||
page = client.get("/comunidad/calendario?mes=2026-10")
|
||||
|
||||
assert page.status_code == 200
|
||||
body = page.get_data(as_text=True)
|
||||
assert "Asamblea" in body
|
||||
assert "faltan los eventos del sitio" in body
|
||||
|
||||
|
||||
# --- the .ics -------------------------------------------------------------
|
||||
|
||||
def test_the_ics_is_a_calendar_a_phone_understands(client, an_event, owner_id, sign_in):
|
||||
an_event("Asamblea", "2026-10-24", starts_at="19:00",
|
||||
location="Local de la asociación")
|
||||
sign_in(owner_id)
|
||||
|
||||
response = client.get("/comunidad/calendario/1.ics")
|
||||
|
||||
assert response.mimetype == "text/calendar"
|
||||
body = response.get_data(as_text=True)
|
||||
assert body.startswith("BEGIN:VCALENDAR\r\n")
|
||||
assert body.endswith("END:VCALENDAR\r\n")
|
||||
assert "DTSTART;TZID=Europe/Vienna:20261024T190000" in body
|
||||
assert "SUMMARY:Asamblea" in body
|
||||
assert "UID:evento-1@vienalatina.com" in body # stable, so re-adding updates
|
||||
|
||||
|
||||
def test_an_event_with_no_time_lasts_the_whole_day(client, an_event, owner_id, sign_in):
|
||||
"""VALUE=DATE rather than inventing midnight, which is how a calendar shows
|
||||
it as a band across the top of the day."""
|
||||
an_event("Jornada", "2026-10-24")
|
||||
sign_in(owner_id)
|
||||
|
||||
body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True)
|
||||
|
||||
assert "DTSTART;VALUE=DATE:20261024" in body
|
||||
|
||||
|
||||
def test_a_comma_in_the_place_is_escaped(client, an_event, owner_id, sign_in):
|
||||
"""An unescaped comma in LOCATION makes the rest of the line a second
|
||||
value, and the address arrives truncated."""
|
||||
an_event("Asamblea", "2026-10-24", location="Plaza de Ottakring, junto al mercado")
|
||||
sign_in(owner_id)
|
||||
|
||||
body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True)
|
||||
|
||||
assert "LOCATION:Plaza de Ottakring\\, junto al mercado" in body
|
||||
|
||||
|
||||
def test_the_ics_needs_a_session(client, an_event):
|
||||
an_event()
|
||||
# The fixture had to sign in to create it; this is about the visitor who
|
||||
# finds the URL afterwards.
|
||||
with client.session_transaction() as session:
|
||||
session.clear()
|
||||
|
||||
response = client.get("/comunidad/calendario/1.ics")
|
||||
|
||||
assert response.status_code == 302
|
||||
assert "/login" in response.headers["Location"]
|
||||
|
||||
|
||||
# --- refusals -------------------------------------------------------------
|
||||
|
||||
def test_an_event_without_a_date_is_refused(client, db, post, owner_id, sign_in, quiet_gitea):
|
||||
sign_in(owner_id)
|
||||
|
||||
response = post("/comunidad/calendario/nuevo", {"title": "Algún día"})
|
||||
|
||||
assert response.status_code == 400
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"] == 0
|
||||
|
||||
|
||||
def test_a_nonsense_time_is_refused(client, db, post, owner_id, sign_in, quiet_gitea):
|
||||
sign_in(owner_id)
|
||||
|
||||
post("/comunidad/calendario/nuevo",
|
||||
{"title": "Asamblea", "starts_on": "2026-10-24", "starts_at": "25:99"})
|
||||
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"] == 0
|
||||
|
||||
|
||||
# --- erasure --------------------------------------------------------------
|
||||
|
||||
def test_erasing_the_admin_leaves_the_event_standing(
|
||||
db, post, an_event, owner_id, make_member, sign_in, quiet_gitea):
|
||||
"""The meeting still happens after they leave: the event belongs to the
|
||||
association, so the row stays and the name goes."""
|
||||
admin = make_member("admina", role="admin")
|
||||
sign_in(admin)
|
||||
post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"})
|
||||
|
||||
sign_in(owner_id)
|
||||
post(f"/comunidad/miembros/{admin}/eliminar")
|
||||
|
||||
row = db.execute("SELECT title, created_by FROM events").fetchone()
|
||||
assert (row["title"], row["created_by"]) == ("Asamblea", None)
|
||||
@ -180,19 +180,26 @@ def test_erasing_a_member_keeps_their_threads_readable(app, db, post, owner_id,
|
||||
assert row["display_name"] == "Miembro eliminado"
|
||||
|
||||
|
||||
def test_the_member_list_renders_for_each_role(client, db, owner_id, make_member, sign_in):
|
||||
"""Every role takes a different branch through members.html — the owner
|
||||
sees transfer and erase, an admin sees suspend, a user sees neither — so
|
||||
each one is rendered here rather than trusted."""
|
||||
def test_the_member_page_renders_for_each_role(client, db, owner_id, make_member, sign_in):
|
||||
"""Every role takes a different branch through member.html — the owner sees
|
||||
transfer and erase, an admin sees suspend, a plain member sees neither — so
|
||||
each one is rendered here rather than trusted.
|
||||
|
||||
These controls used to be on the cards in the directory and are on the
|
||||
person's page now, which is what this looks at. The owner's branch needs an
|
||||
admin to transfer to, so the page opened is the admin's.
|
||||
"""
|
||||
admin_id = make_member("admina", role="admin")
|
||||
user_id = make_member("usuaria")
|
||||
|
||||
for member_id, expected in ((owner_id, "Transferir titularidad"),
|
||||
(admin_id, "Suspender"),
|
||||
(user_id, None)):
|
||||
(make_member("usuaria"), None)):
|
||||
sign_in(member_id)
|
||||
body = client.get("/comunidad/miembros").get_data(as_text=True)
|
||||
assert "usuaria" in body
|
||||
# Never your own page: nobody manages themselves, so the block is not
|
||||
# drawn there and the test would pass for the wrong reason.
|
||||
who = "usuaria" if member_id == admin_id else "admina"
|
||||
body = client.get(f"/comunidad/miembro/{who}").get_data(as_text=True)
|
||||
assert who.title() in body
|
||||
if expected:
|
||||
assert expected in body
|
||||
else:
|
||||
@ -353,15 +360,16 @@ def test_erasing_a_member_lets_the_name_be_used_again(
|
||||
"SELECT 1 FROM members WHERE gitea_login = 'salvador'").fetchone() is not None
|
||||
|
||||
|
||||
# --- the directory --------------------------------------------------------
|
||||
# --- the directory and the page -------------------------------------------
|
||||
#
|
||||
# Miembros used to be a five-column admin table whose last column held four
|
||||
# forms, wrapping on top of each other. It is a directory now: everybody sees
|
||||
# the people, admins open a per-card block for the controls. Both halves are
|
||||
# asserted, because "the table is gone" is only an improvement if the controls
|
||||
# came with it.
|
||||
# forms, wrapping on top of each other; then it was cards, each carrying a bio,
|
||||
# some links and a fold-out admin block. It is faces and names now, and
|
||||
# everything about one person — their profile, the conversation with them, and
|
||||
# the controls — is on their own page. Both halves are asserted, because "the
|
||||
# cards are simpler" is only an improvement if nothing was lost on the way.
|
||||
|
||||
def test_everybody_sees_the_people(client, db, make_member, sign_in):
|
||||
def test_the_directory_is_faces_and_names(client, db, make_member, sign_in):
|
||||
maria = make_member("maria")
|
||||
db.execute("UPDATE members SET bio = ? WHERE id = ?",
|
||||
("Vivo en Ottakring.\nSegunda línea.", maria))
|
||||
@ -370,33 +378,57 @@ def test_everybody_sees_the_people(client, db, make_member, sign_in):
|
||||
body = client.get("/comunidad/miembros").get_data(as_text=True)
|
||||
|
||||
assert "Maria" in body and "maria" in body
|
||||
assert "/comunidad/miembro/maria" in body # the card is the way in
|
||||
# The bio is on their page. A grid whose job is to let you find one person
|
||||
# should not be four lines of reading each.
|
||||
assert "Vivo en Ottakring." not in body
|
||||
|
||||
|
||||
def test_their_page_is_who_they_are_and_where_you_write(client, db, make_member, sign_in):
|
||||
maria = make_member("maria")
|
||||
db.execute("UPDATE members SET bio = ?, links = ? WHERE id = ?",
|
||||
("Vivo en Ottakring.", '[{"label": "Mi web", "url": "https://ejemplo.at"}]',
|
||||
maria))
|
||||
sign_in(make_member("otra"))
|
||||
|
||||
body = client.get("/comunidad/miembro/maria").get_data(as_text=True)
|
||||
|
||||
assert "Vivo en Ottakring." in body
|
||||
assert "Segunda línea." not in body # the first line only, as a summary
|
||||
assert f'/comunidad/privados/con/{maria}' in body # somewhere to write from
|
||||
assert 'href="https://ejemplo.at"' in body and 'rel="nofollow noopener"' in body
|
||||
assert f'action="/comunidad/privados/con/{maria}"' in body # the write box
|
||||
assert "No ha publicado una página pública." in body
|
||||
|
||||
|
||||
def test_a_plain_member_sees_no_controls_and_no_addresses(client, make_member, sign_in):
|
||||
make_member("maria")
|
||||
sign_in(make_member("otra"))
|
||||
|
||||
body = client.get("/comunidad/miembros").get_data(as_text=True)
|
||||
|
||||
for url in ("/comunidad/miembros", "/comunidad/miembro/maria"):
|
||||
body = client.get(url).get_data(as_text=True)
|
||||
for control in ("Gestionar", "Suspender", "Cambiar rol", "Eliminar",
|
||||
"Enviar invitación", "maria@example.com"):
|
||||
assert control not in body, control
|
||||
assert control not in body, f"{control} in {url}"
|
||||
|
||||
|
||||
def test_an_admin_keeps_every_control(client, make_member, sign_in):
|
||||
make_member("maria")
|
||||
sign_in(make_member("admina", role="admin"))
|
||||
|
||||
body = client.get("/comunidad/miembros").get_data(as_text=True)
|
||||
body = client.get("/comunidad/miembro/maria").get_data(as_text=True)
|
||||
|
||||
for control in ("Gestionar", "Suspender", "Cambiar rol", "Enviar invitación",
|
||||
"maria@example.com"):
|
||||
assert control in body, control
|
||||
assert "Eliminar" not in body # erasure is the owner's alone
|
||||
|
||||
# And none of it leaks back onto the directory, which is where it was.
|
||||
# Asserted on the forms rather than the words: the grid's footnote says in
|
||||
# so many words that the controls are under «Gestionar» on each page, which
|
||||
# is the sentence that sends an admin to the right place.
|
||||
grid = client.get("/comunidad/miembros").get_data(as_text=True)
|
||||
assert "/estado" not in grid and "/rol" not in grid
|
||||
assert "maria@example.com" not in grid
|
||||
|
||||
|
||||
def test_a_photo_shows_inside_even_when_the_page_is_not_published(
|
||||
app, client, db, make_member, sign_in):
|
||||
@ -430,3 +462,18 @@ def test_the_members_area_photo_needs_a_session(app, client, db, make_member):
|
||||
|
||||
assert response.status_code == 302
|
||||
assert "/login" in response.headers["Location"]
|
||||
|
||||
|
||||
def test_a_moderator_gets_no_controls_either(client, make_member, sign_in):
|
||||
"""A moderator curates content, not people. The block is hidden from them
|
||||
and the routes refuse them, which is the half that matters."""
|
||||
maria = make_member("maria")
|
||||
sign_in(make_member("luisa", role="moderator"))
|
||||
|
||||
body = client.get("/comunidad/miembro/maria").get_data(as_text=True)
|
||||
assert "Gestionar" not in body
|
||||
|
||||
assert client.get("/comunidad/miembros/nuevo").status_code == 403
|
||||
assert client.post(f"/comunidad/miembros/{maria}/estado",
|
||||
data={"csrf_token": "token-for-tests", "active": "0"}
|
||||
).status_code == 403
|
||||
|
||||
@ -1,12 +1,17 @@
|
||||
"""Private messages, unread marks and blocking.
|
||||
|
||||
A conversation is addressed by the person, not by an id: `/privados/con/<id>`
|
||||
is "what I have said to them and they to me", and it exists as a page before it
|
||||
exists as a row. That makes the access rule structural rather than checked — a
|
||||
lookup is always scoped to the member doing the looking, so there is no query
|
||||
that could return somebody else's correspondence. The tests below still come at
|
||||
it from the outside, because the failure mode here is not an error, it is
|
||||
somebody quietly reading what is not theirs.
|
||||
A conversation is addressed by the person and read on their page:
|
||||
`/comunidad/miembro/<usuario>` is "who they are, and what I have said to them
|
||||
and they to me", and it exists as a page before it exists as a row. That makes
|
||||
the access rule structural rather than checked — a lookup is always scoped to
|
||||
the member doing the looking, so there is no query that could return somebody
|
||||
else's correspondence. The tests below still come at it from the outside,
|
||||
because the failure mode here is not an error, it is somebody quietly reading
|
||||
what is not theirs.
|
||||
|
||||
Sending is a POST of its own (`/privados/con/<id>`), which is why the two
|
||||
helpers below are separate: `page` is where a conversation is read, `send` is
|
||||
the only thing that writes to one.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@ -17,7 +22,13 @@ from pathlib import Path
|
||||
PNG = b"\x89PNG\r\n\x1a\n" + b"\x00" * 64
|
||||
|
||||
|
||||
def talk(member_id: int) -> str:
|
||||
def page(login: str) -> str:
|
||||
"""Where the conversation with somebody is read: their page."""
|
||||
return f"/comunidad/miembro/{login}"
|
||||
|
||||
|
||||
def send(member_id: int) -> str:
|
||||
"""Where a message is posted. By id, as the form on that page does."""
|
||||
return f"/comunidad/privados/con/{member_id}"
|
||||
|
||||
|
||||
@ -27,49 +38,50 @@ def test_a_third_person_sees_their_own_empty_conversation(
|
||||
client, post, make_member, sign_in):
|
||||
"""The old design gave conversations their own ids, so this test had to
|
||||
check that a stranger opening one got a 404. Addressing by person removes
|
||||
the question: `/privados/con/<jose>` means *my* conversation with José, so
|
||||
a third person opening the same URL sees an empty page, not this one."""
|
||||
the question: José's page shows *my* conversation with José, so a third
|
||||
person opening the same URL sees his page with an empty conversation on it,
|
||||
not this one."""
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
post(talk(jose), {"body": "Algo privado"})
|
||||
post(send(jose), {"body": "Algo privado"})
|
||||
|
||||
sign_in(make_member("curiosa"))
|
||||
page = client.get(talk(jose))
|
||||
response = client.get(page("jose"))
|
||||
|
||||
assert page.status_code == 200
|
||||
assert "Algo privado" not in page.get_data(as_text=True)
|
||||
assert response.status_code == 200
|
||||
assert "Algo privado" not in response.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_writing_to_somebody_does_not_join_you_to_their_other_conversations(
|
||||
client, db, post, make_member, sign_in):
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
post(talk(jose), {"body": "Para José"})
|
||||
post(send(jose), {"body": "Para José"})
|
||||
|
||||
curiosa = make_member("curiosa")
|
||||
sign_in(curiosa)
|
||||
post(talk(jose), {"body": "Para José también"})
|
||||
post(send(jose), {"body": "Para José también"})
|
||||
|
||||
# Two separate conversations, and neither shows the other's messages.
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM conversations").fetchone()["n"] == 2
|
||||
assert "Para José" not in client.get(talk(jose)).get_data(as_text=True).replace(
|
||||
assert "Para José" not in client.get(page("jose")).get_data(as_text=True).replace(
|
||||
"Para José también", "")
|
||||
|
||||
|
||||
def test_the_two_parties_see_it(client, post, make_member, sign_in):
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
post(talk(jose), {"body": "Hola José"})
|
||||
post(send(jose), {"body": "Hola José"})
|
||||
|
||||
sign_in(jose)
|
||||
assert "Hola José" in client.get(talk(maria)).get_data(as_text=True)
|
||||
assert "Hola José" in client.get(page("maria")).get_data(as_text=True)
|
||||
|
||||
|
||||
def test_writing_twice_reuses_the_one_conversation(client, db, post, make_member, sign_in):
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
post(talk(jose), {"body": "Una"})
|
||||
post(talk(jose), {"body": "Dos"})
|
||||
post(send(jose), {"body": "Una"})
|
||||
post(send(jose), {"body": "Dos"})
|
||||
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM conversations").fetchone()["n"] == 1
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM messages").fetchone()["n"] == 2
|
||||
@ -84,63 +96,108 @@ def test_the_box_is_there_before_anything_has_been_said(
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
|
||||
page = client.get(talk(jose))
|
||||
response = client.get(page("jose"))
|
||||
|
||||
assert page.status_code == 200
|
||||
body = page.get_data(as_text=True)
|
||||
assert response.status_code == 200
|
||||
body = response.get_data(as_text=True)
|
||||
assert 'name="body"' in body # the textarea, on first arrival
|
||||
assert "Todavía no os habéis escrito" in body
|
||||
|
||||
|
||||
def test_merely_looking_creates_nothing(client, db, make_member, sign_in):
|
||||
"""Otherwise the inbox fills with "Sin mensajes todavía" for every name
|
||||
somebody was curious about."""
|
||||
"""Looking at somebody's page is not writing to them, and a directory of
|
||||
faces means a page gets opened out of curiosity all the time."""
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
|
||||
client.get(talk(jose))
|
||||
client.get(page("jose"))
|
||||
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM conversations").fetchone()["n"] == 0
|
||||
|
||||
|
||||
def test_the_picker_sends_you_straight_there(client, make_member, sign_in):
|
||||
# --- the addresses that moved ---------------------------------------------
|
||||
|
||||
def test_the_old_section_still_leads_somewhere(client, make_member, sign_in):
|
||||
"""*Privados* was a section for months. A bookmark to it lands on the
|
||||
directory rather than on a 404."""
|
||||
sign_in(make_member("maria"))
|
||||
|
||||
response = client.get("/comunidad/privados")
|
||||
|
||||
assert response.status_code == 302
|
||||
assert response.headers["Location"].endswith("/comunidad/miembros")
|
||||
|
||||
|
||||
def test_an_old_conversation_link_lands_on_the_person(client, make_member, sign_in):
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
|
||||
response = client.get(f"/comunidad/privados/con?member_id={jose}")
|
||||
response = client.get(f"/comunidad/privados/con/{jose}")
|
||||
|
||||
assert response.status_code == 302
|
||||
assert response.headers["Location"].endswith(f"/privados/con/{jose}")
|
||||
assert response.headers["Location"].endswith("/comunidad/miembro/jose")
|
||||
|
||||
|
||||
def test_you_cannot_write_to_yourself(client, make_member, sign_in):
|
||||
def test_your_own_page_has_no_conversation_on_it(client, make_member, sign_in):
|
||||
"""It is a real page — it is how you see what the others see — but there is
|
||||
nothing to say to yourself and nothing to mark read."""
|
||||
maria = make_member("maria")
|
||||
sign_in(maria)
|
||||
assert client.get(talk(maria)).status_code == 400
|
||||
|
||||
body = client.get(page("maria")).get_data(as_text=True)
|
||||
|
||||
assert 'name="body"' not in body
|
||||
assert "Esta es tu ficha" in body
|
||||
|
||||
|
||||
def test_you_cannot_write_to_somebody_who_is_not_a_member(client, make_member, sign_in):
|
||||
def test_you_cannot_write_to_yourself(client, post, make_member, sign_in):
|
||||
maria = make_member("maria")
|
||||
sign_in(maria)
|
||||
assert post(send(maria), {"body": "Hola yo"}).status_code == 400
|
||||
|
||||
|
||||
def test_you_cannot_write_to_somebody_who_is_not_a_member(
|
||||
client, post, make_member, sign_in):
|
||||
sign_in(make_member("maria"))
|
||||
assert client.get(talk(9999)).status_code == 404
|
||||
assert post(send(9999), {"body": "Hola"}).status_code == 404
|
||||
assert client.get(page("nadie")).status_code == 404
|
||||
|
||||
|
||||
# --- unread ---------------------------------------------------------------
|
||||
|
||||
def test_unread_is_per_member_and_clears_on_reading(client, post, make_member, sign_in):
|
||||
"""The badge is on *Miembros* now, and on the card of whoever wrote. Both
|
||||
come from the same two numbers, so this is also the test that the directory
|
||||
counts per person rather than in total."""
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
post(talk(jose), {"body": "¿Vienes?"})
|
||||
post(send(jose), {"body": "¿Vienes?"})
|
||||
|
||||
badge = '<span class="tag">1</span>'
|
||||
|
||||
# The sender has nothing unread — their own message does not count.
|
||||
assert badge not in client.get("/comunidad/privados").get_data(as_text=True)
|
||||
assert badge not in client.get("/comunidad/miembros").get_data(as_text=True)
|
||||
|
||||
sign_in(jose)
|
||||
assert badge in client.get("/comunidad/privados").get_data(as_text=True)
|
||||
assert badge in client.get("/comunidad/miembros").get_data(as_text=True)
|
||||
|
||||
client.get(talk(maria)) # opening marks it read
|
||||
assert badge not in client.get("/comunidad/privados").get_data(as_text=True)
|
||||
client.get(page("maria")) # opening marks it read
|
||||
assert badge not in client.get("/comunidad/miembros").get_data(as_text=True)
|
||||
|
||||
|
||||
def test_the_person_who_wrote_is_at_the_top(client, post, make_member, sign_in):
|
||||
"""Without this the directory is alphabetical and the person waiting for an
|
||||
answer is wherever the alphabet put them — which is the one thing the old
|
||||
inbox did that a grid of faces does not."""
|
||||
make_member("ana") # sorts first by name, nothing unread
|
||||
maria, zoe = make_member("maria"), make_member("zoe")
|
||||
sign_in(zoe)
|
||||
post(send(maria), {"body": "¿Vienes?"})
|
||||
|
||||
sign_in(maria)
|
||||
body = client.get("/comunidad/miembros").get_data(as_text=True)
|
||||
|
||||
assert body.index("/comunidad/miembro/zoe") < body.index("/comunidad/miembro/ana")
|
||||
|
||||
|
||||
# --- blocking -------------------------------------------------------------
|
||||
@ -151,12 +208,12 @@ def test_a_block_stops_both_directions(client, post, make_member, sign_in):
|
||||
safety feature."""
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
post(talk(jose), {"body": "Hola"})
|
||||
post(send(jose), {"body": "Hola"})
|
||||
post(f"/comunidad/privados/bloquear/{jose}") # maria blocks jose
|
||||
|
||||
assert post(talk(jose), {"body": "Otra cosa"}).status_code == 403 # …and maria too
|
||||
assert post(send(jose), {"body": "Otra cosa"}).status_code == 403 # …and maria too
|
||||
sign_in(jose)
|
||||
assert post(talk(maria), {"body": "¿Hola?"}).status_code == 403
|
||||
assert post(send(maria), {"body": "¿Hola?"}).status_code == 403
|
||||
|
||||
|
||||
def test_a_block_is_enforced_in_the_handler_not_the_template(
|
||||
@ -168,17 +225,17 @@ def test_a_block_is_enforced_in_the_handler_not_the_template(
|
||||
post(f"/comunidad/privados/bloquear/{maria}")
|
||||
|
||||
sign_in(maria) # never reloaded the page, still has the form
|
||||
assert post(talk(jose), {"body": "Hola"}).status_code == 403
|
||||
assert post(send(jose), {"body": "Hola"}).status_code == 403
|
||||
|
||||
|
||||
def test_a_blocked_person_still_sees_the_history_but_no_box(
|
||||
client, post, make_member, sign_in):
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
post(talk(jose), {"body": "Antes del bloqueo"})
|
||||
post(send(jose), {"body": "Antes del bloqueo"})
|
||||
post(f"/comunidad/privados/bloquear/{jose}")
|
||||
|
||||
body = client.get(talk(jose)).get_data(as_text=True)
|
||||
body = client.get(page("jose")).get_data(as_text=True)
|
||||
assert "Antes del bloqueo" in body
|
||||
assert 'name="body"' not in body
|
||||
assert "bloqueo entre vosotros" in body
|
||||
@ -197,12 +254,18 @@ def test_unblocking_only_removes_your_own(client, db, post, make_member, sign_in
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM blocks").fetchone()["n"] == 1
|
||||
|
||||
|
||||
def test_a_blocked_person_is_not_offered_in_the_list(client, post, make_member, sign_in):
|
||||
def test_a_blocked_person_is_still_in_the_directory(client, post, make_member, sign_in):
|
||||
"""A deliberate change. The old inbox had a picker of people you could
|
||||
write to, and a blocked person was left out of it. The directory is not a
|
||||
picker — it is the list of who is in the association, and somebody you have
|
||||
blocked has not left. The block is stated on their page, where the write
|
||||
box would have been."""
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
post(f"/comunidad/privados/bloquear/{jose}")
|
||||
|
||||
assert "Jose" not in client.get("/comunidad/privados").get_data(as_text=True)
|
||||
assert "Jose" in client.get("/comunidad/miembros").get_data(as_text=True)
|
||||
assert "bloqueo entre vosotros" in client.get(page("jose")).get_data(as_text=True)
|
||||
|
||||
|
||||
# --- pictures -------------------------------------------------------------
|
||||
@ -213,7 +276,7 @@ def test_a_picture_in_a_message_is_private_to_the_two_of_them(
|
||||
signed in is nowhere near enough of a check."""
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
post(talk(jose), {"body": "Mira", "pictures": (io.BytesIO(PNG), "foto.png")},
|
||||
post(send(jose), {"body": "Mira", "pictures": (io.BytesIO(PNG), "foto.png")},
|
||||
content_type="multipart/form-data")
|
||||
|
||||
name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"]
|
||||
@ -229,7 +292,7 @@ def test_a_picture_in_a_message_is_private_to_the_two_of_them(
|
||||
def test_an_empty_message_with_no_picture_is_refused(client, db, post, make_member, sign_in):
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
post(talk(jose), {"body": " "})
|
||||
post(send(jose), {"body": " "})
|
||||
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM messages").fetchone()["n"] == 0
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM conversations").fetchone()["n"] == 0
|
||||
@ -244,7 +307,7 @@ def test_erasing_a_member_takes_their_private_messages(
|
||||
somebody's erased correspondence is what erasure exists to prevent."""
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
post(talk(jose), {"body": "Privado", "pictures": (io.BytesIO(PNG), "f.png")},
|
||||
post(send(jose), {"body": "Privado", "pictures": (io.BytesIO(PNG), "f.png")},
|
||||
content_type="multipart/form-data")
|
||||
name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"]
|
||||
|
||||
@ -268,3 +331,29 @@ def test_erasing_a_member_removes_blocks_either_way(
|
||||
post(f"/comunidad/miembros/{maria}/eliminar")
|
||||
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM blocks").fetchone()["n"] == 0
|
||||
|
||||
|
||||
# --- where sending lands --------------------------------------------------
|
||||
|
||||
def test_sending_lands_back_on_their_page(client, post, make_member, sign_in):
|
||||
"""The form posts by id and the page is addressed by login, so the redirect
|
||||
is the one place the two have to agree."""
|
||||
maria, jose = make_member("maria"), make_member("jose")
|
||||
sign_in(maria)
|
||||
|
||||
response = post(send(jose), {"body": "Hola"})
|
||||
|
||||
assert response.status_code == 302
|
||||
assert response.headers["Location"].endswith("/comunidad/miembro/jose#final")
|
||||
|
||||
|
||||
def test_a_suspended_member_has_a_page_but_no_box(client, post, make_member, sign_in):
|
||||
"""They are in the directory, so their page has to exist; the handler
|
||||
refuses a message to them, so the box is not drawn and the page says why."""
|
||||
make_member("jose", active=0)
|
||||
sign_in(make_member("maria"))
|
||||
|
||||
body = client.get(page("jose")).get_data(as_text=True)
|
||||
|
||||
assert "suspendido" in body
|
||||
assert 'name="body"' not in body
|
||||
|
||||
@ -302,6 +302,11 @@ def test_the_app_starts_against_a_database_from_before_all_this(tmp_path):
|
||||
assert (kept["stored_name"], kept["thread_id"], kept["bytes"]) == (
|
||||
"foto-abc123abc123.jpg", 1, 2048)
|
||||
|
||||
# Step 5: somewhere to keep an event's own date, in both tables.
|
||||
for table in ("submissions", "content_cache"):
|
||||
columns = {row[1] for row in db.execute(f"PRAGMA table_info({table})")}
|
||||
assert {"event_date", "event_time", "event_location"} <= columns, table
|
||||
|
||||
# Step 4: the role list is wider, the one-owner rule survived the rebuild,
|
||||
# and nothing that pointed at a member row lost its target.
|
||||
db.execute("INSERT INTO members (gitea_login, display_name, role) "
|
||||
|
||||
@ -1,7 +1,7 @@
|
||||
"""What each role can see and reach.
|
||||
|
||||
This file exists because of a bug that no other test in this suite could have
|
||||
caught: *Privados*, *Mi perfil* and *Contenido* were all inside one
|
||||
caught: private messages, *Mi perfil* and *Contenido* were all inside one
|
||||
`{% if g.member.role in ('owner', 'admin') %}` block in base.html, so an
|
||||
ordinary member signed in to a wall and a member list and nothing else. Every
|
||||
feature worked. Every test passed. Most of the members area was simply invisible
|
||||
@ -21,8 +21,9 @@ import pytest
|
||||
SECTIONS = {
|
||||
"Inicio": "/comunidad/",
|
||||
"Muro": "/comunidad/muro",
|
||||
"Privados": "/comunidad/privados",
|
||||
"Miembros": "/comunidad/miembros",
|
||||
"Publicaciones": "/comunidad/publicaciones",
|
||||
"Calendario": "/comunidad/calendario",
|
||||
}
|
||||
ADMIN_ONLY = {"Gestión": "/comunidad/gestion"}
|
||||
|
||||
@ -38,7 +39,7 @@ def nav(client, sign_in):
|
||||
|
||||
|
||||
@pytest.mark.parametrize("role", ["user", "moderator"])
|
||||
def test_a_member_sees_the_four_shared_sections(role, nav, make_member):
|
||||
def test_a_member_sees_the_five_shared_sections(role, nav, make_member):
|
||||
"""The regression. Not one of these may depend on a role again."""
|
||||
body = nav(make_member("maria", role=role))
|
||||
for label in SECTIONS:
|
||||
@ -175,7 +176,7 @@ def test_a_member_gets_their_name_and_their_sections(client, make_member, sign_i
|
||||
assert state["signed_in"] is True
|
||||
assert state["name"] == "Maria"
|
||||
assert [s["label"] for s in state["sections"]] == [
|
||||
"Inicio", "Muro", "Privados", "Publicaciones"]
|
||||
"Inicio", "Muro", "Miembros", "Publicaciones", "Calendario"]
|
||||
assert state["csrf"] # the bar renders a real logout form
|
||||
|
||||
|
||||
|
||||
@ -219,30 +219,67 @@ def test_the_form_says_what_publishing_means(client, make_member, sign_in):
|
||||
|
||||
# --- names as doors -------------------------------------------------------
|
||||
#
|
||||
# A profile nobody can reach from inside the members area is a profile nobody
|
||||
# visits. Every screen renders names through the one macro in
|
||||
# templates/_person.html, which links only when there is a page to link to —
|
||||
# the rule is in one place because both failures are silent: never linking
|
||||
# hides the profiles, always linking sends people to a 404.
|
||||
# Every screen renders names through the one macro in templates/_person.html,
|
||||
# and it used to link to somebody's *public* page, only when they had published
|
||||
# one — so most names on the wall were plain text and there was no way to get
|
||||
# from a post to writing to its author. It links inside now, to
|
||||
# /comunidad/miembro/<usuario>, which exists for every member; their public page
|
||||
# is linked from there when they have one.
|
||||
#
|
||||
# The rule is in one place because both failures are silent: never linking
|
||||
# hides the people, always linking sends somebody to a 404.
|
||||
|
||||
def test_a_name_on_the_wall_links_to_a_published_page(client, post, published, sign_in):
|
||||
def test_a_name_on_the_wall_links_to_their_page_inside(client, post, published, sign_in):
|
||||
author = published("maria")
|
||||
sign_in(author)
|
||||
post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"})
|
||||
|
||||
for url in ("/comunidad/muro", "/comunidad/tema/1", "/comunidad/"):
|
||||
assert 'href="/maria"' in client.get(url).get_data(as_text=True), url
|
||||
assert ('href="/comunidad/miembro/maria"'
|
||||
in client.get(url).get_data(as_text=True)), url
|
||||
|
||||
|
||||
def test_a_name_without_a_page_is_not_a_link(client, post, published, sign_in):
|
||||
def test_a_name_links_even_without_a_public_page(client, post, published, sign_in):
|
||||
"""The change this phase makes. Somebody who has published nothing is still
|
||||
somebody you can reach — and their page says in as many words that there is
|
||||
no public one."""
|
||||
author = published("maria", profile_published=0)
|
||||
sign_in(author)
|
||||
post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"})
|
||||
|
||||
for url in ("/comunidad/muro", "/comunidad/tema/1"):
|
||||
body = client.get(url).get_data(as_text=True)
|
||||
assert 'href="/maria"' not in body, url
|
||||
assert "Maria" in body, url # the name is still there
|
||||
assert 'href="/comunidad/miembro/maria"' in body, url
|
||||
assert 'href="/maria"' not in body, url # their public page is not there
|
||||
|
||||
page = client.get("/comunidad/miembro/maria").get_data(as_text=True)
|
||||
assert 'href="/maria"' not in page
|
||||
|
||||
|
||||
def test_their_page_links_out_to_the_public_one_when_there_is_one(
|
||||
client, published, make_member, sign_in):
|
||||
published("maria")
|
||||
sign_in(make_member("jose"))
|
||||
|
||||
assert 'href="/maria"' in client.get("/comunidad/miembro/maria").get_data(as_text=True)
|
||||
|
||||
|
||||
def test_an_erased_members_name_is_not_a_link(client, post, owner_id,
|
||||
make_member, sign_in):
|
||||
"""The one name with no page behind it. An erased member's writing is
|
||||
reassigned to the tombstone, which is not a person and has nothing to
|
||||
show — and `members.show` 404s for it, so a link there would be a dead
|
||||
end on the wall."""
|
||||
maria = make_member("maria")
|
||||
sign_in(maria)
|
||||
post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"})
|
||||
|
||||
sign_in(owner_id)
|
||||
post(f"/comunidad/miembros/{maria}/eliminar")
|
||||
|
||||
body = client.get("/comunidad/muro").get_data(as_text=True)
|
||||
assert "Miembro eliminado" in body
|
||||
assert "/comunidad/miembro/__removed__" not in body
|
||||
|
||||
|
||||
def test_a_comment_and_a_private_message_link_too(client, post, published,
|
||||
@ -256,6 +293,6 @@ def test_a_comment_and_a_private_message_link_too(client, post, published,
|
||||
post("/comunidad/privados/con/%d" % jose, {"body": "Hola José"})
|
||||
|
||||
sign_in(jose)
|
||||
assert 'href="/maria"' in client.get("/comunidad/tema/1").get_data(as_text=True)
|
||||
assert 'href="/maria"' in client.get(
|
||||
f"/comunidad/privados/con/{maria}").get_data(as_text=True)
|
||||
link = 'href="/comunidad/miembro/maria"'
|
||||
assert link in client.get("/comunidad/tema/1").get_data(as_text=True)
|
||||
assert link in client.get("/comunidad/miembro/maria").get_data(as_text=True)
|
||||
|
||||
@ -469,3 +469,33 @@ def test_an_approved_post_is_signed_by_the_member_not_the_moderator(
|
||||
assert front["author"] == "Maria"
|
||||
assert front["author_url"] == "/maria"
|
||||
assert repo.authors == [{"name": "Maria", "email": "maria@example.com"}]
|
||||
|
||||
|
||||
def test_a_member_can_propose_an_event_and_it_keeps_its_date(
|
||||
repo, db, post, maria, luisa, sign_in):
|
||||
"""Same form, same queue, same approval — and the event that reaches the
|
||||
site is the one the member described, dated when it happens."""
|
||||
import yaml
|
||||
sign_in(maria)
|
||||
propose(post, categories=["Evento"], event_date="2026-11-07",
|
||||
event_time="20:00", event_location="Sala Ottakring")
|
||||
submission_id = only_submission(db)["id"]
|
||||
|
||||
sign_in(luisa)
|
||||
post(f"/comunidad/publicaciones/{submission_id}/aprobar")
|
||||
|
||||
path, = repo.files
|
||||
front = yaml.safe_load(repo.files[path].decode().split("---")[1])
|
||||
assert front["event_date"] == "2026-11-07"
|
||||
assert front["event_time"] == "20:00"
|
||||
assert front["event_location"] == "Sala Ottakring"
|
||||
assert front["author"] == "Maria"
|
||||
|
||||
|
||||
def test_an_event_proposal_without_a_date_is_refused(db, post, maria, sign_in):
|
||||
sign_in(maria)
|
||||
|
||||
response = propose(post, categories=["Evento"])
|
||||
|
||||
assert response.status_code == 400
|
||||
assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0
|
||||
|
||||
@ -148,7 +148,7 @@ PROSE_BOXES = {
|
||||
"thread_form.html": "body",
|
||||
"comment_form.html": "body",
|
||||
"thread.html": "body",
|
||||
"conversation.html": "body",
|
||||
"member.html": "body",
|
||||
"submission_form.html": "body",
|
||||
"content_form.html": "body",
|
||||
"profile_edit.html": "bio",
|
||||
@ -174,3 +174,36 @@ def test_the_fields_that_are_not_prose_stay_plain():
|
||||
html = (Path(__file__).resolve().parents[1] / "templates" / name).read_text(encoding="utf-8")
|
||||
opening = re.search(rf'<textarea id="{box}"[^>]*>', html)
|
||||
assert opening and "data-markdown" not in opening.group(0), name
|
||||
|
||||
|
||||
# --- the form controls are named by what they are not ---------------------
|
||||
|
||||
UNSTYLED_ON_PURPOSE = {"checkbox", "radio", "file", "submit",
|
||||
"button", "reset", "image", "hidden"}
|
||||
|
||||
|
||||
def test_the_form_rule_is_an_exclusion_and_not_a_list_of_accepted_types():
|
||||
"""It used to be `input[type=text], input[type=email], input[type=date],
|
||||
input:not([type])` — an allowlist, which is wrong the moment anybody adds a
|
||||
field. It was: the password box on the sign-in page was a browser default
|
||||
sitting under a full-width username box, and the number box for a page's
|
||||
order was the same. Nothing errors; the form just looks unfinished, which
|
||||
only a person looking at it can catch.
|
||||
|
||||
So the guard is on the shape of the rule rather than on any one type: it has
|
||||
to exclude the controls that are not text boxes and style everything else.
|
||||
"""
|
||||
css = (Path(__file__).resolve().parents[1] / "static" / "board.css").read_text(encoding="utf-8")
|
||||
selector = [line for line in css.splitlines() if line.startswith("input:not(")]
|
||||
assert selector, (
|
||||
"board.css has no `input:not(...)` form rule. If it is back to listing "
|
||||
"accepted types, the next field somebody adds will be unstyled."
|
||||
)
|
||||
excluded = set(re.findall(r'\[type="([a-z]+)"\]', selector[0]))
|
||||
assert excluded == UNSTYLED_ON_PURPOSE, (
|
||||
f"the stylesheet excludes {sorted(excluded)}; expected "
|
||||
f"{sorted(UNSTYLED_ON_PURPOSE)}. Anything a person types in belongs in "
|
||||
"the rule, not outside it."
|
||||
)
|
||||
for typed_in in ("password", "number", "email", "date", "text", "search", "url"):
|
||||
assert typed_in not in excluded, f"{typed_in} is a box somebody types in"
|
||||
|
||||
19
config.yaml
19
config.yaml
@ -79,10 +79,13 @@ languages:
|
||||
|
||||
params:
|
||||
# The picture a share card falls back on when a post or page has none, and the
|
||||
# organisation's logo in the structured data. One path — /uploads/algo.png —
|
||||
# and WhatsApp, Signal, Mastodon and Bluesky all start showing an image. Left
|
||||
# empty until there is a logo to put here; a link then shares as title and
|
||||
# description, which is what happens today.
|
||||
# organisation's logo in the structured data.
|
||||
#
|
||||
# **The logo uploaded in Gestión → Marca is used first**, so this is now only
|
||||
# for a site that wants a different share picture from its logo — a photo of
|
||||
# the city, say. One path (/uploads/algo.png) and WhatsApp, Signal, Mastodon
|
||||
# and Bluesky all start showing an image. Empty, with no logo either, means a
|
||||
# link shares as title and description.
|
||||
defaultImage: ""
|
||||
|
||||
# The organisation's profiles elsewhere, for `sameAs` in the Organization
|
||||
@ -103,6 +106,14 @@ outputFormats:
|
||||
mediaType: "text/plain"
|
||||
baseName: "llms"
|
||||
isPlainText: true
|
||||
# One .ics beside an event's page, so "añadir a mi calendario" is a link and
|
||||
# not an instruction. Only pages whose frontmatter lists this output generate
|
||||
# one, and the editor writes that line for a post in the Evento category —
|
||||
# see apps/board/content.py.
|
||||
ics:
|
||||
mediaType: "text/calendar"
|
||||
baseName: "index"
|
||||
isPlainText: true
|
||||
|
||||
outputs:
|
||||
home: ["HTML", "RSS", "llms"]
|
||||
|
||||
11
content/page/agenda.es.md
Normal file
11
content/page/agenda.es.md
Normal file
@ -0,0 +1,11 @@
|
||||
---
|
||||
title: Agenda
|
||||
lang: es
|
||||
layout: agenda
|
||||
weight: 4
|
||||
manual_translation: false
|
||||
description: Todo lo que organiza la comunidad latinoamericana en Viena, mes a mes.
|
||||
---
|
||||
|
||||
Lo que viene: ferias, charlas, conciertos y encuentros. Cada evento se puede
|
||||
añadir al calendario del móvil desde su propia página.
|
||||
@ -415,16 +415,38 @@ finds Gitea level with your local `main`, and answers *"Already up to date."*
|
||||
which is true about the wrong remote, and reads exactly like there is nothing
|
||||
to do.
|
||||
|
||||
An update is a named pull, a push to Gitea so the build pipeline sees it, and a
|
||||
rebuild:
|
||||
**Paste one line at a time.** Every deploy that has gone wrong here went wrong
|
||||
in the terminal rather than in the code: three commands pasted on one line
|
||||
separated by commas, so git looked for a branch whose name ended in a comma; and
|
||||
a block pasted into a session that was still answering `ssh`'s host-key
|
||||
question, which swallowed the rest as answers. One line, one Enter, read what it
|
||||
says.
|
||||
|
||||
An update is **two** named pulls, a push to Gitea so the build pipeline sees it,
|
||||
and a rebuild:
|
||||
|
||||
```sh
|
||||
cd ~/vienalatina
|
||||
git pull --no-rebase --no-edit github <the-branch-name>
|
||||
git push gitea main
|
||||
git pull --no-rebase --no-edit gitea main # see below — Gitea moves on its own
|
||||
sudo bash scripts/deploy-board.sh
|
||||
git push gitea main
|
||||
```
|
||||
|
||||
**The second pull is the one this page used to be missing**, and the push fails
|
||||
without it with a non-fast-forward rejection. The translate step of the pipeline
|
||||
*commits* the generated German and Portuguese files back to Gitea
|
||||
(`translate: update N generated siblings [skip-translate]`), so every time
|
||||
anything is published, `gitea/main` gains a commit this checkout does not have.
|
||||
A push then has nothing to fast-forward from. Pulling it first merges the
|
||||
pipeline's own work into yours, which is all that is needed — there is never a
|
||||
conflict, because nothing but the pipeline writes those files.
|
||||
|
||||
**The order of the last two lines matters when a release changes both halves.**
|
||||
`deploy-board.sh` puts the members area up; the push is what rebuilds the public
|
||||
site. Anything on the static side that calls the app — the members' bar asking
|
||||
`/comunidad/sesion.json` — then finds it already there.
|
||||
|
||||
Both flags earn their place. `main` and the branch have genuinely diverged —
|
||||
main carries the previous merge, the branch carries the new work — and a git
|
||||
with no `pull.rebase` set refuses to guess, with *"fatal: Need to specify how to
|
||||
@ -650,13 +672,36 @@ Limits: 4 images per message, and `BOARD_UPLOAD_MAX_BYTES` (8MB by default)
|
||||
each. Adding a picture to a post *after* publishing it means posting a reply —
|
||||
editing changes the words, and leaves the pictures alone.
|
||||
|
||||
### 11.10 Private messages (`/comunidad/privados/`)
|
||||
### 11.10 Private messages (on each person's page)
|
||||
|
||||
An inbox between two members: conversations, unread badges, photos, blocking.
|
||||
Between two members: conversations, unread badges, photos, blocking.
|
||||
Deliberately not live chat — that needs a connection held open per signed-in
|
||||
member, which gunicorn's sync workers cannot do, and it would be the first
|
||||
thing on this box with a real scaling limit.
|
||||
|
||||
**There is no inbox.** You write to somebody by opening their page —
|
||||
`/comunidad/miembro/<usuario>`, reached from *Miembros* or from their name
|
||||
anywhere on the wall — and the whole conversation with them is on it, under
|
||||
their photo and bio, with the write box at the foot. One place per person
|
||||
rather than a mailbox listing people.
|
||||
|
||||
Three consequences worth knowing:
|
||||
|
||||
* **The unread badge is on *Miembros***, and repeated on the card of whoever
|
||||
wrote. Those cards are sorted so that anybody with something unread is at the
|
||||
top of the grid — without that, the person waiting for an answer is wherever
|
||||
the alphabet put them.
|
||||
* **Opening the page marks it read.** There is no second step any more, so
|
||||
there is no moment where the messages are on screen and still counted unread.
|
||||
* **The old addresses redirect.** `/comunidad/privados` goes to the directory
|
||||
and `/comunidad/privados/con/<id>` to that person's page; the POST that sends
|
||||
a message is still `/comunidad/privados/con/<id>`, which is why the two look
|
||||
alike in the logs.
|
||||
|
||||
A member's own page carries no conversation and no box: it is there so they can
|
||||
see what the others see, and their own private messages are each on the page of
|
||||
the person they had them with.
|
||||
|
||||
**Blocking is symmetric.** One block stops messages in both directions, and
|
||||
either person can only remove their own. A block that silenced just the blocked
|
||||
person would leave the blocker able to keep writing, which is a megaphone
|
||||
@ -671,7 +716,7 @@ of the choice, and deliberate.
|
||||
### 11.10b The members' bar on the public site
|
||||
|
||||
A signed-in member sees a slim bar above the public header on vienalatina.com,
|
||||
with the same five sections the members area has. The public pages are files on
|
||||
with the same sections the members area has. The public pages are files on
|
||||
disk and get cached, so the bar is drawn in the browser:
|
||||
`themes/vienalatina/assets/js/memberbar.js` asks `/comunidad/sesion.json` who is
|
||||
reading, and that endpoint is the only thing that decides anything — a visitor
|
||||
@ -778,7 +823,7 @@ the same problem the Gitea theme has. If the colours change in
|
||||
`themes/vienalatina/assets/css/main.css`, change them in
|
||||
`apps/board/templates/profile.html` too.
|
||||
|
||||
### 11.13 The five sections, and the moderation queue
|
||||
### 11.13 The six sections, and the moderation queue
|
||||
|
||||
Signing in lands on **Inicio**, a dashboard of what has happened since the last
|
||||
visit. The navigation is the same for everybody except the last entry:
|
||||
@ -787,19 +832,26 @@ visit. The navigation is the same for everybody except the last entry:
|
||||
|---|---|---|
|
||||
| **Inicio** | `/comunidad/` | everybody |
|
||||
| **Muro** | `/comunidad/muro` | everybody |
|
||||
| **Privados** | `/comunidad/privados` | everybody |
|
||||
| **Miembros** | `/comunidad/miembros` | everybody |
|
||||
| **Publicaciones** | `/comunidad/publicaciones` | everybody, with two different pages behind it |
|
||||
| **Calendario** | `/comunidad/calendario` | everybody; admins add events |
|
||||
| **Gestión** | `/comunidad/gestion` | admins and the owner |
|
||||
|
||||
Gestión holds three things: Miembros, the published **Artículos**, and the
|
||||
site's static **Páginas**. A moderator cannot open it, so their route to the
|
||||
published articles is the *Ya publicado* link on Publicaciones — the only one
|
||||
they have, which is why it sits beside the button rather than inside a
|
||||
**Miembros replaced Privados**, which was a list of conversations. The people
|
||||
are the section now — a grid of faces and names — and each person's page holds
|
||||
their profile, the private conversation with them, and (for an admin) the
|
||||
controls for that one person. §11.10 has the mechanics. The unread badge moved
|
||||
to this entry with the messages.
|
||||
|
||||
Gestión holds Miembros' *Dar de alta*, the published **Artículos**, the site's
|
||||
static **Páginas** and **Marca**. A moderator cannot open it, so their route to
|
||||
the published articles is the *Ya publicado* link on Publicaciones — the only
|
||||
one they have, which is why it sits beside the button rather than inside a
|
||||
paragraph.
|
||||
|
||||
*Mi perfil*, *Descargar mis datos* and *Salir* are in the menu under the member's
|
||||
own name, top right. They are not sections of the site, and while they were in the
|
||||
navigation three of the five entries were admin-only — which meant an ordinary
|
||||
navigation three of the entries were admin-only — which meant an ordinary
|
||||
member signed in to a wall and a member list, with their own profile and their own
|
||||
private messages hidden from them. `apps/board/tests/test_navigation.py` asserts
|
||||
the navigation per role now, so that cannot come back quietly.
|
||||
@ -844,18 +896,21 @@ only the title and the description. Editing a post keeps the author it already
|
||||
had, so correcting somebody's typo never re-signs their article.
|
||||
|
||||
**On the wall itself**: one 👍 per member per post or comment, which clicking
|
||||
again takes back, and every name is a link to that person's page — but only when
|
||||
they have published one, so nobody is sent to a 404. Both rules live in one place
|
||||
each (`templates/_reaction.html`, `templates/_person.html`) so no screen has to
|
||||
again takes back, and every name is a link to that person's page inside the
|
||||
members area — which exists for everybody, published page or not. The one name
|
||||
that is not a link is *Miembro eliminado*, the tombstone an erased member's
|
||||
writing is reassigned to. Both rules live in one place each
|
||||
(`templates/_reaction.html`, `templates/_person.html`) so no screen has to
|
||||
remember them.
|
||||
|
||||
**Miembros is a directory**, not an admin table: a card per person with their
|
||||
photo, username, role, the first line of their bio, somewhere to write to them
|
||||
and a link to their page. Admins get the controls — suspend, re-invite, change
|
||||
role, erase — inside a *Gestionar* block on each card, closed by default. A
|
||||
member's photo shows here even when their public page is unpublished, because
|
||||
this side is behind the login; `profiles.member_photo` serves it and the profile
|
||||
form says so in plain words.
|
||||
**Miembros is a directory of faces and names**: a card per person with their
|
||||
photo, username and role, and the whole card is a link to their page. Everything
|
||||
about one person is on that page — their bio and links, the private conversation
|
||||
with them, and, for an admin, the controls (suspend, re-invite, change role,
|
||||
erase) inside a *Gestionar* block, closed by default. A member's photo shows
|
||||
here even when their public page is unpublished, because this side is behind the
|
||||
login; `profiles.member_photo` serves it and the profile form says so in plain
|
||||
words.
|
||||
|
||||
### 11.15 The public menu is built from the pages
|
||||
|
||||
@ -880,6 +935,40 @@ WordPress: hover and `:focus-within`, inline on a phone, no script.
|
||||
Only *Inicio* and *Comunidad* remain in `config.yaml`. Weight under 5 puts a menu
|
||||
entry before the pages, 5 or more after them.
|
||||
|
||||
### 11.15b Two calendars
|
||||
|
||||
**Public events are posts** in the **Evento** category, with three fields of
|
||||
their own: `event_date`, `event_time` and `event_location`. The post's own `date`
|
||||
is when it was announced — usually weeks earlier, and what Hugo sorts the blog by
|
||||
— so the event's date cannot be the same field. Ticking Evento without a date is
|
||||
refused. Members can propose events exactly as they propose anything else, and a
|
||||
moderator approves them.
|
||||
|
||||
An event's page leads with the day, the time and the place, shows its picture
|
||||
full width, and offers **Añadir a mi calendario**: a `.ics` beside the page,
|
||||
generated because the editor writes `outputs: ["HTML", "ics"]` into an event's
|
||||
frontmatter. It also carries `Event` structured data, which is what puts a date
|
||||
beside the result in a search listing.
|
||||
|
||||
`vienalatina.com/page/agenda/` is a month grid per month, from the first event to
|
||||
the last, built at build time. `assets/js/agenda.js` shows one and moves between
|
||||
them — so with JavaScript off every month is on the page as a list, and with it
|
||||
on, moving months costs no request and starts on the month the *reader* is in
|
||||
rather than the month the site was built in.
|
||||
|
||||
**The private calendar** is `/comunidad/calendario`: rows in SQLite, written by
|
||||
admins, read by every member, never published. It shows the public events too,
|
||||
marked, so a member has one place to look; those come from the `content_cache`
|
||||
that the editor's listing already fills, which is why **migration 5** adds three
|
||||
columns to it and to `submissions`. If the git server is unreachable the private
|
||||
events still render and the page says so — `gitea.py` now turns a refused
|
||||
connection into a `GiteaError` rather than letting `requests`' own exception
|
||||
through, which is what made that possible.
|
||||
|
||||
The month grid is Python's `calendar.Calendar`; there is no date arithmetic of
|
||||
ours anywhere in it. Erasing an admin clears `events.created_by` and leaves the
|
||||
event standing: the meeting still happens after they leave.
|
||||
|
||||
### 11.16 Sharing, SEO and answer engines
|
||||
|
||||
`partials/seo-head.html` was already emitting hreflang, Open Graph, a Twitter
|
||||
@ -919,6 +1008,72 @@ Choosing a picture shows a thumbnail with its name and size before anything is
|
||||
uploaded. That is the one reason `blob:` is in the `img-src` policy — a handle to
|
||||
bytes already in the page, which reaches no network.
|
||||
|
||||
### 11.18 Marca: the admin owns the look
|
||||
|
||||
*Gestión* → **Marca**, admins only. Colours, a logo and a favicon for both
|
||||
halves of the site, with an *Avanzado* fold holding every token as a text field
|
||||
and a free CSS box.
|
||||
|
||||
**`apps/board/brand.py`'s `FACTORY` is the single source of truth for the
|
||||
palette.** The two `:root` blocks — `themes/vienalatina/assets/css/main.css` and
|
||||
`apps/board/static/board.css` — each still carry their own copy, because they are
|
||||
served by different things and each has to stand alone; what changed is that
|
||||
`apps/board/tests/test_brand.py` parses both and fails the build if either
|
||||
disagrees with `FACTORY`. The comment that used to say *"If the brand colours
|
||||
change, change them in both"* was an instruction, which is the weakest kind of
|
||||
guarantee there is.
|
||||
|
||||
**One save, two destinations**, because the two halves cannot read the same
|
||||
store:
|
||||
|
||||
| Where | What | Why |
|
||||
|---|---|---|
|
||||
| SQLite, table `brand`, one row | the tokens, the custom CSS, both pictures under `/data/uploads` | the members area must render when the git server is down |
|
||||
| the content repository: `data/brand.yaml`, `static/brand/logo.*`, `static/brand/favicon.png` | the same values | the public site is files on disk and has no database |
|
||||
|
||||
**SQLite first, then the commits.** If Gitea is unreachable the change still
|
||||
takes effect in the members area, `published_at` stays NULL, and the screen says
|
||||
so with a *Reintentar publicar* button. The other order would let a git outage
|
||||
block a change that does not need git. A colour therefore reaches
|
||||
vienalatina.com on the next pipeline run — a couple of minutes — and the members
|
||||
area immediately.
|
||||
|
||||
Three details worth knowing before changing any of it:
|
||||
|
||||
* **Only what differs from the factory is stored**, as JSON in one column. A
|
||||
token added here later arrives with its default already in place for every
|
||||
existing install, which a snapshot of all thirteen would not.
|
||||
* **`--brand-dark`, `--brand-soft` and `--brand-softer` are worked out from
|
||||
`--brand`** in HLS (hue and saturation kept, lightness moved), so an admin
|
||||
picks one colour and gets a coherent set. Each can be overridden in
|
||||
*Avanzado*. With no brand colour stored, the factory hexes are used verbatim —
|
||||
deriving from an unchanged colour would shift the palette by a rounding error
|
||||
the first time anybody opened the screen.
|
||||
* **A WCAG contrast warning, not a refusal.** Text on background below 4.5:1,
|
||||
or white on the brand colour below 3:1, is named with its ratio and saved
|
||||
anyway. An admin may have a reason; what this prevents is shipping an
|
||||
unreadable site without once being told.
|
||||
|
||||
**The Marca screen deliberately does not load the generated stylesheet.** Every
|
||||
other page does. That is what keeps *Restaurar lo de fábrica* reachable after
|
||||
somebody puts `* { display: none }` in the CSS box — and the reason the colours
|
||||
an admin picks do not show on the page where they pick them. The live preview
|
||||
block is where they see them, restyled by `board.js` setting the custom
|
||||
properties on that one element (a DOM write, not an inline `style` attribute,
|
||||
which is what makes it work under a policy with no `'unsafe-inline'`).
|
||||
|
||||
**No SVG and no ICO.** The logo takes PNG, JPG or WebP and the favicon PNG only,
|
||||
both identified from their bytes by the same sniffer the wall uses. An SVG is XML
|
||||
that can carry script and would be served from our own origin; ICO would be one
|
||||
more branch in the sniffer for a format every current browser no longer needs.
|
||||
|
||||
The pictures are committed to stable paths, so saving a new logo replaces the
|
||||
file instead of leaving every previous one deployed and unreferenced; a logo
|
||||
saved in a different format has its predecessor deleted. `scripts/translate.py`
|
||||
needs nothing — it walks `content/` only, and `data/` and `static/` are outside
|
||||
it. A site with no `data/brand.yaml` builds byte-for-byte the HTML it built
|
||||
before any of this existed, which is asserted by building both ways.
|
||||
|
||||
## 12. Make Gitea look like the site
|
||||
|
||||
Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its
|
||||
|
||||
@ -60,6 +60,9 @@ CONTENT_DIR = REPO_ROOT / "content"
|
||||
# Frontmatter strings translated alongside the body. Note `categories` is
|
||||
# deliberately absent: the taxonomy terms stay Spanish in every language, or
|
||||
# Hugo would fork the taxonomy per language.
|
||||
# `event_location` is deliberately absent: an address is how somebody finds the
|
||||
# place, and a translated street or venue name is worse than an untranslated one.
|
||||
# `event_date` and `event_time` are data, not prose.
|
||||
TRANSLATED_KEYS = ("title", "description", "image_alt")
|
||||
|
||||
# `faq` is a list of "question|answer" lines, so it cannot go through the loop
|
||||
|
||||
@ -3816,3 +3816,133 @@ a.notif-card__message:hover {
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
/* --- an event, and the agenda ------------------------------------------ */
|
||||
|
||||
/* The three things somebody needs before they read a word. */
|
||||
.event-card {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 20px;
|
||||
margin: 20px 0 24px;
|
||||
padding: 16px 20px;
|
||||
background: var(--brand-softer, #fdf1ed);
|
||||
border: 1px solid var(--brand-soft, #fbe2db);
|
||||
border-radius: var(--radius-xl, 18px);
|
||||
}
|
||||
|
||||
.event-card__date {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
line-height: 1.05;
|
||||
color: var(--brand, #c0391c);
|
||||
}
|
||||
|
||||
.event-card__day { font-size: 2.4rem; font-weight: 800; }
|
||||
.event-card__month { font-size: 0.95rem; font-weight: 700; }
|
||||
.event-card__year { font-size: 0.8rem; opacity: 0.75; }
|
||||
|
||||
.event-card__facts { margin: 0; flex: 1 1 200px; }
|
||||
.event-card__facts dt {
|
||||
font-size: 0.72rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
color: var(--muted, #5c3d37);
|
||||
}
|
||||
.event-card__facts dd { margin: 0 0 8px; font-weight: 600; }
|
||||
.event-card__facts dd:last-child { margin-bottom: 0; }
|
||||
|
||||
.event-card__add {
|
||||
display: inline-block;
|
||||
padding: 8px 16px;
|
||||
border-radius: 999px;
|
||||
background: var(--brand, #c0391c);
|
||||
color: #fff;
|
||||
font-size: 0.86rem;
|
||||
font-weight: 700;
|
||||
text-decoration: none;
|
||||
}
|
||||
.event-card__add:hover { background: var(--brand-dark, #9a2a0f); color: #fff; }
|
||||
|
||||
/* An event's picture carries the page rather than illustrating it. */
|
||||
.article-single__cover--hero {
|
||||
width: 100%;
|
||||
max-height: 420px;
|
||||
object-fit: cover;
|
||||
border-radius: var(--radius-lg, 12px);
|
||||
}
|
||||
|
||||
.agenda__intro { color: var(--muted, #5c3d37); margin-bottom: 16px; }
|
||||
|
||||
.agenda__bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 16px;
|
||||
margin: 16px 0;
|
||||
}
|
||||
|
||||
.agenda__move {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: 50%;
|
||||
border: 1px solid var(--border-light, #e0cec8);
|
||||
background: var(--surface, #fff);
|
||||
color: var(--brand, #c0391c);
|
||||
font-size: 1.1rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
.agenda__move:hover:not(:disabled) { border-color: var(--brand, #c0391c); }
|
||||
.agenda__move:disabled { opacity: 0.35; cursor: default; }
|
||||
.agenda__current { font-size: 1.05rem; min-width: 10rem; text-align: center; }
|
||||
|
||||
/* Until agenda.js runs, every month is visible and the controls would lie
|
||||
about which one is showing — so the bar appears only once it has. */
|
||||
.agenda__bar { display: none; }
|
||||
.has-agenda-script .agenda__bar { display: flex; }
|
||||
.has-agenda-script .agenda__heading { display: none; }
|
||||
|
||||
.agenda__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(7, 1fr);
|
||||
gap: 4px;
|
||||
list-style: none;
|
||||
margin: 0 0 24px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.agenda__day, .agenda__pad {
|
||||
min-height: 92px;
|
||||
padding: 6px;
|
||||
border: 1px solid var(--border-light, #e0cec8);
|
||||
border-radius: var(--radius-sm, 5px);
|
||||
background: var(--surface, #fff);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.agenda__pad { background: transparent; border-color: transparent; }
|
||||
.agenda__number { color: var(--subtle, #9a7870); font-weight: 700; }
|
||||
.agenda__day--busy { background: var(--brand-softer, #fdf1ed); border-color: var(--brand-soft, #fbe2db); }
|
||||
|
||||
.agenda__event {
|
||||
display: block;
|
||||
margin-top: 4px;
|
||||
color: var(--brand-dark, #9a2a0f);
|
||||
text-decoration: none;
|
||||
line-height: 1.3;
|
||||
}
|
||||
.agenda__event time { font-weight: 700; }
|
||||
.agenda__event:hover { text-decoration: underline; }
|
||||
|
||||
.agenda__empty { text-align: center; margin: -12px 0 24px; }
|
||||
|
||||
/* A seven-column grid on a phone is seven columns of nothing. Below 640px the
|
||||
month becomes a list of the days that have something in them. */
|
||||
@media (max-width: 640px) {
|
||||
.agenda__grid { display: block; }
|
||||
.agenda__pad { display: none; }
|
||||
.agenda__day { display: none; min-height: 0; margin-bottom: 6px; }
|
||||
.agenda__day--busy { display: block; }
|
||||
.agenda__number { display: inline-block; margin-right: 8px; }
|
||||
}
|
||||
|
||||
52
themes/vienalatina/assets/js/agenda.js
Normal file
52
themes/vienalatina/assets/js/agenda.js
Normal file
@ -0,0 +1,52 @@
|
||||
// Which month the agenda is showing.
|
||||
//
|
||||
// Every month is already on the page — the layout builds them all — so this
|
||||
// only decides which one is visible and moves between them. Three consequences
|
||||
// worth keeping: a reader with no JavaScript sees every month stacked instead of
|
||||
// a blank page, moving months makes no request, and the month it starts on is
|
||||
// decided here rather than when the site was built, so it is right however long
|
||||
// ago that was.
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
var months = [].slice.call(document.querySelectorAll(".agenda__month"));
|
||||
if (months.length === 0) return;
|
||||
|
||||
var label = document.querySelector("[data-agenda-label]");
|
||||
var buttons = [].slice.call(document.querySelectorAll("[data-agenda-move]"));
|
||||
var keys = months.map(function (section) { return section.dataset.month; });
|
||||
|
||||
// The month the reader is in, or the nearest one the page has.
|
||||
var now = new Date();
|
||||
var current = now.getFullYear() + "-" + ("0" + (now.getMonth() + 1)).slice(-2);
|
||||
var index = keys.indexOf(current);
|
||||
if (index === -1) {
|
||||
index = 0;
|
||||
for (var i = 0; i < keys.length; i++) {
|
||||
if (keys[i] <= current) index = i;
|
||||
}
|
||||
}
|
||||
|
||||
function show(next) {
|
||||
index = Math.max(0, Math.min(months.length - 1, next));
|
||||
months.forEach(function (section, i) {
|
||||
section.hidden = i !== index;
|
||||
});
|
||||
if (label) label.textContent = months[index].dataset.label;
|
||||
buttons.forEach(function (button) {
|
||||
var step = parseInt(button.dataset.agendaMove, 10);
|
||||
button.disabled = index + step < 0 || index + step > months.length - 1;
|
||||
});
|
||||
}
|
||||
|
||||
buttons.forEach(function (button) {
|
||||
button.addEventListener("click", function () {
|
||||
show(index + parseInt(button.dataset.agendaMove, 10));
|
||||
});
|
||||
});
|
||||
|
||||
// Only now: until this runs the page is the no-JavaScript version, every
|
||||
// month visible, which is what a crawler and a reader without scripts get.
|
||||
document.documentElement.classList.add("has-agenda-script");
|
||||
show(index);
|
||||
})();
|
||||
@ -7,6 +7,7 @@
|
||||
{{ partial "seo-head.html" . }}
|
||||
{{ $css := resources.Get "css/main.css" | minify | fingerprint }}
|
||||
<link rel="stylesheet" href="{{ $css.RelPermalink }}" integrity="{{ $css.Data.Integrity }}">
|
||||
{{ partial "brand-head.html" . }}
|
||||
<link rel="canonical" href="{{ .Permalink }}">
|
||||
{{ range .AlternativeOutputFormats -}}
|
||||
<link rel="{{ .Rel }}" type="{{ .MediaType.Type }}" href="{{ .Permalink | safeURL }}">
|
||||
|
||||
@ -36,12 +36,41 @@
|
||||
|
||||
<h1 class="article-single__title">{{ .Title }}</h1>
|
||||
|
||||
{{/* An event leads with the three things somebody needs before they read
|
||||
a word: when, what time, and where. Everything else on the page is
|
||||
the same article it would otherwise be. */}}
|
||||
{{ with .Params.event_date }}
|
||||
{{ $when := . | time.AsTime }}
|
||||
<aside class="event-card">
|
||||
<div class="event-card__date">
|
||||
<span class="event-card__day">{{ $when.Format "2" }}</span>
|
||||
<span class="event-card__month">{{ partial "month-name.html" (dict "month" ($when.Format "1") "lang" $.Site.Language.Lang) }}</span>
|
||||
<span class="event-card__year">{{ $when.Format "2006" }}</span>
|
||||
</div>
|
||||
<dl class="event-card__facts">
|
||||
{{ with $.Params.event_time }}
|
||||
<dt>{{ partial "t.html" (dict "key" "time" "lang" $.Site.Language.Lang) }}</dt><dd>{{ . }}</dd>
|
||||
{{ end }}
|
||||
{{ with $.Params.event_location }}
|
||||
<dt>{{ partial "t.html" (dict "key" "place" "lang" $.Site.Language.Lang) }}</dt><dd>{{ . }}</dd>
|
||||
{{ end }}
|
||||
</dl>
|
||||
{{/* The .ics is generated for this page because its frontmatter asks
|
||||
for the format — see apps/board/content.py, which writes that
|
||||
line for anything in the Evento category. */}}
|
||||
{{ with $.OutputFormats.Get "ics" }}
|
||||
<a class="event-card__add" href="{{ .RelPermalink }}" download>{{ partial "t.html" (dict "key" "add" "lang" $.Site.Language.Lang) }}</a>
|
||||
{{ end }}
|
||||
</aside>
|
||||
{{ end }}
|
||||
|
||||
{{ with .Description }}
|
||||
<p class="article-single__summary">{{ . }}</p>
|
||||
{{ end }}
|
||||
|
||||
{{ with .Params.image }}
|
||||
<img class="article-single__cover" src="{{ . | relURL }}" alt="">
|
||||
<img class="article-single__cover {{ if $.Params.event_date }}article-single__cover--hero{{ end }}"
|
||||
src="{{ . | relURL }}" alt="{{ $.Params.image_alt | default $.Title }}" loading="lazy">
|
||||
{{ end }}
|
||||
|
||||
<div class="article-single__body">
|
||||
|
||||
40
themes/vienalatina/layouts/_default/single.ics
Normal file
40
themes/vienalatina/layouts/_default/single.ics
Normal file
@ -0,0 +1,40 @@
|
||||
{{- /* One event, as a file a calendar app understands.
|
||||
|
||||
RFC 5545 in fifteen lines. The things that actually matter here:
|
||||
|
||||
* CRLF line endings. The spec says so and some readers are strict about
|
||||
it; Hugo writes what this template contains, so the \r is explicit.
|
||||
* UID has to be stable and unique — the permalink is both, and re-adding
|
||||
an event updates the entry instead of duplicating it.
|
||||
* Times are written with a TZID of Europe/Vienna rather than converted to
|
||||
UTC. Every event here happens in one city, and a local time that stays
|
||||
local survives a daylight-saving change the way a converted one does
|
||||
not.
|
||||
* An event with no time is a whole day: VALUE=DATE, which is how a
|
||||
calendar shows it as a band across the top instead of inventing
|
||||
midnight. */ -}}
|
||||
{{- $date := .Params.event_date | time.AsTime -}}
|
||||
{{- $stamp := now.UTC.Format "20060102T150405Z" -}}
|
||||
BEGIN:VCALENDAR{{ printf "\r" }}
|
||||
VERSION:2.0{{ printf "\r" }}
|
||||
PRODID:-//{{ .Site.Title }}//agenda//ES{{ printf "\r" }}
|
||||
CALSCALE:GREGORIAN{{ printf "\r" }}
|
||||
METHOD:PUBLISH{{ printf "\r" }}
|
||||
BEGIN:VEVENT{{ printf "\r" }}
|
||||
UID:{{ .Permalink }}{{ printf "\r" }}
|
||||
DTSTAMP:{{ $stamp }}{{ printf "\r" }}
|
||||
{{ with .Params.event_time -}}
|
||||
DTSTART;TZID=Europe/Vienna:{{ $date.Format "20060102" }}T{{ replace . ":" "" }}00{{ printf "\r" }}
|
||||
{{ else -}}
|
||||
DTSTART;VALUE=DATE:{{ $date.Format "20060102" }}{{ printf "\r" }}
|
||||
{{ end -}}
|
||||
SUMMARY:{{ .Title | plainify | replaceRE "[,;\\\\]" "\\${0}" }}{{ printf "\r" }}
|
||||
{{ with .Params.event_location -}}
|
||||
LOCATION:{{ . | plainify | replaceRE "[,;\\\\]" "\\${0}" }}{{ printf "\r" }}
|
||||
{{ end -}}
|
||||
{{ with .Description -}}
|
||||
DESCRIPTION:{{ . | plainify | replaceRE "[,;\\\\]" "\\${0}" }}{{ printf "\r" }}
|
||||
{{ end -}}
|
||||
URL:{{ .Permalink }}{{ printf "\r" }}
|
||||
END:VEVENT{{ printf "\r" }}
|
||||
END:VCALENDAR{{ printf "\r" }}
|
||||
101
themes/vienalatina/layouts/page/agenda.html
Normal file
101
themes/vienalatina/layouts/page/agenda.html
Normal file
@ -0,0 +1,101 @@
|
||||
{{/* The public agenda: one grid per month, all of them built here.
|
||||
|
||||
Every month between the first event and the last is rendered, plus the
|
||||
current one, and assets/js/agenda.js shows one at a time. Two things fall
|
||||
out of building them all rather than fetching a month at a time:
|
||||
|
||||
* **With JavaScript off, every month is on the page**, stacked, each under
|
||||
its own heading. Nothing is hidden from a reader who has no script, and
|
||||
nothing is hidden from a crawler either.
|
||||
* Moving between months is instant and makes no request.
|
||||
|
||||
The weekday arithmetic is the awkward part, because Hugo exposes no
|
||||
AddDate: the length of a month comes from a table plus a leap-year check,
|
||||
and the weekday of the first falls out of formatting that date. It looks
|
||||
like something simpler was missed, and it is not. */}}
|
||||
{{ define "main" }}
|
||||
{{ $lang := .Site.Language.Lang }}
|
||||
{{ $events := where (where .Site.RegularPages "Section" "post") "Params.event_date" "!=" nil }}
|
||||
|
||||
{{/* The span to render: from the earliest event to the latest, and always
|
||||
including the month the site was built in, so an empty agenda still shows
|
||||
the reader where they are. */}}
|
||||
{{ $months := slice }}
|
||||
{{ range $events }}{{ $months = $months | append (substr .Params.event_date 0 7) }}{{ end }}
|
||||
{{ $months = $months | append (now.Format "2006-01") }}
|
||||
{{ $months = sort (uniq $months) }}
|
||||
{{ $from := index $months 0 }}
|
||||
{{ $to := index $months (sub (len $months) 1) }}
|
||||
|
||||
{{/* Expanded so a month with nothing in it can still be visited. */}}
|
||||
{{ $span := slice }}
|
||||
{{ range $y := seq (int (substr $from 0 4)) (int (substr $to 0 4)) }}
|
||||
{{ range $m := seq 1 12 }}
|
||||
{{ $key := printf "%04d-%02d" $y $m }}
|
||||
{{ if and (ge $key $from) (le $key $to) }}{{ $span = $span | append $key }}{{ end }}
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
|
||||
{{ $script := resources.Get "js/agenda.js" | minify | fingerprint }}
|
||||
<script src="{{ $script.RelPermalink }}" integrity="{{ $script.Data.Integrity }}" defer></script>
|
||||
|
||||
<main class="feed feed--agenda">
|
||||
<h1 class="feed__title">{{ .Title }}</h1>
|
||||
{{ with .Content }}<div class="agenda__intro">{{ . }}</div>{{ end }}
|
||||
|
||||
<nav class="agenda__bar" aria-label="{{ partial "t.html" (dict "key" "agenda" "lang" $lang) }}">
|
||||
<button class="agenda__move" type="button" data-agenda-move="-1"
|
||||
aria-label="{{ partial "t.html" (dict "key" "previous" "lang" $lang) }}">←</button>
|
||||
<strong class="agenda__current" data-agenda-label></strong>
|
||||
<button class="agenda__move" type="button" data-agenda-move="1"
|
||||
aria-label="{{ partial "t.html" (dict "key" "next" "lang" $lang) }}">→</button>
|
||||
</nav>
|
||||
|
||||
{{ range $key := $span }}
|
||||
{{ $year := int (substr $key 0 4) }}
|
||||
{{ $month := int (substr $key 5 2) }}
|
||||
{{ $firstDay := printf "%s-01" $key }}
|
||||
|
||||
{{/* Days in the month: a table, with February decided by the leap rule —
|
||||
every four years, not every hundred, except every four hundred. */}}
|
||||
{{ $lengths := slice 31 28 31 30 31 30 31 31 30 31 30 31 }}
|
||||
{{ $days := index $lengths (sub $month 1) }}
|
||||
{{ if eq $month 2 }}
|
||||
{{ if or (and (eq (mod $year 4) 0) (ne (mod $year 100) 0)) (eq (mod $year 400) 0) }}
|
||||
{{ $days = 29 }}
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
|
||||
{{/* Monday first, as in Austria and most of Latin America. Go names the
|
||||
weekday; this turns the name into a column offset. */}}
|
||||
{{ $offsets := dict "Mon" 0 "Tue" 1 "Wed" 2 "Thu" 3 "Fri" 4 "Sat" 5 "Sun" 6 }}
|
||||
{{ $lead := index $offsets (($firstDay | time.AsTime).Format "Mon") }}
|
||||
|
||||
<section class="agenda__month" data-month="{{ $key }}"
|
||||
data-label="{{ partial "month-name.html" (dict "month" $month "lang" $lang) }} {{ $year }}">
|
||||
<h2 class="agenda__heading">{{ partial "month-name.html" (dict "month" $month "lang" $lang) }} {{ $year }}</h2>
|
||||
|
||||
<ol class="agenda__grid">
|
||||
{{ if gt $lead 0 }}{{ range seq $lead }}<li class="agenda__pad" aria-hidden="true"></li>{{ end }}{{ end }}
|
||||
{{ range $day := seq 1 $days }}
|
||||
{{ $date := printf "%s-%02d" $key $day }}
|
||||
{{ $onThisDay := where $events "Params.event_date" $date }}
|
||||
<li class="agenda__day {{ if $onThisDay }}agenda__day--busy{{ end }}">
|
||||
<span class="agenda__number">{{ $day }}</span>
|
||||
{{ range $onThisDay }}
|
||||
<a class="agenda__event" href="{{ .RelPermalink }}">
|
||||
{{ with .Params.event_time }}<time>{{ . }}</time> {{ end }}{{ .Title }}
|
||||
</a>
|
||||
{{ end }}
|
||||
</li>
|
||||
{{ end }}
|
||||
</ol>
|
||||
|
||||
{{ $inMonth := where (where $events "Params.event_date" "ge" (printf "%s-01" $key)) "Params.event_date" "le" (printf "%s-31" $key) }}
|
||||
{{ if not $inMonth }}
|
||||
<p class="muted agenda__empty">{{ partial "t.html" (dict "key" "noevents" "lang" $lang) }}</p>
|
||||
{{ end }}
|
||||
</section>
|
||||
{{ end }}
|
||||
</main>
|
||||
{{ end }}
|
||||
31
themes/vienalatina/layouts/partials/brand-head.html
Normal file
31
themes/vienalatina/layouts/partials/brand-head.html
Normal file
@ -0,0 +1,31 @@
|
||||
{{/* The admin's colours and the favicon, from data/brand.yaml.
|
||||
|
||||
That file is written by the members area — Gestión → Marca commits it
|
||||
through the contents API, the pipeline runs, and the colours arrive here on
|
||||
the next build. The whole partial is inside a `with`, so a site with no
|
||||
brand.yaml emits nothing at all and its HTML is byte-identical to before
|
||||
this existed.
|
||||
|
||||
Built with resources.FromString rather than written into a <style> block:
|
||||
the public site has no Content-Security-Policy of its own today, but the
|
||||
members area does and this stylesheet is generated the same way on both
|
||||
sides. Fingerprinted, which is what makes a colour change reach a browser
|
||||
that already has the old file.
|
||||
|
||||
The favicon carries ?v= the stamp instead, because it is a static file
|
||||
Caddy serves under its own name — replacing the picture does not change
|
||||
the path. */}}
|
||||
{{ with site.Data.brand }}
|
||||
{{ $tokens := "" }}
|
||||
{{ range $name, $value := .tokens }}{{ $tokens = printf "%s--%s:%s;" $tokens $name $value }}{{ end }}
|
||||
{{ $sheet := "" }}
|
||||
{{ with $tokens }}{{ $sheet = printf ":root{%s}" . }}{{ end }}
|
||||
{{ with $.Site.Data.brand.custom_css }}{{ $sheet = printf "%s\n%s" $sheet . }}{{ end }}
|
||||
{{ with $sheet }}
|
||||
{{ $brand := resources.FromString "css/brand.css" . | minify | fingerprint }}
|
||||
<link rel="stylesheet" href="{{ $brand.RelPermalink }}" integrity="{{ $brand.Data.Integrity }}">
|
||||
{{ end }}
|
||||
{{ with .favicon }}
|
||||
<link rel="icon" type="image/png" href="{{ . }}?v={{ $.Site.Data.brand.stamp }}">
|
||||
{{ end }}
|
||||
{{ end }}
|
||||
@ -4,7 +4,21 @@
|
||||
<header class="site-bar">
|
||||
<div class="site-bar__inner">
|
||||
<a class="site-bar__brand" href="{{ .Site.Home.Permalink }}" aria-label="Inicio">
|
||||
{{/* The logo uploaded in Gestión → Marca, and the site's name in
|
||||
letters when there is none. The alt text is the name either way,
|
||||
so a reader who does not see the picture reads the same thing.
|
||||
|
||||
Read through two variables rather than as
|
||||
`site.Data.brand.logo`, because on a site with no data/brand.yaml
|
||||
that expression is a field lookup on nil and fails the build —
|
||||
which is precisely the state every install starts in. */}}
|
||||
{{ $logo := "" }}{{ $stamp := "0" }}
|
||||
{{ with site.Data.brand }}{{ $logo = .logo }}{{ $stamp = .stamp }}{{ end }}
|
||||
{{ with $logo }}
|
||||
<img class="site-bar__logo" src="{{ . }}?v={{ $stamp }}" alt="{{ site.Title }}">
|
||||
{{ else }}
|
||||
<span class="site-bar__brand-text">{{ .Site.Title }}</span>
|
||||
{{ end }}
|
||||
</a>
|
||||
|
||||
<nav class="site-bar__nav" aria-label="Idioma">
|
||||
|
||||
12
themes/vienalatina/layouts/partials/month-name.html
Normal file
12
themes/vienalatina/layouts/partials/month-name.html
Normal file
@ -0,0 +1,12 @@
|
||||
{{- /* The month in the page's own language.
|
||||
|
||||
Hugo's time.Format follows the site's language only when the translation
|
||||
tables are installed, and this theme ships no i18n files — three languages,
|
||||
twelve words each, is a table rather than a dependency. */ -}}
|
||||
{{- $names := dict
|
||||
"es" (slice "enero" "febrero" "marzo" "abril" "mayo" "junio" "julio" "agosto" "septiembre" "octubre" "noviembre" "diciembre")
|
||||
"de" (slice "Januar" "Februar" "März" "April" "Mai" "Juni" "Juli" "August" "September" "Oktober" "November" "Dezember")
|
||||
"pt-br" (slice "janeiro" "fevereiro" "março" "abril" "maio" "junho" "julho" "agosto" "setembro" "outubro" "novembro" "dezembro")
|
||||
-}}
|
||||
{{- $table := index $names .lang | default (index $names "es") -}}
|
||||
{{- index $table (sub (int .month) 1) -}}
|
||||
@ -10,15 +10,22 @@
|
||||
renders raggedly in some readers and truncated in others. */}}
|
||||
{{ $desc = trim ($desc | plainify | replaceRE "\\s+" " ") " " }}
|
||||
|
||||
{{/* The picture a share card shows. A page's own image when it has one, the
|
||||
site default when it does not — `params.defaultImage` is empty until the
|
||||
logo arrives, and a card with no picture is what happens meanwhile, which is
|
||||
also what happens today. Absolute, because WhatsApp, Signal, Mastodon and
|
||||
Bluesky all fetch it from outside and a relative path means nothing to
|
||||
them. */}}
|
||||
{{/* The picture a share card shows. A page's own image when it has one, and
|
||||
otherwise the fallback: the logo uploaded in Gestión → Marca, or
|
||||
`params.defaultImage` when there is no logo. The logo comes first because
|
||||
it is the one somebody can change without the repository — and because
|
||||
`defaultImage` only ever existed as the line to fill in once a logo
|
||||
arrived. With neither, a card shows title and description and no picture,
|
||||
which is what happened before either existed.
|
||||
|
||||
Absolute, because WhatsApp, Signal, Mastodon and Bluesky all fetch it from
|
||||
outside and a relative path means nothing to them. */}}
|
||||
{{ $brandLogo := "" }}
|
||||
{{ with site.Data.brand }}{{ $brandLogo = .logo }}{{ end }}
|
||||
{{ $fallback := or $brandLogo .Site.Params.defaultImage }}
|
||||
{{ $image := "" }}
|
||||
{{ with .Params.image }}{{ $image = . | absURL }}
|
||||
{{ else }}{{ with .Site.Params.defaultImage }}{{ $image = . | absURL }}{{ end }}{{ end }}
|
||||
{{ else }}{{ with $fallback }}{{ $image = . | absURL }}{{ end }}{{ end }}
|
||||
|
||||
<meta name="description" content="{{ $desc }}">
|
||||
|
||||
@ -85,6 +92,36 @@
|
||||
{{ partial "breadcrumbs-schema.html" . }}
|
||||
{{ partial "faq-schema.html" . }}
|
||||
|
||||
{{/* An event is also an Event. This is what puts a date next to the result in a
|
||||
search listing, and what an answer engine reads when somebody asks what is
|
||||
on in Vienna this weekend — the article alone says none of it in a form a
|
||||
machine can use. */}}
|
||||
{{ with .Params.event_date }}
|
||||
{{ $when := . | time.AsTime }}
|
||||
{{ $start := $when.Format "2006-01-02" }}
|
||||
{{ with $.Params.event_time }}{{ $start = printf "%sT%s:00" $start . }}{{ end }}
|
||||
{{ $event := dict
|
||||
"@context" "https://schema.org"
|
||||
"@type" "Event"
|
||||
"name" $.Title
|
||||
"startDate" $start
|
||||
"url" $.Permalink
|
||||
"inLanguage" $.Site.Language.LanguageCode
|
||||
"eventAttendanceMode" "https://schema.org/OfflineEventAttendanceMode"
|
||||
"eventStatus" "https://schema.org/EventScheduled"
|
||||
"organizer" (dict "@type" "Organization" "name" $.Site.Title "url" $.Site.Home.Permalink)
|
||||
}}
|
||||
{{ with $desc }}{{ $event = merge $event (dict "description" .) }}{{ end }}
|
||||
{{ with $image }}{{ $event = merge $event (dict "image" .) }}{{ end }}
|
||||
{{ with $.Params.event_location }}
|
||||
{{ $event = merge $event (dict "location" (dict
|
||||
"@type" "Place"
|
||||
"name" .
|
||||
"address" (dict "@type" "PostalAddress" "addressLocality" "Wien" "addressCountry" "AT"))) }}
|
||||
{{ end }}
|
||||
<script type="application/ld+json">{{ $event | jsonify (dict "indent" " ") | safeJS }}</script>
|
||||
{{ end }}
|
||||
|
||||
{{ else if .IsHome }}
|
||||
{{/* ---- Home ---- */}}
|
||||
<meta property="og:type" content="website">
|
||||
@ -93,6 +130,14 @@
|
||||
<meta property="og:description" content="{{ $desc }}">
|
||||
<meta property="og:url" content="{{ .Permalink }}">
|
||||
<meta property="og:locale" content="{{ $locale }}">
|
||||
{{/* The home page shared without a picture until there was one to use. Now
|
||||
that an admin can upload a logo, the front page of the site is the last
|
||||
place that should share as a bare link. */}}
|
||||
{{ with $image }}
|
||||
<meta property="og:image" content="{{ . }}">
|
||||
<meta property="og:image:alt" content="{{ $.Site.Title }}">
|
||||
<meta name="twitter:image" content="{{ . }}">
|
||||
{{ end }}
|
||||
|
||||
{{ $org := dict
|
||||
"@context" "https://schema.org"
|
||||
@ -102,7 +147,10 @@
|
||||
"description" .Site.Params.description
|
||||
"areaServed" (dict "@type" "City" "name" "Wien" "addressCountry" "AT")
|
||||
}}
|
||||
{{ with .Site.Params.defaultImage }}{{ $org = merge $org (dict "logo" (. | absURL)) }}{{ end }}
|
||||
{{/* The same fallback as the share card: the admin's logo, then the configured
|
||||
default. This is the field a search engine uses to put a mark beside the
|
||||
organisation's name, so it should be the logo somebody actually uploaded. */}}
|
||||
{{ with $fallback }}{{ $org = merge $org (dict "logo" (. | absURL)) }}{{ end }}
|
||||
{{ with .Site.Params.sameAs }}{{ $org = merge $org (dict "sameAs" .) }}{{ end }}
|
||||
<script type="application/ld+json">{{ $org | jsonify (dict "indent" " ") | safeJS }}</script>
|
||||
|
||||
|
||||
27
themes/vienalatina/layouts/partials/t.html
Normal file
27
themes/vienalatina/layouts/partials/t.html
Normal file
@ -0,0 +1,27 @@
|
||||
{{- /* The handful of words the templates themselves say.
|
||||
|
||||
Everything else on this site is content and arrives already translated by
|
||||
the pipeline. These are the labels around it — "Lugar", "Hoy" — and there
|
||||
are eleven of them, which is a table rather than a reason to install i18n
|
||||
files and a translation workflow for the theme.
|
||||
|
||||
Usage: {{ partial "t.html" (dict "key" "place" "lang" .Site.Language.Lang) }}
|
||||
An unknown key returns itself, so a typo is visible on the page instead of
|
||||
rendering as nothing. */ -}}
|
||||
{{- $words := dict
|
||||
"time" (dict "es" "Hora" "de" "Uhrzeit" "pt-br" "Hora")
|
||||
"place" (dict "es" "Lugar" "de" "Ort" "pt-br" "Local")
|
||||
"add" (dict "es" "Añadir a mi calendario" "de" "Zum Kalender hinzufügen" "pt-br" "Adicionar ao meu calendário")
|
||||
"agenda" (dict "es" "Agenda" "de" "Termine" "pt-br" "Agenda")
|
||||
"today" (dict "es" "Hoy" "de" "Heute" "pt-br" "Hoje")
|
||||
"previous" (dict "es" "Mes anterior" "de" "Voriger Monat" "pt-br" "Mês anterior")
|
||||
"next" (dict "es" "Mes siguiente" "de" "Nächster Monat" "pt-br" "Próximo mês")
|
||||
"noevents" (dict "es" "No hay nada en este mes." "de" "In diesem Monat ist nichts geplant." "pt-br" "Nada marcado neste mês.")
|
||||
"allevents" (dict "es" "Todos los eventos" "de" "Alle Termine" "pt-br" "Todos os eventos")
|
||||
-}}
|
||||
{{- $entry := index $words .key -}}
|
||||
{{- if $entry -}}
|
||||
{{- index $entry .lang | default (index $entry "es") -}}
|
||||
{{- else -}}
|
||||
{{- .key -}}
|
||||
{{- end -}}
|
||||
Loading…
Reference in New Issue
Block a user