Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
097a27fcf3 | ||
|
|
93f66d6aca | ||
|
|
eef81ea323 | ||
|
|
a21acaa409 | ||
|
|
f261fed1af | ||
|
|
e6f0659cbf |
+5
-2
@@ -28,7 +28,9 @@ PRONOTE_AUTH_MODE=password
|
||||
# PRONOTE_ACCOUNT_PIN=
|
||||
|
||||
# --- CalDAV ---
|
||||
CALDAV_URL=https://caldav.example.com/calendars/user/pronote/
|
||||
# Endpoint commun (URL potentiellement sensible, masquée dans les journaux)
|
||||
CALDAV_ENDPOINT__URL=https://caldav.example.com/calendars/user/pronote/
|
||||
# Ancien nom temporairement supporté avec un avertissement de dépréciation : CALDAV_URL
|
||||
CALDAV_USERNAME=user@example.com
|
||||
CALDAV_PASSWORD=your_caldav_password
|
||||
CALDAV_CALENDAR_PATH=/pronote-sync/
|
||||
@@ -92,7 +94,8 @@ AI_BASE_URL=https://api.openai.com/v1
|
||||
|
||||
# --- Blog ---
|
||||
BLOG_ENABLED=false
|
||||
BLOG_RSS_URL=https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2
|
||||
BLOG_ENDPOINT__URL=https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2
|
||||
# Ancien nom temporairement supporté avec un avertissement de dépréciation : BLOG_RSS_URL
|
||||
|
||||
# --- Divers ---
|
||||
DRY_RUN=false
|
||||
|
||||
+2
-2
@@ -140,7 +140,7 @@
|
||||
"filename": "GUIDE_DEV_PYTHON.md",
|
||||
"hashed_secret": "90bd1b48e958257948487b90bee080ba5ed00caa",
|
||||
"is_verified": false,
|
||||
"line_number": 5186
|
||||
"line_number": 5183
|
||||
}
|
||||
],
|
||||
"tests/unit/test_caldav_gateway.py": [
|
||||
@@ -185,5 +185,5 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"generated_at": "2026-09-12T22:12:56Z"
|
||||
"generated_at": "2026-09-13T09:52:29Z"
|
||||
}
|
||||
|
||||
+2
-3
@@ -40,7 +40,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [0.1.0] - 2026-09-08
|
||||
|
||||
Initial release covering milestones M1 through M15.
|
||||
Initial release covering milestones M1 through M15, except the optional Gitea Actions workflow.
|
||||
|
||||
### Added
|
||||
- **M1 (Scaffolding)**: Python project structure with `pyproject.toml`, and tooling configuration for `ruff`, `mypy`, `bandit`, and `pre-commit`.
|
||||
@@ -57,5 +57,4 @@ Initial release covering milestones M1 through M15.
|
||||
- **M12 (CLI entry point)**: `pronote-sync` command with `--dry-run` and `--log-level` options, redacted error display, and safe traceback in DEBUG mode.
|
||||
- **M13 (Tests & coverage)**: 636 tests with 95.67% coverage, test fixtures (`pronote-4e.ics`, `pronote-6e.ics`), shared `conftest.py`, and secret non-leak tests.
|
||||
- **M14 (Deployment)**: systemd service and timer (daily at 18:00), logrotate configuration (daily, rotate 7, compress), `check_secrets.py` pre-deployment scanner, and exploitation guide.
|
||||
- **M15 (Documentation)**: README, README.LLM.md (AI agent setup guide), MIT LICENSE, CHANGELOG, and Gitea Actions CI/CD reference for LXC/VPS (Debian/CentOS).
|
||||
- **Other**: MIT License. Gitea Actions CI/CD reference for LXC/VPS (Debian/CentOS) is planned and optional, not delivered in this release.
|
||||
- **M15 (Documentation)**: README, README.LLM.md (AI agent setup guide), MIT LICENSE, CHANGELOG, and local validation procedures. Gitea Actions CI/CD remains optional and is not delivered in this release.
|
||||
|
||||
+5
-8
@@ -264,7 +264,7 @@ Le projet utilise **`pydantic-settings`** pour valider et charger la configurati
|
||||
| `PRONOTE_USERNAME` | Identifiant Pronote (si `pronotepy` utilisé). | `parent.dupont` | `str` |
|
||||
| `PRONOTE_PASSWORD` | Mot de passe Pronote (si `pronotepy` utilisé). | `SecretStr` (masqué) | `SecretStr` |
|
||||
| `PRONOTE_ENT` | Slug ENT supporté, résolu vers une fonction de `pronotepy.ent`. | `monbureaunumerique` | `str` |
|
||||
| `CALDAV_URL` | URL du serveur CalDAV (masquée en `SecretStr`). | `https://caldav.example.com/calendars/...` | `SecretStr` |
|
||||
| `CALDAV_ENDPOINT__URL` | URL du serveur CalDAV, via l'endpoint commun (masquée en `SecretStr`). | `https://caldav.example.com/calendars/...` | `ExternalEndpoint` |
|
||||
| `CALDAV_USERNAME` | Identifiant CalDAV. | `user@example.com` | `str` |
|
||||
| `CALDAV_PASSWORD` | Mot de passe CalDAV. | `SecretStr` (masqué) | `SecretStr` |
|
||||
| `CALDAV_CALENDAR_PATH` | Chemin du calendrier CalDAV de destination. | `/pronote-sync/` | `str` |
|
||||
@@ -1113,7 +1113,7 @@ La déduplication des articles du blog repose sur leur **GUID** (ou leur URL si
|
||||
|
||||
Aucun fichier d'état local n'est utilisé : l'état est géré en mémoire par run.
|
||||
# Initialisation
|
||||
rss_client = BlogRSSClient(rss_url=settings.blog.rss_url)
|
||||
rss_client = BlogRSSClient(rss_url=settings.blog.endpoint.url.get_secret_value())
|
||||
blog_state = ## (section obsolète supprimée)()
|
||||
|
||||
# Récupération des nouveaux articles
|
||||
@@ -1218,7 +1218,7 @@ Ajouter les variables suivantes dans la configuration :
|
||||
| **Variable** | **Description** | **Valeur par défaut** | **Type** |
|
||||
|----------------------------|-------------------------------------------------------------------------------|-----------------------|-------------------|
|
||||
| `BLOG_ENABLED` | Activer la récupération du blog. | `False` | `bool` |
|
||||
| `BLOG_RSS_URL` | URL du flux RSS du blog. | `https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2` | `str` |
|
||||
| `BLOG_ENDPOINT__URL` | URL du flux RSS via l'endpoint commun (masquée en `SecretStr`). | `https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2` | `ExternalEndpoint` |
|
||||
|
||||
#### 5 bis.9.2 Modèle Pydantic pour la configuration du blog
|
||||
|
||||
@@ -1230,10 +1230,7 @@ from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
class BlogSettings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_prefix="BLOG_", env_file=".env", extra="ignore")
|
||||
enabled: bool = Field(False, description="Activer la récupération du blog")
|
||||
rss_url: str = Field(
|
||||
"https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2",
|
||||
description="URL du flux RSS du blog",
|
||||
)
|
||||
endpoint: ExternalEndpoint
|
||||
```
|
||||
|
||||
**Intégration dans `Settings`** :
|
||||
@@ -1253,7 +1250,7 @@ class Settings(BaseSettings):
|
||||
```ini
|
||||
# --- Blog du collège ---
|
||||
BLOG_ENABLED=true
|
||||
BLOG_RSS_URL=https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2
|
||||
BLOG_ENDPOINT__URL=https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -12,8 +12,8 @@ Synchronise l'agenda et les devoirs de **Pronote** vers un calendrier **CalDAV**
|
||||
|
||||
```bash
|
||||
# Cloner le dépôt
|
||||
git clone <repo-url>
|
||||
cd pronote-sync
|
||||
git clone https://git.antoineve.me/AntoineVe/college-infos
|
||||
cd college-infos
|
||||
|
||||
# Créer l'environnement virtuel
|
||||
python3.13 -m venv .venv
|
||||
@@ -48,6 +48,23 @@ pas garantir un état persistant cohérent pendant une simulation.
|
||||
|
||||
---
|
||||
|
||||
## Validation et CI
|
||||
|
||||
Aucun workflow Gitea Actions n'est livré actuellement. Les validations du projet sont donc
|
||||
exécutées localement avec les commandes suivantes :
|
||||
|
||||
```bash
|
||||
pytest
|
||||
ruff check .
|
||||
mypy .
|
||||
bandit -r pronote_sync/
|
||||
```
|
||||
|
||||
`pre-commit run --all-files` regroupe également les contrôles de formatage, typage, sécurité et
|
||||
détection de secrets.
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Déploiement
|
||||
|
||||
Les artefacts pour **systemd/timer** et **logrotate** sont fournis dans `deploy/`. Voir [docs/exploitation.md](docs/exploitation.md) pour plus de détails.
|
||||
|
||||
@@ -308,5 +308,5 @@ Rédiger la documentation utilisateur et finaliser le projet.
|
||||
|
||||
### Critères d'acceptation
|
||||
- `README.md` permet d'installer et de lancer le projet sans le guide.
|
||||
- Gitea Actions exécute tests + lint + sécurité.
|
||||
- Les procédures locales de test, lint et sécurité sont documentées et exécutables.
|
||||
- Aucun secret dans la documentation.
|
||||
|
||||
+162
-41
@@ -10,21 +10,76 @@ from __future__ import annotations
|
||||
|
||||
import warnings
|
||||
from datetime import date
|
||||
from typing import Literal
|
||||
from typing import Annotated, Literal
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from pydantic import (
|
||||
AfterValidator,
|
||||
BaseModel,
|
||||
ConfigDict,
|
||||
Field,
|
||||
SecretStr,
|
||||
ValidationInfo,
|
||||
field_serializer,
|
||||
field_validator,
|
||||
model_validator,
|
||||
)
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
from pronote_sync.utils.redaction import redact_url
|
||||
|
||||
_EXTERNAL_ENDPOINT_SCHEMES: frozenset[str] = frozenset({"file", "http", "https"})
|
||||
_LOOPBACK_HOSTS: frozenset[str] = frozenset({"localhost", "127.0.0.1", "::1"})
|
||||
|
||||
|
||||
def _validate_external_endpoint_url(value: SecretStr) -> SecretStr:
|
||||
"""Valide la structure et le schéma d'une URL d'endpoint externe.
|
||||
|
||||
:param value: URL potentiellement sensible à valider.
|
||||
:return: URL validée, toujours encapsulée dans ``SecretStr``.
|
||||
:rtype: SecretStr
|
||||
:raises ValueError: Si l'URL est malformée ou utilise un schéma inconnu.
|
||||
"""
|
||||
is_valid = False
|
||||
try:
|
||||
parsed = urlparse(value.get_secret_value())
|
||||
_ = parsed.port
|
||||
is_valid = (
|
||||
parsed.scheme in _EXTERNAL_ENDPOINT_SCHEMES
|
||||
and (parsed.scheme not in {"http", "https"} or parsed.hostname is not None)
|
||||
and (parsed.scheme != "file" or bool(parsed.path))
|
||||
)
|
||||
except ValueError:
|
||||
pass
|
||||
if not is_valid:
|
||||
raise ValueError("Endpoint externe invalide : URL ou schéma non supporté") from None
|
||||
return value
|
||||
|
||||
|
||||
EndpointUrl = Annotated[SecretStr, AfterValidator(_validate_external_endpoint_url)]
|
||||
|
||||
|
||||
class ExternalEndpoint(BaseModel):
|
||||
"""Représente un endpoint externe potentiellement sensible.
|
||||
|
||||
Le socle accepte les transports ``https``, ``http`` et ``file``. Chaque
|
||||
connecteur restreint ensuite cette liste selon sa propre politique de
|
||||
sécurité. L'URL reste encapsulée dans :class:`pydantic.SecretStr` et sa
|
||||
sérialisation conserve uniquement une représentation expurgée.
|
||||
"""
|
||||
|
||||
model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True)
|
||||
|
||||
url: EndpointUrl
|
||||
|
||||
@field_serializer("url")
|
||||
def _serialize_url(self, value: SecretStr) -> str:
|
||||
"""Expurge l'URL lors de la sérialisation.
|
||||
|
||||
:param value: URL encapsulée à sérialiser.
|
||||
:return: URL expurgée.
|
||||
:rtype: str
|
||||
"""
|
||||
return redact_url(value.get_secret_value())
|
||||
|
||||
|
||||
class PronoteSettings(BaseSettings):
|
||||
"""Paramètres d'accès à Pronote (flux iCal et API ``pronotepy``).
|
||||
@@ -91,73 +146,88 @@ class CalDAVSettings(BaseSettings):
|
||||
|
||||
Les variables d'environnement correspondantes sont préfixées par
|
||||
``CALDAV_``. L'URL est traitée comme potentiellement sensible (au même
|
||||
titre que ``PRONOTE_ICAL_URL``) : elle est de type ``SecretStr`` et
|
||||
titre que ``PRONOTE_ICAL_ENDPOINT__URL``) : elle est de type ``SecretStr`` et
|
||||
masquée lors de la sérialisation. Par défaut, seul HTTPS est accepté ;
|
||||
HTTP n'est toléré que pour un hôte de boucle locale (``localhost``,
|
||||
``127.0.0.1``, ``::1``) lorsque ``allow_insecure_http`` vaut ``True``.
|
||||
Le nouvel endpoint se configure avec ``CALDAV_ENDPOINT__URL`` ;
|
||||
``CALDAV_URL`` reste temporairement pris en charge avec un avertissement
|
||||
de dépréciation.
|
||||
"""
|
||||
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore", env_prefix="CALDAV_")
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_nested_delimiter="__",
|
||||
extra="ignore",
|
||||
env_prefix="CALDAV_",
|
||||
)
|
||||
|
||||
allow_insecure_http: bool = False
|
||||
url: SecretStr | None = None
|
||||
endpoint: ExternalEndpoint | None = None
|
||||
url: SecretStr | None = Field(
|
||||
default=None,
|
||||
exclude=True,
|
||||
deprecated="Utiliser endpoint.url à la place (CALDAV_URL obsolète).",
|
||||
)
|
||||
username: str | None = None
|
||||
password: SecretStr | None = None
|
||||
calendar_path: str = "/pronote-sync/"
|
||||
|
||||
@field_serializer("url")
|
||||
def _serialize_url(self, value: SecretStr | None) -> str | None:
|
||||
"""Masque l'URL CalDAV lors de la sérialisation (repr, str, JSON).
|
||||
|
||||
:param value: Valeur du champ ``url`` (secret potentiel).
|
||||
:return: URL avec les éléments sensibles remplacés par ``REDACTED``,
|
||||
ou ``None`` si la valeur est absente.
|
||||
:rtype: str | None
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
return redact_url(value.get_secret_value())
|
||||
|
||||
@field_validator("url")
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _validate_url_https(cls, v: SecretStr | None, info: ValidationInfo) -> SecretStr | None:
|
||||
"""Valide le schéma de l'URL CalDAV (HTTPS obligatoire par défaut).
|
||||
def _migrate_legacy_url(cls, data: object) -> object:
|
||||
"""Migre ``url`` vers l'endpoint commun avec un avertissement.
|
||||
|
||||
:param data: Données brutes du modèle.
|
||||
:return: Données complétées avec ``endpoint`` si nécessaire.
|
||||
:rtype: object
|
||||
"""
|
||||
if not isinstance(data, dict) or data.get("url") is None:
|
||||
return data
|
||||
migrated_data = data.copy()
|
||||
warnings.warn(
|
||||
"CALDAV_URL est obsolète : utiliser CALDAV_ENDPOINT__URL.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
if migrated_data.get("endpoint") is None:
|
||||
migrated_data["endpoint"] = {"url": migrated_data["url"]}
|
||||
return migrated_data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_endpoint_policy(self) -> CalDAVSettings:
|
||||
"""Applique la politique HTTPS/HTTP loopback propre à CalDAV.
|
||||
|
||||
HTTPS est toujours accepté. HTTP n'est accepté que pour un hôte de
|
||||
boucle locale (``localhost``, ``127.0.0.1``, ``::1``) et uniquement
|
||||
lorsque ``allow_insecure_http`` vaut ``True``. Les messages d'erreur
|
||||
ne contiennent jamais l'URL brute (susceptible de contenir des
|
||||
identifiants).
|
||||
lorsque ``allow_insecure_http`` vaut ``True``. Les autres schémas du
|
||||
socle commun sont refusés pour ce connecteur.
|
||||
|
||||
:param v: Valeur du champ ``url`` à valider.
|
||||
:param info: Contexte de validation (accès aux autres champs).
|
||||
:return: La valeur validée inchangée.
|
||||
:rtype: SecretStr | None
|
||||
:return: Instance validée inchangée.
|
||||
:rtype: CalDAVSettings
|
||||
:raises ValueError: Si le schéma n'est pas supporté ou si l'URL HTTP
|
||||
n'est pas autorisée.
|
||||
"""
|
||||
if v is None:
|
||||
return v
|
||||
raw_url = v.get_secret_value()
|
||||
if self.endpoint is None:
|
||||
return self
|
||||
raw_url = self.endpoint.url.get_secret_value()
|
||||
parsed = urlparse(raw_url)
|
||||
if parsed.scheme not in ("http", "https"):
|
||||
raise ValueError("URL CalDAV invalide : schéma non supporté") from None
|
||||
if parsed.scheme == "https":
|
||||
return v
|
||||
return self
|
||||
# HTTP — check allow_insecure_http flag and loopback
|
||||
allow_insecure = info.data.get("allow_insecure_http", False)
|
||||
if not allow_insecure:
|
||||
if not self.allow_insecure_http:
|
||||
raise ValueError(
|
||||
"URL CalDAV non sécurisée : HTTPS requis (ou activer "
|
||||
"CALDAV_ALLOW_INSECURE_HTTP pour localhost)"
|
||||
) from None
|
||||
hostname = parsed.hostname or ""
|
||||
loopback_hosts = {"localhost", "127.0.0.1", "::1"}
|
||||
if hostname not in loopback_hosts:
|
||||
if hostname not in _LOOPBACK_HOSTS:
|
||||
raise ValueError(
|
||||
"URL CalDAV non sécurisée : HTTP autorisé uniquement pour localhost"
|
||||
) from None
|
||||
return v
|
||||
return self
|
||||
|
||||
|
||||
_XMPP_LOOPBACK_HOSTS: frozenset[str] = frozenset({"localhost", "127.0.0.1", "::1"})
|
||||
@@ -282,10 +352,60 @@ class BlogSettings(BaseSettings):
|
||||
``BLOG_``.
|
||||
"""
|
||||
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore", env_prefix="BLOG_")
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_nested_delimiter="__",
|
||||
extra="ignore",
|
||||
env_prefix="BLOG_",
|
||||
)
|
||||
|
||||
enabled: bool = False
|
||||
rss_url: str = "https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2"
|
||||
endpoint: ExternalEndpoint = Field(
|
||||
default_factory=lambda: ExternalEndpoint(
|
||||
url=SecretStr("https://blogpeda.ac-bordeaux.fr/cjeliote/?feed=rss2")
|
||||
)
|
||||
)
|
||||
rss_url: str | None = Field(
|
||||
default=None,
|
||||
exclude=True,
|
||||
deprecated="Utiliser endpoint.url à la place (BLOG_RSS_URL obsolète).",
|
||||
)
|
||||
|
||||
@model_validator(mode="before")
|
||||
@classmethod
|
||||
def _migrate_legacy_rss_url(cls, data: object) -> object:
|
||||
"""Migre ``rss_url`` vers l'endpoint commun avec un avertissement.
|
||||
|
||||
:param data: Données brutes du modèle.
|
||||
:return: Données complétées avec ``endpoint`` si nécessaire.
|
||||
:rtype: object
|
||||
"""
|
||||
if not isinstance(data, dict) or data.get("rss_url") is None:
|
||||
return data
|
||||
migrated_data = data.copy()
|
||||
warnings.warn(
|
||||
"BLOG_RSS_URL est obsolète : utiliser BLOG_ENDPOINT__URL.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
if migrated_data.get("endpoint") is None:
|
||||
migrated_data["endpoint"] = {"url": migrated_data["rss_url"]}
|
||||
return migrated_data
|
||||
|
||||
@model_validator(mode="after")
|
||||
def _validate_endpoint_policy(self) -> BlogSettings:
|
||||
"""Refuse les transports non sûrs pour le flux RSS de production.
|
||||
|
||||
Le transport ``file`` reste autorisé pour les fixtures locales.
|
||||
|
||||
:return: Instance validée inchangée.
|
||||
:rtype: BlogSettings
|
||||
:raises ValueError: Si le schéma n'est ni ``https`` ni ``file``.
|
||||
"""
|
||||
scheme = urlparse(self.endpoint.url.get_secret_value()).scheme
|
||||
if scheme not in {"https", "file"}:
|
||||
raise ValueError("URL RSS invalide : HTTPS ou file requis") from None
|
||||
return self
|
||||
|
||||
|
||||
class AppSettings(BaseSettings):
|
||||
@@ -342,9 +462,10 @@ class Settings(BaseSettings):
|
||||
self.pronote.password,
|
||||
self.pronote.qr_pin,
|
||||
self.pronote.account_pin,
|
||||
self.caldav.url,
|
||||
self.caldav.endpoint.url if self.caldav.endpoint is not None else None,
|
||||
self.caldav.password,
|
||||
self.xmpp.password,
|
||||
self.ai.api_key,
|
||||
self.blog.endpoint.url,
|
||||
]
|
||||
return tuple(dict.fromkeys(secret for secret in secrets if secret is not None))
|
||||
|
||||
@@ -138,7 +138,11 @@ class PipelineRunner:
|
||||
comparator = (
|
||||
AgendaComparator(theoretical_provider) if theoretical_provider is not None else None
|
||||
)
|
||||
blog_client = BlogRSSClient(settings.blog.rss_url) if settings.blog.enabled else None
|
||||
blog_client = (
|
||||
BlogRSSClient(settings.blog.endpoint.url.get_secret_value())
|
||||
if settings.blog.enabled
|
||||
else None
|
||||
)
|
||||
blog_state = (
|
||||
BlogRSSState(persistence_enabled=persistence_enabled) if settings.blog.enabled else None
|
||||
)
|
||||
|
||||
@@ -97,7 +97,10 @@ class BlogRSSState:
|
||||
redact_exception(exc),
|
||||
)
|
||||
|
||||
def _save(self) -> None:
|
||||
def _save(
|
||||
self,
|
||||
state: tuple[set[str], str | None, str | None] | None = None,
|
||||
) -> bool:
|
||||
"""Sauvegarde l'état dans le fichier JSON de manière atomique.
|
||||
|
||||
La sortie est déterministe : ``known_guids`` est trié
|
||||
@@ -107,20 +110,30 @@ class BlogRSSState:
|
||||
jamais laisser un fichier partiel en cas d'interruption. En cas
|
||||
d'erreur d'écriture, une erreur est journalisée sans être
|
||||
propagée et le fichier temporaire est supprimé.
|
||||
|
||||
:param state: État à sauvegarder ; l'état courant est utilisé par défaut.
|
||||
:return: ``True`` si l'état a été sauvegardé ou si la persistance est désactivée.
|
||||
:rtype: bool
|
||||
"""
|
||||
if not self._persistence_enabled:
|
||||
return
|
||||
return True
|
||||
known_guids, etag, last_modified = state or (
|
||||
self._known_guids,
|
||||
self._etag,
|
||||
self._last_modified,
|
||||
)
|
||||
payload = {
|
||||
"version": _STATE_VERSION,
|
||||
"known_guids": sorted(self._known_guids),
|
||||
"etag": self._etag,
|
||||
"last_modified": self._last_modified,
|
||||
"known_guids": sorted(known_guids),
|
||||
"etag": etag,
|
||||
"last_modified": last_modified,
|
||||
}
|
||||
tmp_file = self._state_file.with_suffix(".tmp")
|
||||
try:
|
||||
with open(tmp_file, "w", encoding="utf-8") as handle:
|
||||
json.dump(payload, handle, indent=2)
|
||||
tmp_file.replace(self._state_file)
|
||||
return True
|
||||
except Exception as exc:
|
||||
logger.error(
|
||||
"Impossible d'écrire le fichier d'état blog RSS %s : %s.",
|
||||
@@ -134,6 +147,7 @@ class BlogRSSState:
|
||||
"Nettoyage du fichier temporaire échoué : %s",
|
||||
redact_exception(cleanup_exc),
|
||||
)
|
||||
return False
|
||||
|
||||
def get_known_guids(self) -> frozenset[str]:
|
||||
"""Renvoie une copie immuable des GUID d'articles déjà connus.
|
||||
@@ -168,10 +182,13 @@ class BlogRSSState:
|
||||
"""
|
||||
if result.not_modified:
|
||||
return
|
||||
self._known_guids.update(article.id for article in result.articles)
|
||||
self._etag = result.etag
|
||||
self._last_modified = result.last_modified
|
||||
self._save()
|
||||
new_state = (
|
||||
self._known_guids | {article.id for article in result.articles},
|
||||
result.etag,
|
||||
result.last_modified,
|
||||
)
|
||||
if self._save(new_state):
|
||||
self._known_guids, self._etag, self._last_modified = new_state
|
||||
|
||||
def get_cache_headers(self) -> tuple[str | None, str | None]:
|
||||
"""Renvoie les en-têtes de cache HTTP mémorisés.
|
||||
|
||||
@@ -79,11 +79,12 @@ class CalDAVGateway:
|
||||
else cast(Callable[..., Any], caldav.DAVClient)
|
||||
)
|
||||
self._calendar_path: str = settings.calendar_path
|
||||
url_secret = settings.endpoint.url if settings.endpoint is not None else None
|
||||
self._redacted_url: str | None = (
|
||||
redact_url(settings.url.get_secret_value()) if settings.url else None
|
||||
redact_url(url_secret.get_secret_value()) if url_secret else None
|
||||
)
|
||||
self._username: str | None = settings.username
|
||||
self._url_secret: SecretStr | None = settings.url
|
||||
self._url_secret: SecretStr | None = url_secret
|
||||
self._password_secret: SecretStr | None = settings.password
|
||||
self._client: Any = None
|
||||
self._calendar: Any = None
|
||||
|
||||
@@ -96,7 +96,7 @@ def synchronize(
|
||||
)
|
||||
|
||||
if (
|
||||
settings.caldav.url is None
|
||||
settings.caldav.endpoint is None
|
||||
or settings.caldav.username is None
|
||||
or settings.caldav.password is None
|
||||
):
|
||||
|
||||
+6
-5
@@ -7,9 +7,10 @@ name = "pronote-sync"
|
||||
version = "0.1.2"
|
||||
description = "Synchronisation Pronote → CalDAV + XMPP"
|
||||
license = {text = "MIT"}
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.13.5"
|
||||
authors = [
|
||||
{name = "Votre Nom", email = "votre@email.com"}
|
||||
{name = "Antoine Van Elstraete", email = "antoine@van-elstraete.net"}
|
||||
]
|
||||
keywords = ["pronote", "caldav", "xmpp", "sync", "school"]
|
||||
classifiers = [
|
||||
@@ -57,10 +58,10 @@ dev = [
|
||||
pronote-sync = "pronote_sync.cli.main:main"
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/votre-utilisateur/pronote-sync"
|
||||
Documentation = "https://github.com/votre-utilisateur/pronote-sync#readme"
|
||||
Repository = "https://github.com/votre-utilisateur/pronote-sync"
|
||||
Issues = "https://github.com/votre-utilisateur/pronote-sync/issues"
|
||||
Homepage = "https://git.antoineve.me/AntoineVe/college-infos"
|
||||
Documentation = "https://git.antoineve.me/AntoineVe/college-infos/wiki"
|
||||
Repository = "https://git.antoineve.me/AntoineVe/college-infos"
|
||||
Issues = "https://git.antoineve.me/AntoineVe/college-infos/issues"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["."]
|
||||
|
||||
@@ -425,4 +425,41 @@ def test_atomic_save_preserves_on_error(tmp_path: Path) -> None:
|
||||
assert state.get_known_guids() == frozenset({"original-guid-1", "original-guid-2", "new-guid"})
|
||||
|
||||
|
||||
def test_acknowledge_does_not_advance_memory_when_save_fails(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""Conserve l'état précédent en mémoire si l'acquittement ne peut pas être sauvegardé.
|
||||
|
||||
:param tmp_path: Fixture pytest pour un répertoire temporaire.
|
||||
:return: None
|
||||
"""
|
||||
state_file = tmp_path / "state.json"
|
||||
state = BlogRSSState(state_file)
|
||||
state.add_guids(["existing-guid"])
|
||||
state.update_cache_headers("old-etag", "old-last-modified")
|
||||
article = BlogArticle(
|
||||
id="new-guid",
|
||||
title="Article",
|
||||
url="https://example.com/article",
|
||||
published_at=datetime(2026, 9, 12, 8, 0, tzinfo=UTC),
|
||||
updated_at=None,
|
||||
category=None,
|
||||
author=None,
|
||||
content_html="<p>Contenu</p>",
|
||||
content_text="Contenu",
|
||||
)
|
||||
|
||||
with patch.object(Path, "replace", side_effect=OSError("replace failed")):
|
||||
state.acknowledge(
|
||||
BlogRSSFetchResult(
|
||||
articles=(article,),
|
||||
etag="new-etag",
|
||||
last_modified="new-last-modified",
|
||||
)
|
||||
)
|
||||
|
||||
assert state.get_known_guids() == frozenset({"existing-guid"})
|
||||
assert state.get_cache_headers() == ("old-etag", "old-last-modified")
|
||||
|
||||
|
||||
# Ensure trailing newline
|
||||
|
||||
Reference in New Issue
Block a user