Configuration par variables MC_*, heure de Paris sans zoneinfo, JSON atomique, journal masquant les secrets, verrou, pause. SQLite 14 jours, cle unique (source, station, dh_utc). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
237 lignes
8.5 KiB
Python
237 lignes
8.5 KiB
Python
"""Outils communs : configuration, heure de Paris, JSON atomique, journal, verrou, masquage des secrets.
|
|
|
|
Aucun chemin, nom de serveur ni secret n'est écrit en dur : tout vient de variables d'environnement
|
|
(voir `Config.depuis_env`) avec des valeurs par défaut relatives au dossier personnel.
|
|
"""
|
|
import datetime as dt
|
|
import json
|
|
import os
|
|
import re
|
|
import urllib.parse
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
try: # fcntl n'existe que sous Unix (le VPS) ; les tests tournent aussi sous Windows
|
|
import fcntl
|
|
except ImportError: # pragma: no cover
|
|
fcntl = None
|
|
|
|
UTC = dt.timezone.utc
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Configuration
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@dataclass
|
|
class Config:
|
|
base: Path # état, journal, base SQLite
|
|
public: Path # racine servie par Caddy (on écrit dans public/data/)
|
|
quota_commun: Path # compteur partagé avec le collecteur GWS et meteo-direct
|
|
jeton_infoclimat: Path # lu au moment de l'appel, jamais copié
|
|
cle_romma: Path
|
|
stations: Path # liste des stations Infoclimat suivies (JSON)
|
|
plafond_commun: int = 4999 # même plafond que le collecteur (décision du 29/09)
|
|
plafond_site: int = 1000 # plafond propre au site (décision du 16/10)
|
|
seuil_alerte: float = 0.80
|
|
alerte_active: bool = False # aucun envoi réel tant que Théo ne l'a pas activé
|
|
ntfy_url: str = ""
|
|
compte_par_station: bool = False # parade si Infoclimat compte une requête par station (§2.4)
|
|
lot_max: int = 25
|
|
garder_jours: int = 14
|
|
fiche_heures: int = 48
|
|
romma_actif: bool = True
|
|
infoclimat_actif: bool = True
|
|
direct_compat: Path = None # si défini : écrit aussi l'ancien direct.json (site LAN)
|
|
|
|
@classmethod
|
|
def depuis_env(cls, env=None):
|
|
e = os.environ if env is None else env
|
|
home = Path.home()
|
|
base = Path(e.get("MC_BASE") or home / "meteo-collecte")
|
|
|
|
def chemin(nom, defaut):
|
|
return Path(e[nom]) if e.get(nom) else defaut
|
|
|
|
def oui(nom, defaut):
|
|
v = e.get(nom)
|
|
return defaut if v is None else v.strip().lower() in ("1", "oui", "true", "yes")
|
|
|
|
return cls(
|
|
base=base,
|
|
public=chemin("MC_PUBLIC", base / "public"),
|
|
quota_commun=chemin("MC_QUOTA_COMMUN", home / "gws-collecte" / "quota.json"),
|
|
jeton_infoclimat=chemin("MC_JETON_INFOCLIMAT", home / "gws-collecte" / "infoclimat.token"),
|
|
cle_romma=chemin("MC_CLE_ROMMA", base / ".secrets" / "romma.key"),
|
|
stations=chemin("MC_STATIONS", Path(__file__).resolve().parent.parent / "config" / "stations.json"),
|
|
plafond_commun=int(e.get("MC_PLAFOND_COMMUN", 4999)),
|
|
plafond_site=int(e.get("MC_PLAFOND_SITE", 1000)),
|
|
alerte_active=oui("MC_ALERTE_ACTIVE", False),
|
|
ntfy_url=e.get("MC_NTFY_URL", ""),
|
|
compte_par_station=oui("MC_COMPTE_PAR_STATION", False),
|
|
lot_max=int(e.get("MC_LOT_MAX", 25)),
|
|
romma_actif=oui("MC_ROMMA_ACTIF", True),
|
|
infoclimat_actif=oui("MC_INFOCLIMAT_ACTIF", True),
|
|
direct_compat=chemin("MC_DIRECT_COMPAT", None),
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Heure de Paris (règle européenne codée ici : zoneinfo demande tzdata, absent sous Windows)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def _dernier_dimanche(annee, mois):
|
|
d = dt.date(annee, mois, 31)
|
|
return d - dt.timedelta(days=(d.weekday() + 1) % 7)
|
|
|
|
|
|
def decalage_paris(utc):
|
|
"""Décalage de Paris sur l'UTC à l'instant `utc` (aware) : 1 h (CET) ou 2 h (CEST)."""
|
|
a = utc.year
|
|
debut = dt.datetime.combine(_dernier_dimanche(a, 3), dt.time(1), UTC)
|
|
fin = dt.datetime.combine(_dernier_dimanche(a, 10), dt.time(1), UTC)
|
|
return dt.timedelta(hours=2 if debut <= utc < fin else 1)
|
|
|
|
|
|
def vers_paris(utc):
|
|
return (utc + decalage_paris(utc)).replace(tzinfo=None)
|
|
|
|
|
|
def paris_vers_utc(local, maintenant=None):
|
|
"""Heure locale de Paris (naïve) -> instant UTC.
|
|
|
|
None si l'heure n'existe pas (passage à l'heure d'été). Pour l'heure doublée d'octobre, on garde la plus
|
|
récente des deux qui n'est pas dans le futur par rapport à `maintenant` (sinon la plus ancienne).
|
|
"""
|
|
possibles = []
|
|
for h in (2, 1):
|
|
c = (local - dt.timedelta(hours=h)).replace(tzinfo=UTC)
|
|
if (c + decalage_paris(c)).replace(tzinfo=None) == local:
|
|
possibles.append(c)
|
|
if not possibles:
|
|
return None
|
|
if len(possibles) == 1 or maintenant is None:
|
|
return possibles[0]
|
|
passes = [c for c in possibles if c <= maintenant]
|
|
return max(passes) if passes else min(possibles)
|
|
|
|
|
|
def jour_paris(utc):
|
|
return str(vers_paris(utc).date())
|
|
|
|
|
|
def fmt_utc(t):
|
|
return t.astimezone(UTC).strftime("%Y-%m-%d %H:%M:%S")
|
|
|
|
|
|
def lire_utc(s):
|
|
return dt.datetime.strptime(s, "%Y-%m-%d %H:%M:%S").replace(tzinfo=UTC)
|
|
|
|
|
|
def iso(t):
|
|
return t.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Fichiers
|
|
# ---------------------------------------------------------------------------
|
|
|
|
def lire_json(p, defaut):
|
|
try:
|
|
return json.loads(Path(p).read_text(encoding="utf-8"))
|
|
except (OSError, ValueError):
|
|
return defaut
|
|
|
|
|
|
def ecrire_json(p, d, compact=True):
|
|
"""Écriture atomique : fichier temporaire dans le même dossier, puis os.replace."""
|
|
p = Path(p)
|
|
p.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = p.with_name(p.name + ".tmp-%d" % os.getpid())
|
|
texte = json.dumps(d, ensure_ascii=False, separators=(",", ":") if compact else None,
|
|
indent=None if compact else 1)
|
|
tmp.write_text(texte, encoding="utf-8")
|
|
os.replace(tmp, p)
|
|
|
|
|
|
def lire_secret(p):
|
|
"""Lit un jeton ou une clé au moment de l'appel. Le contenu n'est jamais journalisé."""
|
|
return Path(p).read_text(encoding="utf-8").strip()
|
|
|
|
|
|
def scrub(texte, *secrets):
|
|
"""Masque tout paramètre token=/apikey= d'URL et chaque secret, en clair ou encodé pour l'URL."""
|
|
texte = re.sub(r"(?i)\b(token|apikey)=[^&\s)\"']*", lambda m: m.group(1) + "=***", str(texte))
|
|
for s in secrets:
|
|
if s:
|
|
texte = texte.replace(s, "***")
|
|
enc = urllib.parse.quote(s, safe="")
|
|
if enc != s:
|
|
texte = texte.replace(enc, "***")
|
|
return texte
|
|
|
|
|
|
class Journal:
|
|
"""Journal texte horodaté (heure de Paris). Tout message passe par `scrub`."""
|
|
|
|
def __init__(self, fichier):
|
|
self.fichier = Path(fichier)
|
|
self.secrets = []
|
|
|
|
def masquer(self, *secrets):
|
|
self.secrets.extend(s for s in secrets if s)
|
|
|
|
def __call__(self, msg, maintenant=None):
|
|
t = maintenant or dt.datetime.now(UTC)
|
|
self.fichier.parent.mkdir(parents=True, exist_ok=True)
|
|
with open(self.fichier, "a", encoding="utf-8") as f:
|
|
f.write(vers_paris(t).strftime("%Y-%m-%d %H:%M:%S ") + scrub(msg, *self.secrets) + "\n")
|
|
|
|
|
|
class Verrou:
|
|
"""Verrou exclusif non bloquant (fcntl). Sans fcntl (Windows, tests), le verrou est toujours obtenu."""
|
|
|
|
def __init__(self, fichier):
|
|
self.fichier = Path(fichier)
|
|
self.f = None
|
|
|
|
def __enter__(self):
|
|
self.fichier.parent.mkdir(parents=True, exist_ok=True)
|
|
self.f = open(self.fichier, "w")
|
|
if fcntl is not None:
|
|
try:
|
|
fcntl.flock(self.f, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
except OSError:
|
|
self.f.close()
|
|
self.f = None
|
|
return False
|
|
return True
|
|
|
|
def __exit__(self, *a):
|
|
if self.f:
|
|
self.f.close()
|
|
|
|
|
|
class Pause:
|
|
"""Pause après erreur (fichier contenant un timestamp), reprise de direct.py : 15 min par défaut."""
|
|
|
|
def __init__(self, fichier, duree_s=15 * 60):
|
|
self.fichier = Path(fichier)
|
|
self.duree_s = duree_s
|
|
|
|
def active(self, maintenant):
|
|
try:
|
|
return float(self.fichier.read_text()) > maintenant.timestamp()
|
|
except (OSError, ValueError):
|
|
return False
|
|
|
|
def jusqua(self):
|
|
try:
|
|
return dt.datetime.fromtimestamp(float(self.fichier.read_text()), UTC)
|
|
except (OSError, ValueError):
|
|
return None
|
|
|
|
def poser(self, maintenant):
|
|
self.fichier.parent.mkdir(parents=True, exist_ok=True)
|
|
self.fichier.write_text(str(maintenant.timestamp() + self.duree_s))
|