"""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 re import secrets import threading import db import photos import profil as profil_mod import roles TITRE_MAX, CORPS_MAX = 150, 20000 EPINGLES_MAX = 5 # sujet fixe compris FICHE_PHOTOS_MAX = 3 # photos épinglées sur la fiche publique d'une station 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 # SESSION_JOURS : durée du cookie (« se souvenir »), pas de la session # Session en base : 1 h au plus, comme le jeton du Hub. Au-delà, le forum repasse par le Hub (sans clic si la # session Gastinel est toujours valable) : un ban, un changement de mot de passe ou des jetons révoqués côté Hub # coupent donc le forum en 1 h au plus. SESSION_MINUTES = 60 MODIF_JOURS = 7 # un message se modifie une fois, pendant une semaine COMMENTAIRE_MAX = 500 # commentaire sous une réponse : texte simple, liens cliquables, pas de photo # Réactions (clé -> libellé), dans l'ordre d'affichage. Pictos SVG dans server.py (REACTIONS_SVG). REACTIONS = {"soleil": "Merci", "flocon": "Superbe", "sommet": "Bravo", "oeil": "Vu aussi", "eclair": "Impressionnant", "goutte": "Dommage"} def nom_sql(u="u"): """Nom affiché d'un auteur (SQL) : username du profil public, sinon « Membre » ; jamais le nom du compte Gastinel, sauf pour les comptes d'avant le profil public (profil NULL). Compte supprimé : « Ancien membre ».""" return ("(CASE WHEN {u}.supprime=1 THEN 'Ancien membre' WHEN {u}.profil IS NULL THEN {u}.display_name" " WHEN {u}.profil='public' AND {u}.username IS NOT NULL THEN {u}.username" " WHEN {u}.profil='prive' THEN 'Membre privé' ELSE 'Membre' END)").format(u=u) def nom_public(u): """Même règle que nom_sql, pour une ligne de la table users.""" if u["supprime"]: return "Ancien membre" if u["profil"] is None: return u["display_name"] if u["profil"] == "public" and u["username"]: return u["username"] return "Membre privé" if u["profil"] == "prive" else "Membre" ROLES_VISIBLES_SANS_COMPTE = {roles.MODERATEUR, roles.ADHERENT, roles.STATION, roles.PROPRIETAIRE, roles.ADJOINT} PLUS_TARD_MAX = 3 PLUS_TARD_HEURES = 20 # une « connexion » de plus : au moins 20 h après le dernier « Plus tard » 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, proprietaire_id=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 self.proprietaire_id = proprietaire_id or None # id Gastinel de Théo (FORUM_PROPRIETAIRE_ID) self.apres_roles = None # fonction(hub_id, roles) : envoie les rôles au Hub (branchée par server.py) self.version = 0 # augmente à chaque changement visible sur les fiches de station (cache de server.py) def _pousser_roles(self, hub_id): if not self.apres_roles: return c = self.con.execute("SELECT id FROM users WHERE hub_id=?", (hub_id,)).fetchone() if c is None: return rs = [r[0] for r in self.con.execute("SELECT role FROM user_roles WHERE user_id=?", (c[0],))] threading.Thread(target=self.apres_roles, args=(hub_id, rs), daemon=True).start() # --- connexion Gastinel et sessions ---------------------------------- @staticmethod def _hache(s): return hashlib.sha256(s.encode("utf-8")).hexdigest() def connexion_gastinel(self, hub_id, pseudo): """Après « Se connecter avec Gastinel » : crée ou met à jour le compte ; le propriétaire configuré reçoit son rôle.""" avant = self.con.execute("SELECT id, supprime FROM users WHERE hub_id=?", (hub_id,)).fetchone() u = self.utilisateur(hub_id, pseudo) if avant is None or avant["supprime"]: # Nouveau compte (ou compte supprimé qui revient) : écran de bienvenue, aucun profil choisi. self.con.execute("UPDATE users SET bienvenue=0, profil='attente', supprime=0, plus_tard=0, plus_tard_le=NULL" " WHERE id=?", (u["id"],)) self.con.commit() u = self.con.execute("SELECT * FROM users WHERE id=?", (u["id"],)).fetchone() if self.proprietaire_id and hub_id == self.proprietaire_id: u = self.fixer_proprietaire(hub_id, pseudo) self._pousser_roles(hub_id) return u def ouvrir_session(self, user, jours=None, portee=""): """Retourne l'identifiant aléatoire à mettre dans le cookie ; seul son haché est stocké. `portee` (ex. « panneau ») sépare les sessions : un jeton du forum ne vaut rien dans le panneau, et inversement. Sans `jours` : SESSION_MINUTES (cf. plus haut).""" jeton = secrets.token_urlsafe(32) duree = "+%d minutes" % SESSION_MINUTES if jours is None else "+%d days" % jours self.con.execute("DELETE FROM sessions WHERE expires_at < datetime('now')") self.con.execute("INSERT INTO sessions(id_hache, user_id, expires_at) VALUES (?, ?, datetime('now', ?))", (self._hache(portee + ":" + jeton), user["id"], duree)) self.con.commit() return jeton def utilisateur_de_session(self, jeton, portee=""): if not jeton: return None return self.con.execute("SELECT u.* FROM sessions s JOIN users u ON u.id=s.user_id" " WHERE s.id_hache=? AND s.expires_at > datetime('now')", (self._hache(portee + ":" + jeton),)).fetchone() def fermer_session(self, jeton, portee=""): self.con.execute("DELETE FROM sessions WHERE id_hache=?", (self._hache(portee + ":" + (jeton or "")),)) self.con.commit() def noter_etat(self, etat, verifier): """Mémorise une demande de connexion (state -> code_verifier PKCE).""" self.con.execute("DELETE FROM oauth_etats WHERE created_at < datetime('now', ?)", ("-%d minutes" % ETAT_MINUTES,)) self.con.execute("INSERT INTO oauth_etats(etat_hache, verifier) VALUES (?, ?)", (self._hache(etat), verifier)) self.con.commit() def prendre_etat(self, etat): """Usage unique : retourne le code_verifier si le state est connu et récent, sinon None.""" h = self._hache(etat or "") r = self.con.execute("SELECT verifier FROM oauth_etats WHERE etat_hache=? AND created_at >= datetime('now', ?)", (h, "-%d minutes" % ETAT_MINUTES)).fetchone() self.con.execute("DELETE FROM oauth_etats WHERE etat_hache=?", (h,)) self.con.commit() return r["verifier"] if r else None # --- utilisateurs et rôles ----------------------------------------- def utilisateur_existant(self, hub_id): """Le compte lié à cet identifiant s'il existe déjà, sans le créer (panneau : aucune inscription).""" return self.con.execute("SELECT * FROM users WHERE hub_id=? AND hub_id<>?", (hub_id, db.SYSTEME)).fetchone() def tous_les_utilisateurs(self, acteur): self._exiger(acteur, "gerer_roles") return self.con.execute("SELECT * FROM users WHERE hub_id<>? ORDER BY display_name COLLATE NOCASE", (db.SYSTEME,)).fetchall() 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() self._pousser_roles(hub_id) 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() self._pousser_roles(hub_id) # --- 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 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` : activite (dernier message), recents / anciens (création), longs / courts (taille du premier message). `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", "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.*, " + nom_sql() + " AS auteur, u.hub_id AS auteur_hub," " (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," " (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" " FROM topics t JOIN users u ON u.id=t.author_id" " ORDER BY t.fixed DESC, t.pinned DESC, t.pin_pos, " + ordre, (int(voit), uid)).fetchall() rows = [r for r in rows if self._visible(user, r)] if media in ("avec", "sans"): rows = [r for r in rows if bool(r["media"]) == (media == "avec")] return rows def noter_lecture(self, user, topic_id, dernier_post): """Le compte a vu le sujet jusqu'à ce message (pas de suivi pour les visiteurs).""" if user is None or not dernier_post: return self.con.execute("INSERT INTO lectures(user_id, topic_id, dernier_post) VALUES (?, ?, ?)" " ON CONFLICT(user_id, topic_id) DO UPDATE SET dernier_post=MAX(dernier_post, excluded.dernier_post)", (user["id"], topic_id, dernier_post)) self.con.commit() def creer_sujets_stations(self): """Un sujet publié par station connue (auteur : compte technique), même sans message. Le propriétaire de la station le reprend en publiant sa présentation. Retourne le nombre créé.""" sid = self.con.execute("SELECT id FROM users WHERE hub_id=?", (db.SYSTEME,)).fetchone()[0] n = 0 for station, nom in self.stations.items(): if self.con.execute("SELECT 1 FROM topics WHERE station=? AND status<>'refuse'", (station,)).fetchone(): continue self.con.execute("INSERT INTO topics(title, author_id, status, station) VALUES (?, ?, 'publie', ?)", ("Station · " + nom, sid, station)) n += 1 self.con.commit() if n: self.version += 1 return n 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, p.ancien_body, p.format," " " + nom_sql() + " AS auteur, u.username AS auteur_username, u.profil AS auteur_profil, u.photo AS auteur_photo," " u.avatar_illustre AS auteur_avatar, u.supprime AS auteur_supprime 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 a_la_une(self): """Dernier bulletin visible par un visiteur et nombre de nouveaux sujets publics sur sept jours.""" bulletin = self.con.execute( "SELECT t.id AS sujet, t.title AS titre, p.body AS corps, " + nom_sql() + " AS auteur" " FROM topics t JOIN posts p ON p.topic_id=t.id JOIN users u ON u.id=p.author_id" " WHERE t.fixed=1 AND t.status='publie' AND t.hidden=0 AND p.hidden=0" " ORDER BY p.id DESC LIMIT 1" ).fetchone() n = self.con.execute( "SELECT COUNT(*) FROM topics WHERE fixed=0 AND status='publie' AND hidden=0" " AND created_at >= datetime('now', '-7 days')" ).fetchone()[0] return bulletin, n 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) if re.search(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", s): raise Invalide("%s : caractères de contrôle refusés" % nom) return s 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, 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=(), 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") if not self.profil_permet_sujet(user): raise Refus("profil privé : passe en profil public pour ouvrir un 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 [] 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.""" self._exiger(user, "creer_sujet_station") 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, 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"])) self.con.execute("INSERT INTO posts(topic_id, author_id, body, ip) VALUES (?, ?, ?, ?)", (t["id"], user["id"], corps, ip)) self.version += 1 return t["id"] if t is not None: raise Invalide("cette station a déjà son sujet") titre = "Station · " + self.stations.get(station, station) return self._nouveau_sujet(user, titre, corps, 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() self.version += 1 def repondre(self, user, topic_id, corps, ip=None, format_="texte"): 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") if format_ not in ("texte", "md"): raise Invalide("format inconnu") cur = self.con.execute("INSERT INTO posts(topic_id, author_id, body, ip, format) VALUES (?, ?, ?, ?, ?)", (topic_id, user["id"], self._texte(corps, CORPS_MAX, "message"), ip, format_)) 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") deja = self.photos_de(post_id) prets = self._preparer_photos(fichiers, deja, self._peut(user, "photos_illimitees")) ids = [] for nom, mime, propre in prets: empreinte, chemin = self._stocker(self.dossier_photos, mime, propre) 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 _preparer_photos(self, fichiers, deja=(), illimite=False): """Vérifie limites et formats, retire les métadonnées ; rien n'est écrit. -> [(nom, mime, octets)]""" if not self.dossier_photos: raise Invalide("photos non configurées") if not illimite: 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)) return prets @staticmethod def _stocker(dossier, mime, propre): os.makedirs(dossier, exist_ok=True) empreinte = hashlib.sha256(propre).hexdigest() chemin = os.path.join(dossier, 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) return empreinte, chemin # --- demandes d'adhésion --------------------------------------------- # Méthodes prévues pour être reprises telles quelles par le panneau LAN. @property def dossier_demandes(self): """Photos des demandes : hors du dossier public, servies seulement au propriétaire et à l'adjoint.""" return os.path.join(self.dossier_photos, "demandes") if self.dossier_photos else None def demander_adhesion(self, user, message, fichiers=()): """Un membre demande à devenir adhérent météo : message + jusqu'à 10 photos (25 Mo). Une demande en cours à la fois.""" self._exiger(user, "demander_adhesion") if roles.ADHERENT in self.roles_de(user): raise Invalide("tu es déjà adhérent") if self.con.execute("SELECT 1 FROM adhesions WHERE user_id=? AND status='en_attente'", (user["id"],)).fetchone(): raise Invalide("une demande est déjà en cours") message = self._texte(message, ADHESION_MAX, "message") prets = self._preparer_photos(list(fichiers)) if fichiers else [] cur = self.con.execute("INSERT INTO adhesions(user_id, message) VALUES (?, ?)", (user["id"], message)) try: for nom, mime, propre in prets: empreinte, chemin = self._stocker(self.dossier_demandes, mime, propre) self.con.execute("INSERT INTO adhesion_photos(adhesion_id, filename, mime, size, sha256, stored_path)" " VALUES (?, ?, ?, ?, ?, ?)", (cur.lastrowid, nom, mime, len(propre), empreinte, chemin)) except OSError: self.con.rollback() raise self.con.commit() return cur.lastrowid def ma_demande_adhesion(self, user): """Dernière demande de cet utilisateur (ou None), pour lui afficher où elle en est.""" if user is None: return None return self.con.execute("SELECT * FROM adhesions WHERE user_id=? ORDER BY id DESC LIMIT 1", (user["id"],)).fetchone() def demandes_adhesion(self, acteur, statut="en_attente"): """Liste des demandes (propriétaire et adjoint). statut : en_attente, acceptee, refusee ou None (toutes).""" self._exiger(acteur, "valider_adhesion") return self.con.execute( "SELECT a.*, u.display_name AS pseudo, u.hub_id," " (SELECT COUNT(*) FROM adhesion_photos p WHERE p.adhesion_id=a.id) AS n_photos" " FROM adhesions a JOIN users u ON u.id=a.user_id WHERE (? IS NULL OR a.status=?) ORDER BY a.id", (statut, statut)).fetchall() def demande_adhesion(self, acteur, demande_id): """Retourne (demande, photos).""" self._exiger(acteur, "valider_adhesion") d = self.con.execute("SELECT a.*, u.display_name AS pseudo, u.hub_id FROM adhesions a" " JOIN users u ON u.id=a.user_id WHERE a.id=?", (demande_id,)).fetchone() if d is None: raise Invalide("demande introuvable") return d, self.con.execute("SELECT * FROM adhesion_photos WHERE adhesion_id=? ORDER BY id", (demande_id,)).fetchall() def decider_adhesion(self, acteur, demande_id, accepte): """Accepter donne le rôle adhérent météo ; refuser clôt la demande (une nouvelle reste possible).""" self._exiger(acteur, "valider_adhesion") d, _ = self.demande_adhesion(acteur, demande_id) if d["status"] != "en_attente": raise Invalide("demande déjà traitée") self.con.execute("UPDATE adhesions SET status=?, decided_by=?, decided_at=datetime('now') WHERE id=?", ("acceptee" if accepte else "refusee", acteur["id"], demande_id)) if accepte: self.con.execute("INSERT OR IGNORE INTO user_roles(user_id, role, given_by) VALUES (?, ?, ?)", (d["user_id"], roles.ADHERENT, acteur["id"])) self.con.commit() def photo_adhesion(self, acteur, nom): """Chemin d'une photo de demande, si l'acteur a le droit de la voir et qu'elle appartient à une demande.""" self._exiger(acteur, "valider_adhesion") for r in self.con.execute("SELECT stored_path FROM adhesion_photos WHERE sha256=?", (nom.split(".")[0],)): if os.path.basename(r["stored_path"]) == nom and os.path.isfile(r["stored_path"]): return r["stored_path"] raise Invalide("photo introuvable") 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 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 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") 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() self.version += 1 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() self.version += 1 # --- commentaires aux réponses (un seul niveau, texte simple) --------- def _commentaire(self, comment_id): c = self.con.execute("SELECT * FROM comments WHERE id=?", (comment_id,)).fetchone() if c is None: raise Invalide("commentaire introuvable") return c def peut_commenter(self, user, t, p): """Membre connecté (profil privé compris), message visible, sujet publié et ouvert ; jamais dans le Bulletin.""" if user is None or not self._peut(user, "commenter"): return False return not (p["hidden"] or t["fixed"] or t["locked"] or t["hidden"] or t["status"] != "publie") def commenter(self, user, post_id, corps, ip=None): self._exiger(user, "commenter") self._frais(user) p = self._post(post_id) t, _ = self.sujet(user, p["topic_id"]) if not self.peut_commenter(user, t, p): raise Refus("commentaire impossible ici") corps = self._texte((corps or "").replace("\r\n", "\n"), COMMENTAIRE_MAX, "commentaire") if re.search(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", corps): raise Invalide("commentaire : caractères de contrôle refusés") cur = self.con.execute("INSERT INTO comments(post_id, author_id, body, ip) VALUES (?, ?, ?, ?)", (post_id, user["id"], corps, ip)) self.con.commit() return cur.lastrowid def commentaires(self, user, post_ids): """{post_id: [commentaires]} dans l'ordre ; masqués seulement pour les modérateurs et propriétaires. Mêmes colonnes d'auteur que les messages (nom_sql, avatar, profil).""" ids = [int(i) for i in post_ids] out = {i: [] for i in ids} if not ids: return out voit = self._peut(user, "voir_masques") rows = self.con.execute( "SELECT c.id, c.post_id, c.author_id, c.body, c.created_at, c.hidden, " + nom_sql() + " AS auteur," " u.username AS auteur_username, u.profil AS auteur_profil, u.photo AS auteur_photo," " u.avatar_illustre AS auteur_avatar, u.supprime AS auteur_supprime" " FROM comments c JOIN users u ON u.id=c.author_id" " WHERE c.post_id IN (%s) AND (c.hidden=0 OR ?) ORDER BY c.id" % ",".join("?" * len(ids)), ids + [int(voit)]).fetchall() for r in rows: out[r["post_id"]].append(r) return out def _sujet_du_commentaire(self, user, c): """Le commentaire doit être dans un sujet visible pour cet utilisateur ; retourne (topic_id, post_id).""" p = self._post(c["post_id"]) self.sujet(user, p["topic_id"]) return p["topic_id"], p["id"] def supprimer_commentaire(self, user, comment_id): """L'auteur supprime son commentaire (effacé de la base, signalements compris).""" c = self._commentaire(comment_id) if user is None or c["author_id"] != user["id"]: raise Refus("pas ton commentaire") lieu = self._sujet_du_commentaire(user, c) with self.con: self.con.execute("DELETE FROM comment_reports WHERE comment_id=?", (comment_id,)) self.con.execute("DELETE FROM comments WHERE id=?", (comment_id,)) return lieu def signaler_commentaire(self, user, comment_id, motif): self._exiger(user, "signaler") c = self._commentaire(comment_id) if c["hidden"]: raise Invalide("commentaire introuvable") lieu = self._sujet_du_commentaire(user, c) self.con.execute("INSERT OR IGNORE INTO comment_reports(comment_id, reporter_id, reason) VALUES (?, ?, ?)", (comment_id, user["id"], self._texte(motif, 500, "motif"))) self.con.commit() return lieu def signalements_commentaires(self, user): self._exiger(user, "voir_signalements") return self.con.execute("SELECT r.*, c.body, c.post_id, c.hidden, p.topic_id FROM comment_reports r" " JOIN comments c ON c.id=r.comment_id JOIN posts p ON p.id=c.post_id" " ORDER BY r.id DESC").fetchall() def masquer_commentaire(self, user, comment_id, masque=True): self._exiger(user, "masquer") lieu = self._sujet_du_commentaire(user, self._commentaire(comment_id)) self.con.execute("UPDATE comments SET hidden=? WHERE id=?", (int(masque), comment_id)) self.con.commit() return lieu # --- réactions (une par membre et par message) ----------------------- def peut_reagir(self, user, t, p): """Mêmes conditions que les commentaires : membre connecté, message visible, sujet publié et ouvert, pas le Bulletin.""" if user is None or not self._peut(user, "reagir"): return False return not (p["hidden"] or t["fixed"] or t["locked"] or t["hidden"] or t["status"] != "publie") def reagir(self, user, post_id, kind): """Même réaction : retirée ; autre réaction : remplacée (nouvelle date). Retourne le topic_id.""" self._exiger(user, "reagir") self._frais(user) if kind not in REACTIONS: raise Invalide("réaction inconnue") p = self._post(post_id) t, _ = self.sujet(user, p["topic_id"]) if not self.peut_reagir(user, t, p): raise Refus("réaction impossible ici") with self.con: avant = self.con.execute("SELECT kind FROM reactions WHERE post_id=? AND user_id=?", (post_id, user["id"])).fetchone() if avant is not None and avant["kind"] == kind: self.con.execute("DELETE FROM reactions WHERE post_id=? AND user_id=?", (post_id, user["id"])) else: self.con.execute("INSERT OR REPLACE INTO reactions(post_id, user_id, kind) VALUES (?, ?, ?)", (post_id, user["id"], kind)) return p["topic_id"] def reactions(self, user, post_ids): """{post_id: {"liste": [(kind, [noms])] dans l'ordre de REACTIONS, "mien": kind ou None}}. Noms affichés comme les auteurs (nom_sql : username, « Membre privé », « Ancien membre »).""" ids = [int(i) for i in post_ids] out = {i: {"liste": [], "mien": None} for i in ids} if not ids: return out par = {} for r in self.con.execute( "SELECT r.post_id, r.user_id, r.kind, " + nom_sql() + " AS nom FROM reactions r JOIN users u ON u.id=r.user_id" " WHERE r.post_id IN (%s) ORDER BY r.created_at, r.user_id" % ",".join("?" * len(ids)), ids): par.setdefault(r["post_id"], {}).setdefault(r["kind"], []).append(r["nom"]) if user is not None and r["user_id"] == user["id"]: out[r["post_id"]]["mien"] = r["kind"] for pid, kinds in par.items(): out[pid]["liste"] = [(k, kinds[k]) for k in REACTIONS if k in kinds] return out 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() # --- fiche publique d'une station (page station de vercors.me) ------ def _photo_de_station(self, attachment_id): r = self.con.execute( "SELECT a.id, a.post_id, p.topic_id, p.hidden AS message_masque, t.station, t.status, t.hidden AS sujet_masque" " FROM attachments a JOIN posts p ON p.id=a.post_id JOIN topics t ON t.id=p.topic_id WHERE a.id=?", (attachment_id,)).fetchone() if r is None: raise Invalide("photo introuvable") if not r["station"]: raise Invalide("cette photo n'est pas dans le sujet d'une station") return r def peut_epingler_photo(self, user, station): """Propriétaire et adjoint : toutes les stations ; propriétaire de station : la sienne seulement.""" rs = self.roles_de(user) if not station or not roles.peut(rs, "epingler_photo_fiche"): return False return bool(rs & roles.PROPRIOS) or station in self.stations_de(user) def epingler_photo(self, user, attachment_id, epingle=True): """Épingle (ou retire) une photo du sujet de la station sur sa fiche publique, FICHE_PHOTOS_MAX au plus.""" ph = self._photo_de_station(attachment_id) if not self.peut_epingler_photo(user, ph["station"]): raise Refus("épingler une photo de cette station") if epingle: if ph["status"] != "publie" or ph["sujet_masque"] or ph["message_masque"]: raise Invalide("seule une photo publiée peut aller sur la fiche") if self.con.execute("SELECT 1 FROM fiche_photos WHERE attachment_id=?", (attachment_id,)).fetchone(): return ph["topic_id"], ph["post_id"] n = self.con.execute("SELECT COUNT(*) FROM fiche_photos WHERE station=?", (ph["station"],)).fetchone()[0] if n >= FICHE_PHOTOS_MAX: raise Refus("%d photos au plus sur la fiche ; retires-en une d'abord" % FICHE_PHOTOS_MAX) self.con.execute("INSERT INTO fiche_photos(attachment_id, station, pinned_by) VALUES (?, ?, ?)", (attachment_id, ph["station"], user["id"])) else: self.con.execute("DELETE FROM fiche_photos WHERE attachment_id=?", (attachment_id,)) self.con.commit() self.version += 1 return ph["topic_id"], ph["post_id"] def photos_fiche_ids(self, station): return {r[0] for r in self.con.execute("SELECT attachment_id FROM fiche_photos WHERE station=?", (station,))} def fiche_station(self, station): """Lecture publique : sujet publié de la station et ses photos épinglées encore visibles.""" if station not in self.stations: raise Invalide("station inconnue") t = self.con.execute("SELECT id FROM topics WHERE station=? AND status='publie' AND hidden=0", (station,)).fetchone() photos_ = [] if t is not None: photos_ = [{"fichier": os.path.basename(r["stored_path"]), "auteur": r["auteur"]} for r in self.con.execute( "SELECT a.stored_path, " + nom_sql() + " AS auteur FROM fiche_photos f" " JOIN attachments a ON a.id=f.attachment_id JOIN posts p ON p.id=a.post_id JOIN users u ON u.id=p.author_id" " WHERE f.station=? AND p.topic_id=? AND p.hidden=0 ORDER BY f.pinned_at, f.attachment_id LIMIT ?", (station, t["id"], FICHE_PHOTOS_MAX))] return {"station": station, "sujet": t["id"] if t is not None else None, "photos": photos_} # --- écran de bienvenue et profil public (06/11/2026) ----------------- def _frais(self, user): """Ligne à jour du compte (celle de la session peut dater du début de la requête).""" if user is None: raise Refus("connexion requise") u = self.con.execute("SELECT * FROM users WHERE id=?", (user["id"],)).fetchone() if u is None or u["supprime"]: raise Refus("compte supprimé") return u def profil_permet_sujet(self, user): """Un profil privé (ou pas encore choisi) répond et réagit, mais n'ouvre pas de sujet.""" if user is None: return False u = self._frais(user) return u["profil"] is None or u["profil"] == "public" def peut_creer_sujet(self, user): return self._peut(user, "creer_sujet") and self.profil_permet_sujet(user) @staticmethod def profil_complet(u): return bool(u["username"] and u["bio"] and (u["photo"] or u["avatar_illustre"])) def bienvenue_a_montrer(self, user, explicite=True): """Étape de l'écran de bienvenue à montrer après une connexion Gastinel (1 ou 2), sinon None. explicite : « Se connecter avec Gastinel » cliqué (sinon : rafraîchissement silencieux de la session).""" u = self._frais(user) if u["bienvenue"] == 0: return 1 if explicite else None if u["bienvenue"] == 1: if u["profil"] != "public" or self.profil_complet(u): self.con.execute("UPDATE users SET bienvenue=2 WHERE id=?", (u["id"],)) self.con.commit() return None if u["plus_tard_le"] is None: return 2 loin = self.con.execute("SELECT ? <= datetime('now', ?)", (u["plus_tard_le"], "-%d hours" % PLUS_TARD_HEURES)).fetchone()[0] return 2 if (explicite or loin) else None return None def choisir_profil(self, user, choix, regles, notifs_json): """Écran 1 : règles acceptées (case obligatoire), profil public ou privé (pas de choix par défaut).""" u = self._frais(user) if not regles: raise Invalide("Coche « J'ai lu les règles et je les respecte » pour continuer.") if choix not in ("prive", "public"): raise Invalide("Choisis un profil : privé ou public.") self.con.execute("UPDATE users SET profil=?, notifs=?, bienvenue=? WHERE id=?", (choix, notifs_json, 2 if choix == "prive" else 1, u["id"])) self.con.commit() @property def dossier_profils(self): return os.path.join(self.dossier_photos, "profils") if self.dossier_photos else None def _photo_profil(self, data): if len(data) > profil_mod.PHOTO_MAX: raise Invalide("Photo trop lourde : %d Mo au plus." % (profil_mod.PHOTO_MAX // 1048576)) if not self.dossier_photos: raise Invalide("photos non configurées") try: mime, propre = photos.nettoyer(data) except photos.PhotoInvalide as ex: raise Invalide("Photo refusée : %s." % ex) _, chemin = self._stocker(self.dossier_profils, mime, propre) return os.path.basename(chemin) def prochain_changement(self, u): """Date (SQLite) à partir de laquelle le username peut changer, ou None si c'est déjà possible.""" if not u["username"] or not u["username_le"]: return None return self.con.execute("SELECT CASE WHEN datetime(?, ?) > datetime('now') THEN datetime(?, ?) END", (u["username_le"], "+%d days" % profil_mod.CHANGEMENT_JOURS) * 2).fetchone()[0] def enregistrer_profil(self, user, username=None, bio=None, photo=None, avatar=None, retirer_photo=False, choix=None, notifs_json=None): """Modifie le profil. username vide : inchangé. choix : 'public' ou 'prive' (passer en public exige un username). Tout est vérifié avant d'écrire. Retourne la ligne à jour.""" u = self._frais(user) maj = {} username = (username or "").strip() nouveau_nom = False if username: try: username = profil_mod.verifier_username(username) except profil_mod.UsernameInvalide as ex: raise Invalide(str(ex)) cle = profil_mod.cle_unicite(username) if username != u["username"]: if cle != u["username_cle"]: if self.con.execute("SELECT 1 FROM users WHERE username_cle=? AND id<>?", (cle, u["id"])).fetchone(): raise Invalide("Ce username est déjà pris.") quand = self.prochain_changement(u) if quand: raise Invalide("Un changement de username tous les %d jours : prochain changement possible le %s." % (profil_mod.CHANGEMENT_JOURS, quand[:10])) nouveau_nom = True maj.update(username=username, username_cle=cle) if bio is not None: try: maj["bio"] = profil_mod.verifier_bio(bio) except ValueError as ex: raise Invalide(str(ex)) if avatar is not None: if avatar and avatar not in profil_mod.AVATARS: raise Invalide("avatar inconnu") maj["avatar_illustre"] = avatar or None if retirer_photo: maj["photo"] = None if photo: maj["photo"] = self._photo_profil(photo) if choix is not None: if choix not in ("prive", "public"): raise Invalide("Choisis un profil : privé ou public.") if choix == "public" and u["profil"] != "public" and not (maj.get("username") or u["username"]): raise Invalide("Pour passer en profil public, choisis d'abord un username.") maj["profil"] = choix if notifs_json is not None: maj["notifs"] = notifs_json if not maj: return u with self.con: if nouveau_nom: if u["username"]: self.con.execute("INSERT INTO usernames_anciens(user_id, username) VALUES (?, ?)", (u["id"], u["username"])) maj["username_le"] = self.con.execute("SELECT datetime('now')").fetchone()[0] self.con.execute("UPDATE users SET %s WHERE id=?" % ", ".join("%s=?" % k for k in maj), (*maj.values(), u["id"])) self.version += 1 return self._frais(u) def plus_tard(self, user): """Écran 2, « Plus tard » (3 fois au plus). Retourne 'ok', 'decompte' (3e fois, username mais photo ou bio manquante) ou 'username' (3e fois sans username : fenêtre à fermer par OK).""" u = self._frais(user) if u["bienvenue"] != 1 or u["plus_tard"] >= PLUS_TARD_MAX: raise Invalide("« Plus tard » n'est plus possible.") n = u["plus_tard"] + 1 self.con.execute("UPDATE users SET plus_tard=?, plus_tard_le=datetime('now') WHERE id=?", (n, u["id"])) self.con.commit() if n < PLUS_TARD_MAX: return "ok" if not u["username"]: return "username" return "ok" if self.profil_complet(u) else "decompte" def ignorer_bienvenue(self, user): """4e connexion : « Ignorer ». Sans username, l'accès public est suspendu (profil privé). -> 'ok' ou 'suspendu'.""" u = self._frais(user) if u["bienvenue"] != 1: return "ok" suspendu = not u["username"] self.con.execute("UPDATE users SET bienvenue=2, profil=CASE WHEN ? THEN 'prive' ELSE profil END WHERE id=?", (int(suspendu), u["id"])) self.con.commit() return "suspendu" if suspendu else "ok" def fin_ecran2(self, user): """Après « Enregistrer » sur l'écran 2 : fini si le profil est complet ou si c'était la dernière fois.""" u = self._frais(user) if u["bienvenue"] == 1 and (self.profil_complet(u) or u["plus_tard"] >= PLUS_TARD_MAX): self.con.execute("UPDATE users SET bienvenue=2 WHERE id=?", (u["id"],)) self.con.commit() def profil_visible(self, lecteur, cible): """Page /@username : profil public avec username, pas supprimé. Un visiteur sans compte ne voit que les modérateurs, adhérents météo, propriétaires et propriétaires de station.""" if cible is None or cible["supprime"] or cible["profil"] != "public" or not cible["username"]: return False if lecteur is not None: return True return bool(self.roles_de(cible) & ROLES_VISIBLES_SANS_COMPTE) def profil_public(self, lecteur, username): """Compte de la page /@username ; invisible = introuvable.""" c = self.con.execute("SELECT * FROM users WHERE username_cle=?", (profil_mod.cle_unicite(username or ""),)).fetchone() if not self.profil_visible(lecteur, c): raise Invalide("profil introuvable") return c def resume_profil(self, lecteur, cible): """Nombre de messages visibles, 5 derniers sujets visibles du lecteur, stations, anciens usernames (membres).""" n = self.con.execute("SELECT COUNT(*) FROM posts p JOIN topics t ON t.id=p.topic_id" " WHERE p.author_id=? AND p.hidden=0 AND t.hidden=0 AND t.status='publie'", (cible["id"],)).fetchone()[0] sujets = [t for t in self.con.execute("SELECT * FROM topics WHERE author_id=? AND fixed=0 ORDER BY id DESC LIMIT 30", (cible["id"],)) if self._visible(lecteur, t) and t["status"] == "publie"][:5] stations = [] for st in sorted(self.stations_de(cible)): t = self.con.execute("SELECT id FROM topics WHERE station=? AND status='publie' AND hidden=0", (st,)).fetchone() stations.append((st, self.stations.get(st, st), t["id"] if t else None)) anciens = [r["username"] for r in self.con.execute( "SELECT username FROM usernames_anciens WHERE user_id=? ORDER BY id DESC", (cible["id"],))] if lecteur is not None else [] return {"messages": n, "sujets": sujets, "stations": stations, "anciens": anciens} def photo_profil_publique(self, lecteur, nom): """Chemin de la photo de profil si son compte est public (ou si c'est le sien), sinon Invalide.""" for c in self.con.execute("SELECT * FROM users WHERE photo=?", (nom,)): soi = lecteur is not None and lecteur["id"] == c["id"] if (soi or (c["profil"] == "public" and not c["supprime"])) and self.dossier_profils: chemin = os.path.join(self.dossier_profils, nom) if os.path.isfile(chemin): return chemin raise Invalide("photo introuvable") def supprimer_profil(self, user): """Supprime le compte du forum : profil effacé, messages gardés et signés « Ancien membre ».""" u = self._frais(user) if roles.PROPRIETAIRE in self.roles_de(u): raise Refus("le compte du propriétaire ne se supprime pas ici") with self.con: self.con.execute("UPDATE users SET supprime=1, profil='prive', username=NULL, username_cle=NULL, username_le=NULL," " bio='', photo=NULL, avatar_illustre=NULL, notifs=NULL, bienvenue=2 WHERE id=?", (u["id"],)) for table in ("usernames_anciens", "sessions", "brouillons", "lectures", "user_roles"): self.con.execute("DELETE FROM %s WHERE user_id=?" % table, (u["id"],)) self.version += 1 self._pousser_roles(u["hub_id"]) # --- 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.""" n = 0 for table in ("posts", "comments"): n += self.con.execute("UPDATE %s SET ip=NULL WHERE ip IS NOT NULL AND created_at < datetime('now', ?)" % table, ("-%d months" % mois,)).rowcount self.con.commit() return n