diff --git a/README.md b/README.md index 4bf543d..089855d 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ Les connexions TLS (Nextcloud et LDAPS) sont validées avec le magasin de certif Nextcloud et Android affichent la photo en carré, voire en rond, découpé au milieu d'une photo verticale : les cheveux sont coupés. L'outil recadre donc chaque photo en carré autour du visage, détecté localement par le modèle YuNet d'OpenCV (`src/ldap2nextcloud/models/`). Aucune photo ne sort de la machine. Les yeux sont placés à la même hauteur sur toutes les photos, et le carré reste dans la photo. Si aucun visage n'est trouvé, le carré est aligné en haut ; le nombre de ces photos est journalisé en mode `-v`. Les réglages sont dans `mapping.yaml` (`fields.photo.crop`). Changer un réglage renvoie toutes les fiches avec photo au passage suivant. -`LDAP_FILTER` délimite la population synchronisée. Si l'appartenance aux groupes n'est pas portée par les fiches, `LDAP_GROUP_DNS` restreint la synchro aux membres de ces groupes (DN séparés par `;`). +`LDAP_FILTER` délimite la population synchronisée. Avec `skip_without_group_and_phone: true` dans `mapping.yaml`, les fiches dont l'attribut Direction est vide et qui n'ont aucun téléphone sont aussi écartées ; leur nombre figure dans le journal. Celles qui sont déjà dans le carnet en sont supprimées au passage suivant : si elles dépassent `MAX_DELETE_RATIO`, ce passage demande `--force`. Si l'appartenance aux groupes n'est pas portée par les fiches, `LDAP_GROUP_DNS` restreint la synchro aux membres de ces groupes (DN séparés par `;`). ## Premier passage diff --git a/mapping.example.yaml b/mapping.example.yaml index b43df15..2e8938e 100644 --- a/mapping.example.yaml +++ b/mapping.example.yaml @@ -2,6 +2,10 @@ # Copier en mapping.yaml et adapter aux attributs de votre annuaire. key: uid organization: "Exemple" +# true : une fiche dont l'attribut Direction (fields.group) est vide et qui n'a aucun +# téléphone n'est pas synchronisée ; si elle est déjà dans le carnet, elle en est supprimée. +# Un code Direction absent de directions.yaml ne compte pas comme vide. +skip_without_group_and_phone: false fields: given_name: givenName family_name: sn diff --git a/src/ldap2nextcloud/config.py b/src/ldap2nextcloud/config.py index f239a69..c217d30 100644 --- a/src/ldap2nextcloud/config.py +++ b/src/ldap2nextcloud/config.py @@ -80,6 +80,7 @@ class Mapping: photo: str | None = None birthday_attr: str | None = None photo_crop: PhotoCrop | None = None + skip_without_group_and_phone: bool = False def _values(env_file: Path | None) -> dict[str, str | None]: @@ -211,6 +212,9 @@ def load_mapping(path: Path) -> Mapping: ] except (KeyError, TypeError, ValueError) as exc: raise ConfigError(f"{path} : règle email ou téléphone invalide") from exc + skip = data.get("skip_without_group_and_phone", False) + if not isinstance(skip, bool): + raise ConfigError(f"{path} : « skip_without_group_and_phone » doit valoir true ou false") return Mapping( key=str(data["key"]), organization=data.get("organization"), @@ -224,6 +228,7 @@ def load_mapping(path: Path) -> Mapping: photo=_attr(fields.get("photo")), birthday_attr=_attr(fields.get("birthday")), photo_crop=_photo_crop(fields.get("photo"), path), + skip_without_group_and_phone=skip, ) diff --git a/src/ldap2nextcloud/mapping.py b/src/ldap2nextcloud/mapping.py index 8fad88f..db8fccc 100644 --- a/src/ldap2nextcloud/mapping.py +++ b/src/ldap2nextcloud/mapping.py @@ -81,6 +81,18 @@ def _emails(entry: RawEntry, mapping: Mapping) -> tuple[Email, ...]: return tuple(result) +def is_excluded(entry: RawEntry, mapping: Mapping) -> bool: + """Fiche à ne pas synchroniser : attribut Direction vide et aucun téléphone, si l'option est active. + + Un code Direction inconnu de directions.yaml n'est pas une Direction vide. + """ + if not mapping.skip_without_group_and_phone: + return False + if _first(entry, mapping.group_attr) is not None: + return False + return not any(_texts(entry, rule.attr) for rule in mapping.phones) + + def entry_to_contact( entry: RawEntry, mapping: Mapping, directions: dict[str, str], with_birthday: bool ) -> Contact | None: diff --git a/src/ldap2nextcloud/sync.py b/src/ldap2nextcloud/sync.py index 53ae9c1..b1f50a3 100644 --- a/src/ldap2nextcloud/sync.py +++ b/src/ldap2nextcloud/sync.py @@ -9,7 +9,7 @@ from datetime import datetime, timezone from .carddav import CardDavClient, CardDavError from .config import Mapping, Settings from .ldap_source import LdapSource, required_attributes -from .mapping import entry_to_contact +from .mapping import entry_to_contact, is_excluded from .model import Contact, contact_href, fingerprint from .photo import prepare_photo from .planner import Desired, check_guards, compute_plan @@ -37,7 +37,11 @@ def _build_desired( birthday_keys = source.fetch_birthday_keys(mapping.key) desired: dict[str, Desired] = {} contacts: dict[str, Contact] = {} + excluded = 0 for entry in entries: + if is_excluded(entry, mapping): + excluded += 1 + continue contact = entry_to_contact(entry, mapping, directions, False) if contact is None: continue @@ -53,7 +57,13 @@ def _build_desired( ) ) contacts[href] = contact - log.info("Annuaire : %d fiches (%d avec date de naissance)", len(desired), len(birthday_keys)) + if mapping.skip_without_group_and_phone: + log.info( + "Annuaire : %d fiches (%d avec date de naissance, %d écartées (ni Direction ni téléphone))", + len(desired), len(birthday_keys), excluded, + ) + else: + log.info("Annuaire : %d fiches (%d avec date de naissance)", len(desired), len(birthday_keys)) return desired, contacts diff --git a/tests/test_config.py b/tests/test_config.py index b2c27de..8f16be3 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -144,3 +144,20 @@ def test_load_directions_example_file(): d = load_directions(ROOT / "directions.example.yaml") assert len(d) == 3 assert d["620"] == "Direction des systèmes d'information" + + +def test_skip_without_group_and_phone_defaults_to_false(tmp_path): + assert mapping_with_photo(tmp_path, "").skip_without_group_and_phone is False + + +def test_skip_without_group_and_phone_is_read(tmp_path): + path = tmp_path / "mapping.yaml" + path.write_text("key: uid\nskip_without_group_and_phone: true\nfields:\n given_name: givenName\n family_name: sn\n") + assert load_mapping(path).skip_without_group_and_phone is True + + +def test_skip_without_group_and_phone_must_be_boolean(tmp_path): + path = tmp_path / "mapping.yaml" + path.write_text("key: uid\nskip_without_group_and_phone: oui\nfields:\n given_name: givenName\n family_name: sn\n") + with pytest.raises(ConfigError, match="skip_without_group_and_phone"): + load_mapping(path) diff --git a/tests/test_mapping.py b/tests/test_mapping.py index 337d400..182de7e 100644 --- a/tests/test_mapping.py +++ b/tests/test_mapping.py @@ -3,7 +3,9 @@ from datetime import date from pathlib import Path from ldap2nextcloud.config import PhoneRule, load_directions, load_mapping -from ldap2nextcloud.mapping import entry_to_contact, format_phone, parse_birthday +from dataclasses import replace + +from ldap2nextcloud.mapping import entry_to_contact, format_phone, is_excluded, parse_birthday from ldap2nextcloud.model import Email, Phone ROOT = Path(__file__).resolve().parent.parent @@ -111,3 +113,33 @@ def test_full_name_fallback_without_cn(): def test_preferred_email_domain(): c = entry_to_contact(entry(mail=["x@autre.fr", "x@example.org"]), MAPPING, DIRECTIONS, True) assert c.emails == (Email("x@example.org", "work", True), Email("x@autre.fr", "work", False)) + + +# --- Fiches écartées : ni Direction ni téléphone ----------------------------- + +STRICT = replace(MAPPING, skip_without_group_and_phone=True) + + +def test_entry_without_direction_nor_phone_is_excluded(): + assert is_excluded(entry(usrDirectionId=None, telephoneNumber=None), STRICT) + + +def test_blank_direction_counts_as_missing(): + assert is_excluded(entry(usrDirectionId=[" "], telephoneNumber=[""]), STRICT) + + +def test_entry_with_phone_but_no_direction_is_kept(): + assert not is_excluded(entry(usrDirectionId=None), STRICT) + + +def test_entry_with_direction_but_no_phone_is_kept(): + assert not is_excluded(entry(telephoneNumber=None), STRICT) + + +def test_unknown_direction_code_is_not_an_empty_direction(): + assert not is_excluded(entry(usrDirectionId=["999"], telephoneNumber=None), STRICT) + + +def test_rule_is_off_by_default(): + assert not MAPPING.skip_without_group_and_phone + assert not is_excluded(entry(usrDirectionId=None, telephoneNumber=None), MAPPING) diff --git a/tests/test_sync.py b/tests/test_sync.py index 118cc91..e3c446a 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -7,6 +7,8 @@ from PIL import Image from ldap2nextcloud.carddav import CardDavError from ldap2nextcloud.photo import PreparedPhoto +from dataclasses import replace + from ldap2nextcloud.config import Settings, load_directions, load_mapping from ldap2nextcloud.model import contact_href from ldap2nextcloud.planner import GuardError @@ -278,3 +280,19 @@ def test_dry_run_does_not_start_progress(tmp_path): progress = RecordingProgress() run(tmp_path, FakeClient(), dry_run=True, progress=progress) assert progress.total is None + + +def test_entries_without_direction_nor_phone_are_not_synced(tmp_path, caplog): + source = FakeSource() + for entry in source.entries[:2]: + del entry["telephoneNumber"] + del source.entries[0]["usrDirectionId"] # seule la première n'a ni l'un ni l'autre + client = FakeClient({contact_href("omalmare"): ("x", "BEGIN:VCARD")}) + settings = make_settings(tmp_path) + strict = replace(MAPPING, skip_without_group_and_phone=True) + with caplog.at_level(logging.INFO), StateDB(settings.state_db) as state: + summary = run_sync(settings, strict, DIRECTIONS, source, client, state, force=True) + assert contact_href("omalmare") not in client.cards # fiche déjà présente : supprimée + assert contact_href("cbarssac") in client.cards + assert (summary.created, summary.deleted) == (2, 1) + assert "1 écartées (ni Direction ni téléphone)" in caplog.text