diff --git a/forum/apercu.js b/forum/apercu.js index abcbd5e..759615f 100644 --- a/forum/apercu.js +++ b/forum/apercu.js @@ -111,3 +111,86 @@ document.querySelectorAll("a.copier-lien").forEach(function (a) { if (ev.key === "ArrowLeft") montrer(i - 1); }); })(); + +// Page « Publier » : barre Markdown, aperçu instantané (rendu par le serveur) et brouillon enregistré +// environ 1 s après l'arrêt de la frappe. Sans JavaScript : boutons « Mettre à jour l'aperçu » et « Enregistrer le brouillon ». +(function () { + var form = document.getElementById("form-publier"); + if (!form || !window.fetch) return; + var base = form.getAttribute("action").replace(/\/publier$/, ""); + var zone = form.querySelector("textarea[name=corps]"); + var vue = form.querySelector(".apercu-md"); + var etat = form.querySelector(".etat-brouillon"); + var cache = form.querySelector("input[name=brouillon]"); + var barre = form.querySelector(".barre-md"); + var sansJs = form.querySelector(".sans-js"); + if (sansJs) sansJs.hidden = true; + + function corpsFormulaire(champs) { + var p = new URLSearchParams(); + Object.keys(champs).forEach(function (k) { p.append(k, champs[k]); }); + return p; + } + + // Barre de mise en forme : insère la syntaxe autour de la sélection. + var outils = [ + ["Gras", "**", "**", "texte en gras"], + ["Italique", "*", "*", "texte en italique"], + ["Titre", "\n## ", "\n", "Titre"], + ["Liste", "\n- ", "\n- \n", "élément"], + ["Lien", "[", "](https://)", "texte du lien"], + ["Tableau", "\n| Colonne 1 | Colonne 2 |\n| --- | --- |\n| ", " | |\n", "valeur"] + ]; + outils.forEach(function (o) { + var b = document.createElement("button"); + b.type = "button"; + b.textContent = o[0]; + b.setAttribute("aria-label", "Insérer : " + o[0].toLowerCase()); + b.addEventListener("click", function () { + var d = zone.selectionStart, f = zone.selectionEnd; + var choix = zone.value.slice(d, f) || o[3]; + zone.setRangeText(o[1] + choix + o[2], d, f, "end"); + zone.focus(); + zone.setSelectionRange(d + o[1].length, d + o[1].length + choix.length); + zone.dispatchEvent(new Event("input", { bubbles: true })); + }); + barre.appendChild(b); + }); + barre.hidden = false; + + var minuteApercu = null, minuteBrouillon = null; + function apercu() { + fetch(base + "/apercu-md", { method: "POST", credentials: "same-origin", body: corpsFormulaire({ corps: zone.value }) }) + .then(function (r) { return r.ok ? r.text() : Promise.reject(); }) + .then(function (h) { vue.innerHTML = h || "
"; }) + .catch(function () {}); + } + function enregistrer() { + var titre = form.querySelector("input[name=titre]").value, corps = zone.value; + if (!cache.value && !titre.trim() && !corps.trim()) return; + var prevenir = form.querySelector("input[name=prevenir]"); + fetch(base + "/brouillon", { + method: "POST", credentials: "same-origin", + body: corpsFormulaire({ brouillon: cache.value, titre: titre, corps: corps, + station: form.querySelector("select[name=station]").value, prevenir: prevenir.checked ? "1" : "" }) + }).then(function (r) { return r.ok ? r.json() : Promise.reject(); }) + .then(function (d) { + if (!cache.value) { + cache.value = d.id; + history.replaceState(null, "", base + "/publier?brouillon=" + d.id); + } + etat.textContent = "Enregistré à " + d.heure; + }) + .catch(function () { etat.textContent = "Brouillon non enregistré (connexion perdue ?). Utilise « Enregistrer le brouillon »."; }); + } + form.addEventListener("input", function (ev) { + if (ev.target === zone) { clearTimeout(minuteApercu); minuteApercu = setTimeout(apercu, 300); } + if (ev.target.type === "file") return; + clearTimeout(minuteBrouillon); + minuteBrouillon = setTimeout(enregistrer, 1000); + }); + form.addEventListener("change", function (ev) { + if (ev.target.name === "station" || ev.target.name === "prevenir") { clearTimeout(minuteBrouillon); minuteBrouillon = setTimeout(enregistrer, 1000); } + }); + form.addEventListener("submit", function () { clearTimeout(minuteBrouillon); }); +})(); diff --git a/forum/db.py b/forum/db.py index ff453bf..b40d6fd 100644 --- a/forum/db.py +++ b/forum/db.py @@ -111,6 +111,17 @@ CREATE TABLE IF NOT EXISTS lectures ( dernier_post INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (user_id, topic_id) ); +-- Brouillons de la page « Publier » : privés, un auteur ne voit que les siens ; supprimés à la publication. +CREATE TABLE IF NOT EXISTS brouillons ( + id INTEGER PRIMARY KEY, + user_id INTEGER NOT NULL REFERENCES users(id), + titre TEXT NOT NULL DEFAULT '', + corps TEXT NOT NULL DEFAULT '', + station TEXT NOT NULL DEFAULT '', + prevenir INTEGER NOT NULL DEFAULT 0, + maj TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_brouillons_user ON brouillons(user_id, maj); CREATE UNIQUE INDEX IF NOT EXISTS idx_un_sujet_par_station ON topics(station) WHERE station IS NOT NULL AND status <> 'refuse'; """ @@ -126,6 +137,13 @@ def connecter(chemin=":memory:"): # 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 + if "format" not in {r[1] for r in con.execute("PRAGMA table_info(posts)")}: + con.execute("ALTER TABLE posts ADD COLUMN format TEXT NOT NULL DEFAULT 'texte'") # 'texte' ou 'md' (page Publier) + cols = {r[1] for r in con.execute("PRAGMA table_info(topics)")} + if "station_liee" not in cols: + con.execute("ALTER TABLE topics ADD COLUMN station_liee TEXT") # station citée (facultatif), distincte du sujet de station + if "prevenir" not in cols: + con.execute("ALTER TABLE topics ADD COLUMN prevenir INTEGER NOT NULL DEFAULT 0") # « Me prévenir des réponses » (enregistré, pas encore d'envoi) 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 1d6b6b9..30fa4f0 100644 --- a/forum/forum.py +++ b/forum/forum.py @@ -266,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, p.ancien_body," + "SELECT p.id, p.topic_id, p.author_id, p.body, p.created_at, p.edited_at, p.hidden, p.ancien_body, p.format," " 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 @@ -301,26 +301,79 @@ class Forum: raise Invalide("%s vide ou trop long" % nom) return s - def _nouveau_sujet(self, user, titre, corps, ip, status="publie", station=None, prets=()): + def _nouveau_sujet(self, user, titre, corps, ip, status="publie", station=None, prets=(), format_="texte", + station_liee=None, prevenir=False): # Les fichiers sont deja valides ; aucune publication partielle si le # stockage echoue. Des fichiers sans reference peuvent rester sur disque. with self.con: - cur = self.con.execute("INSERT INTO topics(title, author_id, status, station) VALUES (?, ?, ?, ?)", - (titre, user["id"], status, station)) - post = self.con.execute("INSERT INTO posts(topic_id, author_id, body, ip) VALUES (?, ?, ?, ?)", - (cur.lastrowid, user["id"], corps, ip)) + cur = self.con.execute("INSERT INTO topics(title, author_id, status, station, station_liee, prevenir) VALUES (?, ?, ?, ?, ?, ?)", + (titre, user["id"], status, station, station_liee, int(bool(prevenir)))) + post = self.con.execute("INSERT INTO posts(topic_id, author_id, body, ip, format) VALUES (?, ?, ?, ?, ?)", + (cur.lastrowid, user["id"], corps, ip, format_)) for nom, mime, propre in prets: empreinte, chemin = self._stocker(self.dossier_photos, mime, propre) self.con.execute("INSERT INTO attachments(post_id, filename, mime, size, sha256, stored_path) VALUES (?, ?, ?, ?, ?, ?)", (post.lastrowid, nom, mime, len(propre), empreinte, chemin)) return cur.lastrowid, post.lastrowid - def creer_sujet(self, user, titre, corps, ip=None, fichiers=()): - """Adherents et proprietaires ; photos validees avant creation du sujet.""" + def creer_sujet(self, user, titre, corps, ip=None, fichiers=(), format_="texte", station_liee="", prevenir=False, brouillon=None): + """Adherents et proprietaires ; photos validees avant creation du sujet. + Page « Publier » : format 'md', station citée facultative, brouillon supprimé après publication.""" self._exiger(user, "creer_sujet") titre, corps = self._texte(titre, TITRE_MAX, "titre"), self._texte(corps, CORPS_MAX, "message") + if format_ not in ("texte", "md"): + raise Invalide("format inconnu") + station_liee = self._station_facultative(station_liee) + if brouillon: + self.brouillon(user, brouillon) # le brouillon doit être à l'auteur prets = self._preparer_photos(list(fichiers), illimite=self._peut(user, "photos_illimitees")) if fichiers else [] - return self._nouveau_sujet(user, titre, corps, ip, prets=prets)[0] + tid = self._nouveau_sujet(user, titre, corps, ip, prets=prets, format_=format_, + station_liee=station_liee or None, prevenir=prevenir)[0] + if brouillon: + self.supprimer_brouillon(user, brouillon) + return tid + + # --- brouillons (page « Publier ») --------------------------------------- + def _station_facultative(self, station): + station = (station or "").strip() + if station and station not in self.stations: + raise Invalide("station inconnue") + return station + + def brouillon(self, user, brouillon_id): + """Brouillon de l'auteur ; celui d'un autre est introuvable.""" + if user is None: + raise Refus("connexion requise") + b = self.con.execute("SELECT * FROM brouillons WHERE id=? AND user_id=?", (int(brouillon_id), user["id"])).fetchone() + if b is None: + raise Invalide("brouillon introuvable") + return b + + def brouillons(self, user): + if user is None: + raise Refus("connexion requise") + return self.con.execute("SELECT * FROM brouillons WHERE user_id=? ORDER BY maj DESC, id DESC", (user["id"],)).fetchall() + + def enregistrer_brouillon(self, user, brouillon_id, titre, corps, station="", prevenir=False): + """Crée ou met à jour un brouillon de l'auteur ; retourne (id, maj).""" + self._exiger(user, "creer_sujet") + titre, corps = (titre or "")[:TITRE_MAX], (corps or "")[:CORPS_MAX] + station = self._station_facultative(station) + with self.con: + if brouillon_id: + self.brouillon(user, brouillon_id) + self.con.execute("UPDATE brouillons SET titre=?, corps=?, station=?, prevenir=?, maj=datetime('now') WHERE id=? AND user_id=?", + (titre, corps, station, int(bool(prevenir)), int(brouillon_id), user["id"])) + bid = int(brouillon_id) + else: + bid = self.con.execute("INSERT INTO brouillons(user_id, titre, corps, station, prevenir) VALUES (?, ?, ?, ?, ?)", + (user["id"], titre, corps, station, int(bool(prevenir)))).lastrowid + return bid, self.brouillon(user, bid)["maj"] + + def supprimer_brouillon(self, user, brouillon_id): + self.brouillon(user, brouillon_id) + with self.con: + self.con.execute("DELETE FROM brouillons WHERE id=? AND user_id=?", (int(brouillon_id), user["id"])) def creer_sujet_station(self, user, station, corps, ip=None): """Propriétaire de station : un seul sujet pour sa station, titre préconfiguré, à valider.""" diff --git a/forum/markdown_sur.py b/forum/markdown_sur.py new file mode 100644 index 0000000..fdcfa98 --- /dev/null +++ b/forum/markdown_sur.py @@ -0,0 +1,112 @@ +"""Convertisseur Markdown maison, volontairement réduit et sûr (aucune bibliothèque externe). + +Tout le texte est d'abord échappé (html.escape) : aucune balise de l'auteur ne passe. +On reconnaît ensuite : titres (#, ##, ###), gras (**x**), italique (*x* ou _x_), listes (- * ou 1.), +liens [texte](http(s)://…) seulement, code en ligne (`x`), paragraphes et tableaux (syntaxe pipe). +""" +import html +import re + +CODE = re.compile(r"`([^`\n]+)`") +LIEN = re.compile(r"\[([^\]\n]+)\]\(([^)\s]+)\)") +URL_OK = re.compile(r"^https?://[^\s\x00]+$", re.I) +GRAS = re.compile(r"\*\*(?=\S)(.+?)(?<=\S)\*\*") +ITALIQUE = re.compile(r"(? HTML en ligne (le code est protégé des autres règles).""" + codes = [] + + def garder(m): + codes.append("%s" % m.group(1))
+ return "\x00%d\x00" % (len(codes) - 1)
+
+ t = CODE.sub(garder, t)
+
+ def lien(m):
+ texte, url = m.group(1), html.unescape(m.group(2))
+ if not URL_OK.match(url):
+ return m.group(0) # javascript:, data:, relatif… : laissé en texte
+ return "%s" % (html.escape(url, quote=True), texte)
+
+ t = LIEN.sub(lien, t)
+ t = GRAS.sub(r"\1", t)
+ t = ITALIQUE.sub(lambda m: "%s" % (m.group(1) or m.group(2)), t)
+ return re.sub("\x00(\\d+)\x00", lambda m: codes[int(m.group(1))], t)
+
+
+def _cellules(ligne):
+ ligne = ligne.strip()
+ if ligne.startswith("|"):
+ ligne = ligne[1:]
+ if ligne.endswith("|"):
+ ligne = ligne[:-1]
+ return [c.strip() for c in ligne.split("|")]
+
+
+def _alignements(sep):
+ out = []
+ for c in _cellules(sep):
+ g, d = c.startswith(":"), c.endswith(":")
+ out.append(" class='centre'" if g and d else " class='droite'" if d else "")
+ return out
+
+
+def rendu(texte):
+ """Markdown -> HTML sûr."""
+ lignes = html.escape((texte or "").replace("\r\n", "\n").replace("\r", "\n"), quote=True).split("\n")
+ out, para, i = [], [], 0
+
+ def fermer_para():
+ if para:
+ out.append("%s
" % "| %s | " % (al[k], _en_ligne(c)) for k, c in enumerate(tete)] + h.append("
|---|
| %s | " % (al[k], _en_ligne(c)) for k, c in enumerate(cs))) + i += 1 + h.append("
La création de sujets est réservée aux adhérents météo. Demander à devenir adhérent · C’est gratuit.
" def liste(self, user, filtre="", stations_seules=False, tri="activite", media="", page=1): @@ -800,11 +836,104 @@ class Handler(BaseHTTPRequestHandler): radios("tri", choix, tri), radios("media", medias, media), "q=" + e(filtre) if filtre else "")) - def nouveau(self, user): - if not roles.peut(self.app.forum.roles_de(user), "creer_sujet"): - return self.page("Nouveau sujet", "Une observation, une question ou un récit : donne un titre précis et partage ce que tu as remarqué.
Une observation, une question ou un récit : donne un titre précis et partage ce que tu as remarqué.
" + "Tes sujets en cours d’écriture. Toi seul les vois ; ils disparaissent une fois publiés.
"] + if q.get("suite", [""])[0] == "supprime": + out.append("Brouillon supprimé.
") + if not bs: + out.append(etat_vide("Aucun brouillon pour le moment.")) + else: + out.append("Les adhérents ouvrent des sujets et publient le Bulletin de la semaine. " "C'est gratuit : présente-toi, montre tes photos ou ce que tu observes, le propriétaire te répond.
"] if roles.ADHERENT in f.roles_de(user): - out.append("Tu es déjà adhérent météo. Ouvrir un sujet
") + out.append("Tu es déjà adhérent météo. Ouvrir un sujet
") return self.page("Devenir adhérent", "".join(out), user) d = f.ma_demande_adhesion(user) if d is not None and d["status"] == "en_attente": @@ -1014,7 +1145,11 @@ class Handler(BaseHTTPRequestHandler): q = parse_qs(u.query) return self.liste(user, filtre, stations_seules=True, tri=q.get("tri", [""])[0], media=q.get("media", [""])[0], page=entier(q.get("page", ["1"])[0])) if u.path == "/nouveau": - return self.nouveau(user) + return self.rediriger("/publier") + if u.path == "/publier": + return self.publier(user, parse_qs(u.query)) + if u.path == "/brouillons": + return self.page_brouillons(user, parse_qs(u.query)) if u.path == "/profil": return self.profil(user) m = re.fullmatch(r"/t/(\d+)", u.path) @@ -1064,6 +1199,17 @@ class Handler(BaseHTTPRequestHandler): if user is None: raise Refus("connexion requise") d, fichiers = self.lire_formulaire(user) + if chemin == "/publier": + return self.publier_post(user, d, fichiers, ip) + if chemin == "/brouillon": # enregistrement automatique (apercu.js) : réponse JSON + bid, maj = f.enregistrer_brouillon(user, entier(d.get("brouillon", ""), 0), d.get("titre"), d.get("corps"), + d.get("station", ""), d.get("prevenir") == "1") + return self.envoyer(200, json.dumps({"id": bid, "heure": heure_fr(maj)}, ensure_ascii=False), "application/json; charset=utf-8") + if chemin == "/apercu-md": # aperçu instantané : même rendu que l'affichage + return self.envoyer(200, markdown_sur.rendu(d.get("corps", "")[:CORPS_MAX])) + if chemin == "/brouillon/supprimer": + f.supprimer_brouillon(user, entier(d.get("brouillon", ""), 0)) + return self.rediriger("/brouillons?suite=supprime") if chemin == "/sujet": return self.rediriger("/t/%d" % f.creer_sujet(user, d.get("titre"), d.get("corps"), ip, fichiers=fichiers)) if chemin == "/station": diff --git a/forum/tests/test_ameliorations.py b/forum/tests/test_ameliorations.py index 247f235..fa5e1ae 100644 --- a/forum/tests/test_ameliorations.py +++ b/forum/tests/test_ameliorations.py @@ -142,7 +142,7 @@ class TestApercu(base.BaseHTTP): self.assertEqual(st, 200) self.assertIn("javascript", h["Content-Type"]) self.assertIn(b"Aper", corps) - st, h, page = self.req("/nouveau", "a1") + st, h, page = self.req("/publier", "a1") self.assertIn("", page.decode()) self.assertIn("script-src 'self'", h["Content-Security-Policy"]) self.assertIn("script-src 'self';", h["Content-Security-Policy"]) diff --git a/forum/tests/test_forum.py b/forum/tests/test_forum.py index 3de61a5..231b5c0 100644 --- a/forum/tests/test_forum.py +++ b/forum/tests/test_forum.py @@ -786,12 +786,12 @@ class TestPrefixe(BaseHTTP): self.assertEqual(st, 200, chemin) b = b.decode() self.assertIn("action='/forum/deconnexion'", b) - self.assertIn("href='/forum/nouveau'", b) + self.assertIn("href='/forum/publier'", b) self.assertIn("href='/forum/'", b) self.assertNotIn("href='/'", b) self.assertNotIn("action='/sujet'", b) - formulaire = self.req("/forum/nouveau", "a1")[2].decode() - self.assertIn("action='/forum/sujet'", formulaire) + formulaire = self.req("/forum/publier", "a1")[2].decode() + self.assertIn("action='/forum/publier'", formulaire) self.assertNotIn("action='/sujet'", formulaire) b = self.req("/forum/")[2].decode() self.assertIn("href='/forum/connexion/gastinel'", b) diff --git a/forum/tests/test_publier.py b/forum/tests/test_publier.py new file mode 100644 index 0000000..d2f8b0f --- /dev/null +++ b/forum/tests/test_publier.py @@ -0,0 +1,155 @@ +"""Page « Publier » : Markdown sûr, tableaux, brouillons privés, publication (vrai HTTP local, SQLite jetable).""" +import json +import re +import unittest +from urllib.parse import urlencode + +import test_forum as base +import markdown_sur +from forum import Invalide + + +class TestMarkdown(unittest.TestCase): + def test_html_echappe_et_liens_surs(self): + h = markdown_sur.rendu("\n