diff --git a/apps/board/app.py b/apps/board/app.py index bdb1a09..03138ad 100644 --- a/apps/board/app.py +++ b/apps/board/app.py @@ -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" @@ -114,6 +114,9 @@ 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(): diff --git a/apps/board/home.py b/apps/board/home.py index 4328da1..8683d1f 100644 --- a/apps/board/home.py +++ b/apps/board/home.py @@ -122,7 +122,7 @@ 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")}, ] diff --git a/apps/board/members.py b/apps/board/members.py index 5998273..446e9b1 100644 --- a/apps/board/members.py +++ b/apps/board/members.py @@ -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__) @@ -224,23 +225,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, - (SELECT COUNT(*) FROM threads t - WHERE t.author_id = m.id AND t.deleted_at IS NULL) AS posts + 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, + ({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_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(): @@ -338,7 +407,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) @@ -351,10 +420,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//estado", methods=["POST"]) @@ -366,7 +435,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//rol", methods=["POST"]) @@ -390,7 +459,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//transferir", methods=["POST"]) @@ -399,10 +468,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//eliminar", methods=["POST"]) diff --git a/apps/board/messages.py b/apps/board/messages.py index 5637d9f..19ac6f7 100644 --- a/apps/board/messages.py +++ b/apps/board/messages.py @@ -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,141 +95,148 @@ def unread_count() -> int: ).fetchone()["n"] +def unread_sql(me: str = ":me", other: str = "m.id") -> str: + """How many unread messages the signed-in member has from `other`. + + 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 = msg.conversation_id AND mine.member_id = {me} + JOIN conversation_members theirs + 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) + """ + + +def history(other_id: int) -> dict: + """The conversation with `other_id`, and the fact of having read it. + + 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. + """ + db = get_db() + blocked = blocked_between(g.member["id"], other_id) + conversation_id = existing_conversation(other_id) + if conversation_id is None: + return {"messages": [], "images": {}, "blocked": blocked} + + rows = db.execute( + """SELECT m.*, a.display_name AS author, + a.gitea_login AS author_login, + a.profile_published AS author_published + FROM messages m JOIN members a ON a.id = m.author_id + WHERE m.conversation_id = ? AND m.deleted_at IS NULL + ORDER BY m.created_at""", + (conversation_id,), + ).fetchall() + db.execute( + """UPDATE conversation_members SET last_read_at = datetime('now') + 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, + } + + +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(): - 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 - JOIN conversation_members mine - ON mine.conversation_id = c.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() + """Kept as a redirect, not deleted. - # 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. + 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("messages.talk", - member_id=request.args.get("member_id", type=int) or 0)) + return redirect(url_for("members.index")) -@bp.route("/privados/con/", methods=["GET", "POST"]) +@bp.route("/privados/con/") +@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/", methods=["POST"]) @login_required def talk(member_id: int): - """One page for a conversation, whether or not it exists yet. + """Send one message. The reading half is `history()`, on the member page. - 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. + 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) - other = get_db().execute( + 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) - blocked = blocked_between(g.member["id"], member_id) - if blocked and request.method == "POST": + if blocked_between(g.member["id"], member_id): abort(403) - db = get_db() - conversation_id = existing_conversation(member_id) + 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)) - 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. - 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") - - rows = [] - if conversation_id is not None: - rows = db.execute( - """SELECT m.*, a.display_name AS author, - a.gitea_login AS author_login, - a.profile_published AS author_published - FROM messages m JOIN members a ON a.id = m.author_id - WHERE m.conversation_id = ? AND m.deleted_at IS NULL - ORDER BY m.created_at""", - (conversation_id,), - ).fetchall() - db.execute( - """UPDATE conversation_members SET last_read_at = datetime('now') - WHERE conversation_id = ? AND member_id = ?""", - (conversation_id, g.member["id"]), - ) - - 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, + # 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/", 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/", 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)) diff --git a/apps/board/static/board.css b/apps/board/static/board.css index ffd393c..92e1e92 100644 --- a/apps/board/static/board.css +++ b/apps/board/static/board.css @@ -511,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; @@ -532,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); diff --git a/apps/board/templates/_person.html b/apps/board/templates/_person.html index 9044858..e4d0c0e 100644 --- a/apps/board/templates/_person.html +++ b/apps/board/templates/_person.html @@ -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 -%} -{{ name }} + 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/, + 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 -%} +{{ name }} {%- else -%} {{ name }} {%- endif -%} diff --git a/apps/board/templates/base.html b/apps/board/templates/base.html index 100544d..77f18eb 100644 --- a/apps/board/templates/base.html +++ b/apps/board/templates/base.html @@ -36,17 +36,23 @@ {% if g.member %}