249 lignes
13 KiB
Python
249 lignes
13 KiB
Python
"""Schéma SQLite et accès aux données (version 4 : + sessions Gastinel, demandes d'adhésion, photos de la fiche station)."""
|
|
import sqlite3
|
|
import threading
|
|
|
|
SCHEMA = """
|
|
CREATE TABLE IF NOT EXISTS users (
|
|
id INTEGER PRIMARY KEY,
|
|
hub_id TEXT NOT NULL UNIQUE, -- identifiant du compte Gastinel (Hub)
|
|
display_name TEXT NOT NULL, -- pseudo du compte Gastinel
|
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
);
|
|
-- Rôles cumulables ; « membre » est implicite pour tout compte. station : id de station pour proprietaire_station.
|
|
CREATE TABLE IF NOT EXISTS user_roles (
|
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
|
role TEXT NOT NULL CHECK (role IN ('adherent','moderateur','proprietaire','proprietaire_adjoint','proprietaire_station')),
|
|
station TEXT NOT NULL DEFAULT '',
|
|
given_by INTEGER REFERENCES users(id),
|
|
given_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
PRIMARY KEY (user_id, role, station)
|
|
);
|
|
CREATE TABLE IF NOT EXISTS topics (
|
|
id INTEGER PRIMARY KEY,
|
|
title TEXT NOT NULL,
|
|
author_id INTEGER NOT NULL REFERENCES users(id),
|
|
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
locked INTEGER NOT NULL DEFAULT 0,
|
|
hidden INTEGER NOT NULL DEFAULT 0,
|
|
fixed INTEGER NOT NULL DEFAULT 0, -- sujet fixe (Bulletin de la semaine) : toujours épinglé en tête
|
|
pinned INTEGER NOT NULL DEFAULT 0,
|
|
pin_pos INTEGER NOT NULL DEFAULT 0,
|
|
replies_open INTEGER NOT NULL DEFAULT 1, -- 0 : seuls les rôles « publier_bulletin » écrivent
|
|
status TEXT NOT NULL DEFAULT 'publie' CHECK (status IN ('publie','en_attente','refuse')),
|
|
station TEXT -- sujet d'une station (propriétaire de station)
|
|
);
|
|
CREATE TABLE IF NOT EXISTS posts (
|
|
id INTEGER PRIMARY KEY,
|
|
topic_id INTEGER NOT NULL REFERENCES topics(id),
|
|
author_id INTEGER NOT NULL REFERENCES users(id),
|
|
body TEXT NOT NULL,
|
|
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
edited_at TEXT,
|
|
hidden INTEGER NOT NULL DEFAULT 0,
|
|
ip TEXT -- obligation légale (un an), purgée ensuite (purger_ips)
|
|
);
|
|
CREATE TABLE IF NOT EXISTS attachments (
|
|
id INTEGER PRIMARY KEY,
|
|
post_id INTEGER NOT NULL REFERENCES posts(id),
|
|
filename TEXT NOT NULL,
|
|
mime TEXT NOT NULL,
|
|
size INTEGER NOT NULL,
|
|
sha256 TEXT NOT NULL,
|
|
stored_path TEXT NOT NULL,
|
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
);
|
|
CREATE TABLE IF NOT EXISTS reports (
|
|
id INTEGER PRIMARY KEY,
|
|
post_id INTEGER NOT NULL REFERENCES posts(id),
|
|
reporter_id INTEGER NOT NULL REFERENCES users(id),
|
|
reason TEXT NOT NULL,
|
|
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
UNIQUE (post_id, reporter_id)
|
|
);
|
|
-- Sessions du forum (connexion Gastinel) : seul le haché SHA-256 de l'identifiant du cookie est gardé.
|
|
CREATE TABLE IF NOT EXISTS sessions (
|
|
id_hache TEXT PRIMARY KEY,
|
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
|
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
expires_at TEXT NOT NULL
|
|
);
|
|
-- Demandes de connexion en cours (state haché -> code_verifier PKCE), 10 minutes au plus.
|
|
CREATE TABLE IF NOT EXISTS oauth_etats (
|
|
etat_hache TEXT PRIMARY KEY,
|
|
verifier TEXT NOT NULL,
|
|
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
);
|
|
-- Demandes pour devenir adhérent météo (validées par le propriétaire ou l'adjoint).
|
|
CREATE TABLE IF NOT EXISTS adhesions (
|
|
id INTEGER PRIMARY KEY,
|
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
|
message TEXT NOT NULL,
|
|
status TEXT NOT NULL DEFAULT 'en_attente' CHECK (status IN ('en_attente','acceptee','refusee')),
|
|
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
decided_by INTEGER REFERENCES users(id),
|
|
decided_at TEXT
|
|
);
|
|
CREATE TABLE IF NOT EXISTS adhesion_photos (
|
|
id INTEGER PRIMARY KEY,
|
|
adhesion_id INTEGER NOT NULL REFERENCES adhesions(id),
|
|
filename TEXT NOT NULL,
|
|
mime TEXT NOT NULL,
|
|
size INTEGER NOT NULL,
|
|
sha256 TEXT NOT NULL,
|
|
stored_path TEXT NOT NULL
|
|
);
|
|
-- Photos épinglées sur la fiche publique d'une station (3 au plus), choisies dans le sujet de la station.
|
|
CREATE TABLE IF NOT EXISTS fiche_photos (
|
|
attachment_id INTEGER PRIMARY KEY REFERENCES attachments(id),
|
|
station TEXT NOT NULL,
|
|
pinned_by INTEGER REFERENCES users(id),
|
|
pinned_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_fiche_station ON fiche_photos(station, pinned_at);
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_une_demande_en_cours ON adhesions(user_id) WHERE status = 'en_attente';
|
|
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
|
|
CREATE INDEX IF NOT EXISTS idx_topics_liste ON topics(pinned DESC, pin_pos, id DESC);
|
|
CREATE INDEX IF NOT EXISTS idx_posts_topic ON posts(topic_id, id);
|
|
CREATE INDEX IF NOT EXISTS idx_attach_post ON attachments(post_id);
|
|
-- Dernier message lu par compte et par sujet (pastille « Nouveau », sans cookie de suivi).
|
|
CREATE TABLE IF NOT EXISTS lectures (
|
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
|
topic_id INTEGER NOT NULL REFERENCES topics(id),
|
|
dernier_post INTEGER NOT NULL DEFAULT 0,
|
|
PRIMARY KEY (user_id, topic_id)
|
|
);
|
|
-- Brouillons de la page « Publier » : privés, un auteur ne voit que les siens ; supprimés à la publication.
|
|
CREATE TABLE IF NOT EXISTS brouillons (
|
|
id INTEGER PRIMARY KEY,
|
|
user_id INTEGER NOT NULL REFERENCES users(id),
|
|
titre TEXT NOT NULL DEFAULT '',
|
|
corps TEXT NOT NULL DEFAULT '',
|
|
station TEXT NOT NULL DEFAULT '',
|
|
prevenir INTEGER NOT NULL DEFAULT 0,
|
|
maj TEXT NOT NULL DEFAULT (datetime('now'))
|
|
);
|
|
CREATE INDEX IF NOT EXISTS idx_brouillons_user ON brouillons(user_id, maj);
|
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_un_sujet_par_station ON topics(station) WHERE station IS NOT NULL AND status <> 'refuse';
|
|
"""
|
|
|
|
SYSTEME = "systeme" # compte technique, auteur du sujet fixe
|
|
BULLETIN = "Bulletin de la semaine du Vercors"
|
|
|
|
|
|
class _Resultat:
|
|
"""Résultat déjà lu sous le verrou (les lignes ne dépendent plus de la connexion partagée)."""
|
|
def __init__(self, lignes, rowcount, lastrowid):
|
|
self._l, self.rowcount, self.lastrowid = lignes, rowcount, lastrowid
|
|
def fetchone(self):
|
|
return self._l.pop(0) if self._l else None
|
|
def fetchall(self):
|
|
l, self._l = self._l, []
|
|
return l
|
|
def __iter__(self):
|
|
return iter(self.fetchall())
|
|
|
|
|
|
class ConnexionVerrouillee:
|
|
"""Connexion SQLite partagée entre les fils du serveur : chaque appel passe sous un verrou et lit
|
|
ses lignes tout de suite. Le verrou ne couvre que la base, jamais la lecture du réseau."""
|
|
def __init__(self, con):
|
|
self._con, self.verrou = con, threading.RLock()
|
|
def execute(self, sql, params=()):
|
|
with self.verrou:
|
|
c = self._con.execute(sql, params)
|
|
return _Resultat(c.fetchall(), c.rowcount, c.lastrowid)
|
|
def executemany(self, sql, seq):
|
|
with self.verrou:
|
|
c = self._con.executemany(sql, seq)
|
|
return _Resultat([], c.rowcount, c.lastrowid)
|
|
def executescript(self, sql):
|
|
with self.verrou:
|
|
return self._con.executescript(sql)
|
|
def commit(self):
|
|
with self.verrou:
|
|
self._con.commit()
|
|
def rollback(self):
|
|
with self.verrou:
|
|
self._con.rollback()
|
|
def __enter__(self): # « with con: » = une transaction entière sous le verrou
|
|
self.verrou.acquire()
|
|
try:
|
|
self._con.__enter__()
|
|
except BaseException:
|
|
self.verrou.release()
|
|
raise
|
|
return self
|
|
def __exit__(self, *exc):
|
|
try:
|
|
return self._con.__exit__(*exc)
|
|
finally:
|
|
self.verrou.release()
|
|
def __getattr__(self, nom):
|
|
return getattr(self._con, nom)
|
|
|
|
|
|
def connecter(chemin=":memory:"):
|
|
con = sqlite3.connect(chemin, check_same_thread=False)
|
|
con.row_factory = sqlite3.Row
|
|
con.execute("PRAGMA foreign_keys = ON")
|
|
con.executescript(SCHEMA)
|
|
# migrations douces (colonnes ajoutées après la mise en ligne)
|
|
if "ancien_body" not in {r[1] for r in con.execute("PRAGMA table_info(posts)")}:
|
|
con.execute("ALTER TABLE posts ADD COLUMN ancien_body TEXT") # version d'avant l'unique modification
|
|
if "format" not in {r[1] for r in con.execute("PRAGMA table_info(posts)")}:
|
|
con.execute("ALTER TABLE posts ADD COLUMN format TEXT NOT NULL DEFAULT 'texte'") # 'texte' ou 'md' (page Publier)
|
|
cols = {r[1] for r in con.execute("PRAGMA table_info(topics)")}
|
|
if "station_liee" not in cols:
|
|
con.execute("ALTER TABLE topics ADD COLUMN station_liee TEXT") # station citée (facultatif), distincte du sujet de station
|
|
if "prevenir" not in cols:
|
|
con.execute("ALTER TABLE topics ADD COLUMN prevenir INTEGER NOT NULL DEFAULT 0") # « Me prévenir des réponses » (enregistré, pas encore d'envoi)
|
|
# Écran de bienvenue et profil public (06/11/2026). Les comptes déjà là reçoivent bienvenue=2 (écran déjà passé)
|
|
# et profil NULL (« ancien » : nom Gastinel affiché comme avant) ; un nouveau compte part de bienvenue=0.
|
|
cols = {r[1] for r in con.execute("PRAGMA table_info(users)")}
|
|
for nom, decl in (("profil", "TEXT"), # NULL (ancien compte), 'attente', 'prive', 'public'
|
|
("username", "TEXT"), ("username_cle", "TEXT"), ("username_le", "TEXT"),
|
|
("bio", "TEXT NOT NULL DEFAULT ''"),
|
|
("photo", "TEXT"), # fichier dans <photos>/profils
|
|
("avatar_illustre", "TEXT"), # brume, neige, station (NULL : brume par défaut)
|
|
("notifs", "TEXT"), # réglages des mails (JSON), enregistrés seulement
|
|
("bienvenue", "INTEGER NOT NULL DEFAULT 2"), # 0 : écran 1 à montrer, 1 : écran 2 en cours, 2 : fini
|
|
("plus_tard", "INTEGER NOT NULL DEFAULT 0"), ("plus_tard_le", "TEXT"),
|
|
("supprime", "INTEGER NOT NULL DEFAULT 0")):
|
|
if nom not in cols:
|
|
con.execute("ALTER TABLE users ADD COLUMN %s %s" % (nom, decl))
|
|
con.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_username ON users(username_cle) WHERE username_cle IS NOT NULL")
|
|
con.execute("CREATE TABLE IF NOT EXISTS usernames_anciens (id INTEGER PRIMARY KEY,"
|
|
" user_id INTEGER NOT NULL REFERENCES users(id), username TEXT NOT NULL,"
|
|
" jusqu_au TEXT NOT NULL DEFAULT (datetime('now')))")
|
|
con.execute("CREATE INDEX IF NOT EXISTS idx_usernames_anciens ON usernames_anciens(user_id, id)")
|
|
# Commentaires aux réponses (06/11/2026) : un seul niveau, texte simple ; ils ne comptent pas comme des messages
|
|
# (limite des visiteurs, tris). Tables à part : rien ne change pour posts et reports.
|
|
con.execute("CREATE TABLE IF NOT EXISTS comments (id INTEGER PRIMARY KEY,"
|
|
" post_id INTEGER NOT NULL REFERENCES posts(id), author_id INTEGER NOT NULL REFERENCES users(id),"
|
|
" body TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT (datetime('now')),"
|
|
" hidden INTEGER NOT NULL DEFAULT 0, ip TEXT)")
|
|
con.execute("CREATE INDEX IF NOT EXISTS idx_comments_post ON comments(post_id, id)")
|
|
con.execute("CREATE TABLE IF NOT EXISTS comment_reports (id INTEGER PRIMARY KEY,"
|
|
" comment_id INTEGER NOT NULL REFERENCES comments(id), reporter_id INTEGER NOT NULL REFERENCES users(id),"
|
|
" reason TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT (datetime('now')), UNIQUE (comment_id, reporter_id))")
|
|
# Réactions aux messages (06/11/2026) : une par membre et par message (la clé primaire l'impose) ; created_at est
|
|
# remis à l'heure quand la réaction change (servira au mail groupé « N réactions en 7 jours »). Hors limite des
|
|
# visiteurs et hors tris, comme les commentaires.
|
|
con.execute("CREATE TABLE IF NOT EXISTS reactions (post_id INTEGER NOT NULL REFERENCES posts(id),"
|
|
" user_id INTEGER NOT NULL REFERENCES users(id), kind TEXT NOT NULL,"
|
|
" created_at TEXT NOT NULL DEFAULT (datetime('now')), PRIMARY KEY (post_id, user_id))")
|
|
con.execute("CREATE INDEX IF NOT EXISTS idx_reactions_date ON reactions(created_at)")
|
|
# Journal des suppressions définitives (06/11/2026) : qui, quoi, quand ; l'extrait garde une trace lisible.
|
|
con.execute("CREATE TABLE IF NOT EXISTS journal_suppressions (id INTEGER PRIMARY KEY,"
|
|
" acteur_id INTEGER NOT NULL REFERENCES users(id), acteur_nom TEXT NOT NULL,"
|
|
" quoi TEXT NOT NULL CHECK (quoi IN ('sujet','message','commentaire')), cible_id INTEGER NOT NULL,"
|
|
" sujet_id INTEGER, extrait TEXT NOT NULL DEFAULT '', details TEXT NOT NULL DEFAULT '',"
|
|
" quand TEXT NOT NULL DEFAULT (datetime('now')))")
|
|
con.execute("INSERT OR IGNORE INTO users(hub_id, display_name) VALUES (?, ?)", (SYSTEME, "vercors.me"))
|
|
if con.execute("SELECT 1 FROM topics WHERE fixed=1").fetchone() is None:
|
|
sid = con.execute("SELECT id FROM users WHERE hub_id=?", (SYSTEME,)).fetchone()[0]
|
|
con.execute("INSERT INTO topics(title, author_id, fixed, pinned, pin_pos, replies_open)"
|
|
" VALUES (?, ?, 1, 1, 0, 0)", (BULLETIN, sid))
|
|
con.commit()
|
|
return ConnexionVerrouillee(con)
|