Forum : page « Publier » (éditeur Markdown sûr, aperçu, brouillons)
- Bouton « Publier » dans l'en-tête (droit creer_sujet) ; /nouveau redirige vers /publier.
- /publier en pleine largeur : titre, station liée facultative, photos, « Me prévenir des
réponses » (enregistré seulement), emplacement « Catégorie » marqué bientôt.
- markdown_sur.py : convertisseur maison (HTML échappé d'abord, liens http(s) seulement,
titres, gras, italique, listes, code, paragraphes, tableaux pipe).
- posts.format ('texte' par défaut, 'md' depuis /publier) ; topics.station_liee et prevenir.
- Brouillons privés (table brouillons) : enregistrement auto ~1 s après la frappe
(apercu.js), bouton sans JS, page « Mes brouillons », suppression à la publication.
- Tests : tests/test_publier.py ; tests existants mis à jour pour /publier.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Cette révision appartient à :
1 Parent
7b7be84fdf
révision
c0d43e4e59
9 fichiers modifiés
+600
-30
Aucun fichier ne correspond à votre recherche
@@ -111,3 +111,86 @@ document.querySelectorAll("a.copier-lien").forEach(function (a) {
|
|||||||
if (ev.key === "ArrowLeft") montrer(i - 1);
|
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 || "<p class='meta'>L’aperçu de ton message s’affiche ici.</p>"; })
|
||||||
|
.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); });
|
||||||
|
})();
|
||||||
@@ -111,6 +111,17 @@ CREATE TABLE IF NOT EXISTS lectures (
|
|||||||
dernier_post INTEGER NOT NULL DEFAULT 0,
|
dernier_post INTEGER NOT NULL DEFAULT 0,
|
||||||
PRIMARY KEY (user_id, topic_id)
|
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';
|
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)
|
# 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)")}:
|
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("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"))
|
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:
|
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]
|
sid = con.execute("SELECT id FROM users WHERE hub_id=?", (SYSTEME,)).fetchone()[0]
|
||||||
|
|||||||
+62
-9
@@ -266,7 +266,7 @@ class Forum:
|
|||||||
raise Invalide("sujet introuvable")
|
raise Invalide("sujet introuvable")
|
||||||
voit = self._peut(user, "voir_masques")
|
voit = self._peut(user, "voir_masques")
|
||||||
msgs = self.con.execute(
|
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"
|
" 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()
|
" WHERE p.topic_id=? AND (p.hidden=0 OR ?) ORDER BY p.id", (topic_id, int(voit))).fetchall()
|
||||||
return t, msgs
|
return t, msgs
|
||||||
@@ -301,26 +301,79 @@ class Forum:
|
|||||||
raise Invalide("%s vide ou trop long" % nom)
|
raise Invalide("%s vide ou trop long" % nom)
|
||||||
return s
|
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
|
# Les fichiers sont deja valides ; aucune publication partielle si le
|
||||||
# stockage echoue. Des fichiers sans reference peuvent rester sur disque.
|
# stockage echoue. Des fichiers sans reference peuvent rester sur disque.
|
||||||
with self.con:
|
with self.con:
|
||||||
cur = self.con.execute("INSERT INTO topics(title, author_id, status, station) VALUES (?, ?, ?, ?)",
|
cur = self.con.execute("INSERT INTO topics(title, author_id, status, station, station_liee, prevenir) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
(titre, user["id"], status, station))
|
(titre, user["id"], status, station, station_liee, int(bool(prevenir))))
|
||||||
post = self.con.execute("INSERT INTO posts(topic_id, author_id, body, ip) VALUES (?, ?, ?, ?)",
|
post = self.con.execute("INSERT INTO posts(topic_id, author_id, body, ip, format) VALUES (?, ?, ?, ?, ?)",
|
||||||
(cur.lastrowid, user["id"], corps, ip))
|
(cur.lastrowid, user["id"], corps, ip, format_))
|
||||||
for nom, mime, propre in prets:
|
for nom, mime, propre in prets:
|
||||||
empreinte, chemin = self._stocker(self.dossier_photos, mime, propre)
|
empreinte, chemin = self._stocker(self.dossier_photos, mime, propre)
|
||||||
self.con.execute("INSERT INTO attachments(post_id, filename, mime, size, sha256, stored_path) VALUES (?, ?, ?, ?, ?, ?)",
|
self.con.execute("INSERT INTO attachments(post_id, filename, mime, size, sha256, stored_path) VALUES (?, ?, ?, ?, ?, ?)",
|
||||||
(post.lastrowid, nom, mime, len(propre), empreinte, chemin))
|
(post.lastrowid, nom, mime, len(propre), empreinte, chemin))
|
||||||
return cur.lastrowid, post.lastrowid
|
return cur.lastrowid, post.lastrowid
|
||||||
|
|
||||||
def creer_sujet(self, user, titre, corps, ip=None, fichiers=()):
|
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."""
|
"""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")
|
self._exiger(user, "creer_sujet")
|
||||||
titre, corps = self._texte(titre, TITRE_MAX, "titre"), self._texte(corps, CORPS_MAX, "message")
|
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 []
|
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):
|
def creer_sujet_station(self, user, station, corps, ip=None):
|
||||||
"""Propriétaire de station : un seul sujet pour sa station, titre préconfiguré, à valider."""
|
"""Propriétaire de station : un seul sujet pour sa station, titre préconfiguré, à valider."""
|
||||||
|
|||||||
@@ -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"(?<![\w*])\*(?=\S)(.+?)(?<=\S)\*(?![\w*])|(?<![\w])_(?=\S)(.+?)(?<=\S)_(?![\w])")
|
||||||
|
TITRE = re.compile(r"^(#{1,3})\s+(.+?)\s*#*\s*$")
|
||||||
|
PUCE = re.compile(r"^\s*[-*+]\s+(.*)$")
|
||||||
|
NUMERO = re.compile(r"^\s*\d{1,3}[.)]\s+(.*)$")
|
||||||
|
SEPARATEUR = re.compile(r"^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$")
|
||||||
|
|
||||||
|
|
||||||
|
def _en_ligne(t):
|
||||||
|
"""Texte déjà échappé -> HTML en ligne (le code est protégé des autres règles)."""
|
||||||
|
codes = []
|
||||||
|
|
||||||
|
def garder(m):
|
||||||
|
codes.append("<code>%s</code>" % 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 "<a href='%s' rel='nofollow noopener noreferrer'>%s</a>" % (html.escape(url, quote=True), texte)
|
||||||
|
|
||||||
|
t = LIEN.sub(lien, t)
|
||||||
|
t = GRAS.sub(r"<strong>\1</strong>", t)
|
||||||
|
t = ITALIQUE.sub(lambda m: "<em>%s</em>" % (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("<p>%s</p>" % "<br>".join(_en_ligne(x) for x in para))
|
||||||
|
para.clear()
|
||||||
|
|
||||||
|
while i < len(lignes):
|
||||||
|
l = lignes[i]
|
||||||
|
if not l.strip():
|
||||||
|
fermer_para()
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
m = TITRE.match(l)
|
||||||
|
if m:
|
||||||
|
fermer_para()
|
||||||
|
n = len(m.group(1)) + 1 # # -> h2 (le h1 est le titre du sujet)
|
||||||
|
out.append("<h%d>%s</h%d>" % (n, _en_ligne(m.group(2)), n))
|
||||||
|
i += 1
|
||||||
|
continue
|
||||||
|
if "|" in l and i + 1 < len(lignes) and SEPARATEUR.match(lignes[i + 1]) and "|" in lignes[i + 1]:
|
||||||
|
fermer_para()
|
||||||
|
tete, al = _cellules(l), _alignements(lignes[i + 1])
|
||||||
|
larg = len(tete)
|
||||||
|
al = (al + [""] * larg)[:larg]
|
||||||
|
h = ["<div class='tableau'><table><thead><tr>"]
|
||||||
|
h += ["<th%s>%s</th>" % (al[k], _en_ligne(c)) for k, c in enumerate(tete)]
|
||||||
|
h.append("</tr></thead><tbody>")
|
||||||
|
i += 2
|
||||||
|
while i < len(lignes) and lignes[i].strip() and "|" in lignes[i]:
|
||||||
|
cs = (_cellules(lignes[i]) + [""] * larg)[:larg]
|
||||||
|
h.append("<tr>%s</tr>" % "".join("<td%s>%s</td>" % (al[k], _en_ligne(c)) for k, c in enumerate(cs)))
|
||||||
|
i += 1
|
||||||
|
h.append("</tbody></table></div>")
|
||||||
|
out.append("".join(h))
|
||||||
|
continue
|
||||||
|
for motif, balise in ((PUCE, "ul"), (NUMERO, "ol")):
|
||||||
|
if motif.match(l):
|
||||||
|
fermer_para()
|
||||||
|
items = []
|
||||||
|
while i < len(lignes) and motif.match(lignes[i]):
|
||||||
|
items.append("<li>%s</li>" % _en_ligne(motif.match(lignes[i]).group(1)))
|
||||||
|
i += 1
|
||||||
|
out.append("<%s>%s</%s>" % (balise, "".join(items), balise))
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
para.append(l.strip())
|
||||||
|
i += 1
|
||||||
|
fermer_para()
|
||||||
|
return "\n".join(out)
|
||||||
+161
-15
@@ -32,9 +32,10 @@ from urllib.parse import parse_qs, urlparse
|
|||||||
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||||
import connexion # noqa: E402
|
import connexion # noqa: E402
|
||||||
|
import markdown_sur # noqa: E402
|
||||||
import roles # noqa: E402
|
import roles # noqa: E402
|
||||||
from db import SYSTEME # noqa: E402
|
from db import SYSTEME # noqa: E402
|
||||||
from forum import FICHE_PHOTOS_MAX, OCTETS_MAX, PHOTOS_MAX, SESSION_JOURS, ETAT_MINUTES, Forum, Invalide, Refus # noqa: E402
|
from forum import CORPS_MAX, TITRE_MAX, FICHE_PHOTOS_MAX, OCTETS_MAX, PHOTOS_MAX, SESSION_JOURS, ETAT_MINUTES, Forum, Invalide, Refus # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
MOIS_FR = ("janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc.")
|
MOIS_FR = ("janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.", "déc.")
|
||||||
@@ -238,6 +239,26 @@ details.ancien{margin:10px 0 0;color:var(--gris)}details.ancien summary{cursor:p
|
|||||||
.modifier textarea{min-height:160px}
|
.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}
|
.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}
|
.bouton-apercu{margin-right:8px}
|
||||||
|
.haut .droite{display:flex;align-items:center;gap:14px;flex-wrap:wrap}.haut .publier{margin:0;font-size:16px}
|
||||||
|
.message.md{white-space:normal}.message.md>:first-child{margin-top:0}.message.md>:last-child{margin-bottom:0}
|
||||||
|
.message.md h2,.message.md h3,.message.md h4{margin:18px 0 8px}.message.md h2{font-size:24px}.message.md h3{font-size:20px}.message.md h4{font-size:17px;font-family:Bitter,Georgia,serif;color:var(--sapin)}
|
||||||
|
.message.md code{background:var(--calcaire);border:1px solid var(--pierre);padding:0 4px;font-size:.92em}
|
||||||
|
.tableau{overflow-x:auto;margin:12px 0}.tableau table{border-collapse:collapse;min-width:50%}
|
||||||
|
.tableau th,.tableau td{border:1px solid #a5afa1;padding:6px 10px;text-align:left;vertical-align:top}.tableau th{background:#edf1e9;color:var(--sapin)}
|
||||||
|
.tableau .centre{text-align:center}.tableau .droite{text-align:right}
|
||||||
|
.publier-page{max-width:none}.publier-page h1{max-width:none}
|
||||||
|
.publier-grille{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,260px),1fr));gap:0 24px}
|
||||||
|
.editeur{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,420px),1fr));gap:16px;align-items:stretch}
|
||||||
|
.editeur textarea{min-height:420px;font-family:ui-monospace,Consolas,monospace;font-size:15px}
|
||||||
|
.barre-md{display:flex;flex-wrap:wrap;gap:4px;margin:0 0 6px}.barre-md button{min-height:38px;padding:4px 12px;font-size:15px;margin:0}
|
||||||
|
.label-apercu{margin:20px 0 3px}
|
||||||
|
.apercu-md{border:1px dashed var(--sapin);background:#fafbf8;padding:16px 18px;min-height:420px;overflow-wrap:anywhere}
|
||||||
|
.bientot{color:var(--gris)}.bientot select{background:var(--calcaire);width:100%}.publier-grille select{width:100%}
|
||||||
|
.case{display:flex;gap:10px;align-items:center;font-weight:400}.case input{width:auto;margin:0;min-height:0}
|
||||||
|
.boutons-publier{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-top:24px}.formulaire .boutons-publier button{margin:0}
|
||||||
|
.etat-brouillon{color:var(--gris);font-size:15px;min-height:1.6em;margin:8px 0 0}
|
||||||
|
.brouillons{list-style:none;padding:0;margin:16px 0;display:grid;gap:12px}.brouillons li{background:#fff;border:1px solid #a5afa1;padding:16px 20px;display:flex;justify-content:space-between;gap:12px;flex-wrap:wrap;align-items:center}
|
||||||
|
.brouillons li form{margin:0}.brouillons .actions{margin:0;align-items:center}
|
||||||
@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)}}
|
@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)}}
|
||||||
|
|
||||||
"""
|
"""
|
||||||
@@ -269,6 +290,18 @@ def e(s):
|
|||||||
return html.escape(str(s), quote=True)
|
return html.escape(str(s), quote=True)
|
||||||
|
|
||||||
|
|
||||||
|
def heure_fr(sqlite_utc):
|
||||||
|
"""'2026-11-06 22:41:00' (UTC) -> '23 h 41' (heure de Paris)."""
|
||||||
|
return date_fr(sqlite_utc, True).rpartition(" à ")[2]
|
||||||
|
|
||||||
|
|
||||||
|
def corps_message(texte, format_):
|
||||||
|
"""Message affiché : Markdown sûr pour les messages de la page Publier, texte brut sinon."""
|
||||||
|
if format_ == "md":
|
||||||
|
return "<div class='message md'>%s</div>" % markdown_sur.rendu(texte)
|
||||||
|
return "<p class='message'>%s</p>" % e(texte)
|
||||||
|
|
||||||
|
|
||||||
def navigation(liens, actif, libelle):
|
def navigation(liens, actif, libelle):
|
||||||
return "<nav class='nav' aria-label='%s'>%s</nav>" % (
|
return "<nav class='nav' aria-label='%s'>%s</nav>" % (
|
||||||
e(libelle), "".join("<a href='%s'%s>%s</a>" % (e(url), " aria-current='page'" if actif == url else "", e(nom))
|
e(libelle), "".join("<a href='%s'%s>%s</a>" % (e(url), " aria-current='page'" if actif == url else "", e(nom))
|
||||||
@@ -563,6 +596,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
"<span>Connexion bientôt disponible</span>")
|
"<span>Connexion bientôt disponible</span>")
|
||||||
else:
|
else:
|
||||||
qui = self.menu_compte(user)
|
qui = self.menu_compte(user)
|
||||||
|
if roles.peut(f.roles_de(user), "creer_sujet"):
|
||||||
|
qui = "<div class='droite'><a class='bouton principal publier' href='/publier'>Publier</a>%s</div>" % qui
|
||||||
essai = ""
|
essai = ""
|
||||||
corps = ("<!doctype html><html lang='fr'><head><meta charset='utf-8'>"
|
corps = ("<!doctype html><html lang='fr'><head><meta charset='utf-8'>"
|
||||||
"<meta name='viewport' content='width=device-width,initial-scale=1'>"
|
"<meta name='viewport' content='width=device-width,initial-scale=1'>"
|
||||||
@@ -594,9 +629,10 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
gestion = "<a href='/gestion'>Espace gestion</a>" if self.liens_gestion(user) else ""
|
gestion = "<a href='/gestion'>Espace gestion</a>" if self.liens_gestion(user) else ""
|
||||||
return ("<details class='compte'><summary>%s<span class='qui'><b>%s</b><span class='gerer'>Gérer son compte</span></span></summary>"
|
return ("<details class='compte'><summary>%s<span class='qui'><b>%s</b><span class='gerer'>Gérer son compte</span></span></summary>"
|
||||||
"<div class='compte-menu'><div class='entete'>%s<b>%s</b></div>"
|
"<div class='compte-menu'><div class='entete'>%s<b>%s</b></div>"
|
||||||
"<a href='/profil'>Gérer votre compte</a><a href='/adhesion'>Adhésion météo</a>%s"
|
"<a href='/profil'>Gérer votre compte</a><a href='/adhesion'>Adhésion météo</a>%s%s"
|
||||||
"<form method='post' action='/deconnexion'><button>Se déconnecter</button></form></div></details>"
|
"<form method='post' action='/deconnexion'><button>Se déconnecter</button></form></div></details>"
|
||||||
% (rond, e(nom), rond.replace("class='rond'", "class='rond grand'"), e(nom), gestion))
|
% (rond, e(nom), rond.replace("class='rond'", "class='rond grand'"), e(nom),
|
||||||
|
"<a href='/brouillons'>Mes brouillons</a>" if roles.peut(self.app.forum.roles_de(user), "creer_sujet") else "", gestion))
|
||||||
|
|
||||||
def gestion(self, user):
|
def gestion(self, user):
|
||||||
liens = self.liens_gestion(user)
|
liens = self.liens_gestion(user)
|
||||||
@@ -718,7 +754,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
|
|
||||||
def invitation(self, user):
|
def invitation(self, user):
|
||||||
if roles.peut(self.app.forum.roles_de(user), "creer_sujet"):
|
if roles.peut(self.app.forum.roles_de(user), "creer_sujet"):
|
||||||
return "<a class='bouton principal' href='/nouveau'>Nouveau sujet</a>"
|
return "<a class='bouton principal' href='/publier'>Nouveau sujet</a>"
|
||||||
return "<p class='info'>La création de sujets est réservée aux adhérents météo. <a href='/adhesion'>Demander à devenir adhérent</a> · C’est gratuit.</p>"
|
return "<p class='info'>La création de sujets est réservée aux adhérents météo. <a href='/adhesion'>Demander à devenir adhérent</a> · C’est gratuit.</p>"
|
||||||
|
|
||||||
def liste(self, user, filtre="", stations_seules=False, tri="activite", media="", page=1):
|
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),
|
radios("tri", choix, tri), radios("media", medias, media),
|
||||||
"q=" + e(filtre) if filtre else ""))
|
"q=" + e(filtre) if filtre else ""))
|
||||||
|
|
||||||
def nouveau(self, user):
|
def publier(self, user, q, valeurs=None, message="", code=200):
|
||||||
if not roles.peut(self.app.forum.roles_de(user), "creer_sujet"):
|
"""Page « Publier » en pleine largeur : éditeur Markdown, aperçu, brouillons (sans JS : boutons Aperçu et Enregistrer)."""
|
||||||
return self.page("Nouveau sujet", "<h1>Ouvrir une discussion</h1>" + self.invitation(user), user, 403)
|
f = self.app.forum
|
||||||
limite = "10 photos, 25 Mo au total. Formats JPEG, PNG ou WebP." if not roles.peut(self.app.forum.roles_de(user), "photos_illimitees") else "Formats JPEG, PNG ou WebP. Ton rôle de propriétaire n’a pas la limite de 10 photos / 25 Mo (envoi total limité à 300 Mo)."
|
if not roles.peut(f.roles_de(user), "creer_sujet"):
|
||||||
self.page("Nouveau sujet", "<p><a href='/'>Retour aux sujets</a></p><section class='formulaire'><h1>Nouveau sujet</h1><p class='chapeau'>Une observation, une question ou un récit : donne un titre précis et partage ce que tu as remarqué.</p><div class='boite'><form method='post' action='/sujet' enctype='multipart/form-data'><label for='titre'>Titre du sujet</label><input type='text' id='titre' name='titre' maxlength='150' required placeholder='Ex. : Première gelée à Lans ce matin'><p class='meta'>150 caractères maximum.</p><label for='corps'>Ton message</label><textarea id='corps' name='corps' maxlength='20000' required></textarea><label for='photos'>Photos (facultatif)</label><input type='file' id='photos' name='photos' accept='image/jpeg,image/png,image/webp' multiple aria-describedby='limites'><p class='meta' id='limites'>%s La position GPS et les informations de l’appareil sont retirées.</p><button class='principal'>Publier le sujet</button> <a href='/'>Annuler</a></form></div></section>" % limite, user)
|
return self.page("Publier", "<h1>Ouvrir une discussion</h1>" + self.invitation(user), user, 403)
|
||||||
|
v = valeurs
|
||||||
|
if v is None:
|
||||||
|
v = {"brouillon": "", "titre": "", "corps": "", "station": "", "prevenir": False}
|
||||||
|
bid = entier(q.get("brouillon", [""])[0], 0)
|
||||||
|
if bid:
|
||||||
|
b = f.brouillon(user, bid)
|
||||||
|
v = {"brouillon": str(b["id"]), "titre": b["titre"], "corps": b["corps"], "station": b["station"], "prevenir": bool(b["prevenir"])}
|
||||||
|
if q.get("suite", [""])[0] == "enregistre":
|
||||||
|
message = "Enregistré à %s." % heure_fr(b["maj"])
|
||||||
|
limite = ("%d photos, %d Mo au total. Formats JPEG, PNG ou WebP." % (PHOTOS_MAX, OCTETS_MAX // 1048576)
|
||||||
|
if not roles.peut(f.roles_de(user), "photos_illimitees") else
|
||||||
|
"Formats JPEG, PNG ou WebP. Ton rôle de propriétaire n’a pas la limite de %d photos / %d Mo (envoi total limité à 300 Mo)." % (PHOTOS_MAX, OCTETS_MAX // 1048576))
|
||||||
|
options = "".join("<option value='%s'%s>%s</option>" % (e(k), " selected" if k == v["station"] else "", e(n))
|
||||||
|
for k, n in sorted(f.stations.items(), key=lambda kv: kv[1].lower()))
|
||||||
|
vue = markdown_sur.rendu(v["corps"]) if v["corps"].strip() else "<p class='meta'>L’aperçu de ton message s’affiche ici.</p>"
|
||||||
|
contenu = (
|
||||||
|
"<p class='meta chemin'><span><a href='/'>Tous les sujets</a> / Publier</span><a class='bouton' href='/brouillons'>Mes brouillons</a></p>"
|
||||||
|
"<section class='formulaire publier-page'><h1>Publier un sujet</h1>"
|
||||||
|
"<p class='chapeau'>Une observation, une question ou un récit : donne un titre précis et partage ce que tu as remarqué.</p>"
|
||||||
|
"<form class='boite' method='post' action='/publier' enctype='multipart/form-data' id='form-publier'>"
|
||||||
|
"<input type='hidden' name='brouillon' value='%s'>"
|
||||||
|
"<label for='titre'>Titre du sujet</label>"
|
||||||
|
"<input type='text' id='titre' name='titre' maxlength='%d' required value='%s' placeholder='Ex. : Première gelée à Lans ce matin' aria-describedby='aide-titre'>"
|
||||||
|
"<p class='meta' id='aide-titre'>%d caractères maximum.</p>"
|
||||||
|
"<div class='publier-grille'>"
|
||||||
|
"<div><label for='station'>Station liée (facultatif)</label><select id='station' name='station'><option value=''>Aucune station</option>%s</select></div>"
|
||||||
|
"<div class='bientot'><label for='categorie'>Catégorie <span class='etat'>bientôt</span></label>"
|
||||||
|
"<select id='categorie' disabled aria-describedby='aide-cat'><option>Pas encore disponible</option></select>"
|
||||||
|
"<p class='meta' id='aide-cat'>Les catégories arrivent bientôt.</p></div></div>"
|
||||||
|
"<div class='editeur'><div><label for='corps'>Ton message (Markdown)</label>"
|
||||||
|
"<div class='barre-md' role='toolbar' aria-label='Mise en forme du message' hidden></div>"
|
||||||
|
"<textarea id='corps' name='corps' maxlength='%d' required aria-describedby='aide-md'>%s</textarea>"
|
||||||
|
"<p class='meta' id='aide-md'>**gras**, *italique*, # titre, - liste, [lien](https://…), `code`, tableau : | col | col | puis | --- | --- |.</p></div>"
|
||||||
|
"<div><p class='label-apercu' id='titre-apercu'><b>Aperçu</b></p><section class='apercu-md message md' aria-labelledby='titre-apercu' aria-live='polite'>%s</section></div></div>"
|
||||||
|
"<label for='photos'>Photos (facultatif)</label>"
|
||||||
|
"<input type='file' id='photos' name='photos' accept='image/jpeg,image/png,image/webp' multiple aria-describedby='limites'>"
|
||||||
|
"<p class='meta' id='limites'>%s La position GPS et les informations de l’appareil sont retirées. Les photos ne sont pas gardées dans le brouillon.</p>"
|
||||||
|
"<label class='case'><input type='checkbox' name='prevenir' value='1'%s> Me prévenir des réponses</label>"
|
||||||
|
"<div class='boutons-publier'><button class='principal' name='action' value='publier'>Publier le sujet</button>"
|
||||||
|
"<button name='action' value='brouillon' formnovalidate>Enregistrer le brouillon</button>"
|
||||||
|
"<button name='action' value='apercu' formnovalidate class='sans-js'>Mettre à jour l’aperçu</button> <a href='/'>Annuler</a></div>"
|
||||||
|
"<p class='etat-brouillon' role='status'>%s</p>"
|
||||||
|
"</form></section>"
|
||||||
|
% (e(v["brouillon"]), TITRE_MAX, e(v["titre"]), TITRE_MAX, options, CORPS_MAX, e(v["corps"]), vue,
|
||||||
|
limite, " checked" if v["prevenir"] else "", e(message)))
|
||||||
|
self.page("Publier", contenu, user, code)
|
||||||
|
|
||||||
|
def publier_post(self, user, d, fichiers, ip):
|
||||||
|
f = self.app.forum
|
||||||
|
action = d.get("action", "publier")
|
||||||
|
bid = entier(d.get("brouillon", ""), 0)
|
||||||
|
prevenir = d.get("prevenir") == "1"
|
||||||
|
if action == "brouillon":
|
||||||
|
bid, _ = f.enregistrer_brouillon(user, bid, d.get("titre"), d.get("corps"), d.get("station", ""), prevenir)
|
||||||
|
return self.rediriger("/publier?brouillon=%d&suite=enregistre" % bid)
|
||||||
|
if not roles.peut(f.roles_de(user), "creer_sujet"):
|
||||||
|
raise Refus("publication réservée")
|
||||||
|
if bid:
|
||||||
|
f.brouillon(user, bid) # brouillon d'un autre : introuvable
|
||||||
|
v = {"brouillon": str(bid or ""), "titre": d.get("titre", "")[:TITRE_MAX], "corps": d.get("corps", "")[:CORPS_MAX],
|
||||||
|
"station": d.get("station", ""), "prevenir": prevenir}
|
||||||
|
if action == "apercu":
|
||||||
|
return self.publier(user, {}, v)
|
||||||
|
try:
|
||||||
|
tid = f.creer_sujet(user, d.get("titre"), d.get("corps"), ip, fichiers=fichiers, format_="md",
|
||||||
|
station_liee=d.get("station", ""), prevenir=prevenir, brouillon=bid or None)
|
||||||
|
except Invalide as ex:
|
||||||
|
return self.publier(user, {}, v, "Impossible de publier : %s. Choisis de nouveau les photos s’il y en avait." % ex, code=400)
|
||||||
|
return self.rediriger("/t/%d" % tid)
|
||||||
|
|
||||||
|
def page_brouillons(self, user, q):
|
||||||
|
f = self.app.forum
|
||||||
|
if user is None:
|
||||||
|
raise Refus("connexion requise")
|
||||||
|
bs = f.brouillons(user)
|
||||||
|
out = ["<h1>Mes brouillons</h1><p class='chapeau'>Tes sujets en cours d’écriture. Toi seul les vois ; ils disparaissent une fois publiés.</p>"]
|
||||||
|
if q.get("suite", [""])[0] == "supprime":
|
||||||
|
out.append("<p class='info' role='status'>Brouillon supprimé.</p>")
|
||||||
|
if not bs:
|
||||||
|
out.append(etat_vide("Aucun brouillon pour le moment."))
|
||||||
|
else:
|
||||||
|
out.append("<ul class='brouillons'>")
|
||||||
|
for b in bs:
|
||||||
|
nom = b["titre"] or "(sans titre)"
|
||||||
|
out.append("<li><div><b>%s</b><br><span class='meta'>Enregistré le %s</span></div><div class='actions'>"
|
||||||
|
"<a class='bouton principal' href='/publier?brouillon=%d'>Reprendre</a>"
|
||||||
|
"<form method='post' action='/brouillon/supprimer'><input type='hidden' name='brouillon' value='%d'>"
|
||||||
|
"<button class='danger' aria-label='Supprimer le brouillon %s'>Supprimer</button></form></div></li>"
|
||||||
|
% (e(nom), e(date_fr(b["maj"], True)), b["id"], b["id"], e(nom)))
|
||||||
|
out.append("</ul>")
|
||||||
|
if roles.peut(f.roles_de(user), "creer_sujet"):
|
||||||
|
out.append("<p><a class='bouton' href='/publier'>Nouveau sujet</a></p>")
|
||||||
|
self.page("Mes brouillons", "".join(out), user)
|
||||||
|
|
||||||
def profil(self, user):
|
def profil(self, user):
|
||||||
if user is None:
|
if user is None:
|
||||||
@@ -834,6 +963,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
f.noter_lecture(user, tid, max(m["id"] for m in msgs))
|
f.noter_lecture(user, tid, max(m["id"] for m in msgs))
|
||||||
if t["station"]:
|
if t["station"]:
|
||||||
out.append(self.encadre_station(t["station"]))
|
out.append(self.encadre_station(t["station"]))
|
||||||
|
elif t["station_liee"]:
|
||||||
|
out.append("<p class='meta'>Station liée : <b>%s</b></p>" % e(f.stations.get(t["station_liee"], t["station_liee"])))
|
||||||
fiche = None
|
fiche = None
|
||||||
if t["station"] and t["status"] == "publie" and f.peut_epingler_photo(user, t["station"]):
|
if t["station"] and t["status"] == "publie" and f.peut_epingler_photo(user, t["station"]):
|
||||||
fiche = f.photos_fiche_ids(t["station"])
|
fiche = f.photos_fiche_ids(t["station"])
|
||||||
@@ -861,12 +992,12 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
"<input type='hidden' name='etat' value='%d'><button>%s</button></form>"
|
"<input type='hidden' name='etat' value='%d'><button>%s</button></form>"
|
||||||
% (m["id"], 0 if m["hidden"] else 1, "Afficher" if m["hidden"] else "Masquer"))
|
% (m["id"], 0 if m["hidden"] else 1, "Afficher" if m["hidden"] else "Masquer"))
|
||||||
out.append("<article class='msg%s' id='message-%d'><aside><b>%s</b>%s<br><span class='meta'>%s%s</span>%s</aside>"
|
out.append("<article class='msg%s' id='message-%d'><aside><b>%s</b>%s<br><span class='meta'>%s%s</span>%s</aside>"
|
||||||
"<div class='corps'><p class='message'>%s</p>%s%s%s</div></article>"
|
"<div class='corps'>%s%s%s%s</div></article>"
|
||||||
% (" cache" if m["hidden"] else "", m["id"], e(m["auteur"]), self.badges(m["author_id"]), e(date_fr(m["created_at"], True)),
|
% (" cache" if m["hidden"] else "", m["id"], e(m["auteur"]), self.badges(m["author_id"]), e(date_fr(m["created_at"], True)),
|
||||||
"", "<br><span class='etat'>Masqué</span>" if m["hidden"] else "",
|
"", "<br><span class='etat'>Masqué</span>" if m["hidden"] else "",
|
||||||
e(m["body"]),
|
corps_message(m["body"], m["format"]),
|
||||||
("<details class='ancien'><summary>Modifié le %s · voir l’ancienne version</summary><p class='message'>%s</p></details>"
|
("<details class='ancien'><summary>Modifié le %s · voir l’ancienne version</summary>%s</details>"
|
||||||
% (e(date_fr(m["edited_at"], True)), e(m["ancien_body"] or "")) if m["edited_at"] else ""), gal,
|
% (e(date_fr(m["edited_at"], True)), corps_message(m["ancien_body"] or "", m["format"])) if m["edited_at"] else ""), gal,
|
||||||
"<div class='actions'>%s</div>" % (lien + outils)))
|
"<div class='actions'>%s</div>" % (lien + outils)))
|
||||||
gestion = []
|
gestion = []
|
||||||
if roles.peut(rs, "verrouiller") and not t["fixed"]:
|
if roles.peut(rs, "verrouiller") and not t["fixed"]:
|
||||||
@@ -906,7 +1037,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
"<p class='chapeau'>Les adhérents ouvrent des sujets et publient le Bulletin de la semaine. "
|
"<p class='chapeau'>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.</p>"]
|
"C'est gratuit : présente-toi, montre tes photos ou ce que tu observes, le propriétaire te répond.</p>"]
|
||||||
if roles.ADHERENT in f.roles_de(user):
|
if roles.ADHERENT in f.roles_de(user):
|
||||||
out.append("<p class='info'>Tu es déjà adhérent météo. <a href='/nouveau'>Ouvrir un sujet</a></p>")
|
out.append("<p class='info'>Tu es déjà adhérent météo. <a href='/publier'>Ouvrir un sujet</a></p>")
|
||||||
return self.page("Devenir adhérent", "".join(out), user)
|
return self.page("Devenir adhérent", "".join(out), user)
|
||||||
d = f.ma_demande_adhesion(user)
|
d = f.ma_demande_adhesion(user)
|
||||||
if d is not None and d["status"] == "en_attente":
|
if d is not None and d["status"] == "en_attente":
|
||||||
@@ -1014,7 +1145,11 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
q = parse_qs(u.query)
|
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]))
|
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":
|
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":
|
if u.path == "/profil":
|
||||||
return self.profil(user)
|
return self.profil(user)
|
||||||
m = re.fullmatch(r"/t/(\d+)", u.path)
|
m = re.fullmatch(r"/t/(\d+)", u.path)
|
||||||
@@ -1064,6 +1199,17 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
if user is None:
|
if user is None:
|
||||||
raise Refus("connexion requise")
|
raise Refus("connexion requise")
|
||||||
d, fichiers = self.lire_formulaire(user)
|
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":
|
if chemin == "/sujet":
|
||||||
return self.rediriger("/t/%d" % f.creer_sujet(user, d.get("titre"), d.get("corps"), ip, fichiers=fichiers))
|
return self.rediriger("/t/%d" % f.creer_sujet(user, d.get("titre"), d.get("corps"), ip, fichiers=fichiers))
|
||||||
if chemin == "/station":
|
if chemin == "/station":
|
||||||
|
|||||||
@@ -142,7 +142,7 @@ class TestApercu(base.BaseHTTP):
|
|||||||
self.assertEqual(st, 200)
|
self.assertEqual(st, 200)
|
||||||
self.assertIn("javascript", h["Content-Type"])
|
self.assertIn("javascript", h["Content-Type"])
|
||||||
self.assertIn(b"Aper", corps)
|
self.assertIn(b"Aper", corps)
|
||||||
st, h, page = self.req("/nouveau", "a1")
|
st, h, page = self.req("/publier", "a1")
|
||||||
self.assertIn("<script src='/apercu.js' defer></script>", page.decode())
|
self.assertIn("<script src='/apercu.js' defer></script>", page.decode())
|
||||||
self.assertIn("script-src 'self'", h["Content-Security-Policy"])
|
self.assertIn("script-src 'self'", h["Content-Security-Policy"])
|
||||||
self.assertIn("script-src 'self';", h["Content-Security-Policy"])
|
self.assertIn("script-src 'self';", h["Content-Security-Policy"])
|
||||||
@@ -786,12 +786,12 @@ class TestPrefixe(BaseHTTP):
|
|||||||
self.assertEqual(st, 200, chemin)
|
self.assertEqual(st, 200, chemin)
|
||||||
b = b.decode()
|
b = b.decode()
|
||||||
self.assertIn("action='/forum/deconnexion'", b)
|
self.assertIn("action='/forum/deconnexion'", b)
|
||||||
self.assertIn("href='/forum/nouveau'", b)
|
self.assertIn("href='/forum/publier'", b)
|
||||||
self.assertIn("href='/forum/'", b)
|
self.assertIn("href='/forum/'", b)
|
||||||
self.assertNotIn("href='/'", b)
|
self.assertNotIn("href='/'", b)
|
||||||
self.assertNotIn("action='/sujet'", b)
|
self.assertNotIn("action='/sujet'", b)
|
||||||
formulaire = self.req("/forum/nouveau", "a1")[2].decode()
|
formulaire = self.req("/forum/publier", "a1")[2].decode()
|
||||||
self.assertIn("action='/forum/sujet'", formulaire)
|
self.assertIn("action='/forum/publier'", formulaire)
|
||||||
self.assertNotIn("action='/sujet'", formulaire)
|
self.assertNotIn("action='/sujet'", formulaire)
|
||||||
b = self.req("/forum/")[2].decode()
|
b = self.req("/forum/")[2].decode()
|
||||||
self.assertIn("href='/forum/connexion/gastinel'", b)
|
self.assertIn("href='/forum/connexion/gastinel'", b)
|
||||||
|
|||||||
@@ -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("<script>alert(1)</script>\n<img src=x onerror=alert(1)>")
|
||||||
|
self.assertNotIn("<script", h)
|
||||||
|
self.assertNotIn("<img", h)
|
||||||
|
self.assertIn("<script>", h)
|
||||||
|
for piege in ("[clic](javascript:alert(1))", "[clic](JaVaScRiPt:alert(1))", "[x](data:text/html,a)",
|
||||||
|
"[x](/relatif)", "[x](https://a.fr\"onclick=alert(1))", "[x](https://a.fr'onmouseover='alert(1))"):
|
||||||
|
h = markdown_sur.rendu(piege)
|
||||||
|
self.assertNotIn("href='javascript", h.lower())
|
||||||
|
self.assertNotRegex(h, r"<a [^>]*\s(onclick|onmouseover)=")
|
||||||
|
self.assertNotIn("href='data", h)
|
||||||
|
self.assertNotIn("href='/", h)
|
||||||
|
h = markdown_sur.rendu("[Météo](https://vercors.me/?a=1&b=2)")
|
||||||
|
self.assertIn("<a href='https://vercors.me/?a=1&b=2' rel='nofollow noopener noreferrer'>Météo</a>", h)
|
||||||
|
|
||||||
|
def test_mise_en_forme(self):
|
||||||
|
h = markdown_sur.rendu("# Titre\n\n**gras** et *ita* et _ita2_ et `<b>code</b>`\nligne 2\n\n- un\n- deux\n\n1. a\n2. b")
|
||||||
|
self.assertIn("<h2>Titre</h2>", h)
|
||||||
|
self.assertIn("<strong>gras</strong>", h)
|
||||||
|
self.assertIn("<em>ita</em>", h)
|
||||||
|
self.assertIn("<em>ita2</em>", h)
|
||||||
|
self.assertIn("<code><b>code</b></code>", h)
|
||||||
|
self.assertIn("<br>ligne 2</p>", h)
|
||||||
|
self.assertIn("<ul><li>un</li><li>deux</li></ul>", h)
|
||||||
|
self.assertIn("<ol><li>a</li><li>b</li></ol>", h)
|
||||||
|
self.assertIn("<code>**pas gras**</code>", markdown_sur.rendu("`**pas gras**`"))
|
||||||
|
|
||||||
|
def test_tableaux(self):
|
||||||
|
h = markdown_sur.rendu("| Station | Tmin | Note |\n| --- | ---: | :-: |\n| Gêve | -4,2 | **gel** |\n| <i>x</i> | 1 |")
|
||||||
|
self.assertIn("<table>", h)
|
||||||
|
self.assertIn("<th>Station</th><th class='droite'>Tmin</th><th class='centre'>Note</th>", h)
|
||||||
|
self.assertIn("<td>Gêve</td><td class='droite'>-4,2</td><td class='centre'><strong>gel</strong></td>", h)
|
||||||
|
self.assertIn("<td><i>x</i></td><td class='droite'>1</td><td class='centre'></td>", h) # cellule manquante complétée
|
||||||
|
self.assertNotIn("<table>", markdown_sur.rendu("a | b\nc | d")) # sans ligne de séparation : texte
|
||||||
|
|
||||||
|
|
||||||
|
class TestPublier(base.BaseHTTP):
|
||||||
|
def post(self, chemin, qui, champs, **kw):
|
||||||
|
return self.req(chemin, qui, urlencode(champs).encode(), **kw)
|
||||||
|
|
||||||
|
def test_page_et_bouton_entete(self):
|
||||||
|
page = self.req("/publier", "a1")[2].decode()
|
||||||
|
self.assertIn("class='bouton principal publier' href='/publier'>Publier</a><details class='compte'>", page)
|
||||||
|
self.assertIn("href='/brouillons'>Mes brouillons</a>", page)
|
||||||
|
for libelle in ("for='titre'", "for='station'", "for='corps'", "for='photos'", "Me prévenir des réponses",
|
||||||
|
"Catégorie <span class='etat'>bientôt</span>", "Enregistrer le brouillon", "formnovalidate"):
|
||||||
|
self.assertIn(libelle, page)
|
||||||
|
self.assertNotRegex(page, r"name='prevenir' value='1' checked") # décochée par défaut
|
||||||
|
self.assertIn("Gêve", page) # liste des stations
|
||||||
|
self.assertEqual(self.req("/publier", "m1")[0], 403)
|
||||||
|
self.assertNotIn("href='/publier'", self.req("/", "m1")[2].decode())
|
||||||
|
self.assertNotIn("Mes brouillons", self.req("/", "m1")[2].decode())
|
||||||
|
|
||||||
|
def test_publication_markdown_et_brouillon_supprime(self):
|
||||||
|
st, _, b = self.post("/brouillon", "a1", {"titre": "Gel", "corps": "brouillon", "station": "geve"})
|
||||||
|
bid = json.loads(b)["id"]
|
||||||
|
self.assertRegex(json.loads(b)["heure"], r"^\d{1,2} h \d{2}$")
|
||||||
|
corps = "## Relevés\n\n| Station | Tmin |\n| --- | --- |\n| Gêve | -4 |\n\n<script>alert(1)</script> [x](javascript:alert(1))"
|
||||||
|
st, h, _ = self.post("/publier", "a1", {"brouillon": bid, "titre": "Gel <b>matinal</b>", "corps": corps,
|
||||||
|
"station": "geve", "prevenir": "1", "action": "publier"})
|
||||||
|
self.assertEqual(st, 303)
|
||||||
|
tid = int(re.search(r"/t/(\d+)", h["Location"]).group(1))
|
||||||
|
page = self.req(h["Location"])[2].decode()
|
||||||
|
self.assertIn("<div class='message md'><h3>Relevés</h3>", page)
|
||||||
|
self.assertIn("<td>Gêve</td><td>-4</td>", page)
|
||||||
|
self.assertNotIn("<script>alert", page)
|
||||||
|
self.assertNotIn("href='javascript", page)
|
||||||
|
self.assertIn("Gel <b>matinal</b>", page)
|
||||||
|
self.assertIn("Station liée : <b>", page)
|
||||||
|
t = self.f.con.execute("SELECT prevenir, station_liee FROM topics WHERE id=?", (tid,)).fetchone()
|
||||||
|
self.assertEqual((t[0], t[1]), (1, "geve"))
|
||||||
|
self.assertEqual(self.f.con.execute("SELECT format FROM posts WHERE topic_id=?", (tid,)).fetchone()[0], "md")
|
||||||
|
self.assertEqual(self.f.brouillons(self.adh), [])
|
||||||
|
# Les anciens messages (format texte) restent affichés tels quels
|
||||||
|
ancien = self.f.creer_sujet(self.adh, "Ancien", "**pas gras**\n<i>x</i>")
|
||||||
|
page = self.req("/t/%d" % ancien)[2].decode()
|
||||||
|
self.assertIn("<p class='message'>**pas gras**\n<i>x</i></p>", page)
|
||||||
|
|
||||||
|
def test_brouillons_prives(self):
|
||||||
|
bid, _ = self.f.enregistrer_brouillon(self.adh, 0, "SECRET_TITRE", "SECRET_CORPS")
|
||||||
|
self.assertIn("SECRET_TITRE", self.req("/brouillons", "a1")[2].decode())
|
||||||
|
self.assertIn("SECRET_CORPS", self.req("/publier?brouillon=%d" % bid, "a1")[2].decode())
|
||||||
|
for qui in ("theo", "pere"): # même le propriétaire ne voit pas le brouillon d'un autre
|
||||||
|
self.assertNotIn("SECRET_TITRE", self.req("/brouillons", qui)[2].decode())
|
||||||
|
st, _, b = self.req("/publier?brouillon=%d" % bid, qui)
|
||||||
|
self.assertEqual(st, 404)
|
||||||
|
self.assertNotIn("SECRET", b.decode())
|
||||||
|
self.assertEqual(self.post("/brouillon", qui, {"brouillon": bid, "titre": "pirate", "corps": "x"})[0], 400)
|
||||||
|
self.assertEqual(self.post("/brouillon/supprimer", qui, {"brouillon": bid})[0], 400)
|
||||||
|
self.assertEqual(self.post("/publier", qui, {"brouillon": bid, "titre": "t", "corps": "c", "action": "publier"})[0], 400)
|
||||||
|
self.assertEqual(self.req("/brouillons")[0], 403)
|
||||||
|
self.assertEqual(self.post("/brouillon", None, {"titre": "x"})[0], 403)
|
||||||
|
self.assertEqual(self.post("/brouillon", "m1", {"titre": "x"})[0], 403) # membre sans droit creer_sujet
|
||||||
|
self.assertEqual(self.f.brouillon(self.adh, bid)["titre"], "SECRET_TITRE")
|
||||||
|
with self.assertRaises(Invalide):
|
||||||
|
self.f.brouillon(self.theo, bid)
|
||||||
|
# contrôle d'origine, comme les autres POST
|
||||||
|
self.assertEqual(self.post("/brouillon", "a1", {"brouillon": bid, "titre": "x"}, origine=False)[0], 403)
|
||||||
|
self.assertEqual(self.f.brouillon(self.adh, bid)["titre"], "SECRET_TITRE")
|
||||||
|
|
||||||
|
def test_brouillon_sans_js_reprise_et_suppression(self):
|
||||||
|
st, h, _ = self.post("/publier", "a1", {"titre": "Neige", "corps": "début", "station": "geve", "action": "brouillon"})
|
||||||
|
self.assertEqual(st, 303)
|
||||||
|
self.assertRegex(h["Location"], r"^/publier\?brouillon=\d+&suite=enregistre$")
|
||||||
|
page = self.req(h["Location"], "a1")[2].decode()
|
||||||
|
self.assertRegex(page, r"Enregistré à \d{1,2} h \d{2}\.")
|
||||||
|
self.assertIn("value='Neige'", page)
|
||||||
|
self.assertIn("<option value='geve' selected>", page)
|
||||||
|
bid = int(h["Location"].split("=")[1].split("&")[0])
|
||||||
|
# mise à jour du même brouillon, puis aperçu sans JS
|
||||||
|
self.post("/publier", "a1", {"brouillon": bid, "titre": "Neige fraîche", "corps": "**10 cm**", "action": "brouillon"})
|
||||||
|
self.assertEqual(len(self.f.brouillons(self.adh)), 1)
|
||||||
|
st, _, b = self.post("/publier", "a1", {"brouillon": bid, "titre": "Neige fraîche", "corps": "**10 cm**", "action": "apercu"})
|
||||||
|
self.assertEqual(st, 200)
|
||||||
|
self.assertIn("<strong>10 cm</strong>", b.decode())
|
||||||
|
page = self.req("/brouillons", "a1")[2].decode()
|
||||||
|
self.assertIn("href='/publier?brouillon=%d'>Reprendre</a>" % bid, page)
|
||||||
|
self.assertEqual(self.post("/brouillon/supprimer", "a1", {"brouillon": bid})[0], 303)
|
||||||
|
self.assertIn("Aucun brouillon", self.req("/brouillons", "a1")[2].decode())
|
||||||
|
|
||||||
|
def test_apercu_instantane_et_validation(self):
|
||||||
|
st, _, b = self.post("/apercu-md", "a1", {"corps": "<script>x</script>| a | b |\n|---|---|\n| 1 | 2 |"})
|
||||||
|
self.assertEqual(st, 200)
|
||||||
|
self.assertNotIn("<script>", b.decode())
|
||||||
|
self.assertIn("<td>1</td><td>2</td>", b.decode())
|
||||||
|
self.assertEqual(self.post("/apercu-md", "a1", {"corps": "x"}, origine=False)[0], 403)
|
||||||
|
st, _, b = self.post("/publier", "a1", {"titre": "Sans corps", "corps": " ", "action": "publier"})
|
||||||
|
self.assertEqual(st, 400)
|
||||||
|
self.assertIn("value='Sans corps'", b.decode()) # rien n'est perdu
|
||||||
|
self.assertEqual(self.post("/publier", "a1", {"titre": "t", "corps": "c", "station": "inconnue", "action": "publier"})[0], 400)
|
||||||
|
# photos : même validation que creer_sujet
|
||||||
|
corps = (b'--P\r\nContent-Disposition: form-data; name="titre"\r\n\r\nPhoto\r\n'
|
||||||
|
b'--P\r\nContent-Disposition: form-data; name="corps"\r\n\r\nTexte\r\n'
|
||||||
|
b'--P\r\nContent-Disposition: form-data; name="photos"; filename="x.png"\r\nContent-Type: image/png\r\n\r\ninvalide\r\n--P--\r\n')
|
||||||
|
self.assertEqual(self.req("/publier", "a1", corps, "multipart/form-data; boundary=P")[0], 400)
|
||||||
|
corps = corps.replace(b"invalide", base.png())
|
||||||
|
st, h, _ = self.req("/publier", "a1", corps, "multipart/form-data; boundary=P")
|
||||||
|
self.assertEqual(st, 303)
|
||||||
|
self.assertIn("/photo/", self.req(h["Location"])[2].decode())
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -15,8 +15,11 @@ class TestUX(base.BaseHTTP):
|
|||||||
# connecté : le pseudo mène au compte.
|
# connecté : le pseudo mène au compte.
|
||||||
self.assertNotIn(">Stations</a>",b.decode())
|
self.assertNotIn(">Stations</a>",b.decode())
|
||||||
self.assertEqual("href='/profil'" in b.decode(), qui is not None)
|
self.assertEqual("href='/profil'" in b.decode(), qui is not None)
|
||||||
self.assertEqual("href='/nouveau'" in b.decode(),autorise)
|
# Bouton « Publier » de l'en-tête (remplace /nouveau, gardé en redirection)
|
||||||
self.assertEqual(self.req('/nouveau',qui)[0],200 if autorise else 403)
|
self.assertEqual("href='/publier'" in b.decode(),autorise)
|
||||||
|
self.assertEqual(self.req('/publier',qui)[0],200 if autorise else 403)
|
||||||
|
st,h,_=self.req('/nouveau',qui)
|
||||||
|
self.assertEqual((st,h['Location']),(303,'/publier'))
|
||||||
if not autorise:
|
if not autorise:
|
||||||
self.assertIn('Demander à devenir adhérent',b.decode())
|
self.assertIn('Demander à devenir adhérent',b.decode())
|
||||||
for route in ('/profil','/stations','/adhesion'):
|
for route in ('/profil','/stations','/adhesion'):
|
||||||
|
|||||||
Référencer dans un nouveau ticket
Bloquer un utilisateur