"""Logique du forum : toutes les actions passent par un contrôle de droits. Vocabulaire (Théo, 04/11/2026) : le Forum est la partie du site ; il contient des sujets. Le sujet fixe « Bulletin de la semaine du Vercors » est toujours épinglé en tête et fermé aux réponses. """ import hashlib import os import db import photos import roles TITRE_MAX, CORPS_MAX = 150, 20000 EPINGLES_MAX = 5 # sujet fixe compris PHOTOS_MAX, OCTETS_MAX = 10, 25 * 1024 * 1024 # par message, sauf propriétaires class Refus(Exception): """Action interdite (rôle insuffisant, sujet verrouillé...).""" class Invalide(Exception): """Données incorrectes ou objet introuvable.""" class Forum: def __init__(self, chemin=":memory:", stations=None, dossier_photos=None): self.con = db.connecter(chemin) self.stations = stations or {} # id -> nom affiché (pour le titre des sujets de station) self.dossier_photos = dossier_photos # --- utilisateurs et rôles ----------------------------------------- def utilisateur(self, hub_id, nom=None): """Retourne l'utilisateur lié à ce compte Gastinel (créé au besoin : il est d'office membre).""" if hub_id == db.SYSTEME: raise Invalide("identifiant réservé") r = self.con.execute("SELECT * FROM users WHERE hub_id=?", (hub_id,)).fetchone() if r is None: self.con.execute("INSERT INTO users(hub_id, display_name) VALUES (?, ?)", (hub_id, (nom or hub_id)[:60])) self.con.commit() r = self.con.execute("SELECT * FROM users WHERE hub_id=?", (hub_id,)).fetchone() elif nom and nom[:60] != r["display_name"]: # le pseudo suit celui du compte Gastinel self.con.execute("UPDATE users SET display_name=? WHERE id=?", (nom[:60], r["id"])) self.con.commit() r = self.con.execute("SELECT * FROM users WHERE id=?", (r["id"],)).fetchone() return r def roles_de(self, user): """Ensemble des rôles d'un utilisateur (None pour un visiteur).""" if user is None: return None rs = {roles.MEMBRE} rs |= {r["role"] for r in self.con.execute("SELECT role FROM user_roles WHERE user_id=?", (user["id"],))} return rs def stations_de(self, user): if user is None: return set() return {r["station"] for r in self.con.execute( "SELECT station FROM user_roles WHERE user_id=? AND role=?", (user["id"], roles.STATION))} def badges(self, user_id): """Badges affichés à côté du pseudo, dans l'ordre : [(rôle, libellé), ...].""" lignes = self.con.execute("SELECT role, station FROM user_roles WHERE user_id=?", (user_id,)).fetchall() out = [] for role in roles.ORDRE_BADGES: if role == roles.MEMBRE: if not out: out.append((role, roles.LIBELLES[role])) continue for l in lignes: if l["role"] == role: lib = roles.LIBELLES[role] if role == roles.STATION and l["station"]: lib += " · " + self.stations.get(l["station"], l["station"]) out.append((role, lib)) return out def _peut(self, user, droit): return roles.peut(self.roles_de(user), droit) def _exiger(self, user, droit): if not self._peut(user, droit): raise Refus(droit) def fixer_proprietaire(self, hub_id, nom=None): """Configuration (ligne de commande), jamais depuis l'interface : nomme le propriétaire du forum.""" u = self.utilisateur(hub_id, nom) self.con.execute("INSERT OR IGNORE INTO user_roles(user_id, role) VALUES (?, ?)", (u["id"], roles.PROPRIETAIRE)) self.con.commit() return u def _cible(self, hub_id): c = self.con.execute("SELECT * FROM users WHERE hub_id=?", (hub_id,)).fetchone() if c is None or hub_id == db.SYSTEME: raise Invalide("utilisateur inconnu") return c def donner_role(self, acteur, hub_id, role, station=""): if not roles.peut_donner(self.roles_de(acteur), role): raise Refus("donner le rôle %s" % role) if role == roles.STATION: if station not in self.stations: raise Invalide("station inconnue") else: station = "" cible = self._cible(hub_id) self.con.execute("INSERT OR IGNORE INTO user_roles(user_id, role, station, given_by) VALUES (?, ?, ?, ?)", (cible["id"], role, station, acteur["id"])) self.con.commit() def retirer_role(self, acteur, hub_id, role, station=""): if not roles.peut_donner(self.roles_de(acteur), role): raise Refus("retirer le rôle %s" % role) cible = self._cible(hub_id) self.con.execute("DELETE FROM user_roles WHERE user_id=? AND role=? AND station=?", (cible["id"], role, station if role == roles.STATION else "")) self.con.commit() # --- lecture ------------------------------------------------------- def _visible(self, user, t): """Un sujet masqué ou en attente n'est visible que des modérateurs, propriétaires et de son auteur (attente).""" if t is None: return False if t["hidden"] and not self._peut(user, "voir_masques"): return False if t["status"] != "publie": return self._peut(user, "valider_sujet") or (user is not None and t["author_id"] == user["id"]) return True def sujets(self, user): """Sujets : épinglés d'abord (le Bulletin en tête), puis les plus récents.""" voit = self._peut(user, "voir_masques") rows = self.con.execute( "SELECT t.*, u.display_name AS auteur," " (SELECT COUNT(*) FROM posts p WHERE p.topic_id=t.id AND (p.hidden=0 OR ?)) AS n," " (SELECT MAX(p.id) FROM posts p WHERE p.topic_id=t.id AND p.hidden=0) AS dernier" " FROM topics t JOIN users u ON u.id=t.author_id" " ORDER BY t.fixed DESC, t.pinned DESC, t.pin_pos, COALESCE(dernier, 0) DESC, t.id DESC", (int(voit),)).fetchall() return [r for r in rows if self._visible(user, r)] def sujet(self, user, topic_id): """Retourne (sujet, messages). Invisible = introuvable.""" t = self.con.execute("SELECT * FROM topics WHERE id=?", (topic_id,)).fetchone() if not self._visible(user, t): 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," " 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 def en_attente(self, user): self._exiger(user, "valider_sujet") return self.con.execute("SELECT t.*, u.display_name AS auteur FROM topics t JOIN users u ON u.id=t.author_id" " WHERE t.status='en_attente' ORDER BY t.id").fetchall() def photos_de(self, post_id): return self.con.execute("SELECT * FROM attachments WHERE post_id=? ORDER BY id", (post_id,)).fetchall() # --- écriture ------------------------------------------------------- @staticmethod def _texte(s, maxi, nom): s = (s or "").strip() if not s or len(s) > maxi: raise Invalide("%s vide ou trop long" % nom) return s def _nouveau_sujet(self, user, titre, corps, ip, status="publie", station=None): 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)) self.con.commit() return cur.lastrowid, post.lastrowid def creer_sujet(self, user, titre, corps, ip=None): """Adhérents et propriétaires (un membre écrit seulement dans les sujets existants).""" self._exiger(user, "creer_sujet") return self._nouveau_sujet(user, self._texte(titre, TITRE_MAX, "titre"), self._texte(corps, CORPS_MAX, "message"), ip)[0] def creer_sujet_station(self, user, station, corps, ip=None): """Propriétaire de station : un seul sujet pour sa station, titre préconfiguré, à valider.""" self._exiger(user, "creer_sujet_station") if station not in self.stations_de(user): raise Refus("ce n'est pas votre station") if self.con.execute("SELECT 1 FROM topics WHERE station=? AND status<>'refuse'", (station,)).fetchone(): raise Invalide("cette station a déjà son sujet") titre = "Station · " + self.stations.get(station, station) return self._nouveau_sujet(user, titre, self._texte(corps, CORPS_MAX, "message"), ip, "en_attente", station)[0] def valider_sujet(self, user, topic_id, accepte=True): self._exiger(user, "valider_sujet") t = self.con.execute("SELECT * FROM topics WHERE id=?", (topic_id,)).fetchone() if t is None or t["status"] != "en_attente": raise Invalide("rien à valider") self.con.execute("UPDATE topics SET status=? WHERE id=?", ("publie" if accepte else "refuse", topic_id)) self.con.commit() def repondre(self, user, topic_id, corps, ip=None): self._exiger(user, "repondre") t, _ = self.sujet(user, topic_id) if t["locked"]: raise Refus("sujet verrouillé") if t["status"] != "publie": raise Refus("sujet en attente de validation") if not t["replies_open"] and not self._peut(user, "publier_bulletin"): raise Refus("sujet fermé aux réponses") cur = self.con.execute("INSERT INTO posts(topic_id, author_id, body, ip) VALUES (?, ?, ?, ?)", (topic_id, user["id"], self._texte(corps, CORPS_MAX, "message"), ip)) self.con.commit() return cur.lastrowid def epingler(self, user, topic_id, epingle=True, position=None): """Jusqu'à EPINGLES_MAX sujets épinglés, Bulletin compris ; le Bulletin ne se désépingle pas.""" self._exiger(user, "epingler") t, _ = self.sujet(user, topic_id) if t["fixed"]: raise Refus("le Bulletin de la semaine reste épinglé") if epingle and not t["pinned"]: n = self.con.execute("SELECT COUNT(*) FROM topics WHERE pinned=1").fetchone()[0] if n >= EPINGLES_MAX: raise Refus("%d sujets épinglés au maximum" % EPINGLES_MAX) if position is None: position = (self.con.execute("SELECT COALESCE(MAX(pin_pos), 0) FROM topics WHERE pinned=1").fetchone()[0] + 1) self.con.execute("UPDATE topics SET pinned=?, pin_pos=? WHERE id=?", (int(epingle), max(1, int(position)) if epingle else 0, topic_id)) self.con.commit() def ajouter_photos(self, user, post_id, fichiers): """fichiers : [(nom, octets)]. 10 photos et 25 Mo par message, sauf propriétaires. Métadonnées retirées.""" p = self._post(post_id) if p["author_id"] != user["id"]: raise Refus("pas votre message") if not self.dossier_photos: raise Invalide("photos non configurées") deja = self.photos_de(post_id) if not self._peut(user, "photos_illimitees"): if len(deja) + len(fichiers) > PHOTOS_MAX: raise Refus("%d photos par message au maximum" % PHOTOS_MAX) if sum(a["size"] for a in deja) + sum(len(d) for _, d in fichiers) > OCTETS_MAX: raise Refus("25 Mo par message au maximum") prets = [] for nom, data in fichiers: # tout est vérifié avant d'écrire quoi que ce soit try: mime, propre = photos.nettoyer(data) except photos.PhotoInvalide as e: raise Invalide(str(e)) prets.append((os.path.basename(nom or "photo")[:80], mime, propre)) os.makedirs(self.dossier_photos, exist_ok=True) ids = [] for nom, mime, propre in prets: empreinte = hashlib.sha256(propre).hexdigest() chemin = os.path.join(self.dossier_photos, empreinte + photos.TYPES[mime]) if not os.path.exists(chemin): with open(chemin + ".tmp", "wb") as f: f.write(propre) os.replace(chemin + ".tmp", chemin) cur = self.con.execute("INSERT INTO attachments(post_id, filename, mime, size, sha256, stored_path)" " VALUES (?, ?, ?, ?, ?, ?)", (post_id, nom, mime, len(propre), empreinte, chemin)) ids.append(cur.lastrowid) self.con.commit() return ids def _post(self, post_id): p = self.con.execute("SELECT * FROM posts WHERE id=?", (post_id,)).fetchone() if p is None: raise Invalide("message introuvable") return p def modifier_message(self, user, post_id, corps): 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)) self.con.commit() def signaler(self, user, post_id, motif): self._exiger(user, "signaler") if self._post(post_id)["hidden"]: raise Invalide("message introuvable") self.con.execute("INSERT OR IGNORE INTO reports(post_id, reporter_id, reason) VALUES (?, ?, ?)", (post_id, user["id"], self._texte(motif, 500, "motif"))) self.con.commit() def signalements(self, user): self._exiger(user, "voir_signalements") return self.con.execute("SELECT r.*, p.body, p.topic_id FROM reports r JOIN posts p ON p.id=r.post_id" " ORDER BY r.id DESC").fetchall() def masquer_message(self, user, post_id, masque=True): self._exiger(user, "masquer") self._post(post_id) self.con.execute("UPDATE posts SET hidden=? WHERE id=?", (int(masque), post_id)) self.con.commit() def masquer_sujet(self, user, topic_id, masque=True): self._exiger(user, "masquer") t, _ = self.sujet(user, topic_id) if t["fixed"]: raise Refus("le Bulletin de la semaine ne se masque pas") self.con.execute("UPDATE topics SET hidden=? WHERE id=?", (int(masque), topic_id)) self.con.commit() def verrouiller(self, user, topic_id, verrou=True): self._exiger(user, "verrouiller") self.sujet(user, topic_id) self.con.execute("UPDATE topics SET locked=? WHERE id=?", (int(verrou), topic_id)) self.con.commit() # --- RGPD ---------------------------------------------------------- def purger_ips(self, mois=12): """Efface les adresses IP de plus de `mois` mois (obligation légale : un an). Retourne le nombre de lignes.""" cur = self.con.execute("UPDATE posts SET ip=NULL WHERE ip IS NOT NULL AND created_at < datetime('now', ?)", ("-%d months" % mois,)) self.con.commit() return cur.rowcount