diff --git a/.gitignore b/.gitignore index 5fb4f8f..65b5c15 100644 --- a/.gitignore +++ b/.gitignore @@ -23,7 +23,6 @@ TESTS.txt TESTERGEBNISSE.txt BUGREPORT.md DIAGNOSE_REPORT.md -SKILL.md # ---- Sensible Daten ---- _USER/ diff --git a/CHANGELOG.md b/CHANGELOG.md index ae4c62d..90f6a9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,23 @@ Format basiert auf [Keep a Changelog](https://keepachangelog.com/de/1.1.0/). ## [Unreleased] +### High-End Refactoring: UI-freier Domänenkern `export_core.py`, sprachunabhängiger `QueryBuilderDialog`, Policy P-022 & Size-Pre-Bucketed Deduplizierung (2026-12-06) +- **UI-freier Domänenkern & Export-Schema-Kanonisierung (`export_core.py`, `TW-UDG-05`):** + - Duplizierte Pfad-, Redaktions-, Gerätenamen-, SHA-256-Hash-, Kategorie- und Export-Logik aus `UniversalDocsGrabberV1.py` und `cli.py` in das `PySide6`-freie Kernmodul `export_core.py` extrahiert. + - Kanonisches Export-Schema über Desktop-GUI, Headless-CLI und `EXPORTFORMAT.md` auf `schema = "docsgrabber-library"` (`schema_version = "1.0"`) mit strukturierten Kategoriefeldern (`name`, `source`, `sources`, `profile_names`, `rule_count`, `document_count`) vereinheitlicht (`web_companion/library.js` behält Rückwärtskompatibilität für `docsgrabber-library-v1`). + - Schutz reservierter Windows-Gerätenamen um `CONIN$`, `CONOUT$`, `COM0`, `LPT0` sowie hochgestellte Varianten (`COM¹`..`COM³`, `LPT¹`..`LPT³`) erweitert; SHA-256-Lesepuffer auf 64 KiB angehoben. +- **Sprachunabhängiger `QueryBuilderDialog` & PySide6-`QDate`-Crashfix (`TW-UDG-04`):** + - `QueryBuilderDialog.toggle_dates()` und `QueryBuilderDialog.generate()` von deutschen `currentText()`-Vergleichen auf sprachunabhängige Indizes (`0..3`) umgestellt, automatischen `d_from > d_to` Swap-Guard ergänzt und einen PySide6-Absturz (`QDate.toPyDate` -> `_qdate_to_pydate` via `toPython()`) bei benutzerdefinierten Datumsbereichen behoben. + - Alle `QueryBuilderDialog`- und `max_emails_per_run`-Oberflächentexte über sämtliche 6 Tier-2-Sprachen (`de`, `en`, `es`, `zh`, `ja`, `ru`) in `locales/translations.json` (232 Schlüssel, 100 % Parität) lokalisiert. +- **Policy P-022 Artefakte & konfigurierbare IMAP-UID-Fensterung (`TW-UDG-06`):** + - `SKILL.md` und `llm.txt` für Dual-Use-Bedienung durch Mensch und KI-Agenten ergänzt; `llms.txt` nachgezogen. + - `DownloadSettings.max_emails_per_run` (`30` Standard für volle Rückwärtskompatibilität, `0` = unbegrenzt / alle passenden UIDs) in Datenmodell, `MainWindow`-Einstellungen, `ProfileDialog`-Override, `GrabberWorker.process_profile()`, `cli.load_data()` und Companion-Export integriert. +- **Performance- & Integritäts-Härtung in `GrabberWorker`:** + - `run_deduplication()` gruppiert reguläre Nicht-Symlink-Dateien vorab nach Dateigröße (`st_size`), überspringt Einzelgrößen ohne Disk-Read, schützt `.tmp_`- und `protected_paths`-Dateien und räumt bei Duplikaten deterministisch bereits in `self.db` indizierten Dokumenten Vorrang ein. + - `add_db()` nutzt einen $O(1)$-Pfadindex (`self._db_paths`) statt linearer Suche über `self.db`. +- **Pytest-CWD-Unabhängigkeit & Packaging (`T-20261114-932985855`):** + - Relatives `--basetemp=.pytest_temp` aus `pyproject.toml` entfernt und CWD-sicher in `conftest.py` (`config.rootpath / ".pytest_temp"`) verankert; `[tool.setuptools] py-modules` und `UniversalDocsGrabber.spec` um `export_core` und `locales` ergänzt. + ### Laufzeit-/Vertragstests, lokalisierter Zeitfilter & Web-Companion Schema-Kompatibilität (2026-11-23) - **Neue Testsuite `tests/test_runtime_and_companion_contracts.py` (11 Tests) & Erweiterung `web_companion/tests/library.test.mjs` (+2 Tests):** - Deckt `MainWindow.run_all()` über alle 6 UI-Sprachen, Scheduler-Persistenz (`_save_scheduler`/`_apply_scheduler`) und Tick-Verhalten (`_on_scheduler_tick`), `GrabberWorker` (Account-Gruppierung, Inaktivitäts-Skip, Deduplizierung, Interrupts), Gmail-Fallback + 30-UID-Limit, `UniversalConverter.convert_to_pdf()`, `app_icon_loader`, CLI `list-documents --category --limit=0` sowie Python->Node.js-Exportverträge ab. diff --git a/EXPORTFORMAT.md b/EXPORTFORMAT.md index b7f5891..0dcd25f 100644 --- a/EXPORTFORMAT.md +++ b/EXPORTFORMAT.md @@ -1,6 +1,6 @@ # Exportformat `docsgrabber-library-v1.json` -Stand: 2026-08-12 +Stand: 2026-12-06 Dieses Dokument beschreibt den umgesetzten Austauschvertrag für Desktop, Web/PWA und spätere Plattform-Smokes. Das Format ist bewusst redigiert: Es transportiert @@ -66,11 +66,20 @@ autoritative Vollversion für IMAP, OCR, Konvertierung und Dateisystemzugriff. ## Aktuell exportierte Felder - `accounts`: redigierte `account-`-Referenzen plus Anzahl verknüpfter Profile -- `profiles`: ID, Name, Gruppe, Aktiv-Status, `account_ref`, Zielordner, Filter und effektive Download-/Auto-Kategorisierungs-Einstellungen -- `categories`: zusammengeführt aus globalen Regeln, Profil-Overrides und erkannten Dokumentpfaden +- `profiles`: ID, Name, Gruppe, Aktiv-Status, `account_ref`, Zielordner, Filter und effektive Download-/Auto-Kategorisierungs-Einstellungen (inkl. `max_emails_per_run`, `0` = unbegrenzt) +- `categories`: zusammengeführt aus globalen Regeln, Profil-Overrides und erkannten Dokumentpfaden (`name`, `source`, `sources`, `profile_names`, `rule_count`, `document_count`) - `documents`: Profilname, Dateiname, Datum, Typ, Kategorie, `path_hint`, Status und optionale SHA-256 bei vorhandener lokaler Datei - `run_summary`: Anzahl exportierter Profile/Dokumente, aktiver Profile, Scheduler-Intervall und Profilstatistiken +## Gemeinsamer Domänenkern (`export_core.py`) + +Sowohl die Desktop-App (`UniversalDocsGrabberV1.py`) als auch die Headless-CLI +(`cli.py --export-library`) nutzen das UI-freie Modul `export_core.py` und erzeugen +identisch das kanonische Schema `"schema": "docsgrabber-library"` mit +`"schema_version": "1.0"`. Der Web/PWA-Companion (`web_companion/library.js`) +akzeptiert zur Rückwärtskompatibilität weiterhin auch ältere Dateien mit +`"docsgrabber-library-v1"` (`1.x`). + ## Desktop-Auslöser Der Export wird direkt in der Desktop-App über diff --git a/SKILL.md b/SKILL.md new file mode 100644 index 0000000..b991f0a --- /dev/null +++ b/SKILL.md @@ -0,0 +1,88 @@ +--- +name: universaldocsgrabber +description: Local-first desktop and headless CLI tool for IMAP/Gmail attachment harvesting, PDF conversion, OCR, SHA-256 deduplication, and redacted Web/PWA library exports. +--- + +# UniversalDocsGrabber — Agent & Automation Skill (Policy P-022) + +`UniversalDocsGrabber` (`doc-bricks/UniversalDocsGrabber`, v1.1.7) provides dual-use access for human operators (PySide6 desktop GUI + offline Web/PWA companion) and AI agents / automation pipelines (`cli.py` + UI-free `export_core.py`) with zero cloud egress. + +## Architecture & Entry Surfaces + +- **Headless CLI (`cli.py`):** Display-free JSON/text inspection, redacted companion export (`docsgrabber-library` `1.0`), CSV export with CWE-1236 formula-injection protection, and stack diagnostics. +- **UI-Free Domain Core (`export_core.py`):** Pure-Python path sanitization, Windows/DOS device-name protection, buffered SHA-256 hashing, category inference, and redacted payload assembly without `PySide6`. +- **Desktop GUI (`UniversalDocsGrabberV1.py`):** PySide6 application with OS Keyring credential storage (`keyring`), IMAP `UTF8=ACCEPT` / `X-GM-RAW` search, configurable `max_emails_per_run` (`30` default, `0` = unlimited), OCR (`pytesseract` + `pdf2image`), and 6-language UI (`de`, `en`, `es`, `zh`, `ja`, `ru`). +- **Offline Web/PWA Companion (`web_companion/`):** Static zero-dependency browser viewer reading redacted `docsgrabber-library-v1.json` exports locally. + +## Headless CLI Usage (`--json` Recommended for Agents) + +Always pass `--json` when invoking `cli.py` from an agent or automation script so stdout emits deterministic UTF-8 JSON without interactive dialogs: + +```bash +# Version inquiry +python cli.py --version + +# Runtime stack & storage writability diagnostics +python cli.py --diagnose --json + +# List configured search profiles or masked IMAP accounts +python cli.py --list-profiles --json +python cli.py --list-accounts --json + +# Query indexed documents (supports --profile, --category, and --limit 0 for all) +python cli.py --list-documents --profile "Rechnungen" --category "Steuer" --limit 0 --json + +# Generate redacted Web/PWA companion export (schema: docsgrabber-library 1.0) +python cli.py --export-library ./docsgrabber-library-v1.json --json + +# Export document index as UTF-8-BOM semicolon CSV (formula-injection safe) +python cli.py --export-csv ./documents_export.csv --json +``` + +### Custom Multi-Tenant / Test Paths + +Override the default runtime directory (`~/.univ_docs_grabber/`) explicitly via: +- `--config ` +- `--documents-db ` + +### CLI Exit Codes + +- `0` — Command succeeded (or `--diagnose` confirmed core stack + storage writability ready). +- `1` — Export failed due to OS I/O error or `atomic_io` protected-path guard (`PermissionError`), or `--diagnose` detected missing core components / unwritable storage. +- `2` — Invalid CLI flags or mutually exclusive action conflict (`argparse`). + +## Non-Goals & Current CLI Boundaries + +- **No Headless Live IMAP Fetch in `cli.py` (v1.1.7):** Live IMAP connection, credential retrieval from OS Keyring, attachment downloading, and OCR execution currently run through the desktop application (`UniversalDocsGrabberV1.py`, manual Start or built-in scheduler). Extracting a `QThread`-free `imap_core.py` for `cli.py --run-profiles` is tracked as follow-up `TW-UDG-07`. +- **One-Way Redacted Companion Export:** `web_companion/` is a read-only local viewer; there is no cloud sync and no write-back import into `config_v1.json` or `documents.json`. + +## Python API (`export_core.py`) + +Agents and downstream Python tools that do not need Qt can import `export_core` directly: + +```python +from pathlib import Path +import export_core + +payload = export_core.build_library_export_payload( + profiles=profiles, + accounts=accounts, + documents=documents, + global_settings=global_settings, + base_path=Path("./Downloads/UnivDocs"), + scheduler_interval=30, +) +``` + +## Safety & Governance Invariants + +1. **Zero Cloud Egress (`INV-LOCAL-01`):** Never transmit documents, mail bodies, or account credentials to external APIs. +2. **Credential Protection (`INV-CRED-03` & `INV-REDACT-04`):** Passwords reside in OS Keyring; `--list-accounts` masks passwords (`***MASKED***`), and `--export-library` emits hashed `account-` references only. +3. **Atomic Path-Protected Writes:** Internal files (`config_v1.json`, `documents.json`, `token.json`) and transient `.tmp` / `.temp.pdf` artifacts are guarded by `atomic_io` and excluded from deduplication. +4. **Configurable UID Windowing:** `DownloadSettings.max_emails_per_run` defaults to `30` (`0` = process all matching UIDs without cap). + +## Further Documentation + +- Machine-readable repository summary & invariants: [llms.txt](llms.txt) (pointer: [llm.txt](llm.txt)) +- Redacted Web/PWA export specification: [EXPORTFORMAT.md](EXPORTFORMAT.md) +- Full user & architecture documentation: [README.md](README.md) / [README-DE.md](README-DE.md) diff --git a/UniversalDocsGrabber.spec b/UniversalDocsGrabber.spec index c8ab322..aa547ef 100644 --- a/UniversalDocsGrabber.spec +++ b/UniversalDocsGrabber.spec @@ -10,7 +10,12 @@ a = Analysis( binaries=[], datas=[ ('assets', 'assets'), + ('locales', 'locales'), ('app_icon_loader.py', '.'), + ('export_core.py', '.'), + ('SKILL.md', '.'), + ('llms.txt', '.'), + ('llm.txt', '.'), ], hiddenimports=[ 'PySide6.QtWidgets', diff --git a/UniversalDocsGrabberV1.py b/UniversalDocsGrabberV1.py index ff9f425..bdf2865 100644 --- a/UniversalDocsGrabberV1.py +++ b/UniversalDocsGrabberV1.py @@ -6,7 +6,6 @@ import re import io import shutil -import hashlib import imaplib import email import email.header @@ -142,12 +141,26 @@ def get_default_protected_paths(base_dir=None): def is_protected_path(target, paths): return False +from export_core import ( + DEFAULT_GROUP as DEFAULT_GROUP, + DEFAULT_LIBRARY_FILENAME, + DEFAULT_MAX_EMAILS_PER_RUN, + EXPORT_SCHEMA as EXPORT_SCHEMA, + EXPORT_SCHEMA_VERSION as EXPORT_SCHEMA_VERSION, + build_account_ref as build_account_ref, + build_library_export_payload as _core_build_library_export_payload, + calculate_file_hash as _core_calculate_file_hash, + collect_category_entries as collect_category_entries, + infer_document_category as infer_document_category, + normalize_max_emails_per_run, + redact_path_hint as redact_path_hint, + sanitize_filename as sanitize_filename, +) + # ==================== CONFIG ==================== APP_NAME = "UniversalDocsGrabber_V1" APP_VERSION = "1.x" -EXPORT_SCHEMA = "docsgrabber-library" -EXPORT_SCHEMA_VERSION = "1.0" # ==================== CONSTANTS ==================== @@ -178,7 +191,6 @@ def is_protected_path(target, paths): UI_BTN_BROWSE_PATH = "Ordner wählen..." UI_WARN_NO_ACCOUNT_TITLE = "Fehler" UI_WARN_NO_ACCOUNT_MSG = "Zuerst Account anlegen!" -DEFAULT_GROUP = "Allgemein" # Default group name for uncategorized profiles UI_EXPORT_LABEL = "Companion-Export" UI_BTN_EXPORT_LIBRARY = "Redigierten Export speichern..." UI_EXPORT_SUCCESS_TITLE = "Export gespeichert" @@ -307,6 +319,7 @@ class DownloadSettings: keep_original_after_convert: bool = False enable_hash_check: bool = False auto_categorize: bool = False + max_emails_per_run: int = DEFAULT_MAX_EMAILS_PER_RUN category_rules: List[dict] = field(default_factory=list) formats: List[str] = field(default_factory=lambda: ["pdf", "docx", "doc", "jpg", "png"]) @@ -320,6 +333,10 @@ def from_dict(cls, d): try: valid_keys = {f.name for f in fields(cls)} filtered = {k: v for k, v in d.items() if k in valid_keys and v is not None} + if "max_emails_per_run" in filtered: + filtered["max_emails_per_run"] = normalize_max_emails_per_run( + filtered["max_emails_per_run"], default=DEFAULT_MAX_EMAILS_PER_RUN + ) return cls(**filtered) except (TypeError, ValueError): return cls() @@ -420,108 +437,6 @@ def from_dict(cls, d): return None -def build_account_ref(account_name: Optional[str]) -> str: - """Erzeugt eine stabile, redigierte Referenz für einen Mail-Account.""" - if not account_name or not str(account_name).strip(): - return "account-unknown" - normalized = str(account_name).strip().encode("utf-8") - digest = hashlib.sha256(normalized).hexdigest()[:12] - return f"account-{digest}" - - -def redact_path_hint(path_value: Optional[str], base_path: Path) -> dict: - """Redigiert absolute Pfade auf relative Hinweise oder den Dateinamen.""" - if not path_value or not isinstance(path_value, (str, Path)): - return {"kind": "basename", "value": ""} - path = Path(path_value) - try: - rel_path = path.resolve(strict=False).relative_to(base_path.resolve(strict=False)) - return {"kind": "relative", "value": rel_path.as_posix()} - except (ValueError, TypeError, OSError): - return {"kind": "basename", "value": path.name} - - -def infer_document_category(path_value: Optional[str], base_path: Path, profile_name: str, target_folder: str = "") -> str: - """Leitet optional eine Kategorie aus dem Dokumentpfad ab. - - Kategorien liegen als Unterordner innerhalb des Profil- bzw. Zielordners. - Liegt ein Dokument direkt im Profil-/Zielordner (len(parts) < 2), existiert keine - Kategorie (Rückgabe: leerer String). - """ - if not path_value or not isinstance(path_value, (str, Path)): - return "" - profile_folder = sanitize_filename(profile_name or "") - target_folder_sanitized = sanitize_filename(target_folder) if target_folder else "" - path = Path(path_value) - try: - rel_path = path.resolve(strict=False).relative_to(base_path.resolve(strict=False)) - except (ValueError, TypeError, OSError): - return "" - - parts = list(rel_path.parts[:-1]) - # Mindestens 2 Ebenen unter base_path erforderlich: //.../ - if len(parts) < 2: - return "" - if parts[0] == profile_folder or (target_folder_sanitized and parts[0] == target_folder_sanitized): - return parts[1] - return "" - - -def collect_category_entries( - global_settings: DownloadSettings, - profiles: List[SearchProfile], - documents: List[Document], - base_path: Path, -) -> List[dict]: - """Sammelt Kategorien aus Regeln und vorhandenen Dokumentpfaden.""" - category_map = {} - profile_target_map = {profile.name: profile.target_folder for profile in profiles} - - def add_category(name: str, source: str, profile_name: str = ""): - if not name: - return - entry = category_map.setdefault( - name, - {"name": name, "sources": set(), "profile_names": set()}, - ) - entry["sources"].add(source) - if profile_name: - entry["profile_names"].add(profile_name) - - for rule in global_settings.category_rules or []: - if isinstance(rule, dict): - fld = rule.get("folder") - if isinstance(fld, str) and fld.strip(): - add_category(fld.strip(), "global_rule") - - for profile in profiles: - settings = profile.override_settings if profile.override_settings else global_settings - for rule in (settings.category_rules or []): - if isinstance(rule, dict): - fld = rule.get("folder") - if isinstance(fld, str) and fld.strip(): - add_category(fld.strip(), "profile_rule", profile.name) - - for document in documents: - doc_prof = getattr(document, "profile", "") or "" - raw_path = getattr(document, "path", "") or "" - target_folder = profile_target_map.get(doc_prof, "") - add_category( - infer_document_category(raw_path, base_path, doc_prof, target_folder), - "document_path", - doc_prof, - ) - - return [ - { - "name": name, - "sources": sorted(entry["sources"]), - "profile_names": sorted(entry["profile_names"]), - } - for name, entry in sorted(category_map.items()) - ] - - def build_library_export_payload( profiles: List[SearchProfile], accounts: List[MailAccount], @@ -531,123 +446,26 @@ def build_library_export_payload( scheduler_interval: int = 0, exported_at: Optional[datetime] = None, ) -> dict: - """Baut den redigierten Export für Web/PWA-Companions.""" - export_dt = exported_at or datetime.now().astimezone() - export_timestamp = export_dt.isoformat(timespec="seconds") - account_refs = {account.name: build_account_ref(account.name) for account in accounts} - profile_target_map = {profile.name: profile.target_folder for profile in profiles} - - documents_by_profile = {} - exported_documents = [] - for document in documents: - raw_path = getattr(document, "path", "") or "" - doc_path = Path(raw_path) if raw_path else None - exists = doc_path.exists() if doc_path else False - doc_prof = getattr(document, "profile", "") or "" - target_folder = profile_target_map.get(doc_prof, "") - category = infer_document_category(raw_path, base_path, doc_prof, target_folder) - exported_doc = { - "profile_name": doc_prof, - "filename": getattr(document, "filename", "") or "", - "document_date": getattr(document, "date", "") or "", - "file_type": doc_path.suffix.lower().lstrip(".") if doc_path else "", - "category": category or None, - "path_hint": redact_path_hint(raw_path, base_path), - "status": "available" if exists else "missing", - "sha256": calculate_file_hash(doc_path) if exists and doc_path else None, - } - exported_documents.append(exported_doc) - documents_by_profile.setdefault(doc_prof, []).append(exported_doc) - - exported_profiles = [] - profile_stats = [] - for profile in profiles: - effective_settings = profile.override_settings if profile.override_settings else global_settings - profile_docs = documents_by_profile.get(profile.name, []) - last_document_date = max((doc["document_date"] for doc in profile_docs), default=None) - exported_profiles.append( - { - "id": profile.id, - "name": profile.name, - "group": profile.group or DEFAULT_GROUP, - "active": profile.active, - "account_ref": account_refs.get(profile.account_name, build_account_ref(profile.account_name)), - "target_folder": profile.target_folder, - "filters": { - "subject": profile.query_subject, - "sender": profile.query_sender, - "since": profile.query_since, - "gmail_query": profile.gmail_query, - }, - "effective_settings": { - "download_attachments": effective_settings.download_attachments, - "convert_body_to_pdf": effective_settings.convert_body_to_pdf, - "convert_all_to_pdf": effective_settings.convert_all_to_pdf, - "enable_hash_check": effective_settings.enable_hash_check, - "auto_categorize": effective_settings.auto_categorize, - "category_rule_count": len(effective_settings.category_rules or []), - "formats": list(effective_settings.formats or []), - }, - "document_count": len(profile_docs), - "last_document_date": last_document_date, - } - ) - profile_stats.append( - { - "profile_name": profile.name, - "document_count": len(profile_docs), - "last_document_date": last_document_date, - "active": profile.active, - } - ) - - exported_accounts = [ - { - "ref": account_refs.get(account.name, build_account_ref(account.name)), - "profile_count": sum(1 for profile in profiles if profile.account_name == account.name), - } - for account in accounts - ] - - categories = collect_category_entries(global_settings, profiles, documents, base_path) - - return { - "schema": EXPORT_SCHEMA, - "schema_version": EXPORT_SCHEMA_VERSION, - "app": { - "name": APP_NAME, - "version": APP_VERSION, - "exported_at": export_timestamp, - }, - "capabilities": { - "redacted": True, - "contains_credentials": False, - "contains_document_files": False, - "contains_mail_body_text": False, - }, - "base_path_hint": { - "kind": "basename", - "value": Path(base_path).name, - }, - "accounts": exported_accounts, - "profiles": exported_profiles, - "categories": categories, - "documents": exported_documents, - "run_summary": { - "exported_profile_count": len(exported_profiles), - "active_profile_count": sum(1 for profile in profiles if profile.active), - "exported_document_count": len(exported_documents), - "scheduler_interval_minutes": scheduler_interval, - "profile_stats": profile_stats, - }, - } + """Baut den redigierten Export für Web/PWA-Companions über export_core.""" + return _core_build_library_export_payload( + profiles=profiles, + accounts=accounts, + documents=documents, + global_settings=global_settings, + base_path=base_path, + scheduler_interval=scheduler_interval, + exported_at=exported_at, + app_name=APP_NAME, + app_version=APP_VERSION, + hash_fn=calculate_file_hash, + ) def write_library_export(path: Path, payload: dict) -> None: """Schreibt den redigierten Bibliotheksexport als UTF-8 JSON ohne BOM.""" resolved = Path(path).resolve() if resolved.is_dir(): - resolved = resolved / "docsgrabber-library-v1.json" + resolved = resolved / DEFAULT_LIBRARY_FILENAME atomic_write_json( resolved, payload, @@ -658,34 +476,6 @@ def write_library_export(path: Path, payload: dict) -> None: # ==================== HELPERS ==================== -_RESERVED_DEVICE_NAMES: Set[str] = { - "CON", "PRN", "AUX", "NUL", "CLOCK$", - *(f"COM{i}" for i in range(1, 10)), - *(f"LPT{i}" for i in range(1, 10)), -} - - -def sanitize_filename(name: str) -> str: - """Bereinigt Dateinamen von ungültigen Zeichen und limitiert Länge. - - Args: - name: Roher Dateiname - - Returns: - Bereinigte Dateiname (max 100 Zeichen, Windows- und DOS-Gerätenamen-sicher) - """ - if not name or not isinstance(name, str): - return "unnamed" - s = re.sub(r'[^\w\s\.-]', '', name) - s = re.sub(r'\s+', '_', s) - result = s.strip().rstrip('. ')[:100].rstrip('. ') - if not result: - return "unnamed" - stem = result.split(".")[0].upper() - if result.upper() in _RESERVED_DEVICE_NAMES or stem in _RESERVED_DEVICE_NAMES: - result = f"file_{result}" - return result - def is_format_allowed(ext: str, configured_formats: Optional[Iterable[str]]) -> bool: """Prüft, ob eine Dateiendung in den konfigurierten Formaten erlaubt ist. @@ -713,24 +503,13 @@ def is_format_allowed(ext: str, configured_formats: Optional[Iterable[str]]) -> return True return False -def calculate_file_hash(path: Path) -> Optional[str]: - """Berechnet SHA-256 Hash einer Datei. - - Args: - path: Pfad zur Datei - Returns: - SHA-256 Hash als Hex-String oder None bei Fehler - """ - h = hashlib.sha256() - try: - with open(path, "rb") as f: - for chunk in iter(lambda: f.read(4096), b""): - h.update(chunk) - return h.hexdigest() - except (FileNotFoundError, PermissionError, OSError) as e: - logger.warning(f"Hash calculation failed for {path}: {e}") - return None +def calculate_file_hash(path: Path) -> Optional[str]: + """Berechnet SHA-256 Hash einer Datei über export_core.""" + return _core_calculate_file_hash( + path, + on_error=lambda p, e: logger.warning(f"Hash calculation failed for {p}: {e}"), + ) def safe_decode_payload(payload: Optional[bytes], charset: Optional[str] = None) -> str: @@ -955,10 +734,16 @@ def __init__(self, profiles, accounts, global_settings, base_path, db, date_over self.global_settings = global_settings self.base_path = base_path self.db = db + self._db_paths: Set[str] = self._snapshot_db_paths() self.date_override = date_override # datetime object self.converter = UniversalConverter(lambda x: self.log.emit(x)) self.ocr = OCRProcessor(lambda x: self.log.emit(x)) + def _snapshot_db_paths(self) -> Set[str]: + if not isinstance(self.db, (list, tuple, set)): + return set() + return {d.path for d in self.db if getattr(d, "path", None)} + def get_effective_settings(self, profile): if profile.override_settings: return profile.override_settings return self.global_settings @@ -1178,8 +963,13 @@ def process_profile(self, conn, profile, settings): self.log.emit(LOG_MSG_NO_MAILS) return - # Limit to last 30 to avoid overflow - ids = ids[-30:] + # Configurable UID window (default 30, 0 = unlimited / all matching UIDs) + max_emails = normalize_max_emails_per_run( + getattr(settings, "max_emails_per_run", DEFAULT_MAX_EMAILS_PER_RUN), + default=DEFAULT_MAX_EMAILS_PER_RUN, + ) + if max_emails > 0: + ids = ids[-max_emails:] for num in ids: if self.isInterruptionRequested(): break @@ -1434,31 +1224,106 @@ def process_email(self, conn, num, dl_dir, settings, profile_name): except Exception as e: self.log.emit(f"Mail Parse Error: {e}") + @staticmethod + def _is_transient_or_temp_file(name: str) -> bool: + """Erkennt temporäre Schreib- und OCR-Zwischendateien (atomic_io, CSV, OCR, Diagnose).""" + lower = (name or "").lower() + return ( + lower.startswith(".tmp_") + or (lower.startswith(".") and ".tmp." in lower) + or lower.endswith(".tmp") + or lower.endswith(".temp.pdf") + ) + def run_deduplication(self): self.log.emit(LOG_MSG_DEDUP_START) - hashes = {} + self._db_paths = self._snapshot_db_paths() + resolved_db_paths = { + str(Path(p).resolve(strict=False)) for p in self._db_paths + } + base_resolved = self.base_path.resolve(strict=False) + protected = set(get_default_protected_paths(self.base_path)) | { + CONFIG_FILE.resolve(strict=False), + DOCS_DB.resolve(strict=False), + } + + size_buckets = {} + for entry in self.base_path.rglob("*"): + if self.isInterruptionRequested(): + break + try: + if entry.is_symlink() or not entry.is_file(): + continue + if self._is_transient_or_temp_file(entry.name): + continue + entry_resolved = entry.resolve(strict=False) + try: + entry_resolved.relative_to(base_resolved) + except ValueError: + continue + if is_protected_path(entry, protected): + continue + st_size = entry.stat().st_size + except (OSError, PermissionError): + continue + size_buckets.setdefault(st_size, []).append(entry) + deleted = 0 deleted_paths = set() - files = [f for f in self.base_path.rglob("*") if f.is_file()] - for f in files: - if self.isInterruptionRequested(): break - h = calculate_file_hash(f) - if not h: continue - if h in hashes: - try: - os.remove(f) - deleted += 1 - deleted_paths.add(str(f)) - self.log.emit(f" Duplikat entfernt: {f.name}") - except (OSError, PermissionError): pass - else: hashes[h] = f - if deleted_paths: - self.db[:] = [d for d in self.db if d.path not in deleted_paths] + deleted_resolved = set() + + for _size, candidates in sorted(size_buckets.items()): + if self.isInterruptionRequested(): + break + if len(candidates) < 2: + continue + candidates.sort( + key=lambda p: ( + 0 + if ( + str(p) in self._db_paths + or str(p.resolve(strict=False)) in resolved_db_paths + ) + else 1, + str(p), + ) + ) + hashes_in_bucket = {} + for f in candidates: + if self.isInterruptionRequested(): + break + h = calculate_file_hash(f) + if not h: + continue + if h in hashes_in_bucket: + try: + os.remove(f) + deleted += 1 + deleted_paths.add(str(f)) + deleted_resolved.add(str(f.resolve(strict=False))) + self.log.emit(f" Duplikat entfernt: {f.name}") + except (OSError, PermissionError): + pass + else: + hashes_in_bucket[h] = f + + if deleted_paths and isinstance(self.db, list): + self.db[:] = [ + d + for d in self.db + if d.path not in deleted_paths + and str(Path(d.path).resolve(strict=False)) not in deleted_resolved + ] + self._db_paths = self._snapshot_db_paths() self.log.emit(f"🧹 Fertig. {deleted} gelöscht.") def add_db(self, prof, fname, date, path, snd, sub): - doc = Document(prof, fname, date, path, snd, sub) - if not any(d.path == doc.path for d in self.db): self.db.insert(0, doc) + if isinstance(self.db, list) and len(self._db_paths) != len(self.db): + self._db_paths = self._snapshot_db_paths() + if path not in self._db_paths and isinstance(self.db, list): + doc = Document(prof, fname, date, path, snd, sub) + self.db.insert(0, doc) + self._db_paths.add(path) # ==================== GUI DIALOGS ==================== @@ -1470,63 +1335,89 @@ class QueryBuilderDialog(QDialog): Das Ergebnis ist über get_query() als String abrufbar. """ - def __init__(self, current_query="", parent=None): + def __init__(self, current_query="", parent=None, translator=None): super().__init__(parent) - self.setWindowTitle("Query Builder") + tr = translator or getattr(parent, "translator", None) or get_translator() + self.translator = tr + self.setWindowTitle(tr.t("TITLE_QUERY_BUILDER")) + self.setAccessibleName(tr.t("TITLE_QUERY_BUILDER")) self.resize(500, 400) layout = QVBoxLayout(self) - g_scope = QGroupBox("1. Wo suchen?") + g_scope = QGroupBox(tr.t("QB_SCOPE_GROUP")) gl = QHBoxLayout(g_scope) - self.rb_all = QRadioButton("Überall (außer Müll)"); self.rb_all.setChecked(True) - self.rb_inbox = QRadioButton("Nur Inbox") - self.rb_sent = QRadioButton("Gesendet") - self.rb_trash = QRadioButton("Auch Papierkorb") + self.rb_all = QRadioButton(tr.t("QB_SCOPE_ALL")); self.rb_all.setChecked(True) + self.rb_inbox = QRadioButton(tr.t("QB_SCOPE_INBOX")) + self.rb_sent = QRadioButton(tr.t("QB_SCOPE_SENT")) + self.rb_trash = QRadioButton(tr.t("QB_SCOPE_TRASH")) gl.addWidget(self.rb_all); gl.addWidget(self.rb_inbox) gl.addWidget(self.rb_sent); gl.addWidget(self.rb_trash) layout.addWidget(g_scope) - g_date = QGroupBox("2. Zeitraum") + g_date = QGroupBox(tr.t("QB_DATE_GROUP")) gd = QGridLayout(g_date) self.cb_time = QComboBox() - self.cb_time.addItems(["Alles", "Dieses Jahr", "Letztes Jahr", "Benutzerdefiniert"]) + self.cb_time.addItems([ + tr.t("QB_PRESET_ALL"), + tr.t("QB_PRESET_THIS_YEAR"), + tr.t("QB_PRESET_LAST_YEAR"), + tr.t("QB_PRESET_CUSTOM"), + ]) + self.cb_time.setAccessibleName(tr.t("QB_PRESET")) self.cb_time.currentIndexChanged.connect(self.toggle_dates) self.de_from = QDateEdit(QDate.currentDate().addYears(-1)); self.de_from.setCalendarPopup(True) self.de_to = QDateEdit(QDate.currentDate()); self.de_to.setCalendarPopup(True) + self.de_from.setAccessibleName(tr.t("QB_FROM")) + self.de_to.setAccessibleName(tr.t("QB_TO")) self.de_from.setEnabled(False); self.de_to.setEnabled(False) - gd.addWidget(QLabel("Preset:"), 0, 0); gd.addWidget(self.cb_time, 0, 1) - gd.addWidget(QLabel("Von:"), 1, 0); gd.addWidget(self.de_from, 1, 1) - gd.addWidget(QLabel("Bis:"), 2, 0); gd.addWidget(self.de_to, 2, 1) + gd.addWidget(QLabel(tr.t("QB_PRESET")), 0, 0); gd.addWidget(self.cb_time, 0, 1) + gd.addWidget(QLabel(tr.t("QB_FROM")), 1, 0); gd.addWidget(self.de_from, 1, 1) + gd.addWidget(QLabel(tr.t("QB_TO")), 2, 0); gd.addWidget(self.de_to, 2, 1) layout.addWidget(g_date) - g_crit = QGroupBox("3. Kriterien (Komma für ODER)") + g_crit = QGroupBox(tr.t("QB_CRIT_GROUP")) gc = QGridLayout(g_crit) - self.inp_from = QLineEdit(); self.inp_from.setPlaceholderText("z.B. allianz, tk, aok") - self.inp_sub = QLineEdit(); self.inp_sub.setPlaceholderText("z.B. Rechnung, Invoice, Payment") - self.chk_att = QCheckBox("Muss Anhang haben (has:attachment)"); self.chk_att.setChecked(True) - - gc.addWidget(QLabel("Absender:"), 0, 0); gc.addWidget(self.inp_from, 0, 1) - gc.addWidget(QLabel("Betreff:"), 1, 0); gc.addWidget(self.inp_sub, 1, 1) + self.inp_from = QLineEdit(); self.inp_from.setPlaceholderText(tr.t("QB_PLACEHOLDER_FROM")) + self.inp_from.setAccessibleName(tr.t("LABEL_SENDER")) + self.inp_sub = QLineEdit(); self.inp_sub.setPlaceholderText(tr.t("QB_PLACEHOLDER_SUBJ")) + self.inp_sub.setAccessibleName(tr.t("LABEL_SUBJECT")) + self.chk_att = QCheckBox(tr.t("QB_CRIT_ATTACHMENT")); self.chk_att.setChecked(True) + + gc.addWidget(QLabel(tr.t("LABEL_SENDER")), 0, 0); gc.addWidget(self.inp_from, 0, 1) + gc.addWidget(QLabel(tr.t("LABEL_SUBJECT")), 1, 0); gc.addWidget(self.inp_sub, 1, 1) gc.addWidget(self.chk_att, 2, 0, 1, 2) layout.addWidget(g_crit) self.res_query = QLineEdit(current_query) - self.res_query.setPlaceholderText("Ergebnis Query...") - b_gen = QPushButton("Generieren"); b_gen.clicked.connect(self.generate) - layout.addWidget(b_gen); layout.addWidget(self.res_query) + self.res_query.setPlaceholderText(tr.t("QB_PLACEHOLDER_RESULT")) + self.res_query.setAccessibleName(tr.t("QB_PLACEHOLDER_RESULT")) + self.b_gen = QPushButton(tr.t("QB_BTN_GENERATE")) + self.b_gen.clicked.connect(self.generate) + layout.addWidget(self.b_gen); layout.addWidget(self.res_query) bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(self.accept); bb.rejected.connect(self.reject) layout.addWidget(bb) def toggle_dates(self): - is_custom = self.cb_time.currentText() == "Benutzerdefiniert" + idx = self.cb_time.currentIndex() + is_custom = idx == 3 or (idx < 0 and self.cb_time.currentText() == "Benutzerdefiniert") self.de_from.setEnabled(is_custom) self.de_to.setEnabled(is_custom) + @staticmethod + def _qdate_to_pydate(qdate: QDate) -> date: + if hasattr(qdate, "isValid") and not qdate.isValid(): + return date.today() + if hasattr(qdate, "toPython"): + return qdate.toPython() + if hasattr(qdate, "toPyDate"): + return qdate.toPyDate() + return date(qdate.year(), qdate.month(), qdate.day()) + @staticmethod def _parse_comma_separated_input(prefix, text): """Konvertiert Komma-separierte Eingabe zu Query-Syntax. @@ -1564,12 +1455,20 @@ def generate(self): parts.append("-in:trash") today = date.today() - t = self.cb_time.currentText() + idx = self.cb_time.currentIndex() + txt = self.cb_time.currentText() d_from = None; d_to = None - if t == "Dieses Jahr": d_from = date(today.year, 1, 1) - elif t == "Letztes Jahr": d_from = date(today.year - 1, 1, 1); d_to = date(today.year - 1, 12, 31) - elif t == "Benutzerdefiniert": d_from = self.de_from.date().toPyDate(); d_to = self.de_to.date().toPyDate() + if idx == 1 or (idx < 0 and txt == "Dieses Jahr"): + d_from = date(today.year, 1, 1) + elif idx == 2 or (idx < 0 and txt == "Letztes Jahr"): + d_from = date(today.year - 1, 1, 1) + d_to = date(today.year - 1, 12, 31) + elif idx == 3 or (idx < 0 and txt == "Benutzerdefiniert"): + d_from = self._qdate_to_pydate(self.de_from.date()) + d_to = self._qdate_to_pydate(self.de_to.date()) + if d_from and d_to and d_from > d_to: + d_from, d_to = d_to, d_from if d_from: parts.append(f"after:{d_from.strftime('%Y/%m/%d')}") if d_to: parts.append(f"before:{d_to.strftime('%Y/%m/%d')}") @@ -1675,26 +1574,42 @@ def __init__(self, accounts, profile=None, global_settings=None, parent=None): gb_over = QGroupBox(UI_LABEL_SETTINGS_OVERRIDE); gb_over.setCheckable(True); gb_over.setChecked(bool(profile and profile.override_settings)) self.gb_over = gb_over l_over = QFormLayout(gb_over) - defs = profile.override_settings if (profile and profile.override_settings) else (self.global_settings or DownloadSettings()) + tr = getattr(parent, "translator", None) or get_translator() + self._existing_override = profile.override_settings if profile else None + defs = ( + profile.override_settings + if (profile and profile.override_settings) + else (self.global_settings or DownloadSettings()) + ) self.chk_att = QCheckBox("Anhänge"); self.chk_att.setChecked(defs.download_attachments) self.chk_att.setAccessibleName("Anhänge herunterladen") self.chk_conv = QCheckBox("Body -> PDF"); self.chk_conv.setChecked(defs.convert_body_to_pdf) self.chk_conv.setAccessibleName("E-Mail-Text als PDF umwandeln") self.chk_all = QCheckBox("Alles -> PDF"); self.chk_all.setChecked(defs.convert_all_to_pdf) self.chk_all.setAccessibleName("Alle Dokumente in PDF umwandeln") + self.sp_max_emails = QSpinBox() + self.sp_max_emails.setRange(0, 100000) + self.sp_max_emails.setSpecialValueText(tr.t("SPECIAL_UNLIMITED")) + self.sp_max_emails.setValue(normalize_max_emails_per_run(defs.max_emails_per_run)) + self.sp_max_emails.setToolTip(tr.t("TT_MAX_EMAILS")) + self.sp_max_emails.setAccessibleName(tr.t("ACC_MAX_EMAILS")) self.inp_fmt = QLineEdit(", ".join(defs.formats)) self.inp_fmt.setAccessibleName("Erlaubte Dateiformate") - l_over.addRow(self.chk_att); l_over.addRow(self.chk_conv); l_over.addRow(self.chk_all); l_over.addRow("Formate:", self.inp_fmt) + l_over.addRow(self.chk_att); l_over.addRow(self.chk_conv); l_over.addRow(self.chk_all) + l_over.addRow(tr.t("LABEL_MAX_EMAILS"), self.sp_max_emails) + l_over.addRow("Formate:", self.inp_fmt) lay.addWidget(gb_over) self._existing_id = profile.id if profile else None + self._existing_since = profile.query_since if profile else "" bb = QDialogButtonBox(QDialogButtonBox.StandardButton.Save | QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(self.accept); bb.rejected.connect(self.reject); lay.addWidget(bb) def _open_query_builder(self): """Öffnet den QueryBuilderDialog und überträgt das Ergebnis in das Query-Feld.""" - d = QueryBuilderDialog(self.inp_gmail_query.text(), self) + tr = getattr(self.parent(), "translator", None) or get_translator() + d = QueryBuilderDialog(self.inp_gmail_query.text(), self, translator=tr) if d.exec(): self.inp_gmail_query.setText(d.get_query()) @@ -1703,14 +1618,23 @@ def get_profile(self): over = None if self.gb_over.isChecked(): fmts = [x.strip() for x in self.inp_fmt.text().split(",") if x.strip()] + base_over = self._existing_override over = DownloadSettings( download_attachments=self.chk_att.isChecked(), convert_body_to_pdf=self.chk_conv.isChecked(), + keep_html=base_over.keep_html if base_over else False, convert_all_to_pdf=self.chk_all.isChecked(), + keep_original_after_convert=( + base_over.keep_original_after_convert if base_over else False + ), + enable_hash_check=base_over.enable_hash_check if base_over else False, + auto_categorize=base_over.auto_categorize if base_over else False, + max_emails_per_run=self.sp_max_emails.value(), + category_rules=list(base_over.category_rules) if base_over else [], formats=fmts, ) return SearchProfile(pid, self.inp_name.text(), self.inp_group.text(), self.cb_acc.currentText(), - self.inp_subj.text(), self.inp_send.text(), "", self.inp_folder.text(), + self.inp_subj.text(), self.inp_send.text(), self._existing_since, self.inp_folder.text(), self.chk_active.isChecked(), over, self.inp_gmail_query.text()) @@ -2002,7 +1926,18 @@ def setup_ui(self): self.ip_fmt.setToolTip("Erlaubte Dateiformate als komma-getrennte Liste bearbeiten") self.ip_fmt.setAccessibleName("Erlaubte Formate") self.ip_fmt.setAccessibleDescription("Liste der Dateiformate, die heruntergeladen oder verarbeitet werden.") - fl.addRow("Pfad:", hp); fl.addRow(self.ck_att); fl.addRow(self.ck_pdf); fl.addRow(self.ck_hash); fl.addRow("Formate:", self.ip_fmt) + self.lbl_max_emails = QLabel(self.translator.t("LABEL_MAX_EMAILS")) + self.sp_max_emails = QSpinBox() + self.sp_max_emails.setRange(0, 100000) + self.sp_max_emails.setSpecialValueText(self.translator.t("SPECIAL_UNLIMITED")) + self.sp_max_emails.setValue( + normalize_max_emails_per_run(self.global_settings.max_emails_per_run) + ) + self.sp_max_emails.setToolTip(self.translator.t("TT_MAX_EMAILS")) + self.sp_max_emails.setAccessibleName(self.translator.t("ACC_MAX_EMAILS")) + fl.addRow("Pfad:", hp); fl.addRow(self.ck_att); fl.addRow(self.ck_pdf); fl.addRow(self.ck_hash) + fl.addRow(self.lbl_max_emails, self.sp_max_emails) + fl.addRow("Formate:", self.ip_fmt) self.btn_save_settings = QPushButton("Speichern"); self.btn_save_settings.clicked.connect(self.save_glob); fl.addRow(self.btn_save_settings) self.btn_save_settings.setToolTip("Globale Download- und Format-Einstellungen speichern") self.btn_save_settings.setAccessibleName("Globale Einstellungen speichern") @@ -2677,6 +2612,7 @@ def save_glob(self): self.global_settings.download_attachments = self.ck_att.isChecked() self.global_settings.convert_body_to_pdf = self.ck_pdf.isChecked() self.global_settings.enable_hash_check = self.ck_hash.isChecked() + self.global_settings.max_emails_per_run = self.sp_max_emails.value() self.global_settings.formats = [x.strip() for x in self.ip_fmt.text().split(",") if x.strip()] self.save_config() @@ -2944,6 +2880,12 @@ def retranslate_ui(self): self.ip_fmt.setToolTip(tr.t("TT_FORMATS")) self.ip_fmt.setAccessibleName(tr.t("ACC_FORMATS")) self.ip_fmt.setAccessibleDescription(tr.t("ACC_DESC_FORMATS")) + if hasattr(self, "lbl_max_emails"): + self.lbl_max_emails.setText(tr.t("LABEL_MAX_EMAILS")) + if hasattr(self, "sp_max_emails"): + self.sp_max_emails.setSpecialValueText(tr.t("SPECIAL_UNLIMITED")) + self.sp_max_emails.setToolTip(tr.t("TT_MAX_EMAILS")) + self.sp_max_emails.setAccessibleName(tr.t("ACC_MAX_EMAILS")) if hasattr(self, "btn_save_settings"): self.btn_save_settings.setText(tr.t("BTN_SAVE_SETTINGS")) self.btn_save_settings.setToolTip(tr.t("TT_SAVE_SETTINGS")) diff --git a/cli.py b/cli.py index 2f4c547..66a0e93 100644 --- a/cli.py +++ b/cli.py @@ -24,16 +24,31 @@ import argparse import csv -import hashlib import json -import re import shutil import sys import stat import time from datetime import datetime, timezone from pathlib import Path -from typing import Any, Dict, List, Optional, Sequence, Set, Tuple +from typing import Any, Dict, List, Optional, Sequence, Tuple + +from export_core import ( + DEFAULT_GROUP as DEFAULT_GROUP, + DEFAULT_LIBRARY_FILENAME, + DEFAULT_MAX_EMAILS_PER_RUN, + EXPORT_SCHEMA as EXPORT_SCHEMA, + EXPORT_SCHEMA_VERSION as EXPORT_SCHEMA_VERSION, + build_account_ref as build_account_ref, + build_library_export_payload as _core_build_library_export_payload, + calculate_file_hash as calculate_file_hash, + collect_category_entries as collect_category_entries, + extract_field as _extract_field, + infer_document_category as infer_document_category, + normalize_max_emails_per_run, + redact_path_hint as redact_path_hint, + sanitize_filename as sanitize_filename, +) # Atomic I/O & Durability try: @@ -72,19 +87,9 @@ def is_protected_path(target, paths): DEFAULT_BASE_DIR = Path.home() / ".univ_docs_grabber" DEFAULT_CONFIG_FILE = DEFAULT_BASE_DIR / "config_v1.json" DEFAULT_DOCS_DB = DEFAULT_BASE_DIR / "documents.json" -DEFAULT_LIBRARY_EXPORT = DEFAULT_BASE_DIR / "docsgrabber-library-v1.json" +DEFAULT_LIBRARY_EXPORT = DEFAULT_BASE_DIR / DEFAULT_LIBRARY_FILENAME DEFAULT_CSV_EXPORT = DEFAULT_BASE_DIR / "documents_export.csv" -EXPORT_SCHEMA = "docsgrabber-library-v1" -EXPORT_SCHEMA_VERSION = "1.0.0" -DEFAULT_GROUP = "Allgemein" - -_RESERVED_DEVICE_NAMES: Set[str] = { - "CON", "PRN", "AUX", "NUL", "CLOCK$", - *(f"COM{i}" for i in range(1, 10)), - *(f"LPT{i}" for i in range(1, 10)), -} - def get_default_paths(config_path: Optional[str] = None, db_path: Optional[str] = None) -> Tuple[Path, Path]: """Returns resolved config and documents database paths.""" @@ -93,32 +98,6 @@ def get_default_paths(config_path: Optional[str] = None, db_path: Optional[str] return c_path, d_path -def sanitize_filename(name: str) -> str: - """Sanitizes filename for cross-platform filesystem safety and limits length.""" - if not name or not isinstance(name, str): - return "unnamed" - s = re.sub(r'[^\w\s\.-]', '', name) - s = re.sub(r'\s+', '_', s) - result = s.strip().rstrip('. ')[:100].rstrip('. ') - if not result: - return "unnamed" - stem = result.split(".")[0].upper() - if result.upper() in _RESERVED_DEVICE_NAMES or stem in _RESERVED_DEVICE_NAMES: - result = f"file_{result}" - return result - - -def _extract_field(item: Any, field_name: str, default: Any = "") -> Any: - """Safely extracts a field from either a dict or an object instance.""" - if item is None: - return default - if isinstance(item, dict): - val = item.get(field_name, default) - return default if val is None else val - val = getattr(item, field_name, default) - return default if val is None else val - - def sanitize_csv_cell(value: Any) -> str: """Sanitizes a CSV cell to prevent formula injection (CWE-1236). @@ -158,61 +137,6 @@ def _resolve_export_path( return p -def build_account_ref(account_name: Optional[str]) -> str: - """Builds a stable, redacted reference for an email account.""" - if not account_name or not str(account_name).strip(): - return "account-unknown" - normalized = str(account_name).strip().encode("utf-8") - digest = hashlib.sha256(normalized).hexdigest()[:12] - return f"account-{digest}" - - -def redact_path_hint(path_value: Optional[str], base_path: Path) -> dict: - """Redacts absolute filesystem paths to relative hints or basenames.""" - if not path_value or not isinstance(path_value, (str, Path)): - return {"kind": "basename", "value": ""} - path = Path(path_value) - try: - rel_path = path.resolve(strict=False).relative_to(base_path.resolve(strict=False)) - return {"kind": "relative", "value": rel_path.as_posix()} - except (ValueError, TypeError, OSError): - return {"kind": "basename", "value": path.name} - - -def infer_document_category(path_value: Optional[str], base_path: Path, profile_name: str, target_folder: str = "") -> str: - """Infers an optional category from the document path.""" - if not path_value or not isinstance(path_value, (str, Path)): - return "" - profile_folder = sanitize_filename(profile_name or "") - target_folder_sanitized = sanitize_filename(target_folder) if target_folder else "" - path = Path(path_value) - try: - rel_path = path.resolve(strict=False).relative_to(base_path.resolve(strict=False)) - except (ValueError, TypeError, OSError): - return "" - - parts = list(rel_path.parts[:-1]) - if len(parts) < 2: - return "" - if parts[0] == profile_folder or (target_folder_sanitized and parts[0] == target_folder_sanitized): - return parts[1] - return "" - - -def calculate_file_hash(path: Optional[Path]) -> Optional[str]: - """Calculates cryptographic SHA-256 hash of a file if available.""" - if not path: - return None - h = hashlib.sha256() - try: - with open(path, "rb") as f: - for chunk in iter(lambda: f.read(4096), b""): - h.update(chunk) - return h.hexdigest() - except (FileNotFoundError, PermissionError, OSError, TypeError): - return None - - def load_data( config_path: Optional[str] = None, db_path: Optional[str] = None, @@ -227,6 +151,7 @@ def load_data( "convert_all_to_pdf": False, "enable_hash_check": False, "auto_categorize": False, + "max_emails_per_run": DEFAULT_MAX_EMAILS_PER_RUN, "category_rules": [], "formats": ["pdf", "docx", "doc", "jpg", "png"], } @@ -245,9 +170,27 @@ def load_data( loaded_settings = data.get("global_settings", {}) if isinstance(loaded_settings, dict): global_settings.update(loaded_settings) + global_settings["max_emails_per_run"] = normalize_max_emails_per_run( + global_settings.get("max_emails_per_run"), + default=DEFAULT_MAX_EMAILS_PER_RUN, + ) raw_profiles = data.get("profiles", []) if isinstance(raw_profiles, list): - profiles = [p for p in raw_profiles if isinstance(p, dict)] + normalized_profiles: List[dict] = [] + for raw_prof in raw_profiles: + if not isinstance(raw_prof, dict): + continue + prof_copy = dict(raw_prof) + raw_over = prof_copy.get("override_settings") + if isinstance(raw_over, dict): + over_copy = dict(raw_over) + over_copy["max_emails_per_run"] = normalize_max_emails_per_run( + over_copy.get("max_emails_per_run"), + default=DEFAULT_MAX_EMAILS_PER_RUN, + ) + prof_copy["override_settings"] = over_copy + normalized_profiles.append(prof_copy) + profiles = normalized_profiles raw_accounts = data.get("accounts", []) if isinstance(raw_accounts, list): accounts = [a for a in raw_accounts if isinstance(a, dict)] @@ -271,62 +214,6 @@ def load_data( return base_path, global_settings, profiles, accounts, scheduler_interval, documents -def collect_category_entries( - global_settings: Any, - profiles: List[Any], - documents: List[Any], - base_path: Path, -) -> List[dict]: - """Collects all known category entries across rules and stored document paths.""" - category_map: Dict[str, Dict[str, Any]] = {} - profile_target_map = {_extract_field(p, "name", ""): _extract_field(p, "target_folder", "") for p in profiles} - - def add_category(name: str, source: str, profile_name: str = ""): - if not name: - return - entry = category_map.setdefault( - name, - {"name": name, "sources": set(), "profile_names": set()}, - ) - entry["sources"].add(source) - if profile_name: - entry["profile_names"].add(profile_name) - - global_rules = _extract_field(global_settings, "category_rules", []) or [] - for rule in global_rules: - if isinstance(rule, dict): - add_category(rule.get("folder", ""), "global_rule") - elif hasattr(rule, "folder"): - add_category(getattr(rule, "folder", ""), "global_rule") - - for profile in profiles: - prof_name = _extract_field(profile, "name", "") - over = _extract_field(profile, "override_settings", None) - settings = over if over else global_settings - profile_rules = _extract_field(settings, "category_rules", []) or [] - for rule in profile_rules: - if isinstance(rule, dict): - add_category(rule.get("folder", ""), "profile_rule", prof_name) - elif hasattr(rule, "folder"): - add_category(getattr(rule, "folder", ""), "profile_rule", prof_name) - - for doc in documents: - doc_path = _extract_field(doc, "path", "") - doc_prof = _extract_field(doc, "profile", "") - target_folder = profile_target_map.get(doc_prof, "") - cat = infer_document_category(doc_path, base_path, doc_prof, target_folder) - add_category(cat, "document_path", doc_prof) - - return [ - { - "name": name, - "sources": sorted(entry["sources"]), - "profile_names": sorted(entry["profile_names"]), - } - for name, entry in sorted(category_map.items()) - ] - - def build_library_export_payload( base_path_str: str, global_settings: Any, @@ -336,139 +223,19 @@ def build_library_export_payload( documents: List[Any], exported_at: Optional[datetime] = None, ) -> dict: - """Builds the redacted companion export payload matching docsgrabber-library-v1.json.""" - base_path = Path(base_path_str) - export_dt = exported_at or datetime.now(timezone.utc).astimezone() - export_timestamp = export_dt.isoformat(timespec="seconds") - - account_refs = {_extract_field(a, "name", ""): build_account_ref(_extract_field(a, "name", "")) for a in accounts} - profile_target_map = {_extract_field(p, "name", ""): _extract_field(p, "target_folder", "") for p in profiles} - - documents_by_profile: Dict[str, List[dict]] = {} - exported_documents: List[dict] = [] - - for doc in documents: - raw_path = _extract_field(doc, "path", "") - doc_path = Path(raw_path) if raw_path else None - exists = doc_path.exists() if doc_path else False - prof_name = _extract_field(doc, "profile", "") - target_folder = profile_target_map.get(prof_name, "") - category = infer_document_category(raw_path, base_path, prof_name, target_folder) - - exported_doc = { - "profile_name": prof_name, - "filename": _extract_field(doc, "filename", ""), - "document_date": _extract_field(doc, "date", ""), - "file_type": doc_path.suffix.lower().lstrip(".") if doc_path else "", - "category": category or None, - "path_hint": redact_path_hint(raw_path, base_path), - "status": "available" if exists else "missing", - "sha256": calculate_file_hash(doc_path) if exists and doc_path else None, - } - exported_documents.append(exported_doc) - documents_by_profile.setdefault(prof_name, []).append(exported_doc) - - exported_profiles = [] - profile_stats = [] - - for p in profiles: - prof_name = _extract_field(p, "name", "") - over = _extract_field(p, "override_settings", None) - effective_settings = over if over else global_settings - profile_docs = documents_by_profile.get(prof_name, []) - last_doc_date = max((d["document_date"] for d in profile_docs if d.get("document_date")), default=None) - - acc_name = _extract_field(p, "account_name", "") - acc_ref = account_refs.get(acc_name, build_account_ref(acc_name)) - - filters_obj = _extract_field(p, "filters", None) - if isinstance(filters_obj, dict): - f_subject = filters_obj.get("subject", "") - f_sender = filters_obj.get("sender", "") - f_since = filters_obj.get("since", "") - f_gmail = filters_obj.get("gmail_query", "") - else: - f_subject = _extract_field(p, "query_subject", "") - f_sender = _extract_field(p, "query_sender", "") - f_since = _extract_field(p, "query_since", "") - f_gmail = _extract_field(p, "gmail_query", "") - - cat_rules = _extract_field(effective_settings, "category_rules", []) or [] - formats_list = _extract_field(effective_settings, "formats", []) or [] - - exported_profiles.append({ - "id": _extract_field(p, "id", ""), - "name": prof_name, - "group": _extract_field(p, "group", DEFAULT_GROUP) or DEFAULT_GROUP, - "active": bool(_extract_field(p, "active", True)), - "account_ref": acc_ref, - "target_folder": _extract_field(p, "target_folder", ""), - "filters": { - "subject": f_subject, - "sender": f_sender, - "since": f_since, - "gmail_query": f_gmail, - }, - "effective_settings": { - "download_attachments": bool(_extract_field(effective_settings, "download_attachments", True)), - "convert_body_to_pdf": bool(_extract_field(effective_settings, "convert_body_to_pdf", True)), - "convert_all_to_pdf": bool(_extract_field(effective_settings, "convert_all_to_pdf", False)), - "enable_hash_check": bool(_extract_field(effective_settings, "enable_hash_check", False)), - "auto_categorize": bool(_extract_field(effective_settings, "auto_categorize", False)), - "category_rule_count": len(cat_rules), - "formats": list(formats_list), - }, - "document_count": len(profile_docs), - "last_document_date": last_doc_date, - }) - - profile_stats.append({ - "profile_name": prof_name, - "document_count": len(profile_docs), - "last_document_date": last_doc_date, - "active": bool(_extract_field(p, "active", True)), - }) - - exported_accounts = [ - { - "ref": account_refs.get(_extract_field(a, "name", ""), build_account_ref(_extract_field(a, "name", ""))), - "profile_count": sum(1 for p in profiles if _extract_field(p, "account_name", "") == _extract_field(a, "name", "")), - } - for a in accounts - ] - - categories = collect_category_entries(global_settings, profiles, documents, base_path) - - return { - "schema": EXPORT_SCHEMA, - "schema_version": EXPORT_SCHEMA_VERSION, - "app": { - "name": APP_NAME, - "version": VERSION, - "exported_at": export_timestamp, - }, - "capabilities": { - "redacted": True, - "contains_credentials": False, - "contains_document_files": False, - "contains_mail_body_text": False, - }, - "base_path_hint": { - "kind": "basename", - "value": Path(base_path).name, - }, - "accounts": exported_accounts, - "profiles": exported_profiles, - "categories": categories, - "documents": exported_documents, - "run_summary": { - "exported_profile_count": len(exported_profiles), - "active_profile_count": sum(1 for p in profiles if bool(_extract_field(p, "active", True))), - "exported_document_count": len(exported_documents), - "scheduler_interval_minutes": scheduler_interval, - "profile_stats": profile_stats, - }, - } + """Builds the canonical redacted companion export payload via export_core.""" + return _core_build_library_export_payload( + profiles=profiles, + accounts=accounts, + documents=documents, + global_settings=global_settings, + base_path=Path(base_path_str), + scheduler_interval=scheduler_interval, + exported_at=exported_at, + app_name=APP_NAME, + app_version=VERSION, + hash_fn=calculate_file_hash, + ) def export_documents_to_csv( diff --git a/conftest.py b/conftest.py new file mode 100644 index 0000000..3753879 --- /dev/null +++ b/conftest.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +"""Root Pytest configuration enforcing CWD-independent basetemp resolution.""" + +from __future__ import annotations + +from pathlib import Path + + +def pytest_configure(config) -> None: + """Resolve default temporary test directory against config.rootpath regardless of CWD.""" + if getattr(config.option, "basetemp", None) is None: + config.option.basetemp = str(Path(config.rootpath) / ".pytest_temp") diff --git a/export_core.py b/export_core.py new file mode 100644 index 0000000..c97430c --- /dev/null +++ b/export_core.py @@ -0,0 +1,454 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +"""UI-free domain core for path sanitization, SHA-256 hashing, and redacted library export. + +Shared by both the PySide6 desktop application (UniversalDocsGrabberV1.py) and the +headless automation CLI (cli.py) so schema identifiers, redaction rules, category +inference, and Windows/DOS device-name guards remain 100% identical across surfaces. +""" + +from __future__ import annotations + +import hashlib +import math +import re +from datetime import datetime +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Sequence, Set + +EXPORT_SCHEMA = "docsgrabber-library" +EXPORT_SCHEMA_VERSION = "1.0" +DEFAULT_LIBRARY_FILENAME = "docsgrabber-library-v1.json" +DEFAULT_GROUP = "Allgemein" +DEFAULT_MAX_EMAILS_PER_RUN = 30 +DEFAULT_FORMATS = ("pdf", "docx", "doc", "jpg", "png") + +_RESERVED_DEVICE_NAMES: Set[str] = { + "CON", + "PRN", + "AUX", + "NUL", + "CLOCK$", + "CONIN$", + "CONOUT$", + *(f"COM{i}" for i in range(0, 10)), + *(f"LPT{i}" for i in range(0, 10)), + "COM¹", + "COM²", + "COM³", + "LPT¹", + "LPT²", + "LPT³", +} + + +def extract_field(item: Any, field_name: str, default: Any = "") -> Any: + """Safely extracts a field from either a mapping or a dataclass/object instance.""" + if item is None: + return default + if isinstance(item, dict): + val = item.get(field_name, default) + return default if val is None else val + val = getattr(item, field_name, default) + return default if val is None else val + + +def normalize_max_emails_per_run( + value: Any, + default: int = DEFAULT_MAX_EMAILS_PER_RUN, +) -> int: + """Normalizes max_emails_per_run (0 = unlimited, >0 = last N matching UIDs).""" + if value is None or isinstance(value, bool): + return default + if isinstance(value, float) and not math.isfinite(value): + return default + try: + parsed = int(value) + except (TypeError, ValueError, OverflowError): + return default + return max(0, parsed) + + +def sanitize_filename(name: str) -> str: + """Sanitizes filenames for cross-platform safety, length bounds, and Windows device names.""" + if not name or not isinstance(name, str): + return "unnamed" + cleaned = re.sub(r"[^\w\s\.-]", "", name) + cleaned = re.sub(r"\s+", "_", cleaned) + result = cleaned.strip().rstrip(". ")[:100].rstrip(". ") + if not result: + return "unnamed" + stem = result.split(".")[0].upper() + if result.upper() in _RESERVED_DEVICE_NAMES or stem in _RESERVED_DEVICE_NAMES: + result = f"file_{result}" + return result + + +def build_account_ref(account_name: Optional[str]) -> str: + """Builds a stable, redacted SHA-256 reference for a mail account.""" + if not account_name or not str(account_name).strip(): + return "account-unknown" + normalized = str(account_name).strip().encode("utf-8") + digest = hashlib.sha256(normalized).hexdigest()[:12] + return f"account-{digest}" + + +def redact_path_hint(path_value: Optional[str | Path], base_path: Path) -> dict: + """Redacts absolute filesystem paths to relative hints under base_path or basenames.""" + if not path_value or not isinstance(path_value, (str, Path)): + return {"kind": "basename", "value": ""} + path = Path(path_value) + try: + rel_path = path.resolve(strict=False).relative_to(base_path.resolve(strict=False)) + return {"kind": "relative", "value": rel_path.as_posix()} + except (ValueError, TypeError, OSError): + return {"kind": "basename", "value": path.name} + + +def infer_document_category( + path_value: Optional[str | Path], + base_path: Path, + profile_name: str, + target_folder: str = "", +) -> str: + """Infers an optional category subfolder under the profile or target folder.""" + if not path_value or not isinstance(path_value, (str, Path)): + return "" + profile_folder = sanitize_filename(profile_name or "") + target_folder_sanitized = sanitize_filename(target_folder) if target_folder else "" + path = Path(path_value) + try: + rel_path = path.resolve(strict=False).relative_to(base_path.resolve(strict=False)) + except (ValueError, TypeError, OSError): + return "" + + parts = list(rel_path.parts[:-1]) + if len(parts) < 2: + return "" + if parts[0] == profile_folder or ( + target_folder_sanitized and parts[0] == target_folder_sanitized + ): + return parts[1] + return "" + + +def calculate_file_hash( + path: Optional[Path | str], + on_error: Optional[Callable[[Path, Exception], None]] = None, +) -> Optional[str]: + """Calculates cryptographic SHA-256 hex digest of a file using 64 KiB buffered reads.""" + if not path: + return None + file_path = Path(path) + digest = hashlib.sha256() + try: + with open(file_path, "rb") as handle: + for chunk in iter(lambda: handle.read(65536), b""): + digest.update(chunk) + return digest.hexdigest() + except (FileNotFoundError, PermissionError, OSError, TypeError) as exc: + if on_error is not None: + on_error(file_path, exc) + return None + + +def _extract_rule_folder(rule: Any) -> str: + if isinstance(rule, dict): + raw = rule.get("folder", "") + elif hasattr(rule, "folder"): + raw = getattr(rule, "folder", "") + else: + raw = "" + return raw.strip() if isinstance(raw, str) else "" + + +def collect_category_entries( + global_settings: Any, + profiles: Sequence[Any], + documents: Sequence[Any], + base_path: Path, +) -> List[dict]: + """Collects unified category metadata across global rules, profile overrides, and document paths.""" + category_map: Dict[str, Dict[str, Any]] = {} + profile_target_map = { + extract_field(p, "name", ""): extract_field(p, "target_folder", "") + for p in profiles + if p is not None + } + + def ensure_entry(name: str) -> Optional[Dict[str, Any]]: + cleaned = name.strip() if isinstance(name, str) else "" + if not cleaned: + return None + return category_map.setdefault( + cleaned, + { + "name": cleaned, + "sources": set(), + "profile_names": set(), + "rule_count": 0, + "document_count": 0, + }, + ) + + global_rules = extract_field(global_settings, "category_rules", []) or [] + for rule in global_rules: + folder = _extract_rule_folder(rule) + entry = ensure_entry(folder) + if entry is not None: + entry["sources"].add("global_rule") + entry["rule_count"] += 1 + + for profile in profiles: + if profile is None: + continue + prof_name = extract_field(profile, "name", "") + over = extract_field(profile, "override_settings", None) + if over is not None: + profile_rules = extract_field(over, "category_rules", []) or [] + for rule in profile_rules: + folder = _extract_rule_folder(rule) + entry = ensure_entry(folder) + if entry is not None: + entry["sources"].add("profile_rule") + if prof_name: + entry["profile_names"].add(prof_name) + entry["rule_count"] += 1 + + for doc in documents: + if doc is None: + continue + doc_path = extract_field(doc, "path", "") + doc_prof = extract_field(doc, "profile", "") + target_folder = profile_target_map.get(doc_prof, "") + cat = infer_document_category(doc_path, base_path, doc_prof, target_folder) + entry = ensure_entry(cat) + if entry is not None: + entry["sources"].add("document_path") + if doc_prof: + entry["profile_names"].add(doc_prof) + entry["document_count"] += 1 + + result: List[dict] = [] + for name, entry in sorted(category_map.items()): + sorted_sources = sorted(entry["sources"]) + result.append( + { + "name": name, + "source": ", ".join(sorted_sources) if sorted_sources else "unknown", + "sources": sorted_sources, + "profile_names": sorted(entry["profile_names"]), + "rule_count": entry["rule_count"], + "document_count": entry["document_count"], + } + ) + return result + + +def build_library_export_payload( + *, + profiles: Sequence[Any], + accounts: Sequence[Any], + documents: Sequence[Any], + global_settings: Any, + base_path: Path | str, + scheduler_interval: int = 0, + exported_at: Optional[datetime] = None, + app_name: str = "UniversalDocsGrabber", + app_version: str = "1.1.7", + hash_fn: Callable[[Path], Optional[str]] = calculate_file_hash, +) -> dict: + """Builds the canonical redacted Web/PWA companion payload (schema docsgrabber-library 1.0).""" + resolved_base = Path(base_path) + export_dt = exported_at or datetime.now().astimezone() + export_timestamp = export_dt.isoformat(timespec="seconds") + + account_refs = { + extract_field(a, "name", ""): build_account_ref(extract_field(a, "name", "")) + for a in accounts + if a is not None + } + profile_target_map = { + extract_field(p, "name", ""): extract_field(p, "target_folder", "") + for p in profiles + if p is not None + } + + documents_by_profile: Dict[str, List[dict]] = {} + exported_documents: List[dict] = [] + + for doc in documents: + if doc is None: + continue + raw_path = extract_field(doc, "path", "") + doc_path = Path(raw_path) if raw_path else None + exists = doc_path.exists() if doc_path else False + prof_name = extract_field(doc, "profile", "") + target_folder = profile_target_map.get(prof_name, "") + category = infer_document_category(raw_path, resolved_base, prof_name, target_folder) + + exported_doc = { + "profile_name": prof_name, + "filename": extract_field(doc, "filename", ""), + "document_date": extract_field(doc, "date", ""), + "file_type": doc_path.suffix.lower().lstrip(".") if doc_path else "", + "category": category or None, + "path_hint": redact_path_hint(raw_path, resolved_base), + "status": "available" if exists else "missing", + "sha256": hash_fn(doc_path) if exists and doc_path else None, + } + exported_documents.append(exported_doc) + documents_by_profile.setdefault(prof_name, []).append(exported_doc) + + exported_profiles: List[dict] = [] + profile_stats: List[dict] = [] + + for profile in profiles: + if profile is None: + continue + prof_name = extract_field(profile, "name", "") + over = extract_field(profile, "override_settings", None) + effective_settings = over if over is not None else global_settings + profile_docs = documents_by_profile.get(prof_name, []) + last_doc_date = max( + (d["document_date"] for d in profile_docs if d.get("document_date")), + default=None, + ) + + acc_name = extract_field(profile, "account_name", "") + acc_ref = account_refs.get(acc_name, build_account_ref(acc_name)) + + filters_obj = extract_field(profile, "filters", None) + if isinstance(filters_obj, dict): + f_subject = filters_obj.get("subject", "") or "" + f_sender = filters_obj.get("sender", "") or "" + f_since = filters_obj.get("since", "") or "" + f_gmail = filters_obj.get("gmail_query", "") or "" + else: + f_subject = extract_field(profile, "query_subject", "") + f_sender = extract_field(profile, "query_sender", "") + f_since = extract_field(profile, "query_since", "") + f_gmail = extract_field(profile, "gmail_query", "") + + cat_rules = extract_field(effective_settings, "category_rules", []) or [] + raw_formats = extract_field(effective_settings, "formats", None) + if raw_formats is None and ( + effective_settings is None + or (isinstance(effective_settings, dict) and "formats" not in effective_settings) + ): + formats_list = list(DEFAULT_FORMATS) + else: + formats_list = list(raw_formats or []) + active_flag = bool(extract_field(profile, "active", True)) + + exported_profiles.append( + { + "id": extract_field(profile, "id", ""), + "name": prof_name, + "group": extract_field(profile, "group", DEFAULT_GROUP) or DEFAULT_GROUP, + "active": active_flag, + "account_ref": acc_ref, + "target_folder": extract_field(profile, "target_folder", ""), + "filters": { + "subject": f_subject, + "sender": f_sender, + "since": f_since, + "gmail_query": f_gmail, + }, + "effective_settings": { + "download_attachments": bool( + extract_field(effective_settings, "download_attachments", True) + ), + "convert_body_to_pdf": bool( + extract_field(effective_settings, "convert_body_to_pdf", True) + ), + "convert_all_to_pdf": bool( + extract_field(effective_settings, "convert_all_to_pdf", False) + ), + "enable_hash_check": bool( + extract_field(effective_settings, "enable_hash_check", False) + ), + "auto_categorize": bool( + extract_field(effective_settings, "auto_categorize", False) + ), + "max_emails_per_run": normalize_max_emails_per_run( + extract_field( + effective_settings, + "max_emails_per_run", + DEFAULT_MAX_EMAILS_PER_RUN, + ), + default=DEFAULT_MAX_EMAILS_PER_RUN, + ), + "category_rule_count": len(cat_rules), + "formats": list(formats_list), + }, + "document_count": len(profile_docs), + "last_document_date": last_doc_date, + } + ) + + profile_stats.append( + { + "profile_name": prof_name, + "document_count": len(profile_docs), + "last_document_date": last_doc_date, + "active": active_flag, + } + ) + + exported_accounts = [ + { + "ref": account_refs.get( + extract_field(a, "name", ""), + build_account_ref(extract_field(a, "name", "")), + ), + "profile_count": sum( + 1 + for p in profiles + if p is not None + and extract_field(p, "account_name", "") == extract_field(a, "name", "") + ), + } + for a in accounts + if a is not None + ] + + categories = collect_category_entries( + global_settings=global_settings, + profiles=profiles, + documents=documents, + base_path=resolved_base, + ) + + return { + "schema": EXPORT_SCHEMA, + "schema_version": EXPORT_SCHEMA_VERSION, + "app": { + "name": app_name, + "version": app_version, + "exported_at": export_timestamp, + }, + "capabilities": { + "redacted": True, + "contains_credentials": False, + "contains_document_files": False, + "contains_mail_body_text": False, + }, + "base_path_hint": { + "kind": "basename", + "value": resolved_base.name, + }, + "accounts": exported_accounts, + "profiles": exported_profiles, + "categories": categories, + "documents": exported_documents, + "run_summary": { + "exported_profile_count": len(exported_profiles), + "active_profile_count": sum( + 1 for p in profiles if p is not None and bool(extract_field(p, "active", True)) + ), + "exported_document_count": len(exported_documents), + "scheduler_interval_minutes": scheduler_interval, + "profile_stats": profile_stats, + }, + } diff --git a/llm.txt b/llm.txt new file mode 100644 index 0000000..ba5d506 --- /dev/null +++ b/llm.txt @@ -0,0 +1 @@ +UniversalDocsGrabber machine-readable context: see llms.txt for project overview/invariants and SKILL.md for headless CLI (--json) and Python API usage. diff --git a/llms.txt b/llms.txt index eb487ea..af15f89 100644 --- a/llms.txt +++ b/llms.txt @@ -1,6 +1,6 @@ # UniversalDocsGrabber -## Last-checked: 2026-10-31 (Prior baselines 2026-10-01, 2026-09-30, 2026-09-28, 2026-09-22, 2026-09-14) +## Last-checked: 2026-12-06 (Prior baselines: Last-checked: 2026-10-31, 2026-10-01, 2026-09-30, 2026-09-28, 2026-09-22, 2026-09-14) Canonical repository: https://github.com/doc-bricks/UniversalDocsGrabber Organization: https://github.com/doc-bricks @@ -65,7 +65,7 @@ companion. - `README-DE.md`: German documentation with 100% reciprocal anchor, comparative matrix, and content parity - `README_es.md`: Spanish documentation with 1:1 structural parity, reciprocal anchors, comparative matrix, and statutory notice - `translator.py`: Tier-2 6-languages translation engine (DE, EN, ES, ZH, JA, RU) with deterministic fallback chain -- `locales/translations.json`: 162-key localization catalog with 100% parity across all 6 languages +- `locales/translations.json`: 232-key localization catalog with 100% parity across all 6 languages - `NOTICE`: canonical open-source attribution notice - `SECURITY.md`: bilingual security policy, 48h acknowledgement SLA, and local-first invariants - `CONTRIBUTING.md`: bilingual development guidelines, Plan D setup, unprivileged RunAsInvoker guarantee, and quality gates @@ -74,6 +74,9 @@ companion. - `MARKETING-LOG.txt`: personas, 10-dimension comparative matrix, sibling mapping, and 10 governance invariants - `UniversalDocsGrabberV1.py`: desktop application - `cli.py`: headless automation CLI interface +- `export_core.py`: UI-free shared domain core for redaction, SHA-256 hashing, device-name protection, and canonical `docsgrabber-library` (`1.0`) export payloads +- `SKILL.md`: Policy P-022 agent & automation skill guide (`--json` CLI & Python API) +- `llm.txt`: concise machine-readable pointer to `llms.txt` and `SKILL.md` - `EXPORTFORMAT.md`: redacted companion export schema - `PORTIERUNGSPLAN.md`: current platform, PWA and device-gate status matrix - `web_companion/`: static local Web/PWA companion @@ -94,9 +97,9 @@ companion. ## Verification -- Pytest test suite: 84 passed, 0 failed (100% green) -- Web Companion test suite: 32 passed, 0 failed (100% green) -- Combined contract-test verification: 116 passed, 0 failed (84 Pytest + 32 Node; prior baselines 114, 110 passed) +- Pytest test suite: 272 passed, 0 failed (100% green) +- Web Companion test suite: 35 passed, 0 failed (100% green) +- Combined contract-test verification: 307 passed, 0 failed (272 Pytest + 35 Node; prior baselines: 116 passed, 114 passed, 110 passed) - CI Matrix: Ubuntu, Windows, macOS across Python 3.10, 3.11, 3.12, 3.13 and Node.js 18.x, 20.x, 22.x, 24.x - Build specification: Standard PEP 621 `pyproject.toml` with 20 saturated keywords matching GitHub repository topics diff --git a/locales/translations.json b/locales/translations.json index d1c0e98..cd8e32a 100644 --- a/locales/translations.json +++ b/locales/translations.json @@ -1822,5 +1822,37 @@ "zh": "UniversalDocsGrabber {version}\n\n本地邮件文档抓取器、OCR 处理器与文档归档工具。\n离线优先、隐私保护并完全支持无障碍操作。\n\n许可证:MIT\n维护者:doc-bricks (support@lukasgeiger.com)", "ja": "UniversalDocsGrabber {version}\n\nローカルメール添付書類取得ツール、OCR プロセッサ、ドキュメント整理ツール。\nオフラインファースト、プライバシー重視、完全アクセシブル設計。\n\nライセンス: MIT\nメンテナー: doc-bricks (support@lukasgeiger.com)", "ru": "UniversalDocsGrabber {version}\n\nЛокальный инструмент для загрузки вложений электронной почты, OCR-обработки и архивации документов.\nOffline-first, конфиденциальный и полностью доступный.\n\nЛицензия: MIT\nСопровождающий: doc-bricks (support@lukasgeiger.com)" + }, + "LABEL_MAX_EMAILS": { + "de": "Max. E-Mails pro Lauf:", + "en": "Max emails per run:", + "es": "Máx. correos por ejecución:", + "zh": "每次运行最大邮件数:", + "ja": "1回あたりの最大メール数:", + "ru": "Макс. писем за запуск:" + }, + "SPECIAL_UNLIMITED": { + "de": "Unbegrenzt (0)", + "en": "Unlimited (0)", + "es": "Sin límite (0)", + "zh": "无限制 (0)", + "ja": "無制限 (0)", + "ru": "Без лимита (0)" + }, + "TT_MAX_EMAILS": { + "de": "Maximale Anzahl passender Nachrichten pro Profil und Lauf (0 = alle Treffer ohne Limit)", + "en": "Maximum matching messages processed per profile and run (0 = all matches without limit)", + "es": "Número máximo de mensajes procesados por perfil y ejecución (0 = todos sin límite)", + "zh": "每个配置文件单次运行处理的最大匹配邮件数(0 = 不限制)", + "ja": "プロファイルごとに1回の実行で処理する最大一致メール数(0 = 無制限)", + "ru": "Максимальное число обрабатываемых писем на профиль за запуск (0 = все без ограничения)" + }, + "ACC_MAX_EMAILS": { + "de": "Maximale E-Mails pro Lauf", + "en": "Maximum emails per run", + "es": "Máximo de correos por ejecución", + "zh": "每次运行最大邮件数", + "ja": "1回あたりの最大メール数", + "ru": "Максимум писем за запуск" } -} \ No newline at end of file +} diff --git a/pyproject.toml b/pyproject.toml index 1d082d0..be1077d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -98,9 +98,20 @@ Notice = "https://github.com/doc-bricks/UniversalDocsGrabber/blob/master/NOTICE" "Parent Organization" = "https://github.com/doc-bricks" "Umbrella Ecosystem" = "https://github.com/open-bricks" +[tool.setuptools] +py-modules = [ + "UniversalDocsGrabberV1", + "cli", + "export_core", + "atomic_io", + "translator", + "app_icon_loader", + "manage_translations", +] + [tool.pytest.ini_options] minversion = "7.0" -addopts = "-ra -v --basetemp=.pytest_temp" +addopts = "-ra -v" pythonpath = "." testpaths = ["tests"] python_files = ["test_*.py", "source_platform_smoke.py"] diff --git a/tests/test_bugsweep_cli_and_export_resilience_20261003.py b/tests/test_bugsweep_cli_and_export_resilience_20261003.py index dd926a8..e6b3eaf 100644 --- a/tests/test_bugsweep_cli_and_export_resilience_20261003.py +++ b/tests/test_bugsweep_cli_and_export_resilience_20261003.py @@ -88,7 +88,7 @@ def test_build_library_export_payload_with_null_document_fields(self): scheduler_interval=15, documents=sample_docs, ) - self.assertEqual(payload["schema"], "docsgrabber-library-v1") + self.assertEqual(payload["schema"], "docsgrabber-library") self.assertEqual(len(payload["documents"]), 2) doc0 = payload["documents"][0] self.assertEqual(doc0["profile_name"], "") @@ -172,7 +172,7 @@ def test_cli_export_library_directory_resolution_and_atomic_replace(self): expected_file = target_dir / "docsgrabber-library-v1.json" self.assertTrue(expected_file.exists()) payload = json.loads(expected_file.read_text(encoding="utf-8")) - self.assertEqual(payload["schema"], "docsgrabber-library-v1") + self.assertEqual(payload["schema"], "docsgrabber-library") def test_load_data_none_and_corrupt_fields(self): corrupt_config = { diff --git a/tests/test_bugsweep_cli_and_export_security_20261030.py b/tests/test_bugsweep_cli_and_export_security_20261030.py index fd713e7..e7d75e8 100644 --- a/tests/test_bugsweep_cli_and_export_security_20261030.py +++ b/tests/test_bugsweep_cli_and_export_security_20261030.py @@ -101,7 +101,7 @@ def test_cli_export_library_handles_readonly_target(self): ]) self.assertEqual(exit_code, 0) data = json.loads(target_file.read_text(encoding="utf-8")) - self.assertEqual(data["schema"], "docsgrabber-library-v1") + self.assertEqual(data["schema"], "docsgrabber-library") self.assertEqual(len(data["profiles"]), 1) finally: os.chmod(target_file, stat.S_IWRITE | stat.S_IREAD) @@ -194,7 +194,7 @@ def test_csv_and_library_export_with_dataclass_objects(self): scheduler_interval=30, documents=[doc_obj], ) - self.assertEqual(payload["schema"], "docsgrabber-library-v1") + self.assertEqual(payload["schema"], "docsgrabber-library") self.assertEqual(len(payload["profiles"]), 1) self.assertEqual(payload["profiles"][0]["name"], "Finanzen") self.assertEqual(len(payload["documents"]), 1) diff --git a/tests/test_cli.py b/tests/test_cli.py index 7b79972..a3b4adc 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -275,8 +275,8 @@ def test_export_library_json(self): self.assertTrue(export_file.exists()) payload = json.loads(export_file.read_text(encoding="utf-8")) - self.assertEqual(payload["schema"], "docsgrabber-library-v1") - self.assertEqual(payload["schema_version"], "1.0.0") + self.assertEqual(payload["schema"], "docsgrabber-library") + self.assertEqual(payload["schema_version"], "1.0") self.assertEqual(payload["app"]["name"], "UniversalDocsGrabber") self.assertTrue(payload["capabilities"]["redacted"]) self.assertFalse(payload["capabilities"]["contains_credentials"]) diff --git a/tests/test_high_end_udg_04_06.py b/tests/test_high_end_udg_04_06.py new file mode 100644 index 0000000..3602b01 --- /dev/null +++ b/tests/test_high_end_udg_04_06.py @@ -0,0 +1,379 @@ +# -*- coding: utf-8 -*- +"""High-End Architecture, Localization, P-022 & Performance Contract Tests (TW-UDG-04..06).""" + +from __future__ import annotations + +import ast +import os +from datetime import date +from pathlib import Path + +import pytest + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") + +from PySide6.QtCore import QDate +from PySide6.QtWidgets import QApplication + +import cli +import UniversalDocsGrabberV1 as app +from translator import TranslationSystem, get_translator + +ROOT = Path(__file__).resolve().parent.parent + + +@pytest.fixture(scope="module") +def qapp(): + inst = QApplication.instance() + if inst is None: + inst = QApplication([]) + return inst + + +def test_export_core_ui_free_and_gui_cli_schema_parity(tmp_path): + """TW-UDG-05: export_core is UI-free and unifies GUI + CLI on schema docsgrabber-library 1.0.""" + import export_core + + core_source = (ROOT / "export_core.py").read_text(encoding="utf-8") + tree = ast.parse(core_source) + imported_roots = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + for alias in node.names: + imported_roots.add(alias.name.split(".")[0]) + elif isinstance(node, ast.ImportFrom) and node.module: + imported_roots.add(node.module.split(".")[0]) + assert "PySide6" not in imported_roots + + assert export_core.EXPORT_SCHEMA == "docsgrabber-library" + assert export_core.EXPORT_SCHEMA_VERSION == "1.0" + assert app.EXPORT_SCHEMA == "docsgrabber-library" + assert app.EXPORT_SCHEMA_VERSION == "1.0" + assert cli.EXPORT_SCHEMA == "docsgrabber-library" + assert cli.EXPORT_SCHEMA_VERSION == "1.0" + + # Extended Windows/DOS device names + for raw_dev in ("CON.pdf", "NUL", "COM0.txt", "LPT0.doc", "COM¹.pdf", "LPT².png"): + sanitized = export_core.sanitize_filename(raw_dev) + assert sanitized.startswith("file_"), f"Expected file_ prefix for {raw_dev}, got {sanitized}" + + downloads = tmp_path / "UnivDocs" + cat_dir = downloads / "Invoices" / "Rechnungen" + cat_dir.mkdir(parents=True) + pdf_path = cat_dir / "inv_01.pdf" + pdf_path.write_bytes(b"%PDF-1.4 parity test") + + gui_payload = app.build_library_export_payload( + profiles=[ + app.SearchProfile( + "p-1", + "Invoices", + "Finance", + "Primary", + query_subject="Invoice", + target_folder="Invoices", + override_settings=app.DownloadSettings( + auto_categorize=True, + max_emails_per_run=75, + category_rules=[{"keyword": "invoice", "folder": "Rechnungen"}], + ), + ) + ], + accounts=[app.MailAccount("Primary", "imap.example.org", "user@example.org")], + documents=[app.Document("Invoices", "inv_01.pdf", "2026-11-20", str(pdf_path))], + global_settings=app.DownloadSettings( + max_emails_per_run=30, + category_rules=[{"keyword": "steuer", "folder": "Steuer"}], + ), + base_path=downloads, + scheduler_interval=30, + ) + + cli_payload = cli.build_library_export_payload( + base_path_str=str(downloads), + global_settings={ + "max_emails_per_run": 30, + "category_rules": [{"keyword": "steuer", "folder": "Steuer"}], + }, + profiles=[ + { + "id": "p-1", + "name": "Invoices", + "group": "Finance", + "account_name": "Primary", + "query_subject": "Invoice", + "target_folder": "Invoices", + "active": True, + "override_settings": { + "auto_categorize": True, + "max_emails_per_run": 75, + "category_rules": [{"keyword": "invoice", "folder": "Rechnungen"}], + }, + } + ], + accounts=[{"name": "Primary"}], + scheduler_interval=30, + documents=[{"profile": "Invoices", "filename": "inv_01.pdf", "date": "2026-11-20", "path": str(pdf_path)}], + ) + + assert gui_payload["schema"] == cli_payload["schema"] == "docsgrabber-library" + assert gui_payload["schema_version"] == cli_payload["schema_version"] == "1.0" + assert gui_payload["accounts"] == cli_payload["accounts"] + assert gui_payload["documents"] == cli_payload["documents"] + assert gui_payload["categories"] == cli_payload["categories"] + assert gui_payload["profiles"] == cli_payload["profiles"] + assert gui_payload["profiles"][0]["effective_settings"]["max_emails_per_run"] == 75 + + rechnungen_cat = next(c for c in gui_payload["categories"] if c["name"] == "Rechnungen") + assert rechnungen_cat["document_count"] == 1 + assert rechnungen_cat["rule_count"] == 1 + assert "profile_rule" in rechnungen_cat["sources"] + assert "document_path" in rechnungen_cat["sources"] + assert isinstance(rechnungen_cat["source"], str) and rechnungen_cat["source"] + + +def test_query_builder_dialog_language_independent_across_six_languages(qapp): + """TW-UDG-04: QueryBuilderDialog uses index-based presets across all 6 languages and swaps inverted dates.""" + orig_lang = get_translator().current_lang + today = date.today() + seen_preset_labels = set() + + try: + for lang in TranslationSystem.SUPPORTED_LANGUAGES: + get_translator().set_language(lang) + dlg = app.QueryBuilderDialog() + assert dlg.cb_time.count() == 4 + seen_preset_labels.add(dlg.cb_time.itemText(1)) + + # Index 0: All -> dates disabled, no after:/before: + dlg.cb_time.setCurrentIndex(0) + assert dlg.de_from.isEnabled() is False + assert dlg.de_to.isEnabled() is False + dlg.generate() + q0 = dlg.get_query() + assert "after:" not in q0 and "before:" not in q0 + + # Index 1: This year -> after:/01/01 + dlg.cb_time.setCurrentIndex(1) + assert dlg.de_from.isEnabled() is False + dlg.generate() + q1 = dlg.get_query() + assert f"after:{today.year}/01/01" in q1 + assert "before:" not in q1 + + # Index 2: Last year -> after:/01/01 before:/12/31 + dlg.cb_time.setCurrentIndex(2) + assert dlg.de_from.isEnabled() is False + dlg.generate() + q2 = dlg.get_query() + assert f"after:{today.year - 1}/01/01" in q2 + assert f"before:{today.year - 1}/12/31" in q2 + + # Index 3: Custom -> dates enabled + inverted date range auto-swapped + dlg.cb_time.setCurrentIndex(3) + assert dlg.de_from.isEnabled() is True + assert dlg.de_to.isEnabled() is True + dlg.de_from.setDate(QDate(2026, 8, 20)) + dlg.de_to.setDate(QDate(2026, 2, 10)) + dlg.generate() + q3 = dlg.get_query() + assert "after:2026/02/10" in q3 + assert "before:2026/08/20" in q3 + dlg.close() + + # Verify QueryBuilderDialog actually localized its preset labels across languages + assert len(seen_preset_labels) >= 5 + assert app.QueryBuilderDialog._qdate_to_pydate(QDate()) == today + finally: + get_translator().set_language(orig_lang) + + +def test_configurable_max_emails_per_run_and_ui_persistence(qapp, tmp_path, monkeypatch): + """TW-UDG-06: max_emails_per_run defaults to 30, supports custom caps and 0=unlimited, and persists via UI/CLI.""" + assert app.DownloadSettings().max_emails_per_run == 30 + assert app.DownloadSettings.from_dict({"max_emails_per_run": -7}).max_emails_per_run == 0 + assert app.DownloadSettings.from_dict({"max_emails_per_run": "invalid"}).max_emails_per_run == 30 + assert app.DownloadSettings.from_dict({"max_emails_per_run": float("inf")}).max_emails_per_run == 30 + assert app.DownloadSettings.from_dict({"max_emails_per_run": float("nan")}).max_emails_per_run == 30 + + prof = app.SearchProfile("p1", "BatchProf", "G", "Acc", query_subject="Invoice") + worker = app.GrabberWorker([prof], [], app.DownloadSettings(), tmp_path, []) + + uids_45 = [str(i).encode("ascii") for i in range(1, 46)] + + class FakeImap: + capabilities = (b"IMAP4rev1",) + + def uid(self, cmd, *_args): + if cmd == "search": + return "OK", [b" ".join(uids_45)] + return "OK", [] + + fetched = [] + monkeypatch.setattr(worker, "process_email", lambda _c, uid, *_a: fetched.append(uid)) + + # 1. Default 30 -> last 30 (16..45) + worker.process_profile(FakeImap(), prof, app.DownloadSettings(max_emails_per_run=30)) + assert len(fetched) == 30 and fetched[0] == b"16" and fetched[-1] == b"45" + + # 2. Custom cap 5 -> last 5 (41..45) + fetched.clear() + worker.process_profile(FakeImap(), prof, app.DownloadSettings(max_emails_per_run=5)) + assert fetched == [b"41", b"42", b"43", b"44", b"45"] + + # 3. Unlimited 0 -> all 45 (1..45) + fetched.clear() + worker.process_profile(FakeImap(), prof, app.DownloadSettings(max_emails_per_run=0)) + assert len(fetched) == 45 and fetched[0] == b"1" and fetched[-1] == b"45" + + # UI + Config + CLI persistence roundtrip + cfg_file = tmp_path / "config_v1.json" + docs_file = tmp_path / "documents.json" + monkeypatch.setattr(app, "CONFIG_FILE", cfg_file) + monkeypatch.setattr(app, "DOCS_DB", docs_file) + + win = app.MainWindow() + try: + assert win.sp_max_emails.value() == 30 + win.sp_max_emails.setValue(0) + win.save_glob() + assert win.global_settings.max_emails_per_run == 0 + + pdlg = app.ProfileDialog( + [app.MailAccount("Acc", "imap.example.org", "u@example.org")], + global_settings=win.global_settings, + ) + pdlg.inp_name.setText("UnlimitedProf") + pdlg.gb_over.setChecked(True) + pdlg.sp_max_emails.setValue(120) + built_prof = pdlg.get_profile() + pdlg.close() + assert built_prof.override_settings is not None + assert built_prof.override_settings.max_emails_per_run == 120 + + win.profiles = [built_prof] + win.save_config() + finally: + win._scheduler_timer.stop() + win.close() + + _, cli_settings, cli_profiles, _, _, _ = cli.load_data(str(cfg_file), str(docs_file)) + assert cli_settings["max_emails_per_run"] == 0 + assert cli_profiles[0]["override_settings"]["max_emails_per_run"] == 120 + + # Legacy / negative / non-finite override_settings normalization in cli.load_data + legacy_cfg = tmp_path / "legacy_config.json" + legacy_cfg.write_text( + '{"global_settings": {"max_emails_per_run": Infinity}, ' + '"profiles": [' + '{"name": "LegacyMissing", "override_settings": {"download_attachments": true}}, ' + '{"name": "LegacyNeg", "override_settings": {"max_emails_per_run": -9}}, ' + '{"name": "LegacyInf", "override_settings": {"max_emails_per_run": Infinity}}' + ']}', + encoding="utf-8", + ) + _, leg_settings, leg_profiles, _, _, _ = cli.load_data(str(legacy_cfg), str(docs_file)) + assert leg_settings["max_emails_per_run"] == 30 + assert leg_profiles[0]["override_settings"]["max_emails_per_run"] == 30 + assert leg_profiles[1]["override_settings"]["max_emails_per_run"] == 0 + assert leg_profiles[2]["override_settings"]["max_emails_per_run"] == 30 + + +def test_size_prebucketed_deduplication_and_o1_db_index(tmp_path, monkeypatch): + """HE-UDG-04: run_deduplication skips unique-size files, protects indexed/protected files, and keeps O(1) _db_paths.""" + unique_a = tmp_path / "unique_101.pdf" + unique_b = tmp_path / "unique_202.pdf" + unique_c = tmp_path / "unique_303.pdf" + unique_a.write_bytes(b"A" * 101) + unique_b.write_bytes(b"B" * 202) + unique_c.write_bytes(b"C" * 303) + + dup_payload = b"%PDF-1.4 identical duplicate content" * 12 # 432 bytes + # Name 'aaa_untracked.pdf' sorts lexicographically BEFORE 'zzz_canonical.pdf' + # to prove indexed DB files take deterministic precedence over lexicographic order! + untracked_dup = tmp_path / "aaa_untracked.pdf" + canonical_doc = tmp_path / "zzz_canonical.pdf" + temp_inflight = tmp_path / ".tmp_inflight_write.pdf" + atomic_io_tmp = tmp_path / ".aaa_untracked.pdf.tmp.1234_deadbeef" + ocr_temp_pdf = tmp_path / "scan_ocr.temp.pdf" + diag_tmp = tmp_path / ".write_test_12345.tmp" + protected_cfg = tmp_path / "config_v1.json" + + untracked_dup.write_bytes(dup_payload) + canonical_doc.write_bytes(dup_payload) + temp_inflight.write_bytes(dup_payload) + atomic_io_tmp.write_bytes(dup_payload) + ocr_temp_pdf.write_bytes(dup_payload) + diag_tmp.write_bytes(dup_payload) + protected_cfg.write_bytes(dup_payload) + + # Second collision pair: orphaned atomic_io temp vs unindexed real document + orphan_payload = b"%PDF-1.4 unindexed real document vs orphan tmp" * 11 + orphan_atomic_tmp = tmp_path / ".aaa_doc.pdf.tmp.9999_cafebabe" + unindexed_real_doc = tmp_path / "zzz_unindexed_real.pdf" + orphan_atomic_tmp.write_bytes(orphan_payload) + unindexed_real_doc.write_bytes(orphan_payload) + + worker = app.GrabberWorker([], [], app.DownloadSettings(enable_hash_check=True), tmp_path, []) + worker.add_db("Invoices", canonical_doc.name, "2026-11-20", str(canonical_doc), "s@example.org", "Subj") + worker.add_db("Invoices", canonical_doc.name, "2026-11-20", str(canonical_doc), "s@example.org", "Subj") + assert len(worker.db) == 1 + assert str(canonical_doc) in worker._db_paths + + hashed_files = [] + real_hash = app.calculate_file_hash + + def counting_hash(p): + hashed_files.append(Path(p)) + return real_hash(p) + + monkeypatch.setattr(app, "calculate_file_hash", counting_hash) + monkeypatch.setattr(app, "get_default_protected_paths", lambda base_dir=None: {protected_cfg.resolve()}) + + worker.run_deduplication() + + # Only the 2 colliding regular non-protected, non-.tmp_ files may be hashed! + assert len(hashed_files) == 2 + assert canonical_doc.exists(), "Indexed canonical document must be preserved over untracked duplicate" + assert not untracked_dup.exists(), "Untracked duplicate must be removed" + assert unindexed_real_doc.exists(), "Unindexed real file must never be deleted in favor of .tmp. orphan" + assert temp_inflight.exists(), "In-flight .tmp_ file must never be touched by deduplication" + assert atomic_io_tmp.exists(), "atomic_io ..tmp._ file must never be touched" + assert ocr_temp_pdf.exists(), "OCR *.temp.pdf file must never be touched" + assert diag_tmp.exists(), "Stack diagnostic *.tmp file must never be touched" + assert protected_cfg.exists(), "Protected config file must never be touched by deduplication" + assert [d.path for d in worker.db] == [str(canonical_doc)] + + +def test_policy_p022_skill_md_llm_txt_and_cwd_safe_basetemp(): + """TW-UDG-06 & HE-UDG-05: Verify SKILL.md, llm.txt, CWD-safe conftest.py basetemp, and setuptools py-modules.""" + skill_path = ROOT / "SKILL.md" + llm_pointer_path = ROOT / "llm.txt" + conftest_path = ROOT / "conftest.py" + + assert skill_path.is_file(), "SKILL.md required by Policy P-022" + skill_text = skill_path.read_text(encoding="utf-8") + assert skill_text.startswith("---\n") + assert "name:" in skill_text and "description:" in skill_text + for flag in ("--list-profiles", "--list-documents", "--export-library", "--export-csv", "--diagnose", "--json"): + assert flag in skill_text + assert "CLI Exit Codes" in skill_text + assert "Non-Goals" in skill_text + for doc_ref in ("llms.txt", "EXPORTFORMAT.md", "README.md"): + assert doc_ref in skill_text + + spec_text = (ROOT / "UniversalDocsGrabber.spec").read_text(encoding="utf-8") + for bundled in ("export_core.py", "SKILL.md", "llms.txt", "llm.txt"): + assert bundled in spec_text + + assert llm_pointer_path.is_file(), "llm.txt pointer required by Policy P-022" + llm_text = llm_pointer_path.read_text(encoding="utf-8").strip() + assert "llms.txt" in llm_text and "SKILL.md" in llm_text + + pyproject_text = (ROOT / "pyproject.toml").read_text(encoding="utf-8") + assert "--basetemp=" not in pyproject_text, "Relative --basetemp in addopts violates T-20261114-932985855" + assert '"export_core"' in pyproject_text or "'export_core'" in pyproject_text + + assert conftest_path.is_file(), "conftest.py must configure CWD-independent basetemp" + conftest_text = conftest_path.read_text(encoding="utf-8") + assert ".pytest_temp" in conftest_text and "rootpath" in conftest_text diff --git a/tests/test_metadata.py b/tests/test_metadata.py index 1cdb5ef..5abac0f 100644 --- a/tests/test_metadata.py +++ b/tests/test_metadata.py @@ -416,7 +416,8 @@ def test_pyproject_pep621_license_files_and_notice_url(): assert '"Third-Party Licenses (Text)" = "https://github.com/doc-bricks/UniversalDocsGrabber/blob/master/THIRD_PARTY_LICENSES.txt"' in content assert 'Contributing = "https://github.com/doc-bricks/UniversalDocsGrabber/blob/master/CONTRIBUTING.md"' in content assert 'minversion = "7.0"' in content - assert '--basetemp=.pytest_temp' in content + assert "--basetemp=" not in content + assert (ROOT / "conftest.py").is_file() assert 'norecursedirs = [' in content diff --git a/tests/test_security_license_contract.py b/tests/test_security_license_contract.py index 07d7e9d..cf38f29 100644 --- a/tests/test_security_license_contract.py +++ b/tests/test_security_license_contract.py @@ -104,7 +104,7 @@ def test_no_hardcoded_user_paths_in_repo() -> None: for py_file in ROOT.rglob("*.py"): if py_file.name == Path(__file__).name: continue - if any(part in py_file.parts for part in (".venv", "venv", ".build_venv", "build", "dist", "_archive")): + if any(part in py_file.parts for part in (".venv", "venv", ".build_venv", "build", "dist", "_archive", ".pytest_temp")): continue text = py_file.read_text(encoding="utf-8", errors="ignore") if forbidden in text or forbidden_fwd in text: @@ -136,7 +136,7 @@ def LOCAL_files_iter(): for f in ROOT.rglob("*"): if not f.is_file(): continue - if any(part in f.parts for part in (".git", ".pytest_cache", ".ruff_cache", "assets", "store_assets", "README", "build", "dist")): + if any(part in f.parts for part in (".git", ".pytest_cache", ".pytest_temp", ".ruff_cache", "assets", "store_assets", "README", "build", "dist")): continue if f.suffix.lower() in skip_suffixes: continue