210 lignes
8.7 KiB
Python
210 lignes
8.7 KiB
Python
"""Profil public du forum : username, noms bloqués, biographie, avatars illustrés, réglages des mails.
|
|
|
|
Décisions de Théo du 06/11/2026 (09-Forum/Bienvenue-et-profil.md). Bibliothèque standard seulement.
|
|
"""
|
|
import html
|
|
import json
|
|
import os
|
|
import re
|
|
import unicodedata
|
|
|
|
USERNAME_MIN, USERNAME_MAX = 5, 20
|
|
SPECIAUX = ".@-_!?¿"
|
|
BIO_MAX = 1000
|
|
CHANGEMENT_JOURS = 30 # un changement de username tous les 30 jours
|
|
PHOTO_MAX = 5 * 1024 * 1024 # photo de profil : 5 Mo au plus
|
|
|
|
AVATARS = {"brume": "Dans la brume", "neige": "Sous la neige", "station": "La station au soleil"}
|
|
AVATAR_DEFAUT = "brume"
|
|
|
|
# Réglages des mails (enregistrés seulement : l'envoi n'est pas encore codé).
|
|
# (clé, libellé, actif par défaut, [(clé, libellé, actif par défaut)])
|
|
NOTIFS = (
|
|
("posts", "Posts", True, (("reponse_sujet", "Réponse à ton sujet", True), ("reponse_post", "Réponse à ton post", True),
|
|
("reponse_reponse", "Réponse à ta réponse", False), ("reactions", "Réactions", False))),
|
|
("autre", "Autre", True, (("bulletin", "Bulletin de la semaine", True), ("nouveautes", "Nouveautés du forum", False),
|
|
("station", "Nouvelle station", False))),
|
|
)
|
|
|
|
|
|
class UsernameInvalide(ValueError):
|
|
pass
|
|
|
|
|
|
# --- noms bloqués -------------------------------------------------------------
|
|
_LEET = str.maketrans({"0": "o", "1": "i", "3": "e", "4": "a", "5": "s", "7": "t", "@": "a", "$": "s", "!": "i"})
|
|
|
|
|
|
def _latin_ou_chiffre(c):
|
|
"""Chiffre 0-9 ou lettre de l'alphabet latin (accents compris) : bloque les sosies cyrilliques ou grecs."""
|
|
if "0" <= c <= "9":
|
|
return True
|
|
return c.isalpha() and unicodedata.name(c, "").startswith("LATIN ")
|
|
|
|
|
|
def cle(texte):
|
|
"""Minuscules, sans accents, lettres et chiffres seulement (séparateurs retirés)."""
|
|
s = unicodedata.normalize("NFKD", (texte or "").casefold())
|
|
return "".join(c for c in s if c.isalnum() and not unicodedata.combining(c))
|
|
|
|
|
|
def charger_bloques(chemin=None):
|
|
"""noms_bloques.txt -> (réservés : refusés même au milieu d'un mot, mots grossiers)."""
|
|
chemin = chemin or os.path.join(os.path.dirname(os.path.abspath(__file__)), "noms_bloques.txt")
|
|
reserves, mots, partie = set(), set(), 1
|
|
try:
|
|
with open(chemin, encoding="utf-8") as fh:
|
|
for ligne in fh:
|
|
ligne = ligne.strip()
|
|
if ligne.startswith("#"):
|
|
if "Partie 2" in ligne:
|
|
partie = 2
|
|
continue
|
|
k = cle(ligne)
|
|
if k:
|
|
(reserves if partie == 1 else mots).add(k)
|
|
except OSError:
|
|
pass
|
|
reserves |= {"admin", "moderateur", "meteovercors", "direction", "gastinel"} # même sans le fichier
|
|
return frozenset(reserves), frozenset(mots)
|
|
|
|
|
|
RESERVES, MOTS = charger_bloques()
|
|
|
|
|
|
def est_bloque(username, reserves=None, mots=None):
|
|
"""Vrai si le username contient un nom réservé ou un mot grossier, à l'endroit, à l'envers,
|
|
sans séparateurs ni accents, et en remplaçant les chiffres par des lettres (adm1n, 4dmin)."""
|
|
reserves = RESERVES if reserves is None else reserves
|
|
mots = MOTS if mots is None else mots
|
|
for base in {cle(username), cle(username.casefold().translate(_LEET))}:
|
|
for s in (base, base[::-1]):
|
|
if not s:
|
|
continue
|
|
if any(r in s for r in reserves):
|
|
return True
|
|
# mots courts (con, cul) : seulement le mot entier, pour ne pas bloquer « contamines » ou « habite »
|
|
if any(m == s or (len(m) >= 6 and m in s) for m in mots):
|
|
return True
|
|
return False
|
|
|
|
|
|
def verifier_username(brut):
|
|
"""Retourne le username (NFC) ou lève UsernameInvalide avec ce qui ne va pas."""
|
|
u = unicodedata.normalize("NFC", brut or "")
|
|
if any(c.isspace() for c in u):
|
|
raise UsernameInvalide("Pas d'espace dans le username.")
|
|
if len(u) < USERNAME_MIN:
|
|
raise UsernameInvalide("Trop court : %d caractères minimum." % USERNAME_MIN)
|
|
if len(u) > USERNAME_MAX:
|
|
raise UsernameInvalide("Trop long : %d caractères maximum." % USERNAME_MAX)
|
|
mauvais = []
|
|
for c in u:
|
|
if not (_latin_ou_chiffre(c) or c in SPECIAUX) and c not in mauvais:
|
|
mauvais.append(c)
|
|
if mauvais:
|
|
raise UsernameInvalide("Caractère non accepté : « %s ». Lettres, chiffres et . @ - _ ! ? ¿ seulement."
|
|
% " ".join(c if c.isprintable() else "?" for c in mauvais))
|
|
if not any(c.isalnum() for c in u):
|
|
raise UsernameInvalide("Le username doit contenir au moins une lettre ou un chiffre.")
|
|
if est_bloque(u):
|
|
raise UsernameInvalide("Ce username est réservé. Choisis-en un autre.")
|
|
return u
|
|
|
|
|
|
def cle_unicite(username):
|
|
"""Deux usernames qui ne diffèrent que par les majuscules sont le même."""
|
|
return unicodedata.normalize("NFKC", username).casefold()
|
|
|
|
|
|
# --- biographie ----------------------------------------------------------------
|
|
_URL = re.compile(r"https?://[^\s<>\"'«»]+", re.I)
|
|
|
|
|
|
def verifier_bio(texte):
|
|
t = (texte or "").replace("\r\n", "\n").strip()
|
|
if len(t) > BIO_MAX:
|
|
raise ValueError("Biographie trop longue : %d caractères au plus." % BIO_MAX)
|
|
if re.search(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", t):
|
|
raise ValueError("Biographie : caractères de contrôle refusés.")
|
|
return t
|
|
|
|
|
|
def bio_html(texte):
|
|
"""Texte simple échappé ; les adresses http(s) deviennent des liens (nofollow)."""
|
|
out, i = [], 0
|
|
for m in _URL.finditer(texte or ""):
|
|
url = m.group(0).rstrip(".,;:!?)]")
|
|
out.append(html.escape(texte[i:m.start()]))
|
|
out.append("<a href='%s' rel='nofollow ugc noopener noreferrer'>%s</a>" % (html.escape(url, True), html.escape(url)))
|
|
i = m.start() + len(url)
|
|
out.append(html.escape((texte or "")[i:]))
|
|
return "".join(out)
|
|
|
|
|
|
# --- réglages des mails ----------------------------------------------------------
|
|
def notifs_defaut():
|
|
d = {}
|
|
for cat, _, actif, subs in NOTIFS:
|
|
d[cat] = actif
|
|
for k, _, a in subs:
|
|
d[cat + "." + k] = a
|
|
return d
|
|
|
|
|
|
def notifs_lire(texte):
|
|
d = notifs_defaut()
|
|
try:
|
|
enreg = json.loads(texte) if texte else {}
|
|
except ValueError:
|
|
enreg = {}
|
|
if isinstance(enreg, dict):
|
|
d.update({k: bool(v) for k, v in enreg.items() if k in d})
|
|
return d
|
|
|
|
|
|
def notifs_du_formulaire(champs):
|
|
"""Cases cochées du formulaire (notif_posts, notif_posts_reponse_sujet...) -> JSON."""
|
|
d = {}
|
|
for cat, _, _, subs in NOTIFS:
|
|
d[cat] = champs.get("notif_" + cat) == "1"
|
|
for k, _, _ in subs:
|
|
d[cat + "." + k] = champs.get("notif_%s_%s" % (cat, k)) == "1"
|
|
return json.dumps(d, sort_keys=True)
|
|
|
|
|
|
# --- avatars illustrés (maquette validée par Théo) -------------------------------------
|
|
_TETE = "M60 30c-11 0-19 9-19 21s8 21 19 21 19-9 19-21-8-21-19-21Z"
|
|
_CORPS = "M22 120c2-26 17-41 38-41s36 15 38 41Z"
|
|
|
|
|
|
def _silhouette(couleur, transform=""):
|
|
t = " transform='%s'" % transform if transform else ""
|
|
return "<g fill='%s'%s><path d='%s'/><path d='%s'/></g>" % (couleur, t, _TETE, _CORPS)
|
|
|
|
|
|
_DESSINS = {
|
|
"brume": ("<rect width='120' height='120' fill='#ece9e1'/>"
|
|
"<g stroke='#cfcabd' stroke-width='5'><path d='M0 34h70M30 48h90M0 62h50'/></g>" + _silhouette("#8c938a")),
|
|
"neige": ("<rect width='120' height='120' fill='#dcecef'/>"
|
|
"<path d='M0 92 30 56l18 20 22-30 50 46v28H0Z' fill='#fff' stroke='#6eb5bd' stroke-width='2'/>"
|
|
"<g fill='#6eb5bd'><circle cx='18' cy='20' r='2.5'/><circle cx='44' cy='12' r='2'/><circle cx='96' cy='22' r='2.5'/>"
|
|
"<circle cx='104' cy='44' r='2'/><circle cx='14' cy='46' r='2'/></g>" + _silhouette("#1f4d3a")
|
|
+ "<g fill='#6f8f5c'><path d='M40 47c1-14 9-22 20-22s19 8 20 22Z'/><rect x='38' y='44' width='44' height='7'/>"
|
|
"<circle cx='60' cy='22' r='5'/></g>"),
|
|
"station": ("<rect width='120' height='120' fill='#f1e3d6'/>"
|
|
"<circle cx='94' cy='26' r='12' fill='none' stroke='#b5643c' stroke-width='3'/>"
|
|
"<g stroke='#b5643c' stroke-width='3'><path d='M94 6v6M94 40v6M74 26h6M108 26h6'/></g>"
|
|
"<g stroke='#1f4d3a' stroke-width='3' fill='none'><path d='M18 120V48M10 52h16M10 52l-3 6M26 52l3 6'/>"
|
|
"<rect x='11' y='72' width='14' height='12' fill='#fff'/></g>" + _silhouette("#1f4d3a", "translate(12 0)")),
|
|
}
|
|
|
|
|
|
def svg_avatar(nom):
|
|
"""Fichier SVG autonome d'un avatar illustré (servi en image/svg+xml)."""
|
|
dessin = _DESSINS.get(nom)
|
|
if dessin is None:
|
|
return None
|
|
return ("<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 120 120' width='120' height='120'>"
|
|
"<title>%s</title>%s</svg>" % (html.escape(AVATARS[nom]), dessin))
|