diff --git a/forum/apercu.js b/forum/apercu.js new file mode 100644 index 0000000..77c28fe --- /dev/null +++ b/forum/apercu.js @@ -0,0 +1,65 @@ +// Aperçu avant publication (nouveau sujet, réponse) : texte et photos choisies, sans rien envoyer. +// Facultatif : sans JavaScript, les formulaires marchent comme avant. +document.querySelectorAll("form[action$='/sujet'], form[action$='/repondre']").forEach(function (form) { + var zone = form.querySelector("textarea[name=corps]"); + var envoi = form.querySelector("button:not([type=button])"); + if (!zone || !envoi) return; + var titre = form.querySelector("input[name=titre]"); + var fichiers = form.querySelector("input[type=file]"); + var bouton = document.createElement("button"); + bouton.type = "button"; + bouton.className = "bouton-apercu"; + bouton.textContent = "Aperçu"; + bouton.setAttribute("aria-expanded", "false"); + var vue = document.createElement("section"); + vue.className = "apercu"; + vue.hidden = true; + vue.setAttribute("aria-live", "polite"); + envoi.parentNode.insertBefore(bouton, envoi); + envoi.parentNode.insertBefore(vue, bouton); + var urls = []; + + function dessiner() { + urls.forEach(URL.revokeObjectURL); + urls = []; + vue.textContent = ""; + var tete = document.createElement("p"); + tete.className = "apercu-tete"; + tete.textContent = "Aperçu : rien n'est encore publié"; + vue.appendChild(tete); + if (titre && titre.value.trim()) { + var h = document.createElement("h3"); + h.textContent = titre.value.trim(); + vue.appendChild(h); + } + var p = document.createElement("p"); + p.className = "message"; + p.textContent = zone.value.trim() || "(message vide)"; + vue.appendChild(p); + if (fichiers && fichiers.files.length) { + var gal = document.createElement("div"); + gal.className = "galerie"; + Array.prototype.slice.call(fichiers.files, 0, 20).forEach(function (f) { + if (!/^image\/(jpeg|png|webp)$/.test(f.type)) return; + var img = document.createElement("img"); + var u = URL.createObjectURL(f); + urls.push(u); + img.src = u; + img.alt = f.name; + gal.appendChild(img); + }); + vue.appendChild(gal); + } + } + + bouton.addEventListener("click", function () { + var ouvrir = vue.hidden; + if (ouvrir) dessiner(); + vue.hidden = !ouvrir; + bouton.textContent = ouvrir ? "Fermer l'aperçu" : "Aperçu"; + bouton.setAttribute("aria-expanded", String(ouvrir)); + }); + [zone, titre, fichiers].forEach(function (champ) { + if (champ) champ.addEventListener(champ.type === "file" ? "change" : "input", function () { if (!vue.hidden) dessiner(); }); + }); +}); diff --git a/forum/db.py b/forum/db.py index ef7f623..ff453bf 100644 --- a/forum/db.py +++ b/forum/db.py @@ -123,6 +123,9 @@ def connecter(chemin=":memory:"): con.row_factory = sqlite3.Row con.execute("PRAGMA foreign_keys = ON") con.executescript(SCHEMA) + # migrations douces (colonnes ajoutées après la mise en ligne) + if "ancien_body" not in {r[1] for r in con.execute("PRAGMA table_info(posts)")}: + con.execute("ALTER TABLE posts ADD COLUMN ancien_body TEXT") # version d'avant l'unique modification con.execute("INSERT OR IGNORE INTO users(hub_id, display_name) VALUES (?, ?)", (SYSTEME, "vercors.me")) if con.execute("SELECT 1 FROM topics WHERE fixed=1").fetchone() is None: sid = con.execute("SELECT id FROM users WHERE hub_id=?", (SYSTEME,)).fetchone()[0] diff --git a/forum/forum.py b/forum/forum.py index 340f6d5..1d6b6b9 100644 --- a/forum/forum.py +++ b/forum/forum.py @@ -18,6 +18,7 @@ FICHE_PHOTOS_MAX = 3 # photos épinglées sur la fiche publiqu PHOTOS_MAX, OCTETS_MAX = 10, 25 * 1024 * 1024 # par message, sauf propriétaires (et par demande d'adhésion) ADHESION_MAX = 4000 # longueur du message d'une demande d'adhésion SESSION_JOURS, ETAT_MINUTES = 30, 10 +MODIF_JOURS = 7 # un message se modifie une fois, pendant une semaine class Refus(Exception): @@ -203,7 +204,7 @@ class Forum: return self._peut(user, "valider_sujet") or (user is not None and t["author_id"] == user["id"]) return True - TRIS = ("activite", "recents", "anciens", "longs", "courts") + TRIS = ("activite", "recents", "anciens", "messages", "photos", "medias", "longs", "courts") def sujets(self, user, tri="activite", media=""): """Sujets : épinglés d'abord (le Bulletin en tête), puis selon `tri` : @@ -211,7 +212,9 @@ class Forum: `media` : « avec » ou « sans » photos. Pour un compte, `nouveau` = messages pas encore lus.""" voit = self._peut(user, "voir_masques") ordre = {"activite": "COALESCE(dernier, 0) DESC, t.id DESC", "recents": "t.id DESC", "anciens": "t.id ASC", - "longs": "COALESCE(taille, 0) DESC, t.id DESC", "courts": "COALESCE(taille, 0) ASC, t.id DESC"}.get(tri, "COALESCE(dernier, 0) DESC, t.id DESC") + "longs": "COALESCE(taille, 0) DESC, t.id DESC", "courts": "COALESCE(taille, 0) ASC, t.id DESC", + "messages": "n DESC, COALESCE(dernier, 0) DESC", "photos": "nb_photos DESC, COALESCE(dernier, 0) DESC", + "medias": "COALESCE(dernier_media, 0) DESC, COALESCE(dernier, 0) DESC"}.get(tri, "COALESCE(dernier, 0) DESC, t.id DESC") uid = user["id"] if user is not None else 0 rows = self.con.execute( "SELECT t.*, u.display_name AS auteur, u.hub_id AS auteur_hub," @@ -219,6 +222,8 @@ class Forum: " (SELECT MAX(p.id) FROM posts p WHERE p.topic_id=t.id AND p.hidden=0) AS dernier," " (SELECT LENGTH(p.body) FROM posts p WHERE p.topic_id=t.id AND p.hidden=0 ORDER BY p.id LIMIT 1) AS taille," " EXISTS(SELECT 1 FROM attachments a JOIN posts p ON p.id=a.post_id WHERE p.topic_id=t.id AND p.hidden=0) AS media," + " (SELECT COUNT(*) FROM attachments a JOIN posts p ON p.id=a.post_id WHERE p.topic_id=t.id AND p.hidden=0) AS nb_photos," + " (SELECT MAX(a.id) FROM attachments a JOIN posts p ON p.id=a.post_id WHERE p.topic_id=t.id AND p.hidden=0) AS dernier_media," " EXISTS(SELECT 1 FROM posts p JOIN users me ON me.id=? WHERE p.topic_id=t.id AND p.hidden=0 AND p.author_id<>me.id" " AND p.created_at >= me.created_at" " AND p.id > COALESCE((SELECT l.dernier_post FROM lectures l WHERE l.user_id=me.id AND l.topic_id=t.id), 0)) AS nouveau" @@ -261,7 +266,7 @@ class Forum: raise Invalide("sujet introuvable") voit = self._peut(user, "voir_masques") msgs = self.con.execute( - "SELECT p.id, p.topic_id, p.author_id, p.body, p.created_at, p.edited_at, p.hidden," + "SELECT p.id, p.topic_id, p.author_id, p.body, p.created_at, p.edited_at, p.hidden, p.ancien_body," " u.display_name AS auteur FROM posts p JOIN users u ON u.id=p.author_id" " WHERE p.topic_id=? AND (p.hidden=0 OR ?) ORDER BY p.id", (topic_id, int(voit))).fetchall() return t, msgs @@ -323,9 +328,11 @@ class Forum: if station not in self.stations_de(user): raise Refus("ce n'est pas votre station") corps = self._texte(corps, CORPS_MAX, "message") - t = self.con.execute("SELECT t.id, u.hub_id FROM topics t JOIN users u ON u.id=t.author_id" + t = self.con.execute("SELECT t.id, t.locked, t.hidden, u.hub_id FROM topics t JOIN users u ON u.id=t.author_id" " WHERE t.station=? AND t.status<>'refuse'", (station,)).fetchone() if t is not None and t["hub_id"] == db.SYSTEME: + if t["locked"] or t["hidden"]: # décision de modération : pas de reprise + raise Refus("sujet verrouillé ou masqué") # Sujet créé d'office : le propriétaire (rôle déjà validé) le reprend avec sa présentation. with self.con: self.con.execute("UPDATE topics SET author_id=? WHERE id=?", (user["id"], t["id"])) @@ -501,14 +508,29 @@ class Forum: raise Invalide("message introuvable") return p + def peut_modifier(self, user, p): + """Son propre message, visible, jamais modifié, de moins de 7 jours, dans un sujet ouvert.""" + if user is None or p["author_id"] != user["id"] or p["hidden"] or p["edited_at"]: + return False + if not self._peut(user, "modifier_son_message"): + return False + t = self.con.execute("SELECT locked, hidden FROM topics WHERE id=?", (p["topic_id"],)).fetchone() + if t is None or t["locked"] or t["hidden"]: + return False + return bool(self.con.execute("SELECT ? >= datetime('now', ?)", (p["created_at"], "-%d days" % MODIF_JOURS)).fetchone()[0]) + def modifier_message(self, user, post_id, corps): + """Une seule modification, pendant MODIF_JOURS jours ; l'ancienne version reste consultable.""" self._exiger(user, "modifier_son_message") p = self._post(post_id) - if p["author_id"] != user["id"] or p["hidden"]: - raise Refus("pas votre message") - self.con.execute("UPDATE posts SET body=?, edited_at=datetime('now') WHERE id=?", - (self._texte(corps, CORPS_MAX, "message"), post_id)) + if not self.peut_modifier(user, p): + raise Refus("modification impossible") + corps = self._texte(corps, CORPS_MAX, "message") + cur = self.con.execute("UPDATE posts SET ancien_body=body, body=?, edited_at=datetime('now')" + " WHERE id=? AND edited_at IS NULL", (corps, post_id)) self.con.commit() + if cur.rowcount != 1: + raise Refus("déjà modifié") def signaler(self, user, post_id, motif): self._exiger(user, "signaler") diff --git a/forum/server.py b/forum/server.py index e0bd4d5..fe15827 100644 --- a/forum/server.py +++ b/forum/server.py @@ -215,6 +215,11 @@ input[type=file]::file-selector-button{font:inherit;padding:6px;border:1px solid .stations .sujet-extrait{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;margin:6px 0 8px;font-size:15px} .stations .sujet-lien>.meta{display:none} .tri .actions{align-items:center}.tri .actions .bouton,.tri .actions button{margin:0} +.pages{display:flex;justify-content:space-between;align-items:center;gap:12px;margin:8px 0 24px;color:var(--gris)} +details.ancien{margin:10px 0 0;color:var(--gris)}details.ancien summary{cursor:pointer;font-size:14px}details.ancien .message{border-left:3px solid var(--pierre);padding-left:12px;margin-top:6px} +.modifier textarea{min-height:160px} +.apercu{border:1px dashed var(--sapin);background:#fafbf8;padding:16px 18px;margin:16px 0}.apercu-tete{margin:0 0 8px;color:var(--sapin);font-weight:600}.apercu h3{margin:0 0 8px} +.bouton-apercu{margin-right:8px} @media(max-width:640px){main{padding:20px 16px 40px}.haut{padding:20px 16px;gap:16px}.haut .moi{width:100%}h1{font-size:32px}h2{font-size:24px}.hero{align-items:stretch;flex-direction:column;gap:16px}.hero .bouton{text-align:center}.nav{gap:4px}.nav a{padding:8px 10px}.sujet-lien{padding:18px}.sujet-titre{font-size:21px}.sujet-meta{display:grid;gap:4px}.boite,.fiche{padding:18px}.msg{grid-template-columns:minmax(0,1fr)}.msg aside,.msg .corps{padding:18px}.haut .gastinel{padding:8px}.grille{grid-template-columns:minmax(0,1fr)}} """ @@ -280,6 +285,13 @@ def heure_paris(epoch): return d.hour, d.minute +PAR_PAGE = 10 + + +def entier(texte, defaut=1): + return int(texte) if (texte or "").isdigit() and len(texte) < 6 else defaut + + def etat_vide(message): return "
%s
" % e(message) @@ -502,7 +514,7 @@ class Handler(BaseHTTPRequestHandler): self.send_header("Content-Type", type_) self.send_header("Content-Length", str(len(data))) self.send_header("Content-Security-Policy", - "default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; font-src 'self'; form-action 'self'; frame-ancestors 'none'") + "default-src 'none'; style-src 'unsafe-inline'; script-src 'self'; img-src 'self' blob:; font-src 'self'; form-action 'self'; frame-ancestors 'none'") self.send_header("X-Content-Type-Options", "nosniff") self.send_header("Referrer-Policy", "same-origin") for k, v in extra: @@ -554,7 +566,7 @@ class Handler(BaseHTTPRequestHandler): "Aller au contenu" "