Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XGaEeTZLvHXfYPUNWkgYoi
67 lines
2.1 KiB
Python
67 lines
2.1 KiB
Python
"""Sauvegarde quotidienne de la base de Courrier (classements manuels, courses, a suivre, fiches IA).
|
|
Copie coherente par l'API de sauvegarde SQLite, une par jour, quatorze jours conservees."""
|
|
import logging
|
|
import os
|
|
import sqlite3
|
|
import threading
|
|
import time
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
from app import config
|
|
from app.config import get_tunis_now_iso
|
|
|
|
log = logging.getLogger("courrier.sauvegarde")
|
|
CONSERVES = 14
|
|
|
|
|
|
def _dossier(db_path: Optional[str] = None) -> str:
|
|
d = os.path.join(os.path.dirname(db_path or config.DB_PATH), "sauvegardes")
|
|
os.makedirs(d, exist_ok=True)
|
|
return d
|
|
|
|
|
|
def liste(db_path: Optional[str] = None) -> List[Dict[str, Any]]:
|
|
d = _dossier(db_path)
|
|
out = []
|
|
for nom in sorted(os.listdir(d), reverse=True):
|
|
if nom.startswith("courrier-") and nom.endswith(".db"):
|
|
out.append({"nom": nom, "jour": nom[9:19], "octets": os.path.getsize(os.path.join(d, nom))})
|
|
return out
|
|
|
|
|
|
def sauvegarder(db_path: Optional[str] = None, force: bool = False) -> Optional[str]:
|
|
"""Une sauvegarde par jour. Retourne le nom du fichier cree, ou None s'il existe deja."""
|
|
src = db_path or config.DB_PATH
|
|
jour = get_tunis_now_iso()[:10]
|
|
d = _dossier(src)
|
|
cible = os.path.join(d, "courrier-%s.db" % jour)
|
|
if os.path.exists(cible) and not force:
|
|
return None
|
|
tmp = cible + ".tmp"
|
|
a = sqlite3.connect(src); b = sqlite3.connect(tmp)
|
|
try:
|
|
a.backup(b)
|
|
finally:
|
|
b.close(); a.close()
|
|
os.replace(tmp, cible)
|
|
os.chmod(cible, 0o640)
|
|
for ancien in liste(src)[CONSERVES:]:
|
|
try:
|
|
os.remove(os.path.join(d, ancien["nom"]))
|
|
except OSError:
|
|
pass
|
|
return os.path.basename(cible)
|
|
|
|
|
|
def demarrer(intervalle: int = 3600) -> None:
|
|
def boucle() -> None:
|
|
while True:
|
|
try:
|
|
n = sauvegarder()
|
|
if n:
|
|
log.info("sauvegarde %s", n)
|
|
except Exception:
|
|
log.warning("sauvegarde impossible")
|
|
time.sleep(intervalle)
|
|
threading.Thread(target=boucle, name="sauvegarde-courrier", daemon=True).start()
|