Fichiers
meteo-vercors/forum/forum.py
T
Théo GastineletClaude Opus 5.5 ec4177087c forum : session d'1 h (jeton du Hub) et rafraîchissement silencieux par le Hub (revue sécu 06/11)
Le cookie garde 30 jours, mais la session en base n'en vaut plus qu'une
heure ; au-delà, une page HTML repasse par /oauth/autoriser (sans clic si la
session Gastinel vaut encore) et revient sur la page demandée. 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. Page de retour limitée au site.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 10:17:23 +01:00

699 lignes
38 KiB
Python

"""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 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
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."""
u = self.utilisateur(hub_id, pseudo)
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.*, u.display_name 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,"
" 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 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, u.display_name 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")
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
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, u.display_name 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_}
# --- 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