diff --git a/.dockerignore b/.dockerignore
index 9bd79e5..4e09260 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -1,8 +1,9 @@
.git
.venv
-node_modules
-target
-__pycache__
+**/node_modules
+# Rust build output (phash_rs/target is over a gigabyte)
+**/target
+**/__pycache__
*.pyc
*.pyo
*.pyd
@@ -28,3 +29,22 @@ credentials.json
# Ignore media directories if running locally
photos/
test/
+
+# Never bake local settings, secrets or working data into the image
+.env
+.env.*
+!.env.example
+logs/
+d/
+s/
+
+# Not needed at runtime
+.github/
+.pytest_cache/
+.ruff_cache/
+docs/
+tests/
+interview-prep/
+requirements-dev.txt
+explanation.md
+todo.md
diff --git a/.env.example b/.env.example
index 4c8c9e3..d8bc36f 100644
--- a/.env.example
+++ b/.env.example
@@ -12,6 +12,15 @@ MEDIA_PATH=/home/user/Pictures
# The port the web UI will be accessible on (default 8080)
# CLEAN_BACKUP_PORT=8080
+# The web UI has no login, so by default it is reachable from this machine only.
+# To reach it from other devices on a network you trust, publish it on all
+# interfaces and open it by IP address (http://192.168.x.x:8080):
+# CLEAN_BACKUP_BIND=0.0.0.0
+
+# Opening the UI by a hostname other than localhost (e.g. http://nas.local:8080)
+# requires listing that hostname here (comma-separated). IP addresses always work.
+# CLEAN_BACKUP_ALLOWED_HOSTS=nas.local
+
# Logging level (debug, info, warning, error)
# CLEAN_BACKUP_LOG_LEVEL=info
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 7cbb2c9..c1060d6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -6,6 +6,9 @@ on:
pull_request:
branches: ["main"]
+permissions:
+ contents: read
+
jobs:
lint:
runs-on: ubuntu-latest
@@ -20,8 +23,8 @@ jobs:
- name: Lint Python (ruff)
run: |
- pip install ruff
- ruff check src/ main.py --output-format=github
+ python -m pip install -r requirements-dev.txt
+ python -m ruff check src/ main.py tests/ --output-format=github
- name: Set up Rust
uses: dtolnay/rust-toolchain@stable
@@ -32,7 +35,7 @@ jobs:
working-directory: phash_rs
run: |
cargo fmt --check
- cargo clippy -- -D warnings
+ cargo clippy --locked -- -D warnings
test:
runs-on: ubuntu-latest
@@ -45,7 +48,7 @@ jobs:
- name: Test Rust module
working-directory: phash_rs
- run: cargo test
+ run: cargo test --locked
- name: Set up Python
uses: actions/setup-python@v5
@@ -53,10 +56,12 @@ jobs:
python-version: "3.12"
- name: Install Python dependencies
- run: pip install -r requirements.txt
+ run: |
+ python -m pip install -r requirements.txt -r requirements-dev.txt
+ python -m pip install ./phash_rs
- name: Run Python tests
- run: python -m pytest tests/ -v --tb=short || echo "No tests directory found, skipping"
+ run: python -m pytest tests/ -v --tb=short
docker-build:
runs-on: ubuntu-latest
@@ -72,6 +77,23 @@ jobs:
with:
context: .
push: false
+ load: true
tags: clean-backup:ci-test
cache-from: type=gha
cache-to: type=gha,mode=max
+
+ - name: Smoke-test the built application
+ run: |
+ docker run --detach --publish 127.0.0.1:8080:8080 --name clean-backup-ci clean-backup:ci-test
+ curl --fail --retry 30 --retry-all-errors --retry-delay 2 --retry-max-time 90 --max-time 5 http://127.0.0.1:8080/api/health \
+ | python3 -c 'import json, sys; data = json.load(sys.stdin); assert data["ok"] and data["backend"] == "rust (phash_rs)", data'
+ curl --fail http://127.0.0.1:8080/ \
+ | python3 -c 'import sys; assert "
" in sys.stdin.read(), "Frontend build was not served"'
+
+ - name: Show container logs on failure
+ if: failure()
+ run: docker logs clean-backup-ci || true
+
+ - name: Remove test container
+ if: always()
+ run: docker rm --force clean-backup-ci || true
diff --git a/.gitignore b/.gitignore
index ffe0aeb..50e712c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,6 +5,7 @@ build/
dist/
wheels/
*.egg-info
+.pytest_cache/
# Virtual environments
.venv
diff --git a/Dockerfile b/Dockerfile
index 08a9233..9207bf2 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -3,14 +3,15 @@ FROM rust:slim AS rust-builder
WORKDIR /build
# Install build dependencies if needed (e.g. for maturin or setuptools-rust)
-RUN apt-get update && apt-get install -y python3 python3-pip python3-venv curl
+RUN apt-get update && apt-get install -y --no-install-recommends python3 python3-pip python3-venv \
+ && rm -rf /var/lib/apt/lists/*
COPY phash_rs/ phash_rs/
WORKDIR /build/phash_rs
# Compile the rust extension (outputs a .so or .pyd)
# We use maturin to build a wheel, which makes it easy to install in the python image
RUN pip install maturin --break-system-packages
-RUN maturin build --release -o dist
+RUN maturin build --release --locked -o dist
# ── Stage 2: Frontend Builder ───────────────────────────────────────────
FROM node:20-slim AS frontend-builder
@@ -30,7 +31,7 @@ FROM python:3.12-slim
WORKDIR /app
# Install system dependencies for OpenCV and ONNX
-RUN apt-get update && apt-get install -y \
+RUN apt-get update && apt-get install -y --no-install-recommends \
libgl1 \
libglib2.0-0 \
curl \
@@ -44,22 +45,23 @@ RUN pip install --no-cache-dir -r requirements.txt
COPY --from=rust-builder /build/phash_rs/dist/*.whl /tmp/
RUN pip install --no-cache-dir /tmp/*.whl && rm -f /tmp/*.whl
-# Copy application source BEFORE model download so models aren't overwritten
-COPY . .
-
-# Copy frontend static build from Stage 2 (overwrites the source web/dist)
-COPY --from=frontend-builder /build/web/dist ./web/dist
-
-# Download ONNX models — runs AFTER COPY . . so models persist in the layer
-RUN python src/classify/models/download_models.py
-
-# Set up non-root user
+# Run as a non-root user. Ownership is set while copying: a later
+# `chown -R /app` would store a second copy of every file in a new layer.
RUN useradd -m -u 1000 appuser \
&& mkdir -p /app/data/db /app/data/cache /app/data/config /data/media \
&& chown -R appuser:appuser /app /data/media
USER appuser
+# Copy application source BEFORE model download so models aren't overwritten
+COPY --chown=appuser:appuser . .
+
+# Copy frontend static build from Stage 2 (overwrites the source web/dist)
+COPY --chown=appuser:appuser --from=frontend-builder /build/web/dist ./web/dist
+
+# Download ONNX models (checksum-verified) — runs AFTER COPY . . so they persist
+RUN python src/classify/models/download_models.py
+
# Expose the default port
EXPOSE 8080
@@ -68,6 +70,9 @@ ENV CLEAN_BACKUP_MEDIA_PATH=/data/media
ENV CLEAN_BACKUP_DB_PATH=/app/data/db/clean_backup.sqlite
ENV CLEAN_BACKUP_CONFIG_DIR=/app/data/config
ENV CLEAN_BACKUP_PORT=8080
+# Listen on the container's interfaces; which host interface is exposed is
+# decided by the published port (docker-compose.yml defaults to loopback).
+ENV CLEAN_BACKUP_HOST=0.0.0.0
ENV CLEAN_BACKUP_LOG_LEVEL=info
# Flask entrypoint
diff --git a/README.md b/README.md
index 5947bcb..eb8e6a1 100644
--- a/README.md
+++ b/README.md
@@ -2,8 +2,9 @@
**Intelligent media organization with perceptual deduplication, AI classification, and a hybrid Rust/Python architecture.**
-
-
+
+
+*A 32-second walkthrough of the running web app: scan nine sample images, review three duplicate groups, organize copies by date, and undo the session. Actual screen captures, edited for pace. [Recording details and sample sources](docs/RECORDING.md).*
[](https://github.com/JayacharanR/Clean-Backup/actions/workflows/ci.yml)
[](https://github.com/JayacharanR/Clean-Backup/actions/workflows/release.yml)
@@ -28,7 +29,7 @@ The performance-critical image hashing is written in **Rust** (`phash_rs`), the
Run the full stack with zero setup:
```bash
-docker run -p 8080:8080 -v ~/Photos:/data/media ghcr.io/jayacharanr/clean-backup:latest
+docker run -p 127.0.0.1:8080:8080 -v ~/Photos:/data/media ghcr.io/jayacharanr/clean-backup:latest
```
Then open [http://localhost:8080](http://localhost:8080).
@@ -44,6 +45,16 @@ cp .env.example .env
docker compose up -d
```
+### Network access
+
+The web UI has **no login**. Anyone who can reach it can scan, move and delete files in the mounted library, so by default it is reachable only from the machine it runs on:
+
+- `python main.py --web` listens on `127.0.0.1` (override with `CLEAN_BACKUP_HOST`).
+- `docker compose` publishes the port on `127.0.0.1` (override with `CLEAN_BACKUP_BIND=0.0.0.0` on a network you trust).
+- Requests are accepted only when addressed to `localhost`, an IP address, or a hostname listed in `CLEAN_BACKUP_ALLOWED_HOSTS` (comma-separated, e.g. `nas.local`). State-changing requests from other websites are refused.
+
+Do not expose it to the internet. To reach it remotely, put it behind a VPN or an authenticating reverse proxy.
+
## Architecture
```mermaid
@@ -71,7 +82,7 @@ flowchart TB
subgraph Cloud["Cloud Sync · optional"]
GDrive["Google Drive"]
- S3["AWS S3"]
+ S3["AWS S3 · planned"]
end
UI <-->|polling| API
@@ -92,36 +103,36 @@ flowchart TB
- **Rust-accelerated pHash**: DCT-based perceptual hashing detects visual duplicates even after resize, recompression, or format conversion — not just byte-identical files.
- **Parallel hash computation**: Leverages Rayon's work-stealing thread pool in Rust for concurrent image hashing (`par_iter`), with automatic CPU core utilization.
- **Tunable sensitivity**: Hamming distance threshold from exact-match (0) to aggressive (10+), persisted between sessions.
-- **Name-based detection**: Catches OS-generated duplicates (`file (1).jpg`, `file - Copy.jpg`) across Windows, macOS, and Linux patterns.
+- **No name-based guessing**: files such as `photo (1).jpg` or `photo - Copy.jpg` are never dropped because of their names; only content decides, and organization keeps every named variant.
- **Safe review UI**: Grouped duplicate cards with side-by-side comparison, modal full-resolution preview, keyboard navigation, and protected best-image rules.
### Performance & Parallelization
-Clean-Backup uses a **two-layer parallelization architecture** to maximize throughput:
+Hashing is parallel in Rust; file transfers favour verification over raw speed:
| Layer | Technology | What it parallelizes |
|-------|-----------|---------------------|
| **Rust (native threads)** | Rayon work-stealing thread pool | Image decoding, DCT hash computation, Hamming distance comparisons |
-| **Python (process pool)** | `multiprocessing.Pool` (N-1 cores) | File I/O, EXIF extraction, copy/move operations, compression |
+| **Python (thread pool)** | `ThreadPoolExecutor` (up to 8 workers) | EXIF / video metadata extraction while organizing. Each copy or move is verified (SHA-256 read-back) and published one at a time. |
- **Rayon `par_iter()` in Rust**: `find_duplicates_parallel()` and `compute_hashes_parallel()` use Rayon's data-parallel iterators to distribute image hashing across all CPU cores. Each image is independently decoded, resized, DCT-transformed, and hashed — a perfectly parallelizable workload.
-- **Python multiprocessing for file operations**: The organizer spawns `cpu_count() - 1` worker processes (typically 15 on a 16-core machine) to handle concurrent file copies, moves, and metadata extraction.
-- **10× speedup over pure Python**: The Rust pHash engine with Rayon multi-threading outperforms equivalent Python (Pillow + imagehash) implementations by an order of magnitude on batch duplicate scanning.
-- **PyO3/Maturin bridge**: Rust functions are exposed as native Python functions via PyO3 with abi3 cross-version compatibility, achieving zero-copy data transfer for hash results.
+- **One decode per image**: a scan computes each image's hash and resolution from a single decode and groups those results without touching the files again. On a 320-image, 6-megapixel JPEG test library this cut a web scan from 6.0 s to 2.8 s with identical results.
+- **Responsive during scans**: hashing releases Python's GIL, so progress polling is served while Rust works. A pure-Python fallback is used automatically if the extension is not built (much slower).
+- **PyO3/Maturin bridge**: Rust functions are exposed as native Python functions via PyO3 with abi3 cross-version compatibility.
### Organization & Classification
- **Date-based organization**: Extracts EXIF `DateTimeOriginal`, video container metadata, and filesystem stats to sort into `Year/Month` hierarchies.
-- **AI scene classification**: MobileNetV3 ONNX model tags photos into 15 categories (travel, food, nature, documents, etc.) with configurable confidence thresholds.
+- **AI scene classification**: MobileNetV2 ONNX model tags photos into 15 categories (travel, food, nature, documents, etc.) with configurable confidence thresholds.
- **Face detection & recognition**: YuNet face detection + ArcFace embeddings for automatic face grouping. Name people once, and the system recognizes them across your library.
- **Review queue**: Low-confidence classifications and unresolved face matches are surfaced for human review before any files move.
### Compression
- Three compression levels (high quality → maximum compression) for both images and videos.
-- Parallel processing using all CPU cores. H.264 + AAC for video, libjpeg-turbo for JPEG.
+- Files are processed one at a time. H.264 + AAC for video (requires FFmpeg), Pillow/libjpeg for JPEG. Outputs never replace the source or an existing file.
- Detailed per-file analytics with compression ratios and space savings.
### Cloud Sync
-- **Provider-agnostic**: Google Drive (OAuth2) and AWS S3 support via a pluggable `CloudProvider` interface.
+- **Pluggable providers**: Google Drive (OAuth2) is implemented behind a `CloudProvider` interface. AWS S3 is a placeholder and not functional yet.
- **Manifest-based incremental sync**: SHA-256 content hashing ensures only changed files are uploaded.
- **Secure credential storage**: OS keyring integration with Fernet-encrypted fallback.
- **Undo support**: Synced files can be removed from the cloud provider via the undo system.
@@ -134,22 +145,22 @@ Clean-Backup uses a **two-layer parallelization architecture** to maximize throu
### Web Control Panel
- **Complete workflow tabs**: Duplicates, Organize, Compression, Classify, People, Review, Cloud Sync, Watchers, and Settings.
- **Background job execution**: Long-running operations run asynchronously with live progress polling.
-- **Transactional undo**: Every file operation is journaled. Full session rollback with crash recovery.
-- **Undo observability**: Session filtering, JSON export for auditing and recovery workflows.
+- **Journaled undo**: organize, classification apply and Trash operations are recorded in an append-only journal before they take effect, and can be rolled back per session. Permanent deletion and compression outputs are not undoable.
+- **Undo history**: sessions can be filtered and reverted individually; conflicts (edited or missing files) are kept and reported instead of overwritten.
## Tech Stack
| Layer | Technology |
|-------|-----------|
| **Performance-critical hashing** | Rust (2021 Edition) + Rayon thread pool via `maturin`/PyO3 |
-| **Parallelization** | Rayon (Rust work-stealing threads) + Python `multiprocessing.Pool` |
+| **Parallelization** | Rayon (Rust work-stealing threads) + Python `ThreadPoolExecutor` |
| **Backend & ML pipeline** | Python 3.12+, Flask, ONNX Runtime |
| **Frontend** | React + Vite |
| **Database** | SQLite (WAL mode) |
-| **ML models** | MobileNetV3 (scene), YuNet (face detect), ArcFace (face embed) |
+| **ML models** | MobileNetV2 (scene), YuNet (face detect), ArcFace (face embed) |
| **Image processing** | Pillow, pillow-heif (HEIC), OpenCV |
| **Video metadata** | hachoir, FFmpeg (compression) |
-| **Cloud providers** | Google Drive API, AWS S3 (boto3) |
+| **Cloud providers** | Google Drive API (AWS S3 planned) |
| **Containerization** | Docker (multi-stage build) |
## Local Development
@@ -183,12 +194,33 @@ python main.py # CLI mode
python main.py --web # Web GUI at http://localhost:8080
```
+Classification models (about 275 MB) are not in the repository. Fetch and checksum-verify them once with `python -m src.classify.models.download_models`; without them the classifier falls back to metadata-only heuristics.
+
+### Checks
+
+After completing local setup, install the development tools and run the same checks as CI:
+
+```bash
+pip install -r requirements-dev.txt
+python -m ruff check src/ main.py tests/
+python -m pytest tests/ -v --tb=short
+cargo fmt --manifest-path phash_rs/Cargo.toml --check
+cargo clippy --manifest-path phash_rs/Cargo.toml --locked -- -D warnings
+cargo test --manifest-path phash_rs/Cargo.toml --locked
+```
+
+The Python tests use disposable media, configuration, databases, and undo journals. They require the compiled Rust module and exercise duplicate scanning, image previews, date-based copy/move organization, classification apply, undo and crash recovery, the API's cross-origin and host checks, demo-mode restrictions, and input validation. CI also builds and starts the Docker image, checks its Rust backend health response, and verifies that it serves the frontend. Test failures fail the workflow.
+
## Privacy
-Clean-Backup runs **100% offline**. All machine learning models (ONNX) are baked into the Docker image and require no cloud API calls. Face embeddings and classification tags are stored only in your local SQLite database. No telemetry, no analytics, no data leaves your machine.
+Clean-Backup processes your library locally. The machine learning models (ONNX) are downloaded once at image build time, verified against pinned checksums, and need no cloud API calls at runtime. Face embeddings and classification tags are stored only in your local SQLite database. No telemetry, no analytics, no data leaves your machine.
Cloud sync is entirely optional and user-initiated — credentials are stored in your OS keyring or encrypted locally.
+## Audit
+
+The most recent engineering audit — findings, fixes, measurements and what remains open — is in [docs/AUDIT_REPORT.md](docs/AUDIT_REPORT.md).
+
## License
MIT License — see [LICENSE](LICENSE) for details.
diff --git a/deploy/demo/README.md b/deploy/demo/README.md
index b487051..0bf24ca 100644
--- a/deploy/demo/README.md
+++ b/deploy/demo/README.md
@@ -27,6 +27,11 @@ This directory contains everything needed to deploy a read-only demo of Clean-Ba
| `CLEAN_BACKUP_PORT` | `8080` |
| `CLEAN_BACKUP_LOG_LEVEL` | `info` |
+The server only answers requests addressed to a hostname it expects. Render's
+own `*.onrender.com` name is picked up automatically (`RENDER_EXTERNAL_HOSTNAME`);
+for a custom domain also set `CLEAN_BACKUP_ALLOWED_HOSTS=demo.example.com`.
+In demo mode the API can only read the seeded media folder.
+
### 3. Deploy
Render will build using the repo-root `Dockerfile` automatically. The `render.yaml` blueprint in this directory can also be used for one-click deploy.
diff --git a/deploy/demo/reset_demo.py b/deploy/demo/reset_demo.py
index da0486d..089d5fa 100644
--- a/deploy/demo/reset_demo.py
+++ b/deploy/demo/reset_demo.py
@@ -46,11 +46,13 @@ def reset_demo():
import sqlite3
conn = sqlite3.connect(str(db_path))
# Delete all user-created data, keep schema
+ # Children before parents: the schema declares foreign keys.
for table in [
"watcher_events", "watcher_configs",
- "classifications", "classification_runs",
- "faces", "people", "review_queue",
- "cloud_sync_runs", "cloud_sync_files", "cloud_accounts",
+ "media_tags", "review_queue", "face_embeddings", "people",
+ "classify_run_config",
+ "sync_manifest", "sync_runs", "cloud_accounts",
+ "media_files",
]:
try:
conn.execute(f"DELETE FROM {table}")
diff --git a/deploy/demo/seed_demo_db.py b/deploy/demo/seed_demo_db.py
index 317b0df..26ed25f 100644
--- a/deploy/demo/seed_demo_db.py
+++ b/deploy/demo/seed_demo_db.py
@@ -12,7 +12,6 @@
from __future__ import annotations
-import json
import os
import shutil
import sys
diff --git a/docker-compose.yml b/docker-compose.yml
index aea941e..e302149 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -2,9 +2,11 @@ services:
clean-backup:
build:
context: .
- image: ghcr.io/charan/clean-backup:latest
+ image: ghcr.io/jayacharanr/clean-backup:latest
ports:
- - "${CLEAN_BACKUP_PORT:-8080}:8080"
+ # The web UI has no login. It is published on this machine only unless
+ # CLEAN_BACKUP_BIND is set (for example 0.0.0.0 on a trusted home network).
+ - "${CLEAN_BACKUP_BIND:-127.0.0.1}:${CLEAN_BACKUP_PORT:-8080}:8080"
volumes:
- ${MEDIA_PATH:-./photos}:/data/media
- clean-backup-db:/app/data/db
@@ -15,6 +17,7 @@ services:
- CLEAN_BACKUP_DB_PATH=/app/data/db/clean_backup.sqlite
- CLEAN_BACKUP_CONFIG_DIR=/app/data/config
- CLEAN_BACKUP_LOG_LEVEL=${CLEAN_BACKUP_LOG_LEVEL:-info}
+ - CLEAN_BACKUP_ALLOWED_HOSTS=${CLEAN_BACKUP_ALLOWED_HOSTS:-}
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/api/health"]
diff --git a/docs/AUDIT_REPAIRS.md b/docs/AUDIT_REPAIRS.md
new file mode 100644
index 0000000..854c0e9
--- /dev/null
+++ b/docs/AUDIT_REPAIRS.md
@@ -0,0 +1,64 @@
+# Audit repairs: local file safety
+
+This first repair phase addresses the local file-operation and recovery problems
+in the 13 November 2026 audit. Findings outside this phase remain open.
+
+> **Update, 14 November 2026.** A follow-up audit closed several items listed
+> under "Current limits" below: the API's origin and host boundaries (F09, short
+> of authentication), verified model downloads (part of F37), migration of
+> Trash and classification apply to the verified executor, and job outcome
+> reporting for apply and cloud jobs (F17). Journals are now append-only logs.
+> See [AUDIT_REPORT.md](AUDIT_REPORT.md) for details and the current open list.
+
+| Finding | Progress |
+| --- | --- |
+| F01: filename-based omission | Organization retains named variants. The legacy detection helper compares full content digests instead of name patterns. |
+| F02: destination collisions | Organizer Copy and Move publish exclusively and choose a digest suffix for collisions. Classification and the CLI duplicate handler still need migration to this shared executor. |
+| F03: partial/unverified copies | Organizer transfers write privately, verify SHA-256 and size by reading back the output, check source stability, then publish. Move removes its source only after verification and publication. |
+| F05: destructive undo | New records contain output identity. Undo refuses edited/replaced outputs, occupied restore paths, and removal of a copy whose original content is no longer available. Old path-only journals require manual review. |
+| F06: journals and retry | UUID sessions, atomic journal replacement, intent before organizer publication, per-action recovery state, active-session exclusion and retryable conflicts are implemented. Other legacy mutation callers still record operations afterward and need migration. |
+| F07: compression overwrites | Direct compression refuses source aliases and existing outputs. Directory compression rejects overlapping roots. Encoders write privately; failed output is removed and publication never replaces another file. |
+| F34: threshold zero | The scan and organize forms preserve zero instead of substituting five. The obsolete filename-skip option is removed from the UI and CLI. |
+
+Transfers and undo coordinate cooperating app processes with POSIX advisory locks.
+Organizer workers share one journal scoped to the job. A failed journal write
+propagates instead of being silently treated as successful recovery bookkeeping.
+Completed undo actions are persisted individually; conflicts keep the remaining
+journal available through the existing API.
+
+Validation at this phase: 65 Python tests, including the 16 existing API/workflow
+tests, plus Ruff and a frontend production build. The added regressions cover separate-process name collisions,
+disk-full errors, corrupted copies, changed sources, occupied restore paths,
+partial undo retries, completion-write failures, abrupt process exits at three
+transfer boundaries, and compression failures/races. All fixtures are disposable.
+The 49 tests added by this phase also run from an export of the committed tree.
+Legacy callers now close their journals on return and exceptions, and API Trash
+requests own independent session managers. The read-only classification scan no
+longer opens an unused file-operation journal.
+
+## Current limits and next repairs
+
+- Publication currently requires hard-link support on the destination filesystem.
+ Unsupported filesystems fail without replacing a destination or removing a Move
+ source. FAT/exFAT support needs another verified, atomic non-replacing primitive.
+- Locks coordinate Clean_Backup operations. They cannot exclude unrelated editors
+ or tools; revision checks detect changes at verification boundaries.
+- Abrupt termination can leave hidden `.clean-backup-*.partial*` staging files.
+ Recovery preserves them; automatic discovery and cleanup are still needed.
+ Unpublished staging files are not successful final outputs.
+- The compression encoder's metadata, animation, HDR and stream-preservation
+ limitations (F08) are unchanged. The new publication boundary does not certify
+ the encoded media's semantic fidelity.
+- Perceptual matching and automatic perceptual omission remain heuristic. This
+ phase does not repair F11–F16 or make a safe-exact-mode claim.
+- Prioritize server-owned deletion plans (F04), API authentication/origin/root
+ boundaries (F09), cloud object identity (F27), and safe Docker build inputs
+ (F37) next. These high-priority findings remain open.
+- Migrate classification, CLI duplicate handling and Trash to the executor, fix
+ classification catalog/undo contracts, and add an explicit resume/reconciliation
+ interface. Recovery currently offers safe undo, not automatic forward resume.
+- API job outcome reporting (F17), other workflow/provider/watcher defects,
+ distribution, dependency triage and UI changes remain separate work.
+
+There is no throughput claim or cross-platform certification for this phase.
+Existing uncommitted CI, README, demo and test changes were left out of its commits.
diff --git a/docs/AUDIT_REPORT.md b/docs/AUDIT_REPORT.md
new file mode 100644
index 0000000..a41cb53
--- /dev/null
+++ b/docs/AUDIT_REPORT.md
@@ -0,0 +1,192 @@
+# Engineering audit — 14 November 2026
+
+Scope: the whole repository on branch `codex/audit-file-safety` — Python backend
+(`src/`, `main.py`, `deploy/`), Rust extension (`phash_rs/`), React frontend
+(`web/`), Docker and CI configuration, dependencies and documentation.
+
+This continues the file-safety work recorded in
+[AUDIT_REPAIRS.md](AUDIT_REPAIRS.md). Every "fixed" item below was reproduced
+first (a regression test that fails on the old code, or a measurement) and
+re-verified afterwards. Items that were not exercised are listed as such.
+Nothing here claims the project is free of defects.
+
+## Summary
+
+| Area | Before | After |
+|---|---|---|
+| Python tests | 65 pass | 117 pass (52 new) |
+| Rust tests | 3 pass | 6 pass |
+| Lint (Ruff, rustfmt, Clippy `-D warnings`) | clean | clean |
+| Known advisories in pinned Python packages (OSV) | 84 matches in 7 packages | 0 |
+| npm advisories, runtime / build tooling | 0 / 8 | 0 / 2 |
+| Web duplicate scan, 320 six-megapixel JPEGs | 6.03 s | 2.79 s (identical hashes and groups) |
+| Organize 2,000 small files (copy) | 61.2 s | 9.4 s |
+| Undo 1,000 moved files | 49.8 s | 1.7 s |
+| Rust extension (`phash_rs.abi3.so`) | 2.46 MB | 1.85 MB |
+| Rust dependency tree (`cargo tree` lines) | 195 | 98 |
+| Docker image, built from this working tree | 6.04 GB | 1.72 GB |
+
+## Findings
+
+Severity reflects impact on a user running the app as documented.
+
+### Security
+
+| # | Severity | Finding | Status |
+|---|---|---|---|
+| S1 | Critical | The API has no login, answered every origin with `Access-Control-Allow-Origin: *`, and listened on `0.0.0.0`. Any website open in the user's browser could start a scan of an arbitrary directory, read files from it and permanently delete them. | **Fixed.** Wildcard CORS removed; state-changing requests from another origin and requests with an unexpected `Host` (DNS rebinding) are refused; default listen address is `127.0.0.1`; compose publishes on loopback. Verified by tests and against a running server with `curl`. |
+| S2 | High | `GET /api/image` fell back to sending the raw file when Pillow could not decode it, so any file under a scanned directory (keys, documents) was readable. | **Fixed.** Only media extensions are served; undecodable files are sent as an attachment with `nosniff`. |
+| S3 | High | In `DEMO_MODE` (a public instance) the scan and classify endpoints accepted any server directory; combined with S2 this exposed the host's files to anonymous visitors. | **Fixed.** Demo mode can only read `CLEAN_BACKUP_MEDIA_PATH`. |
+| S4 | High | `PATCH /api/watchers/` interpolated JSON keys into SQL as column names (SQL injection through identifiers). `update_sync_run` had the same pattern, reachable only from internal callers. | **Fixed.** Fixed set of updatable columns; unknown fields return 400. |
+| S5 | Medium | Google Drive queries were built with unescaped file names: a name containing `'` broke the query or changed which remote file `delete`/`verify` matched. | **Fixed** (escaping verified with a fake service; not exercised against Google). |
+| S6 | Medium | The OAuth URL carried two `state` parameters (the library's and a second one appended by the endpoint), and the callback error page reflected exception text as HTML. Pending flows were never evicted. | **Fixed** by construction; the single-state URL and escaping are tested, the full flow against Google is **not verified**. |
+| S7 | Medium | The fallback credential key and token files were created with default permissions and restricted afterwards. | **Fixed.** Created owner-only (0600) and replaced atomically. |
+| S8 | Medium | Trash used `rename` to a name derived from the path and the current second: trashing a second file with the same path within a second silently replaced the first, and it failed across filesystems. Malformed selections raised a 500. | **Fixed.** Trash uses the verified, journaled transfer and is undoable; delete accepts images only. |
+| S9 | Medium | Classification models were downloaded from a mutable branch without verification, although the script's documentation said checksums were verified. | **Fixed.** SHA-256 pinned (upstream files downloaded on audit day match the July copies byte for byte); a mismatch deletes the file and fails the build. |
+| S10 | Medium | `docker-compose.yml` referenced `ghcr.io/charan/clean-backup`, a namespace the project does not publish to; `docker compose pull` would fetch someone else's image if it existed. | **Fixed** (`ghcr.io/jayacharanr/clean-backup`, matching the release workflow). |
+| S11 | Low | Local image builds copied `.env`, `logs/`, and the personal scratch folders `d/` and `s/` (about 225 MB of media) into the image. | **Fixed** in `.dockerignore`. |
+| S12 | Low | `GET /api/face-crop` built a file path from an unvalidated `id`. Not exploitable on Linux as written. | **Fixed** (numeric ids only). |
+| S13 | — | 84 advisory matches in pinned Python packages, 40+ of them in Pillow, which parses untrusted image files. | **Fixed** by targeted upgrades (see Dependencies). |
+
+No secrets were found in tracked files or history-visible configuration.
+`credentials.json` and `.env` exist locally, are git-ignored, and `.env` is
+identical to `.env.example`. No rotation is required as a result of this audit.
+
+### Correctness
+
+| # | Severity | Finding | Status |
+|---|---|---|---|
+| C1 | High | Capture dates were read only from the top-level EXIF IFD. Cameras store `DateTimeOriginal` in the Exif sub-IFD, so real photos were organized by file modification time. The existing tests passed because their fixtures wrote the tag in the non-standard location. The classifier had the same defect for ISO and exposure, so night detection never saw exposure data. | **Fixed**, with fixtures written the way cameras write them. |
+| C2 | High | Classification apply called the job's `(percent, message)` progress callback with one argument. Every run moved or copied files, then failed with a `TypeError` that was swallowed and reported as a *completed* job. It also filed photos under the month they were catalogued, used unverified copy/move, and turned the label "Nature / Scenery" into nested `Nature /` and ` Scenery` folders. | **Fixed.** Capture date, verified journaled transfer, one safe folder name per category, undo verified end to end. |
+| C3 | Medium | Failed apply, cloud-sync and cloud-undo jobs were reported as completed with an `error` field the UI ignores. | **Fixed**; they now fail. |
+| C4 | Medium | The CLI offered Google Drive backup through `src.gdrive_sync`, a module that is not in the repository; choosing it always failed. | **Fixed** (dead prompts removed; cloud sync lives in the web UI). |
+| C5 | Medium | Demo reset deleted from tables that do not exist (`classifications`, `faces`, `cloud_sync_runs`, …) and ignored the errors, so visitor data was never cleared. | **Fixed** and tested against the real schema. |
+| C6 | Low | The CLI printed "Undo operation completed" even when undo reported conflicts; the sensitivity prompt capped at 15 while announcing 64 (web UI: 25); the duplicate report walked the tree seven times and missed `.raf` and upper-case extensions. | **Fixed.** |
+| C7 | Low | Finished jobs, including full scan results, were kept in memory for the life of the server; the Python hash fallback leaked a file handle per image. | **Fixed** (50 most recent finished jobs retained). |
+
+### Performance
+
+| # | Finding | Evidence | Status |
+|---|---|---|---|
+| P1 | A web scan hashed every image in batches, passed the paths back to Rust, which hashed them all again and decoded each a third time to read its dimensions. | 320 six-megapixel JPEGs: 6.03 s → 2.79 s, best of 3; hashes and groups compared equal with `cmp`. | **Fixed.** |
+| P2 | Rust hashing held Python's GIL, so status polling stalled during each batch. | A 10 ms background thread now runs at 99 % of its ideal rate during hashing. No "before" figure was recorded. | **Fixed.** |
+| P3 | Every journal state change rewrote and fsynced the whole journal: cost grew with the square of the session. | Organize (copy) 250 / 500 / 1,000 / 2,000 files: 1.5 / 4.6 / 16.0 / 61.2 s → 1.2 / 2.4 / 4.7 / 9.4 s. Undo 500 / 1,000: 13.0 / 49.8 s → 0.85 / 1.70 s. | **Fixed** with an append-only journal (see below). |
+| P4 | The Rust `image` dependency was built with every default codec. | Extension 2.46 MB → 1.85 MB; `cargo tree` 195 → 98 lines. | **Fixed.** Formats compiled in: JPEG, PNG, GIF, BMP, TIFF, WebP. |
+| P5 | `.dockerignore` listed `target`, which matches only a top-level directory, so `phash_rs/target` (1.4 GB of Rust build output) was sent to the daemon and copied into the image; a final `chown -R /app` then stored a second copy of every application file, including the 275 MB of models. | Local build context 1.72 GB → under 300 MB; image 6.04 GB → 1.72 GB (`COPY . .` layer 1.73 GB → 282 MB, `chown` layer 1.77 GB → 102 kB). A CI build has no `target/`, so there the saving is the duplicated layer, about 280 MB. | **Fixed.** |
+
+Benchmarks ran on the development machine with tiny (2 KB) files for the
+organize/undo measurements, so they isolate journaling overhead; real media adds
+copy-and-verify time that this change does not affect. Peak memory for the scan
+was 443 MB before and 421 MB after.
+
+### Redundancy and documentation
+
+- Removed the dead CLI cloud code (about 70 lines) and consolidated date
+ selection (`get_media_date`) and duplicate grouping (`_python_group`).
+- The README described process-pool parallelism, parallel compression, working
+ S3 support, name-based duplicate detection, MobileNetV3 and a 10× speedup;
+ none matched the code or a measurement. It now states what is implemented,
+ and documents the network model.
+- `phash_rs/README.md` documented an `algorithm=` parameter and three
+ algorithms that do not exist.
+
+## Behaviour changes to be aware of
+
+1. **Listening address.** `python main.py --web` binds `127.0.0.1` instead of
+ all interfaces; compose publishes on `127.0.0.1`. To use the UI from other
+ devices set `CLEAN_BACKUP_BIND=0.0.0.0` (compose) or `CLEAN_BACKUP_HOST=0.0.0.0`
+ (local) and open it by IP address, or add the hostname to
+ `CLEAN_BACKUP_ALLOWED_HOSTS`.
+2. **Cross-origin API use is refused.** The bundled UI and the Vite dev proxy
+ are same-origin and unaffected. Scripts (`curl`, automation) are unaffected.
+3. **Journal format.** Journals are now append-only JSON Lines (still named
+ `journal_*.json`). Journals written before this change remain readable and
+ undoable; older versions of the app cannot read new journals.
+4. **Classification folders.** Photos are filed by capture date, and category
+ folders are single names (`Nature - Scenery`).
+5. **Organization by date** now follows the camera's capture date for files
+ that were previously filed by modification time.
+6. **Model download** fails the Docker build if a model does not match its
+ pinned checksum.
+
+## Dependencies
+
+Python pins changed (and nothing else): pillow 12.3.0 → 13.0.0,
+cryptography 49.0.0 → 50.0.2, oauthlib 3.3.1 → 4.0.1, urllib3 2.7.0 → 2.8.0,
+werkzeug 3.1.8 → 3.1.9, pyasn1 0.6.4 → 0.6.5, certifi 2026.6.17 → 2026.10.23.
+The full suite passes in a clean environment built from the new pins; Fernet
+and a HEIC round-trip were smoke-tested there. `pip-audit` (OSV database)
+reports no known vulnerabilities for `requirements.txt`.
+
+Frontend: `npm audit fix` (semver-compatible) reduced build-tool advisories
+from 8 to 2. The remaining two are in esbuild/Vite's development server and
+need a Vite major upgrade; the built assets and runtime dependencies (React)
+have none. The production bundle is unchanged at 194 kB (58 kB gzip).
+
+Rust dependencies were not checked against an advisory database
+(`cargo-audit` is not installed).
+
+## Validation performed
+
+- `pytest tests/` — 117 passed. `ruff check src/ main.py tests/ deploy/` — clean.
+- `cargo fmt --check`, `cargo clippy --locked -- -D warnings`, `cargo test --locked` — clean, 6 passed.
+- `npm run build` — succeeds.
+- Each new regression test was run against the previous source: 22 of the 29
+ API tests and all 11 correctness tests failed there. (Seven API tests assert
+ behaviour that was already correct, such as same-origin requests succeeding.)
+- A real server was started and probed with `curl`: loopback bind, health,
+ frontend served, foreign `Host` → 403, cross-origin POST → 403, same-origin
+ POST → 200.
+- The Docker image was built from the final tree and a container was driven
+ through the API: health reports the Rust backend, the frontend is served,
+ a foreign `Host` and a cross-origin POST get 403, the three models pass their
+ checksums, and a scan → thumbnail → Trash → undo cycle on a mounted folder
+ restored the file. Trash crosses filesystems in a container (bind mount to
+ container storage), which the previous `rename` could not do.
+
+### Not verified
+
+- ML inference (scene, face detection, face recognition) and the watcher daemon
+ have no automated tests and were not exercised.
+- Google Drive sync and OAuth against the real service; S3 is a stub.
+- Video compression with a real FFmpeg; Windows and macOS behaviour.
+- The GitHub Actions workflows were not run (pushing was not possible from the
+ audit environment).
+
+## Open items
+
+Ordered by priority.
+
+1. **No authentication.** The fixes above stop other websites and other hosts
+ by default, but anyone who can reach the port — after opting in to LAN
+ exposure — has full control of the mounted library. A shared secret or
+ login is the real fix.
+2. **Job outcome.** An organize or compression job whose every file fails
+ still ends as "completed" with an error count rather than "failed".
+3. **Deletion trusts the client** for which image is the "best" in a group
+ (`is_best` comes from the request). Server-owned deletion plans remain open
+ (F04 in the earlier audit).
+4. **The container runs Flask's development server.** Use a production WSGI
+ server (for example waitress or gunicorn with threads).
+5. **CLI duplicate move/copy/delete** still uses unverified `shutil` operations;
+ CLI delete is permanent with a single confirmation.
+6. **Compression** fidelity limits (metadata, animation, HDR) are unchanged (F08).
+7. **Cloud sync** identifies remote files by name and folder, not by stored
+ file id (F27); the throttle is a per-file delay, not a rate limit.
+8. **Repository size.** History contains a 261 MB model file and Rust `target/`
+ build output (362 MB pack). Removing them requires rewriting history and
+ force-pushing, which needs the owner's decision.
+9. **Image size.** The face-embedding model is ArcFace ResNet100 (261 MB, saved
+ as `mobilefacenet.onnx`); the scene model saved as `mobilenetv3_small.onnx`
+ is MobileNetV2. Switching to an actual MobileFaceNet would remove roughly
+ 250 MB but changes recognition behaviour.
+10. **Scan speed** is now dominated by full-resolution JPEG decoding. Scaled
+ decoding would be several times faster but changes hash values, so it needs
+ re-validation of duplicate detection first. Grouping remains O(n²).
+11. **Docker inputs.** Base images (`rust:slim`, `node:20-slim`,
+ `python:3.12-slim`) and `maturin` are not pinned to digests/versions.
+12. **Vite major upgrade** to clear the two remaining dev-server advisories.
+13. Carried over from the earlier audit: hard-link requirement for publication
+ (no FAT/exFAT), leftover `.clean-backup-*.partial` files after a crash,
+ perceptual matching being heuristic, symlinks created by classification are
+ not journaled.
diff --git a/docs/RECORDING.md b/docs/RECORDING.md
index eec18c6..6489733 100644
--- a/docs/RECORDING.md
+++ b/docs/RECORDING.md
@@ -1,62 +1,66 @@
-# Recording the Demo GIF
+# Demo GIF
-## Overview
+[`demo.gif`](demo.gif) is a looping, 32-second walkthrough made from eight screen captures of the running React/Flask app. The captures show real operations on a separate sample library, database, configuration directory, and undo journal. Captions and pauses were added for readability; the app results were not altered.
-The demo GIF should be a 30–45 second screen capture showing:
-1. Drop/select photos → dedupe review UI with card/modal duplicate comparison
-2. Classify wizard → job running with stage progress
-3. People page naming an unidentified face
-4. An undo action reverting a change
+## What the recording shows
-## Tools
+1. **Scan:** nine JPEGs are hashed by the Rust `phash_rs` backend. The scan finds three groups and six duplicates at sensitivity 10.
+2. **Review:** compare duplicate cards and open the image preview. Each group contains an original, a half-resolution copy, and a recompressed copy.
+3. **Organize:** copy all nine images into `2025/March`, `2025/April`, and `2025/May`, using their EXIF dates. The app reports nine processed images and zero errors. Duplicate checks are unchecked for this step so every sample is copied.
+4. **Undo:** revert the session containing nine copy operations. Filesystem checks confirmed that all nine output copies were removed and all nine source images remained intact.
-| Platform | Tool | Notes |
-|----------|------|-------|
-| Linux | [Peek](https://github.com/phw/peek) or [SimpleScreenRecorder](https://www.maartenbaert.be/simplescreenrecorder/) | Peek outputs GIF directly |
-| macOS | `Cmd+Shift+5` or [Kap](https://getkap.co/) | Kap outputs GIF/MP4 |
-| Cross-platform | [OBS Studio](https://obsproject.com/) | Outputs MP4, convert to GIF below |
+This recording covers local deduplication, review, organization, and undo. It does not demonstrate classification, face recognition, or cloud sync.
-## Steps
+## Sample images
-1. Start the app with populated data:
- ```bash
- DEMO_MODE=true python main.py --web
- ```
+The sample library uses these Pexels photos, downloaded under the [Pexels License](https://www.pexels.com/license/):
-2. Open `http://localhost:8080` in a browser with a clean window (no bookmarks bar).
+| Local filename | Source |
+|---|---|
+| `mountains.jpg` | [Pexels photo 3278215](https://www.pexels.com/photo/3278215/) |
+| `food.jpg` | [Pexels photo 1640777](https://www.pexels.com/photo/1640777/) |
+| `puppies.jpg` | [Pexels photo 1108099](https://www.pexels.com/photo/1108099/) |
-3. Record the sequence above in one take.
+Each original was saved at JPEG quality 94 with an EXIF `DateTimeOriginal` of March 15, April 15, or May 15, 2025. Pillow produced a half-resolution variant at quality 72 and a full-resolution variant at quality 32. No personal media or cloud credentials were used.
-4. Convert to optimized GIF (if recording was MP4):
- ```bash
- # Generate palette for high-quality GIF
- ffmpeg -i recording.mp4 -vf "fps=12,scale=960:-1:flags=lanczos,palettegen" palette.png
+## Re-record locally
- # Convert using palette
- ffmpeg -i recording.mp4 -i palette.png -lavfi "fps=12,scale=960:-1:flags=lanczos [x]; [x][1:v] paletteuse" -loop 0 docs/demo.gif
- ```
+Complete the [local setup](../README.md#local-development), build the frontend, and prepare a disposable sample folder containing the photos and variants above. Use absolute paths for the following environment variables. Run from the disposable directory so relative log and undo files also stay separate:
-5. Speed up slow sections (optional):
- ```bash
- ffmpeg -i recording.mp4 -filter:v "setpts=0.5*PTS" -an fast.mp4
- ```
+```bash
+# Set this to the absolute path of your clone.
+REPO=/absolute/path/to/Clean-Backup
+CAPTURE_DIR=$(mktemp -d /tmp/clean-backup-demo.XXXXXX)
+mkdir -p "$CAPTURE_DIR/library" "$CAPTURE_DIR/organized" "$CAPTURE_DIR/config"
+# Put the sample photos and variants into "$CAPTURE_DIR/library".
+cd "$CAPTURE_DIR"
+CLEAN_BACKUP_DB_PATH="$CAPTURE_DIR/showcase.db" \
+CLEAN_BACKUP_CONFIG_DIR="$CAPTURE_DIR/config" \
+CLEAN_BACKUP_PORT=8080 \
+"$REPO/.venv/bin/python" "$REPO/main.py" --web
+```
-6. Verify size is under 10MB:
- ```bash
- ls -lh docs/demo.gif
- ```
+Open `http://localhost:8080`. Use the sample library for **Duplicates**, inspect a group and its preview, then use **Organize** with **Copy** and the disposable `organized` destination. Check the completed summary, open **Undo History**, and revert that sample session. Do not set `DEMO_MODE=true`: the read-only deployment mode blocks organization and undo.
-7. Uncomment the GIF embed in README.md:
- ```markdown
- 
- ```
+Capture the eight states listed above at a consistent desktop viewport. The committed GIF uses 960 × 660 pixels including its caption strip, eight frames with pauses of 3, 4.5, 5, 4, 3.5, 4.5, 3.5, and 4 seconds, and an infinite loop. It is under 1 MB and uses a repository-relative Markdown image link so it displays directly on GitHub.
-## Alternative: MP4
+Verify a replacement before committing it:
-GitHub renders MP4 natively in README files. If the GIF is too large, use MP4:
+```python
+from pathlib import Path
+from PIL import Image
-```markdown
-https://github.com/user-attachments/assets/
+path = Path("docs/demo.gif")
+with Image.open(path) as gif:
+ assert gif.is_animated and gif.n_frames == 8
+ assert gif.info["loop"] == 0
+ assert gif.size == (960, 660)
+ duration = 0
+ for index in range(gif.n_frames):
+ gif.seek(index)
+ duration += gif.info["duration"]
+ assert duration == 32000
+assert path.stat().st_size < 1_000_000
```
-Upload via GitHub's web UI (drag & drop into an issue/PR, copy the URL).
+Inspect every frame visually as well. Confirm that images load, text remains legible, the results match the operations, and the output directory is empty after undo.
diff --git a/docs/demo.gif b/docs/demo.gif
new file mode 100644
index 0000000..475e54c
Binary files /dev/null and b/docs/demo.gif differ
diff --git a/main.py b/main.py
index 22352bd..9e3e460 100644
--- a/main.py
+++ b/main.py
@@ -1,5 +1,3 @@
-from pathlib import Path
-from datetime import datetime
from src.organiser import organise_files, print_summary
from src.duplicate_handler import handle_duplicates, print_duplicate_report
from src.undo_manager import undo_manager
@@ -62,57 +60,11 @@ def main():
if target_session:
confirm = input(f"Are you sure you want to revert {target_session['count']} actions from {target_session['id']}? (y/n): ")
if confirm.lower() == 'y':
- undo_manager.undo_session(target_session['path'])
- print("\n✅ Undo operation completed")
-
- # Ask about Google Drive sync
- sync_choice = input("\n☁️ Backup restored files to Google Drive? (y/n): ").strip().lower()
- if sync_choice == 'y':
- try:
- from src.gdrive_sync import GoogleDriveSync, print_sync_summary, is_gdrive_available
- import json
-
- if not is_gdrive_available():
- print("\n❌ Google Drive support not installed")
- print("Install with: uv pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client")
- else:
- # Read session file to get source directories
- with open(target_session['path'], 'r') as f:
- actions = json.load(f)
-
- # Extract unique source directories
- source_dirs = set()
- for entry in actions:
- src_path = Path(entry.get('src', ''))
- if src_path.exists() and src_path.parent.exists():
- # Get parent directory
- source_dirs.add(src_path.parent)
-
- if source_dirs:
- # Use the most common parent directory
- source_dir = min(source_dirs, key=lambda p: len(p.parts))
-
- print(f"\n📁 Syncing directory: {source_dir}")
- print("🔐 Authenticating with Google Drive...")
- sync = GoogleDriveSync()
-
- backup_name = f"Restored_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
- stats_sync = sync.sync_directory(source_dir, backup_name)
- print_sync_summary(stats_sync)
- else:
- print("❌ No source directories found to sync")
- except FileNotFoundError as e:
- print(f"\n❌ {e}")
- print("\nSetup instructions:")
- print("1. Go to https://console.cloud.google.com/")
- print("2. Create a new project")
- print("3. Enable Google Drive API")
- print("4. Create OAuth 2.0 credentials (Desktop app)")
- print("5. Download credentials.json to project root")
- except Exception as e:
- print(f"\n❌ Sync failed: {e}")
- from src.logger import logger
- logger.error(f"Google Drive sync error: {e}")
+ if undo_manager.undo_session(target_session['path']):
+ print("\n✅ Undo operation completed")
+ else:
+ print("\n⚠️ Some actions could not be reverted and were left in place.")
+ print(" Check the log, then retry the same session.")
else:
print("Invalid selection.")
@@ -131,8 +83,8 @@ def main():
print("❌ Threshold cannot be negative. Setting to 0.")
val = 0
elif val > 25:
- print("❌ Threshold too high (max 64). Setting to 15.")
- val = 15
+ print("❌ Threshold too high (max 25). Setting to 25.")
+ val = 25
current_threshold = val
src.config.save_config("phash_threshold", val)
@@ -201,55 +153,14 @@ def main():
check_dups = input("\nCheck for perceptual duplicates before organizing? (y/n): ").strip().lower()
check_duplicates = (check_dups == 'y')
- check_name_dups = input("Check for name-based duplicates (e.g., photo(1).jpg, Image copy.png)? (y/n): ").strip().lower()
- check_name_duplicates = (check_name_dups == 'y')
-
if check_duplicates:
print(f" Using Rust perceptual hashing to detect duplicate images (Threshold: {current_threshold})")
- if check_name_duplicates:
- print(" Detecting OS duplicate patterns: (1), (copy), - Copy, copy, drag/drop numbers")
-
- stats = organise_files(source, destination, operation, check_duplicates=check_duplicates, duplicate_threshold=current_threshold, check_name_duplicates=check_name_duplicates)
+ print(" Files with similar names are retained; naming conflicts receive a unique suffix.")
+ stats = organise_files(source, destination, operation, check_duplicates=check_duplicates, duplicate_threshold=current_threshold)
print_summary(stats, operation)
print("Check logs for detailed information!")
-
- # Ask about Google Drive sync
- sync_choice = input("\n☁️ Backup organized files to Google Drive? (y/n): ").strip().lower()
- if sync_choice == 'y':
- try:
- from src.gdrive_sync import GoogleDriveSync, print_sync_summary, is_gdrive_available
-
- if not is_gdrive_available():
- print("\n❌ Google Drive support not installed")
- print("Install with: uv pip install google-auth google-auth-oauthlib google-auth-httplib2 google-api-python-client")
- else:
- dest_path = Path(destination)
- if dest_path.exists():
- print("\n🔐 Authenticating with Google Drive...")
- sync = GoogleDriveSync()
-
- backup_name = input("Backup folder name (press Enter for timestamp): ").strip()
- if not backup_name:
- backup_name = f"Organized_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
-
- stats_sync = sync.sync_directory(dest_path, backup_name)
- print_sync_summary(stats_sync)
- else:
- print("❌ Destination folder not found")
- except FileNotFoundError as e:
- print(f"\n❌ {e}")
- print("\nSetup instructions:")
- print("1. Go to https://console.cloud.google.com/")
- print("2. Create a new project")
- print("3. Enable Google Drive API")
- print("4. Create OAuth 2.0 credentials (Desktop app)")
- print("5. Download credentials.json to project root")
- except Exception as e:
- print(f"\n❌ Sync failed: {e}")
- from src.logger import logger
- logger.error(f"Google Drive sync error: {e}")
else:
print("Source and Destination paths are required.")
continue
diff --git a/phash_rs/Cargo.lock b/phash_rs/Cargo.lock
index ecf7932..4251390 100644
--- a/phash_rs/Cargo.lock
+++ b/phash_rs/Cargo.lock
@@ -371,10 +371,8 @@ dependencies = [
"moxcms",
"num-traits",
"png",
- "qoi",
"ravif",
"rayon",
- "rgb",
"tiff",
"zune-core 0.5.0",
"zune-jpeg 0.5.8",
@@ -743,15 +741,6 @@ dependencies = [
"syn",
]
-[[package]]
-name = "qoi"
-version = "0.4.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
-dependencies = [
- "bytemuck",
-]
-
[[package]]
name = "quick-error"
version = "2.0.1"
diff --git a/phash_rs/Cargo.toml b/phash_rs/Cargo.toml
index 36a6a5e..5e6965f 100644
--- a/phash_rs/Cargo.toml
+++ b/phash_rs/Cargo.toml
@@ -11,7 +11,9 @@ crate-type = ["cdylib", "rlib"]
[dependencies]
pyo3 = { version = "0.22", features = ["extension-module", "abi3-py310"] }
-image = "0.25"
+# Only the formats the app scans (see src/constants.py); the default feature
+# set also builds AVIF, EXR, HDR, DDS and other codecs that are never reached.
+image = { version = "0.25", default-features = false, features = ["jpeg", "png", "gif", "bmp", "tiff", "webp", "rayon"] }
rayon = "1.10"
[profile.release]
diff --git a/phash_rs/README.md b/phash_rs/README.md
index 552a174..61c9413 100644
--- a/phash_rs/README.md
+++ b/phash_rs/README.md
@@ -4,10 +4,11 @@ Fast perceptual image hashing library written in Rust with Python bindings.
## Features
-- **Three hash algorithms:**
- - `aHash` (Average Hash) - Fast, good for identical images
- - `dHash` (Difference Hash) - Good balance of speed and accuracy
- - `pHash` (Perceptual Hash) - Most robust, uses DCT
+- **DCT-based pHash** (64-bit), robust to resizing, recompression and format changes
+- **Formats:** JPEG, PNG, GIF, BMP, TIFF and WebP (other codecs are not compiled in)
+- **One decode per image**: hash and resolution are computed together, and
+ grouping works on those results without reopening files
+- **Releases the GIL** while hashing, so other Python threads keep running
- **Parallel processing** using Rayon for multi-core systems
- **Pure Python fallback** if Rust extension is unavailable
@@ -60,7 +61,7 @@ maturin develop --release
import phash_rs
# Compute hash of single image
-hash = phash_rs.compute_hash("image.jpg", algorithm="phash")
+hash = phash_rs.compute_hash("image.jpg")
print(f"Hash: {hash}")
# Compare two images
@@ -75,7 +76,11 @@ for group in duplicates:
print(f"Best quality: {group['best']}")
# Batch hash computation (parallel)
-hashes = phash_rs.compute_hashes_parallel(paths, algorithm="phash")
+hashes = phash_rs.compute_hashes_parallel(paths)
+
+# Hash in batches (e.g. to report progress), then group without re-reading files
+hashed = phash_rs.compute_hashes_with_resolution(paths) # {path: (hash, width*height)}
+groups = phash_rs.group_hashes([(p, h, res) for p, (h, res) in hashed.items()], threshold=10)
```
### Using the Python Wrapper
diff --git a/phash_rs/src/duplicate.rs b/phash_rs/src/duplicate.rs
index cb89ba1..f7ae8ff 100644
--- a/phash_rs/src/duplicate.rs
+++ b/phash_rs/src/duplicate.rs
@@ -3,7 +3,6 @@
//! Provides functionality to find duplicate images based on perceptual hashes.
use crate::hash::{HashAlgorithm, ImageHash};
-use image::GenericImageView;
use rayon::prelude::*;
use std::collections::HashMap;
@@ -18,12 +17,31 @@ pub struct DuplicateGroup {
pub best_path: String,
}
-/// Image info for duplicate detection
+/// A hashed image: everything grouping needs, with no further file access.
#[derive(Debug, Clone)]
-struct ImageInfo {
- path: String,
- hash: ImageHash,
- resolution: u64, // width * height
+pub struct ImageInfo {
+ pub path: String,
+ pub hash: ImageHash,
+ /// width * height
+ pub resolution: u64,
+}
+
+fn hash_one(path: &str, algorithm: HashAlgorithm) -> Result {
+ let (hash, resolution) = ImageHash::from_path_with_resolution(path, algorithm, 8)?;
+ Ok(ImageInfo {
+ path: path.to_string(),
+ hash,
+ resolution,
+ })
+}
+
+/// Hash images in parallel, decoding each file exactly once.
+/// Files that cannot be decoded are omitted.
+pub fn hash_images_parallel(paths: &[String], algorithm: HashAlgorithm) -> Vec {
+ paths
+ .par_iter()
+ .filter_map(|path| hash_one(path, algorithm).ok())
+ .collect()
}
/// Find duplicate images from a list of paths
@@ -32,22 +50,12 @@ pub fn find_duplicates(
algorithm: HashAlgorithm,
threshold: u32,
) -> Result, String> {
- // Compute hashes for all images
let mut images: Vec = Vec::new();
for path in paths {
- match ImageHash::from_path(path, algorithm, 8) {
- Ok(hash) => {
- let resolution = get_image_resolution(path).unwrap_or(0);
- images.push(ImageInfo {
- path: path.clone(),
- hash,
- resolution,
- });
- }
- Err(e) => {
- eprintln!("Warning: Failed to hash {}: {}", path, e);
- }
+ match hash_one(path, algorithm) {
+ Ok(info) => images.push(info),
+ Err(e) => eprintln!("Warning: Failed to hash {}: {}", path, e),
}
}
@@ -60,26 +68,14 @@ pub fn find_duplicates_parallel(
algorithm: HashAlgorithm,
threshold: u32,
) -> Result, String> {
- // Compute hashes in parallel
- let images: Vec = paths
- .par_iter()
- .filter_map(|path| {
- ImageHash::from_path(path, algorithm, 8).ok().map(|hash| {
- let resolution = get_image_resolution(path).unwrap_or(0);
- ImageInfo {
- path: path.clone(),
- hash,
- resolution,
- }
- })
- })
- .collect();
-
- group_duplicates(images, threshold)
+ group_duplicates(hash_images_parallel(paths, algorithm), threshold)
}
-/// Group images by similarity
-fn group_duplicates(images: Vec, threshold: u32) -> Result, String> {
+/// Group already-hashed images by similarity
+pub fn group_duplicates(
+ images: Vec,
+ threshold: u32,
+) -> Result, String> {
if images.is_empty() {
return Ok(Vec::new());
}
@@ -113,12 +109,27 @@ fn group_duplicates(images: Vec, threshold: u32) -> Result> = images.iter().map(|image| image.hash.as_u64()).collect();
+ match words {
+ Some(words) => {
+ for i in 0..n {
+ let word = words[i];
+ for (j, other) in words.iter().enumerate().skip(i + 1) {
+ if (word ^ other).count_ones() <= threshold {
+ union(&mut parent, &mut rank, i, j);
+ }
+ }
+ }
+ }
+ None => {
+ for i in 0..n {
+ for j in (i + 1)..n {
+ if images[i].hash.distance(&images[j].hash) <= threshold {
+ union(&mut parent, &mut rank, i, j);
+ }
+ }
}
}
}
@@ -160,20 +171,49 @@ fn group_duplicates(images: Vec, threshold: u32) -> Result Result {
- let img = image::open(path).map_err(|e| e.to_string())?;
- let (w, h) = img.dimensions();
- Ok(w as u64 * h as u64)
-}
-
#[cfg(test)]
mod tests {
use super::*;
+ fn info(path: &str, hex: &str, resolution: u64) -> ImageInfo {
+ ImageInfo {
+ path: path.to_string(),
+ hash: ImageHash::from_hex(hex).unwrap(),
+ resolution,
+ }
+ }
+
#[test]
fn test_empty_input() {
let result = find_duplicates(&[], HashAlgorithm::PHash, 10).unwrap();
assert!(result.is_empty());
}
+
+ #[test]
+ fn test_groups_precomputed_hashes_and_picks_largest() {
+ let images = vec![
+ info("small.jpg", "ff00ff00ff00ff00", 100),
+ info("large.jpg", "ff00ff00ff00ff01", 400),
+ info("other.jpg", "00ff00ff00ff00ff", 900),
+ ];
+ let mut groups = group_duplicates(images, 2).unwrap();
+ groups.sort_by_key(|g| g.paths.len());
+
+ assert_eq!(groups.len(), 2);
+ assert_eq!(groups[0].paths, vec!["other.jpg"]);
+ assert_eq!(groups[1].paths, vec!["large.jpg", "small.jpg"]);
+ assert_eq!(groups[1].best_path, "large.jpg");
+ }
+
+ #[test]
+ fn test_threshold_zero_only_groups_identical_hashes() {
+ let images = vec![
+ info("a.jpg", "ff00ff00ff00ff00", 1),
+ info("b.jpg", "ff00ff00ff00ff00", 2),
+ info("c.jpg", "ff00ff00ff00ff01", 3),
+ ];
+ let groups = group_duplicates(images, 0).unwrap();
+ assert_eq!(groups.iter().filter(|g| g.paths.len() == 2).count(), 1);
+ assert_eq!(groups.iter().filter(|g| g.paths.len() == 1).count(), 1);
+ }
}
diff --git a/phash_rs/src/hash.rs b/phash_rs/src/hash.rs
index 3525782..05cc059 100644
--- a/phash_rs/src/hash.rs
+++ b/phash_rs/src/hash.rs
@@ -3,7 +3,7 @@
//! Implements DCT-based perceptual hashing for robust duplicate detection
//! that is resistant to resizing, format changes, and minor edits.
-use image::{imageops::FilterType, DynamicImage};
+use image::{imageops::FilterType, DynamicImage, GenericImageView};
use std::path::Path;
/// Hash algorithm type (only pHash supported)
@@ -35,6 +35,24 @@ impl ImageHash {
Ok(Self::from_image(&img, algorithm, hash_size))
}
+ /// Compute the hash and the pixel count (width * height) from one decode.
+ ///
+ /// Duplicate grouping needs both; decoding the file a second time just to
+ /// read its dimensions doubles the cost of a scan.
+ pub fn from_path_with_resolution>(
+ path: P,
+ algorithm: HashAlgorithm,
+ hash_size: usize,
+ ) -> Result<(Self, u64), String> {
+ let img = image::open(path.as_ref()).map_err(|e| format!("Failed to open image: {}", e))?;
+ let (width, height) = img.dimensions();
+
+ Ok((
+ Self::from_image(&img, algorithm, hash_size),
+ width as u64 * height as u64,
+ ))
+ }
+
/// Compute hash from a loaded image (uses pHash)
pub fn from_image(img: &DynamicImage, _algorithm: HashAlgorithm, hash_size: usize) -> Self {
Self::compute_phash(img, hash_size)
@@ -63,6 +81,13 @@ impl ImageHash {
self.bits.iter().map(|b| format!("{:02x}", b)).collect()
}
+ /// The hash as one machine word, when it is the standard 64-bit size.
+ pub fn as_u64(&self) -> Option {
+ <[u8; 8]>::try_from(self.bits.as_slice())
+ .ok()
+ .map(u64::from_be_bytes)
+ }
+
/// Compute Hamming distance to another hash
pub fn distance(&self, other: &ImageHash) -> u32 {
self.bits
@@ -211,4 +236,13 @@ mod tests {
let h3 = ImageHash::from_hex("ff00ff01").unwrap();
assert_eq!(h1.distance(&h3), 1);
}
+
+ #[test]
+ fn test_word_form_matches_byte_distance() {
+ let a = ImageHash::from_hex("abcdef0123456789").unwrap();
+ let b = ImageHash::from_hex("abcdef0123450000").unwrap();
+ let (wa, wb) = (a.as_u64().unwrap(), b.as_u64().unwrap());
+ assert_eq!((wa ^ wb).count_ones(), a.distance(&b));
+ assert!(ImageHash::from_hex("ff00ff00").unwrap().as_u64().is_none());
+ }
}
diff --git a/phash_rs/src/lib.rs b/phash_rs/src/lib.rs
index 4053c47..5cf07fb 100644
--- a/phash_rs/src/lib.rs
+++ b/phash_rs/src/lib.rs
@@ -17,7 +17,10 @@ use pyo3::conversion::ToPyObject;
use pyo3::prelude::*;
use std::collections::HashMap;
-pub use duplicate::{find_duplicates, find_duplicates_parallel, DuplicateGroup};
+pub use duplicate::{
+ find_duplicates, find_duplicates_parallel, group_duplicates, hash_images_parallel,
+ DuplicateGroup, ImageInfo,
+};
pub use hash::{HashAlgorithm, ImageHash};
/// Compute the perceptual hash (pHash) of an image file.
@@ -89,28 +92,88 @@ fn are_similar(path1: &str, path2: &str, threshold: u32) -> PyResult {
#[pyfunction]
#[pyo3(signature = (paths, threshold = 10))]
fn find_duplicate_images(
+ py: Python<'_>,
paths: Vec,
threshold: u32,
) -> PyResult>> {
- let groups = find_duplicates_parallel(&paths, HashAlgorithm::PHash, threshold)
- .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(e.to_string()))?;
+ // Decoding and hashing touch no Python objects: let other threads run.
+ let groups =
+ py.allow_threads(|| find_duplicates_parallel(&paths, HashAlgorithm::PHash, threshold));
+ groups_to_python(py, groups)
+}
+
+fn groups_to_python(
+ py: Python<'_>,
+ groups: Result, String>,
+) -> PyResult>> {
+ let groups = groups.map_err(pyo3::exceptions::PyRuntimeError::new_err)?;
+
+ Ok(groups
+ .into_iter()
+ .filter(|g| g.paths.len() > 1) // Only return actual duplicates
+ .map(|g| {
+ let mut map = HashMap::new();
+ map.insert("paths".to_string(), g.paths.to_object(py));
+ map.insert("hash".to_string(), g.hash.to_object(py));
+ map.insert("best".to_string(), g.best_path.to_object(py));
+ map
+ })
+ .collect())
+}
- Python::with_gil(|py| {
- let result: Vec> = groups
+/// Compute pHash and pixel count (width * height) for many images in parallel.
+///
+/// Each file is decoded once. Use with `group_hashes` to report progress
+/// between hashing batches without hashing anything twice.
+///
+/// Returns:
+/// Dictionary mapping file paths to `(hash, resolution)`.
+/// Failed images are excluded from the result.
+#[pyfunction]
+#[pyo3(signature = (paths))]
+fn compute_hashes_with_resolution(
+ py: Python<'_>,
+ paths: Vec,
+) -> HashMap {
+ py.allow_threads(|| {
+ hash_images_parallel(&paths, HashAlgorithm::PHash)
.into_iter()
- .filter(|g| g.paths.len() > 1) // Only return actual duplicates
- .map(|g| {
- let mut map = HashMap::new();
- map.insert("paths".to_string(), g.paths.clone().to_object(py));
- map.insert("hash".to_string(), g.hash.to_object(py));
- map.insert("best".to_string(), g.best_path.to_object(py));
- map
- })
- .collect();
- Ok(result)
+ .map(|info| (info.path, (info.hash.to_hex(), info.resolution)))
+ .collect()
})
}
+/// Group already-hashed images into duplicate sets without reading any file.
+///
+/// Args:
+/// items: List of `(path, hash, resolution)` tuples
+/// threshold: Maximum Hamming distance for duplicates (default: 10)
+///
+/// Returns:
+/// Same structure as `find_duplicate_images`.
+#[pyfunction]
+#[pyo3(signature = (items, threshold = 10))]
+fn group_hashes(
+ py: Python<'_>,
+ items: Vec<(String, String, u64)>,
+ threshold: u32,
+) -> PyResult>> {
+ let images = items
+ .into_iter()
+ .map(|(path, hex, resolution)| {
+ ImageHash::from_hex(&hex).map(|hash| ImageInfo {
+ path,
+ hash,
+ resolution,
+ })
+ })
+ .collect::, _>>()
+ .map_err(pyo3::exceptions::PyValueError::new_err)?;
+
+ let groups = py.allow_threads(|| group_duplicates(images, threshold));
+ groups_to_python(py, groups)
+}
+
/// Compute pHashes for multiple images in parallel.
///
/// Args:
@@ -121,19 +184,19 @@ fn find_duplicate_images(
/// Failed images are excluded from the result.
#[pyfunction]
#[pyo3(signature = (paths))]
-fn compute_hashes_parallel(paths: Vec) -> PyResult> {
+fn compute_hashes_parallel(py: Python<'_>, paths: Vec) -> HashMap {
use rayon::prelude::*;
- let results: HashMap = paths
- .par_iter()
- .filter_map(|path| {
- ImageHash::from_path(path, HashAlgorithm::PHash, 8)
- .ok()
- .map(|h| (path.clone(), h.to_hex()))
- })
- .collect();
-
- Ok(results)
+ py.allow_threads(|| {
+ paths
+ .par_iter()
+ .filter_map(|path| {
+ ImageHash::from_path(path, HashAlgorithm::PHash, 8)
+ .ok()
+ .map(|h| (path.clone(), h.to_hex()))
+ })
+ .collect()
+ })
}
/// Python module definition
@@ -144,6 +207,8 @@ fn phash_rs(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(are_similar, m)?)?;
m.add_function(wrap_pyfunction!(find_duplicate_images, m)?)?;
m.add_function(wrap_pyfunction!(compute_hashes_parallel, m)?)?;
+ m.add_function(wrap_pyfunction!(compute_hashes_with_resolution, m)?)?;
+ m.add_function(wrap_pyfunction!(group_hashes, m)?)?;
// Add constants for recommended thresholds
m.add("THRESHOLD_IDENTICAL", 0)?;
diff --git a/pyproject.toml b/pyproject.toml
index 452f898..d0a3510 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,7 +1,7 @@
[project]
name = "clean-backup"
version = "0.1.0"
-description = "Add your description here"
+description = "Local photo and video organizer with perceptual deduplication, on-device classification and journaled undo"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
@@ -19,3 +19,11 @@ dependencies = [
"google-api-python-client>=2.100.0",
"watchdog>=6.0.0",
]
+
+[tool.ruff]
+target-version = "py312"
+
+[tool.ruff.lint]
+# Keep the project's existing syntax and undefined/unused-name checks explicit.
+# Ruff upgrades must not silently change the rule set for unchanged code.
+select = ["E4", "E7", "E9", "F"]
diff --git a/requirements-dev.txt b/requirements-dev.txt
new file mode 100644
index 0000000..6d905ae
--- /dev/null
+++ b/requirements-dev.txt
@@ -0,0 +1,3 @@
+# Keep local verification and GitHub Actions on the same tool versions.
+ruff==0.15.22
+pytest==9.0.2
diff --git a/requirements.txt b/requirements.txt
index 6181928..fa31741 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,8 +1,8 @@
# This file was autogenerated by uv via the following command:
-# uv pip compile pyproject.toml -o requirements.txt
+# uv pip compile pyproject.toml -o requirements.txt --python-version 3.12
blinker==1.9.0
# via flask
-certifi==2026.6.17
+certifi==2026.10.23
# via requests
cffi==2.1.0
# via cryptography
@@ -10,7 +10,7 @@ charset-normalizer==3.4.9
# via requests
click==8.4.2
# via flask
-cryptography==49.0.0
+cryptography==50.0.2
# via
# clean-backup (pyproject.toml)
# google-auth
@@ -73,7 +73,7 @@ numpy==2.5.1
# clean-backup (pyproject.toml)
# onnxruntime
# opencv-python-headless
-oauthlib==3.3.1
+oauthlib==4.0.1
# via requests-oauthlib
onnxruntime==1.27.0
# via clean-backup (pyproject.toml)
@@ -81,7 +81,7 @@ opencv-python-headless==5.0.0.93
# via clean-backup (pyproject.toml)
packaging==26.2
# via onnxruntime
-pillow==12.3.0
+pillow==13.0.0
# via
# clean-backup (pyproject.toml)
# pillow-heif
@@ -95,7 +95,7 @@ protobuf==7.35.1
# googleapis-common-protos
# onnxruntime
# proto-plus
-pyasn1==0.6.4
+pyasn1==0.6.5
# via pyasn1-modules
pyasn1-modules==0.4.2
# via google-auth
@@ -115,9 +115,9 @@ tqdm==4.68.4
# via clean-backup (pyproject.toml)
uritemplate==4.2.0
# via google-api-python-client
-urllib3==2.7.0
+urllib3==2.8.0
# via requests
watchdog==6.0.0
# via clean-backup (pyproject.toml)
-werkzeug==3.1.8
+werkzeug==3.1.9
# via flask
diff --git a/src/classify/apply_org.py b/src/classify/apply_org.py
index fdfdccb..1012031 100644
--- a/src/classify/apply_org.py
+++ b/src/classify/apply_org.py
@@ -1,141 +1,118 @@
-import os
-import shutil
+"""Move or copy classified files into category folders."""
+
import logging
+import os
+import re
from pathlib import Path
-from src.classify.db import _get_conn, get_run_config, get_all_tags_for_run
+
+from src.classify.db import get_all_tags_for_run, get_run_config
+from src.file_operations import verified_transfer
+from src.metadata import get_media_date
from src.undo_manager import UndoManager
logger = logging.getLogger(__name__)
+
def apply_classification(run_id, dest_dir, operation, progress_cb=None):
"""
Applies the classification results from the DB to physical files.
+
+ ``progress_cb`` follows the job convention ``(percent, message)``.
"""
- dest_path = Path(dest_dir)
- if not dest_path.exists():
- dest_path.mkdir(parents=True)
+ if operation not in {"move", "copy"}:
+ raise ValueError("operation must be move or copy")
+ with UndoManager() as undo_mgr:
+ return _apply_classification(run_id, dest_dir, operation, progress_cb, undo_mgr)
+
+
+def _folder_name(label):
+ """One safe directory name per category: "Nature / Scenery" -> "Nature - Scenery"."""
+ return re.sub(r"\s*[/\\:]+\s*", " - ", str(label)).strip(" .") or "Other"
+
+
+def _category_folder(folder_scheme, label, yyyy, mm):
+ label = _folder_name(label)
+ if folder_scheme == "yyyy_mm_category":
+ return Path(yyyy) / mm / label
+ if folder_scheme == "category_yyyy_mm":
+ return Path(label) / yyyy / mm
+ return Path(label) # flat_tags
+
+
+def _apply_classification(run_id, dest_dir, operation, progress_cb, undo_mgr):
+ dest_path = Path(dest_dir).expanduser().resolve()
+ dest_path.mkdir(parents=True, exist_ok=True)
- undo_mgr = UndoManager()
- undo_mgr.start_session()
-
config = get_run_config(run_id)
if not config:
raise ValueError(f"Run ID {run_id} not found in DB")
-
+
folder_scheme = config.get("folder_scheme", "yyyy_mm_category")
multi_category = config.get("multi_category", "tags")
-
- tags = get_all_tags_for_run(run_id)
-
- # Group tags by file path
+
+ # get_all_tags_for_run orders by category priority, so each file's first
+ # tag is its primary category.
files = {}
- for tag in tags:
- path = tag["path"]
- if path not in files:
- files[path] = []
- files[path].append(tag)
-
+ for tag in get_all_tags_for_run(run_id):
+ files.setdefault(tag["path"], []).append(tag)
+
total_files = len(files)
processed = 0
-
+ transferred = 0
+ errors = 0
+
for src_path_str, file_tags in files.items():
+ processed += 1
src_path = Path(src_path_str)
- if not src_path.exists():
+ if not src_path.is_file():
logger.warning(f"File not found: {src_path}")
- processed += 1
continue
-
- # The query get_all_tags_for_run already orders by c.priority, so the first is primary
- primary_tag = file_tags[0]
- primary_cat_label = primary_tag["category_label"]
-
- # Extract date from DB or fallback to file modified time
- with _get_conn() as conn:
- c = conn.cursor()
- c.execute("SELECT created_at FROM media_files WHERE path = ?", (src_path_str,))
- row = c.fetchone()
-
- if row and row["created_at"]:
- try:
- from datetime import datetime
- # Assuming timestamp is ISO 8601 string
- dt = datetime.fromisoformat(row["created_at"])
- except (ValueError, TypeError):
- from datetime import datetime
- dt = datetime.fromtimestamp(src_path.stat().st_mtime)
- else:
- from datetime import datetime
- dt = datetime.fromtimestamp(src_path.stat().st_mtime)
-
- yyyy = dt.strftime("%Y")
- mm = dt.strftime("%m")
-
- # Determine primary destination
- if folder_scheme == "yyyy_mm_category":
- rel_dest = Path(yyyy) / mm / primary_cat_label
- elif folder_scheme == "category_yyyy_mm":
- rel_dest = Path(primary_cat_label) / yyyy / mm
- else: # flat_tags
- rel_dest = Path(primary_cat_label)
-
- target_dir = dest_path / rel_dest
- target_dir.mkdir(parents=True, exist_ok=True)
- target_file = target_dir / src_path.name
-
- # Handle duplicate filename in destination
- counter = 1
- stem = src_path.stem
- suffix = src_path.suffix
- while target_file.exists():
- target_file = target_dir / f"{stem}_{counter}{suffix}"
- counter += 1
-
- # Perform primary operation
+
+ # Capture date from the media itself (same rule as date organization),
+ # not the time the file happened to be catalogued.
+ taken = get_media_date(src_path)
+ yyyy, mm = taken.strftime("%Y"), taken.strftime("%m")
+
+ target_dir = dest_path / _category_folder(
+ folder_scheme, file_tags[0]["category_label"], yyyy, mm
+ )
try:
- if operation == "move":
- shutil.move(str(src_path), str(target_file))
- undo_mgr.log_action("move", str(src_path), str(target_file))
- else: # copy
- shutil.copy2(str(src_path), str(target_file))
- undo_mgr.log_action("copy", str(src_path), str(target_file))
-
+ # Verified, journaled and collision-safe; never replaces a file.
+ target_file = verified_transfer(
+ src_path, target_dir / src_path.name, operation, journal=undo_mgr
+ )
+ transferred += 1
except Exception as e:
logger.error(f"Failed to {operation} {src_path}: {e}")
- processed += 1
+ errors += 1
continue
-
+
# Handle multi-category symlinks if enabled
- if multi_category == "symlink" and len(file_tags) > 1:
+ if multi_category == "symlink":
for secondary_tag in file_tags[1:]:
- sec_cat_label = secondary_tag["category_label"]
-
- if folder_scheme == "yyyy_mm_category":
- sec_rel = Path(yyyy) / mm / sec_cat_label
- elif folder_scheme == "category_yyyy_mm":
- sec_rel = Path(sec_cat_label) / yyyy / mm
- else: # flat_tags
- sec_rel = Path(sec_cat_label)
-
- sec_dir = dest_path / sec_rel
- sec_dir.mkdir(parents=True, exist_ok=True)
+ sec_dir = dest_path / _category_folder(
+ folder_scheme, secondary_tag["category_label"], yyyy, mm
+ )
sec_file = sec_dir / target_file.name
-
try:
- # Target needs to be absolute
- if not sec_file.exists():
- os.symlink(str(target_file.absolute()), str(sec_file))
- # Record symlink creation for undo
- # Since undo_manager doesn't have a specific 'symlink' action out of box,
- # we can record it as a 'move' from SYMLINK (dummy) to allow reversing by delete
- undo_mgr.log_action("move", "SYMLINK", str(sec_file))
+ sec_dir.mkdir(parents=True, exist_ok=True)
+ if not os.path.lexists(sec_file):
+ os.symlink(str(target_file), str(sec_file))
except Exception as e:
logger.error(f"Failed to create symlink for {src_path}: {e}")
- processed += 1
if progress_cb and processed % 5 == 0:
- progress_cb(f"Processing {processed}/{total_files}...")
-
+ progress_cb(
+ 5 + int(processed / total_files * 90),
+ f"Processing {processed}/{total_files}...",
+ )
+
if progress_cb:
- progress_cb(f"Finished. Processed {total_files} files.")
-
- return {"total_processed": processed, "session_id": undo_mgr.session_id}
+ progress_cb(98, f"Finished. Processed {total_files} files.")
+
+ return {
+ "total_processed": processed,
+ "transferred": transferred,
+ "errors": errors,
+ "session_id": undo_mgr.session_id,
+ }
diff --git a/src/classify/models/download_models.py b/src/classify/models/download_models.py
index 1817089..d091ab4 100644
--- a/src/classify/models/download_models.py
+++ b/src/classify/models/download_models.py
@@ -5,80 +5,94 @@
python -m src.classify.models.download_models
-Downloads three small models (~10 MB total) from public GitHub / ONNX
-Model Zoo URLs and verifies their SHA-256 checksums.
+Downloads three models (about 275 MB in total, almost all of it the face
+embedding model) from public GitHub repositories and verifies each against a
+pinned SHA-256. A file that does not match is deleted and the script exits
+non-zero, so a changed or tampered upstream file can never be baked into an
+image. A failed download is reported but is not fatal: the pipeline skips
+stages whose model is missing.
"""
from __future__ import annotations
import hashlib
+import os
import sys
import urllib.request
from pathlib import Path
MODELS_DIR = Path(__file__).resolve().parent
-# (filename, url, expected_sha256_prefix)
-# SHA-256 prefixes are used for quick integrity checks — first 16 hex chars.
-MODELS: list[tuple[str, str, str | None]] = [
+# (local filename, source URL, SHA-256 of the expected file)
+# The local names are historical: the scene model is MobileNetV2 and the face
+# embedding model is ArcFace ResNet100.
+MODELS: list[tuple[str, str, str]] = [
(
"mobilenetv3_small.onnx",
"https://github.com/onnx/models/raw/main/validated/vision/classification/mobilenet/model/mobilenetv2-7.onnx",
- None, # skip hash check for public model zoo
+ "c1c513582d56afceff8516c73804e484c81c6a830712ab6d682253f4a3cd042f",
),
(
"yunet.onnx",
"https://github.com/opencv/opencv_zoo/raw/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx",
- None,
+ "8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4",
),
(
"mobilefacenet.onnx",
"https://github.com/onnx/models/raw/main/validated/vision/body_analysis/arcface/model/arcfaceresnet100-8.onnx",
- None,
+ "f3a6bc281e72f88862f5748b53be3d76b3b48f8f1ab1f4a537941bdc4e1b01da",
),
]
-def _sha256_prefix(path: Path, length: int = 16) -> str:
- h = hashlib.sha256()
+def _sha256(path: Path) -> str:
with open(path, "rb") as f:
- for chunk in iter(lambda: f.read(1 << 16), b""):
- h.update(chunk)
- return h.hexdigest()[:length]
+ return hashlib.file_digest(f, "sha256").hexdigest()
-def download_models(force: bool = False) -> None:
- """Download all required ONNX models to *MODELS_DIR*."""
+def download_models(force: bool = False) -> bool:
+ """Download all required ONNX models to *MODELS_DIR*.
+
+ Returns ``False`` if any file failed its checksum (it is removed).
+ """
MODELS_DIR.mkdir(parents=True, exist_ok=True)
+ verified = True
for filename, url, expected_hash in MODELS:
dest = MODELS_DIR / filename
if dest.exists() and not force:
- print(f" ✓ {filename} already exists — skipping")
- continue
+ if _sha256(dest) == expected_hash:
+ print(f" ✓ {filename} already exists — checksum OK")
+ continue
+ print(f" ⚠ {filename} exists but does not match its checksum — replacing")
print(f" ↓ Downloading {filename} …")
+ partial = dest.with_name(dest.name + ".part")
try:
- urllib.request.urlretrieve(url, str(dest))
-
- size_mb = dest.stat().st_size / (1024 * 1024)
- print(f" Saved ({size_mb:.1f} MB)")
-
- if expected_hash:
- actual = _sha256_prefix(dest)
- if actual != expected_hash:
- print(f" ⚠ Hash mismatch: expected {expected_hash}, got {actual}")
- else:
- print(f" ✓ Hash OK ({actual})")
+ urllib.request.urlretrieve(url, str(partial))
except Exception as exc:
print(f" ✗ Download failed: {exc}")
- if dest.exists():
- dest.unlink()
+ partial.unlink(missing_ok=True)
+ continue
+
+ actual = _sha256(partial)
+ if actual != expected_hash:
+ print(f" ✗ Checksum mismatch: expected {expected_hash}, got {actual}")
+ partial.unlink()
+ dest.unlink(missing_ok=True)
+ verified = False
+ continue
+
+ os.replace(partial, dest)
+ print(f" ✓ Saved and verified ({dest.stat().st_size / (1024 * 1024):.1f} MB)")
+
+ return verified
if __name__ == "__main__":
force = "--force" in sys.argv
print("Clean-Backup — Downloading classification models\n")
- download_models(force=force)
- print("\nDone.")
+ ok = download_models(force=force)
+ print("\nDone." if ok else "\nA model failed verification and was removed.")
+ sys.exit(0 if ok else 1)
diff --git a/src/classify/pipeline.py b/src/classify/pipeline.py
index 1541703..da1f917 100644
--- a/src/classify/pipeline.py
+++ b/src/classify/pipeline.py
@@ -36,7 +36,6 @@
from src.classify.tag_resolver import resolve_tags
from src.constants import IMAGE_EXTENSIONS, VIDEO_EXTENSIONS
from src.logger import logger
-from src.undo_manager import undo_manager
def run_classify_pipeline(
@@ -118,9 +117,6 @@ class DummyModel:
# Pre-load known face embeddings for Stage E matching
known_embeddings = db.get_all_known_embeddings() if face_recognizer.available else []
- # ── Start undo session ────────────────────────────────────────────
- undo_manager.start_session()
-
# ── Process each file ─────────────────────────────────────────────
stats: dict[str, int] = defaultdict(int)
category_counts: dict[str, int] = defaultdict(int)
@@ -275,7 +271,6 @@ class DummyModel:
total_review += 1
# ── Finalise ──────────────────────────────────────────────────────
- undo_manager.end_session()
progress_cb(98, "Building summary")
summary = {
diff --git a/src/classify/stage_exif.py b/src/classify/stage_exif.py
index dc283e9..ad5b061 100644
--- a/src/classify/stage_exif.py
+++ b/src/classify/stage_exif.py
@@ -86,8 +86,13 @@ def extract_exif(file_path: str | Path) -> ExifData:
result.has_exif = True
- # Basic tags
- for tag_id, value in exif.items():
+ # Basic tags. Exposure, ISO, capture time and user comments live in
+ # the Exif sub-IFD of camera files, not the top-level IFD.
+ try:
+ exif_ifd = exif.get_ifd(IFD.Exif)
+ except Exception:
+ exif_ifd = {}
+ for tag_id, value in [*exif.items(), *exif_ifd.items()]:
tag_name = TAGS.get(tag_id, str(tag_id))
if tag_name == "Make":
@@ -104,11 +109,8 @@ def extract_exif(file_path: str | Path) -> ExifData:
pass
elif tag_name == "ExposureTime":
try:
- if hasattr(value, "numerator"):
- result.exposure_time = float(value)
- else:
- result.exposure_time = float(value)
- except (TypeError, ValueError):
+ result.exposure_time = float(value)
+ except (TypeError, ValueError, ZeroDivisionError):
pass
elif tag_name == "Software":
result.software = _safe_str(value)
diff --git a/src/cloud/credential_store.py b/src/cloud/credential_store.py
index beb7a7c..1d4d603 100644
--- a/src/cloud/credential_store.py
+++ b/src/cloud/credential_store.py
@@ -14,7 +14,6 @@
import json
import logging
import os
-import stat
from pathlib import Path
logger = logging.getLogger(__name__)
@@ -37,6 +36,15 @@
_USE_KEYRING = False
+def _write_private(path: Path, data: bytes) -> None:
+ """Write *data* to a file that is owner-only from the moment it exists."""
+ temporary = path.with_name(path.name + ".tmp")
+ fd = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
+ with os.fdopen(fd, "wb") as stream:
+ stream.write(data)
+ os.replace(temporary, path)
+
+
def _get_fernet():
"""Return a ``Fernet`` instance, creating the key file if needed."""
from cryptography.fernet import Fernet
@@ -44,8 +52,7 @@ def _get_fernet():
_KEY_DIR.mkdir(parents=True, exist_ok=True)
if not _KEY_FILE.exists():
key = Fernet.generate_key()
- _KEY_FILE.write_bytes(key)
- os.chmod(str(_KEY_FILE), stat.S_IRUSR | stat.S_IWUSR) # 0600
+ _write_private(_KEY_FILE, key)
logger.info("Generated new Fernet key at %s", _KEY_FILE)
return Fernet(_KEY_FILE.read_bytes())
@@ -60,10 +67,7 @@ def store(account_id: str, data: dict) -> None:
logger.info("Stored credentials for %s via keyring", account_id)
else:
fernet = _get_fernet()
- encrypted = fernet.encrypt(payload.encode()).decode()
- cred_file = _KEY_DIR / f"{account_id}.enc"
- cred_file.write_text(encrypted)
- os.chmod(str(cred_file), stat.S_IRUSR | stat.S_IWUSR)
+ _write_private(_KEY_DIR / f"{account_id}.enc", fernet.encrypt(payload.encode()))
logger.info("Stored credentials for %s via Fernet fallback", account_id)
diff --git a/src/cloud/manifest.py b/src/cloud/manifest.py
index 5f9e822..6e911a0 100644
--- a/src/cloud/manifest.py
+++ b/src/cloud/manifest.py
@@ -65,6 +65,9 @@ def create_sync_run(account_id: int, config: dict) -> int:
def update_sync_run(run_id: int, **fields) -> None:
"""Update fields on a sync run (status, started_at, completed_at, etc.)."""
+ unknown = set(fields) - {"status", "started_at", "completed_at"}
+ if unknown:
+ raise ValueError(f"Unknown sync run fields: {sorted(unknown)}")
conn = _get_conn()
sets = ", ".join(f"{k} = ?" for k in fields)
vals = list(fields.values()) + [run_id]
diff --git a/src/cloud/provider_gdrive.py b/src/cloud/provider_gdrive.py
index 1e00b87..ed56f73 100644
--- a/src/cloud/provider_gdrive.py
+++ b/src/cloud/provider_gdrive.py
@@ -40,6 +40,15 @@ def _mime(path: Path) -> str:
return _MIME_TYPES.get(path.suffix.lower(), "application/octet-stream")
+def _q(value: str) -> str:
+ """Quote a value for a Drive ``files.list`` query string literal.
+
+ File and folder names come from the local filesystem; an unescaped
+ apostrophe would break the query or change which files it matches.
+ """
+ return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'"
+
+
def _sha256(path: str) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
@@ -114,7 +123,7 @@ def _get_or_create_folder(self, name: str, parent_id: str) -> str:
# Search for existing
query = (
- f"name='{name}' and '{parent_id}' in parents and "
+ f"name={_q(name)} and {_q(parent_id)} in parents and "
f"mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = self._service.files().list(
@@ -154,7 +163,7 @@ def list_remote(self, path: str) -> list[RemoteFileInfo]:
while True:
resp = self._service.files().list(
- q=f"'{folder_id}' in parents and trashed=false",
+ q=f"{_q(folder_id)} in parents and trashed=false",
spaces="drive",
fields="nextPageToken, files(id, name, size, modifiedTime, properties)",
pageSize=100,
@@ -258,7 +267,7 @@ def delete(self, remote_path: str) -> None:
try:
folder_id = self._resolve_folder_id(folder_path) if folder_path else "root"
- query = f"name='{name}' and '{folder_id}' in parents and trashed=false"
+ query = f"name={_q(name)} and {_q(folder_id)} in parents and trashed=false"
resp = self._service.files().list(
q=query, spaces="drive", fields="files(id)", pageSize=1,
).execute()
@@ -279,7 +288,7 @@ def verify(self, remote_path: str, expected_hash: str) -> bool:
try:
folder_id = self._resolve_folder_id(folder_path) if folder_path else "root"
- query = f"name='{name}' and '{folder_id}' in parents and trashed=false"
+ query = f"name={_q(name)} and {_q(folder_id)} in parents and trashed=false"
resp = self._service.files().list(
q=query, spaces="drive", fields="files(id, properties)", pageSize=1,
).execute()
@@ -294,12 +303,12 @@ def verify(self, remote_path: str, expected_hash: str) -> bool:
# ── OAuth helpers (used by Flask endpoints) ───────────────────────────────
-def start_oauth_flow(redirect_uri: str) -> tuple[str, Any]:
+def start_oauth_flow(redirect_uri: str) -> tuple[str, str, Any]:
"""
Begin the OAuth flow.
- Returns ``(auth_url, flow)`` — the caller must persist *flow* in
- the session/state so the callback can finish it.
+ Returns ``(auth_url, state, flow)`` — the caller must keep *flow* under
+ *state*, the single anti-forgery value Google echoes to the callback.
"""
from google_auth_oauthlib.flow import Flow
@@ -315,12 +324,12 @@ def start_oauth_flow(redirect_uri: str) -> tuple[str, Any]:
scopes=SCOPES,
redirect_uri=redirect_uri,
)
- auth_url, _ = flow.authorization_url(
+ auth_url, state = flow.authorization_url(
access_type="offline",
include_granted_scopes="true",
prompt="consent",
)
- return auth_url, flow
+ return auth_url, state, flow
def finish_oauth_flow(flow: Any, auth_response_url: str) -> dict:
diff --git a/src/compressor.py b/src/compressor.py
index 729d7ee..39d84cc 100644
--- a/src/compressor.py
+++ b/src/compressor.py
@@ -12,6 +12,7 @@
from src.constants import IMAGE_EXTENSIONS, VIDEO_EXTENSIONS
from src.logger import logger
+from src.file_operations import staged_output, validate_roots
pillow_heif.register_heif_opener()
@@ -75,7 +76,7 @@ def get_compression_settings(level: CompressionLevel) -> dict:
return settings.get(level, settings[2])
-def compress_image(
+def _encode_image(
image_path: Path,
output_path: Path,
level: CompressionLevel = 2
@@ -120,7 +121,6 @@ def compress_image(
del save_kwargs['quality'] # PNG doesn't use quality parameter
img.save(output_path, **save_kwargs)
- logger.info(f"Compressed image: {image_path.name} -> {output_path.name}")
return True
except Exception as e:
@@ -128,7 +128,7 @@ def compress_image(
return False
-def compress_video(
+def _encode_video(
video_path: Path,
output_path: Path,
level: CompressionLevel = 2
@@ -168,7 +168,7 @@ def compress_video(
'-c:a', 'aac', # Audio codec
'-b:a', '128k', # Audio bitrate
'-movflags', '+faststart', # Web optimization
- '-y', # Overwrite output
+ '-y', # Only the exclusively created private staging file.
str(output_path)
]
@@ -181,7 +181,6 @@ def compress_video(
)
if result.returncode == 0:
- logger.info(f"Compressed video: {video_path.name} -> {output_path.name}")
return True
else:
logger.error(f"FFmpeg failed for {video_path.name}: {result.stderr}")
@@ -198,6 +197,29 @@ def compress_video(
return False
+def _compress_to_new_output(source, target, level, encoder):
+ source, target = Path(source), Path(target)
+ try:
+ with staged_output(source, target) as temporary:
+ if not encoder(source, temporary, level):
+ raise OSError("Encoder did not complete successfully")
+ logger.info("Compressed and published: %s -> %s", source, target)
+ return True
+ except Exception as exc:
+ logger.error("Compression output was not published for %s: %s", source, exc)
+ return False
+
+
+def compress_image(image_path: Path, output_path: Path, level: CompressionLevel = 2) -> bool:
+ """Encode a new image without replacing a source or existing destination."""
+ return _compress_to_new_output(image_path, output_path, level, _encode_image)
+
+
+def compress_video(video_path: Path, output_path: Path, level: CompressionLevel = 2) -> bool:
+ """Encode to private staging space; publish only after FFmpeg succeeds."""
+ return _compress_to_new_output(video_path, output_path, level, _encode_video)
+
+
def compress_files(
source_dir: str,
output_dir: str,
@@ -218,12 +240,7 @@ def compress_files(
Returns:
CompressionStats: Statistics about the compression operation
"""
- source = Path(source_dir)
- output = Path(output_dir)
-
- if not source.exists():
- logger.error(f"Source directory not found: {source}")
- return CompressionStats()
+ source, output = validate_roots(source_dir, output_dir)
# Create output directory
output.mkdir(parents=True, exist_ok=True)
diff --git a/src/duplicate_handler.py b/src/duplicate_handler.py
index 7b3780f..3e0a77c 100644
--- a/src/duplicate_handler.py
+++ b/src/duplicate_handler.py
@@ -13,16 +13,16 @@
from dataclasses import dataclass
from src import constants
from src.phash import (
- compute_hashes_batch,
+ compute_hashes_with_resolution,
find_duplicates,
- find_duplicates_from_paths,
+ group_hashes,
DuplicateGroup,
is_rust_available,
get_backend,
THRESHOLD_SIMILAR
)
from src.logger import logger
-from src.undo_manager import undo_manager
+from src.undo_manager import UndoManager
@dataclass
@@ -103,17 +103,15 @@ def emit(progress: int, message: str) -> None:
hash_started = time.perf_counter()
chunk_size = 256
total_chunks = (total_images + chunk_size - 1) // chunk_size
- hashes_fetched = 0
- hashed_paths: List[str] = []
+ # path -> (hash, resolution); each image is decoded exactly once here and
+ # the grouping stage below reuses these results.
+ hashes: dict[str, tuple[str, int]] = {}
for idx in range(total_chunks):
start = idx * chunk_size
end = min(start + chunk_size, total_images)
- chunk = image_paths[start:end]
- chunk_hashes = compute_hashes_batch(chunk)
-
- hashes_fetched += len(chunk_hashes)
- hashed_paths.extend(chunk_hashes.keys())
+ hashes.update(compute_hashes_with_resolution(image_paths[start:end]))
+ hashes_fetched = len(hashes)
percent = 21 + int(((idx + 1) / max(total_chunks, 1)) * 49)
emit(
@@ -121,9 +119,7 @@ def emit(progress: int, message: str) -> None:
f"Fetching hashes: {hashes_fetched}/{total_images} | Images found: {total_images}",
)
- # Remove duplicates while preserving order.
- hashed_paths = list(dict.fromkeys(hashed_paths))
- hashes_fetched = len(hashed_paths)
+ hashes_fetched = len(hashes)
hashing_seconds = time.perf_counter() - hash_started
hash_success_rate_pct = (hashes_fetched / total_images) * 100 if total_images else 0.0
images_without_hash = max(total_images - hashes_fetched, 0)
@@ -150,7 +146,7 @@ def emit(progress: int, message: str) -> None:
)
return []
- # Stage 3: run grouping on hashed candidates using existing Rust/Python engine.
+ # Stage 3: group the hashes computed above (no file access).
done = threading.Event()
progress_state = {"value": 71}
@@ -167,7 +163,7 @@ def progress_heartbeat() -> None:
heartbeat = threading.Thread(target=progress_heartbeat, daemon=True)
heartbeat.start()
try:
- groups = find_duplicates_from_paths(hashed_paths, threshold)
+ groups = group_hashes(hashes, threshold)
finally:
done.set()
heartbeat.join(timeout=1.0)
@@ -250,16 +246,21 @@ def handle_duplicates(
Returns:
DuplicateReport with statistics and details
"""
+ with UndoManager() as session:
+ return _handle_duplicates(source_dir, duplicates_dir, action, threshold, keep_best, session)
+
+
+def _handle_duplicates(source_dir, duplicates_dir, action, threshold, keep_best, undo_manager):
source_path = Path(source_dir)
- undo_manager.start_session()
-
# Find duplicates
groups = scan_for_duplicates(source_dir, threshold)
- # Calculate statistics
- total_scanned = sum(len(list(source_path.rglob(f'*{ext}')))
- for ext in ['.jpg', '.jpeg', '.png', '.heic', '.bmp', '.tiff', '.gif'])
+ # Calculate statistics (one walk; same extension rule as the scanner)
+ total_scanned = sum(
+ 1 for p in source_path.rglob('*')
+ if p.suffix.lower() in constants.IMAGE_EXTENSIONS and p.is_file()
+ )
total_duplicates = sum(len(g.paths) - 1 for g in groups) # -1 for keeping best
# Calculate recoverable space
@@ -327,7 +328,6 @@ def handle_duplicates(
logger.error(f"Error deleting {dup}: {e}")
report.errors += 1
- undo_manager.end_session()
return report
diff --git a/src/file_operations.py b/src/file_operations.py
new file mode 100644
index 0000000..1fa9364
--- /dev/null
+++ b/src/file_operations.py
@@ -0,0 +1,239 @@
+"""Verified local transfers with atomic, non-replacing publication.
+
+The final name is a hard link to a fully written and verified temporary file.
+Filesystems without hard-link support fail closed; no replacing fallback is used.
+Locks coordinate Clean_Backup operations, not unrelated editors or filesystem tools.
+"""
+
+from contextlib import contextmanager
+import hashlib
+import os
+from pathlib import Path
+import shutil
+import stat
+import tempfile
+import threading
+
+try:
+ import fcntl
+except ImportError:
+ # Windows still gets process-local locking and exclusive publication.
+ fcntl = None
+
+
+class FileConflictError(OSError):
+ """A source or recorded output no longer matches its expected revision."""
+
+
+_mutation_lock = threading.RLock()
+_held_locks = threading.local()
+
+
+@contextmanager
+def locked_paths(*paths):
+ """Serialize cooperating writers, including separate POSIX app processes."""
+ with _mutation_lock:
+ held = getattr(_held_locks, "paths", {})
+ _held_locks.paths = held
+ acquired = []
+ try:
+ for name in sorted(
+ {str(Path(p).absolute().parent.resolve() / Path(p).name) for p in paths}
+ ):
+ if name in held:
+ continue
+ lock_dir = (
+ Path(tempfile.gettempdir())
+ / f"clean-backup-locks-{getattr(os, 'getuid', lambda: 0)()}"
+ )
+ lock_dir.mkdir(mode=0o700, exist_ok=True)
+ lock_path = lock_dir / hashlib.sha256(name.encode()).hexdigest()
+ fd = os.open(
+ lock_path,
+ os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0),
+ 0o600,
+ )
+ try:
+ if fcntl:
+ fcntl.flock(fd, fcntl.LOCK_EX)
+ except BaseException:
+ os.close(fd)
+ raise
+ held[name] = fd
+ acquired.append(name)
+ yield
+ finally:
+ for name in reversed(acquired):
+ os.close(held.pop(name))
+
+
+def fsync_directory(path):
+ """Persist a directory entry after link, rename or unlink on POSIX."""
+ if os.name != "posix":
+ return
+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
+ try:
+ os.fsync(fd)
+ finally:
+ os.close(fd)
+
+
+def _revision(info):
+ return (info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns)
+
+
+def file_identity(path):
+ """Hash a regular file and refuse symlinks or a revision changed during reading."""
+ path = Path(path)
+ fd = os.open(
+ path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0)
+ )
+ with os.fdopen(fd, "rb") as stream:
+ before = os.fstat(stream.fileno())
+ if not stat.S_ISREG(before.st_mode):
+ raise FileConflictError(f"Not a regular file: {path}")
+ digest = hashlib.file_digest(stream, "sha256").hexdigest()
+ after = os.fstat(stream.fileno())
+ if _revision(before) != _revision(after) or _revision(after) != _revision(
+ path.lstat()
+ ):
+ raise FileConflictError(f"File changed while reading: {path}")
+ return dict(
+ zip(("device", "inode", "size", "mtime_ns", "ctime_ns"), _revision(after)),
+ sha256=digest,
+ )
+
+
+def require_identity(path, expected, *, published=False):
+ if not expected:
+ raise FileConflictError(f"No recorded file identity: {path}")
+ actual = file_identity(path)
+ # Linking/unlinking the staging name changes ctime. Pending journal intents
+ # still identify the exact inode and bytes even across that publication step.
+ keys = (
+ ("device", "inode", "size", "mtime_ns", "sha256")
+ if published
+ else expected.keys()
+ )
+ if any(actual.get(key) != expected.get(key) for key in keys):
+ raise FileConflictError(
+ f"File changed since the operation was recorded: {path}"
+ )
+ return actual
+
+
+def validate_roots(source, destination):
+ source, destination = Path(source).resolve(), Path(destination).resolve()
+ if not source.is_dir():
+ raise ValueError(f"Source directory not found: {source}")
+ if (
+ source == destination
+ or source in destination.parents
+ or destination in source.parents
+ ):
+ raise ValueError("Source and destination directories must not overlap")
+ return source, destination
+
+
+def _temporary_path(target, *, suffix=".partial"):
+ fd, name = tempfile.mkstemp(
+ prefix=".clean-backup-", suffix=suffix, dir=target.parent
+ )
+ os.close(fd)
+ return Path(name)
+
+
+def _publish(temporary, target):
+ # os.link is atomic and refuses all existing targets, including dangling links.
+ os.link(temporary, target, follow_symlinks=False)
+ fsync_directory(target.parent)
+
+
+def verified_transfer(
+ source, target, operation="copy", *, journal=None, collision="rename"
+):
+ """Copy, read back and publish; only then remove an unchanged Move source.
+
+ A journal, when supplied, persists intent before publication and completion
+ afterward. A failure after publication retains the verified output and its
+ pending intent for recovery rather than attempting a destructive rollback.
+ """
+ if operation not in {"copy", "move"} or collision not in {"rename", "error"}:
+ raise ValueError("Invalid transfer operation or collision policy")
+ source, target = Path(source).absolute(), Path(target).absolute()
+ if source.resolve() == target.resolve():
+ raise FileConflictError("Source and destination must differ")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ with locked_paths(source, target):
+ original = file_identity(source)
+ temporary = _temporary_path(target)
+ try:
+ shutil.copy2(source, temporary)
+ with temporary.open("rb") as stream:
+ os.fsync(stream.fileno())
+ copied = file_identity(temporary)
+ if (copied["size"], copied["sha256"]) != (
+ original["size"],
+ original["sha256"],
+ ):
+ raise FileConflictError(f"Copy verification failed: {source}")
+ require_identity(source, original)
+ candidate = target
+ counter = 0
+ while True:
+ entry = (
+ journal.prepare_action(
+ operation, source, candidate, original, copied
+ )
+ if journal
+ else None
+ )
+ try:
+ _publish(temporary, candidate)
+ break
+ except FileExistsError:
+ if journal:
+ journal.cancel_action(entry)
+ if collision == "error":
+ raise
+ counter += 1
+ tail = "" if counter == 1 else f"-{counter}"
+ candidate = target.with_name(
+ f"{target.stem}-{original['sha256'][:12]}{tail}{target.suffix}"
+ )
+ temporary.unlink()
+ # Read back once more under the final name before a Move can remove its source.
+ output_identity = require_identity(candidate, copied, published=True)
+ if operation == "move":
+ require_identity(source, original)
+ source.unlink()
+ fsync_directory(source.parent)
+ if journal:
+ journal.complete_action(entry, output_identity)
+ return candidate
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+@contextmanager
+def staged_output(source, target):
+ """Give an encoder private output space, then publish without replacement."""
+ source, target = Path(source).absolute(), Path(target).absolute()
+ if source.resolve() == target.resolve():
+ raise FileConflictError("Compression cannot overwrite its source")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ with locked_paths(source, target):
+ if os.path.lexists(target):
+ raise FileExistsError(f"Output already exists: {target}")
+ original = file_identity(source)
+ temporary = _temporary_path(target, suffix=f".partial{target.suffix}")
+ try:
+ yield temporary
+ with temporary.open("rb") as stream:
+ os.fsync(stream.fileno())
+ if not temporary.stat().st_size:
+ raise FileConflictError("Encoder produced an empty output")
+ require_identity(source, original)
+ _publish(temporary, target)
+ finally:
+ temporary.unlink(missing_ok=True)
diff --git a/src/metadata.py b/src/metadata.py
index 95d157c..3d2a334 100644
--- a/src/metadata.py
+++ b/src/metadata.py
@@ -1,29 +1,49 @@
import os
from datetime import datetime
+from pathlib import Path
from PIL import Image
-from PIL.ExifTags import TAGS
+from PIL.ExifTags import IFD
from pillow_heif import register_heif_opener
from hachoir.parser import createParser
from hachoir.metadata import extractMetadata
+from src import constants
from src.logger import logger
register_heif_opener()
+_DATETIME_ORIGINAL = 0x9003
+_DATETIME_DIGITIZED = 0x9004
+
+
+def _parse_exif_datetime(value):
+ """Parse EXIF "YYYY:MM:DD HH:MM:SS"; return None for absent or blank values."""
+ if isinstance(value, bytes):
+ value = value.decode("ascii", errors="ignore")
+ if not isinstance(value, str):
+ return None
+ try:
+ return datetime.strptime(value.strip("\x00 ")[:19], "%Y:%m:%d %H:%M:%S")
+ except ValueError:
+ return None
+
+
def get_image_date(file_path):
try:
with Image.open(file_path) as img:
exif_data = img.getexif()
if not exif_data:
return None
-
- # Look for datetime
- for tag_id, value in exif_data.items():
- tag_name = TAGS.get(tag_id, tag_id)
- if tag_name == 'DateTimeOriginal':
- # Format - "YYYY:MM:DD HH:MM:SS"
- return datetime.strptime(value, "%Y:%m:%d %H:%M:%S")
+
+ # Cameras store capture times in the Exif sub-IFD; a few writers
+ # put them in the top-level IFD, so check both.
+ exif_ifd = exif_data.get_ifd(IFD.Exif)
+ for tag_id in (_DATETIME_ORIGINAL, _DATETIME_DIGITIZED):
+ for ifd in (exif_ifd, exif_data):
+ parsed = _parse_exif_datetime(ifd.get(tag_id))
+ if parsed:
+ return parsed
except Exception as e:
logger.warning(f"Could not read EXIF for image {file_path}: {e}")
return None
@@ -45,4 +65,15 @@ def get_video_date(file_path):
#return current system DateTime is no DateTime is extracted or available
def get_file_modification_date(file_path):
- return datetime.fromtimestamp(os.path.getmtime(file_path))
\ No newline at end of file
+ return datetime.fromtimestamp(os.path.getmtime(file_path))
+
+
+def get_media_date(file_path):
+ """Capture date from image/video metadata, else the file's modification time."""
+ ext = Path(file_path).suffix.lower()
+ taken = None
+ if ext in constants.IMAGE_EXTENSIONS:
+ taken = get_image_date(str(file_path))
+ elif ext in constants.VIDEO_EXTENSIONS:
+ taken = get_video_date(str(file_path))
+ return taken or get_file_modification_date(str(file_path))
diff --git a/src/organiser.py b/src/organiser.py
index 64e9dfa..9deb3c0 100644
--- a/src/organiser.py
+++ b/src/organiser.py
@@ -1,92 +1,34 @@
-import shutil
-import re
from pathlib import Path
from collections import defaultdict
-from multiprocessing import Pool, cpu_count
+from concurrent.futures import ThreadPoolExecutor
+from multiprocessing import cpu_count
from tqdm import tqdm
from src import constants
from src.metadata import get_image_date, get_video_date, get_file_modification_date
from src.logger import logger
from src.phash import find_duplicates_from_paths, is_rust_available, THRESHOLD_SIMILAR
-from src.undo_manager import undo_manager
+from src.undo_manager import UndoManager
+from src.file_operations import file_identity, validate_roots, verified_transfer
def detect_name_based_duplicates(file_paths):
+ """Legacy API: return content-identical files, never infer identity from names.
+
+ Organization retains all inputs even when filename hints are requested. Use
+ duplicate review to decide whether a redundant copy should be omitted.
"""
- Detect duplicate files based on common naming patterns from various OS.
-
- Patterns detected:
- - Windows (Download): photo (1).jpg, photo (2).jpg
- - Generic: photo-1.jpg, photo_1.jpg
- - macOS (Duplicate): photo copy.jpg, photoCopy.jpg
- - Windows (Copy): Notes - Copy.txt
- - Linux (Nautilus): Data (copy).csv
- - macOS (Drag/Drop): Image 2.png, Image 3.png
-
- Args:
- file_paths: List of Path objects
-
- Returns:
- set: Paths that should be considered duplicates (keeps original without suffix)
- """
- duplicate_files = set()
- base_name_groups = defaultdict(list)
-
- # Regex patterns to detect duplicate suffixes (order matters - most specific first)
- patterns = [
- r'\s*\((\d+)\)$', # (1), (2) - Windows/Android/iOS downloads
- r'\s*\(copy\)$', # (copy) - Linux Nautilus
- r'\s*-\s*Copy(\d*)$', # - Copy, - Copy2 - Windows
- r'\s+copy(\d*)$', # copy, copy2 - macOS (space before)
- r'[-_]copy(\d*)$', # -copy, _copy - generic
- r'[-_]Copy(\d*)$', # -Copy, _Copy - generic
- r'[-_]COPY(\d*)$', # -COPY, _COPY - generic
- r'[-_](\d+)$', # -1, _1 - generic
- r'\s+(\d+)$', # (space)2, (space)3 - macOS drag/drop
- ]
-
- # Examples of matched patterns:
- # "Installer (1).exe" → base: "Installer.exe"
- # "Data (copy).csv" → base: "Data.csv"
- # "Notes - Copy.txt" → base: "Notes.txt"
- # "Image copy.png" → base: "Image.png"
- # "Photo_1.jpg" → base: "Photo.jpg"
- # "Image 2.png" → base: "Image.png"
-
- for file_path in file_paths:
- if not file_path.is_file():
+ seen = {}
+ duplicates = set()
+ for path in file_paths:
+ path = Path(path)
+ if not path.is_file() or path.is_symlink():
continue
-
- stem = file_path.stem # filename without extension
- suffix = file_path.suffix
-
- # Try to extract base name by removing duplicate suffixes
- base_name = stem
- is_duplicate = False
-
- for pattern in patterns:
- match = re.search(pattern, stem, re.IGNORECASE)
- if match:
- # Remove the duplicate suffix to get base name
- base_name = re.sub(pattern, '', stem, flags=re.IGNORECASE)
- is_duplicate = True
- break
-
- # Group files by base name + extension
- key = f"{base_name}{suffix}".lower()
- base_name_groups[key].append((file_path, is_duplicate, stem))
-
- # Analyze groups to find duplicates
- for base_key, files in base_name_groups.items():
- if len(files) > 1:
- # Sort: originals (no suffix) first, then by name
- files.sort(key=lambda x: (x[1], x[2])) # (is_duplicate, stem)
-
- # Keep the first file (original without suffix), mark rest as duplicates
- for file_path, is_dup, stem in files[1:]:
- duplicate_files.add(file_path)
- logger.info(f"Name-based duplicate detected: {file_path.name} (base: {base_key})")
-
- return duplicate_files
+ identity = file_identity(path)
+ key = (identity["size"], identity["sha256"])
+ if key in seen:
+ duplicates.add(path)
+ else:
+ seen[key] = path
+ return duplicates
def _process_single_file(args):
@@ -99,7 +41,8 @@ def _process_single_file(args):
Returns:
dict: Result dictionary with status, file info, and statistics
"""
- file_path, dest_path, operation, duplicate_files, name_duplicate_files = args
+ file_path, dest_path, operation, duplicate_files, name_duplicate_files = args[:5]
+ journal = args[5] if len(args) > 5 else None
result = {
'status': 'skipped',
@@ -112,13 +55,6 @@ def _process_single_file(args):
}
try:
- # Skip name-based duplicates
- if name_duplicate_files and file_path in name_duplicate_files:
- result['status'] = 'skipped'
- result['reason'] = 'name_duplicate'
- logger.info(f"Skipping name-based duplicate: {file_path.name}")
- return result
-
# Skip perceptual duplicates (use absolute path for comparison)
if duplicate_files and file_path.resolve() in duplicate_files:
result['status'] = 'skipped'
@@ -163,21 +99,9 @@ def _process_single_file(args):
target_file = target_folder / file_path.name
- # Check if file already exists
- if target_file.exists():
- result['status'] = 'skipped'
- result['reason'] = 'duplicate_filename'
- logger.info(f"Skipped duplicate: {file_path.name} already exists in {target_folder}")
- return result
-
- # Move or copy file
- if operation == 'copy':
- shutil.copy2(str(file_path), str(target_file))
- logger.info(f"Copied: {file_path.name} -> {target_folder}")
- else:
- shutil.move(str(file_path), str(target_file))
- logger.info(f"Moved: {file_path.name} -> {target_folder}")
-
+ target_file = verified_transfer(file_path, target_file, operation, journal=journal)
+ logger.info(f"Verified {operation}: {file_path.name} -> {target_file}")
+
result['status'] = 'success'
result['folder_key'] = folder_key
result['source'] = file_path
@@ -210,14 +134,13 @@ def organise_files(
operation: 'move' or 'copy'
check_duplicates: If True, detect and skip duplicate images before organizing (perceptual hashing)
duplicate_threshold: Hamming distance threshold for duplicate detection
- check_name_duplicates: If True, detect and skip files with duplicate naming patterns (e.g., photo(1).jpg)
+ check_name_duplicates: Legacy option; named variants are retained for content review
progress_callback: Optional callback(completed, total, result_dict) invoked per processed file
target_files: Optional list of specific absolute file paths to organize. If provided, only these files are processed.
"""
- src_path = Path(src_dir)
- dest_path = Path(dest_dir)
-
- undo_manager.start_session()
+ if operation not in {"copy", "move"}:
+ raise ValueError("operation must be copy or move")
+ src_path, dest_path = validate_roots(src_dir, dest_dir)
# Statistics tracking
stats = {
@@ -234,19 +157,18 @@ def organise_files(
}
# Gather files
- if target_files:
- all_files = [Path(f) for f in target_files]
+ if target_files is not None:
+ all_files = [Path(f).absolute() for f in target_files]
+ if any(p.is_symlink() or src_path not in p.resolve().parents for p in all_files):
+ raise ValueError("target_files must be regular files inside the source directory")
else:
all_files = list(src_path.rglob('*'))
- # Name-based duplicate detection (if enabled)
+ # Filename resemblance never authorizes omitting an input.
name_duplicate_files = set()
if check_name_duplicates:
- logger.info("Scanning for name-based duplicates (e.g., photo(1).jpg)...")
- name_duplicate_files = detect_name_based_duplicates(all_files)
- stats['name_duplicates'] = len(name_duplicate_files)
- logger.info(f"Found {len(name_duplicate_files)} name-based duplicates")
-
+ logger.info("Filename hints no longer skip inputs; retaining all named variants")
+
# Perceptual duplicate detection (if enabled)
duplicate_files = set() # Files to skip due to perceptual duplication
if check_duplicates:
@@ -299,13 +221,12 @@ def organise_files(
# Collect all files to process
file_list = []
for file_path in all_files:
- if file_path.is_file():
+ if file_path.is_file() and not file_path.is_symlink():
stats['total_scanned'] += 1
file_list.append(file_path)
if not file_list:
logger.info("No files found to process")
- undo_manager.end_session()
if progress_callback:
try:
progress_callback(0, 0, None)
@@ -313,33 +234,25 @@ def organise_files(
pass
return stats
- # Determine number of workers (leave 1 core free)
- num_workers = max(1, cpu_count() - 1)
- logger.info(f"Using {num_workers} worker processes for parallel file organization")
- print(f"\n🚀 Processing {len(file_list)} files with {num_workers} workers...")
-
- # Prepare arguments for worker function
- worker_args = [
- (file_path, dest_path, operation, duplicate_files if check_duplicates else None,
- name_duplicate_files if check_name_duplicates else None)
- for file_path in file_list
- ]
-
- # Process files in parallel with progress bar
+ num_workers = min(8, max(1, cpu_count() - 1), len(file_list))
results = []
total_files = len(file_list)
- with Pool(processes=num_workers) as pool:
- for completed, result in enumerate(tqdm(pool.imap(_process_single_file, worker_args),
- total=total_files,
- desc="Organizing files",
- unit="file"), 1):
- results.append(result)
- if progress_callback:
- try:
+ # Threads share one explicitly scoped journal; no forked singleton state.
+ with UndoManager() as journal:
+ worker_args = [
+ (p, dest_path, operation, duplicate_files if check_duplicates else None,
+ name_duplicate_files, journal)
+ for p in file_list
+ ]
+ with ThreadPoolExecutor(max_workers=num_workers) as pool:
+ for completed, result in enumerate(tqdm(
+ pool.map(_process_single_file, worker_args), total=total_files,
+ desc="Organizing files", unit="file",
+ ), 1):
+ results.append(result)
+ if progress_callback:
progress_callback(completed, total_files, result)
- except Exception:
- pass
-
+
# Aggregate results and update statistics
for result in results:
# Track file types
@@ -356,8 +269,6 @@ def organise_files(
if result['folder_key']:
stats['folders_created'][result['folder_key']] += 1
- # Log to undo manager
- undo_manager.log_action(operation, result['source'], result['destination'])
elif result['status'] == 'skipped':
if result['reason'] == 'duplicate_filename':
@@ -367,7 +278,6 @@ def organise_files(
elif result['status'] == 'error':
stats['errors'] += 1
- undo_manager.end_session()
return stats
diff --git a/src/phash.py b/src/phash.py
index f5e0476..80cd41f 100644
--- a/src/phash.py
+++ b/src/phash.py
@@ -17,7 +17,7 @@
"""
from pathlib import Path
-from typing import List, Dict, Optional
+from typing import List, Dict, Optional, Tuple
from dataclasses import dataclass
from src.logger import logger
from src import constants
@@ -223,6 +223,65 @@ def compute_hashes_batch(
return result
+def _python_resolution(path: str) -> int:
+ try:
+ from PIL import Image
+
+ with Image.open(path) as img:
+ return img.size[0] * img.size[1]
+ except Exception:
+ return 0
+
+
+def compute_hashes_with_resolution(paths: List[str]) -> Dict[str, Tuple[str, int]]:
+ """
+ Hash images and read their pixel counts, decoding each file once.
+
+ Pair with ``group_hashes`` to scan in batches (for progress reporting)
+ without hashing any image a second time.
+
+ Returns:
+ Dictionary mapping each decodable path to ``(hash, width * height)``
+ """
+ if _USE_RUST and hasattr(_phash, "compute_hashes_with_resolution"):
+ try:
+ return _phash.compute_hashes_with_resolution(paths)
+ except Exception as e:
+ logger.error(f"Batch hashing failed: {e}")
+
+ return {
+ path: (h, _python_resolution(path))
+ for path, h in compute_hashes_batch(paths).items()
+ }
+
+
+def group_hashes(
+ hashes: Dict[str, Tuple[str, int]],
+ threshold: int = THRESHOLD_SIMILAR
+) -> List[DuplicateGroup]:
+ """
+ Group already-hashed images into duplicate sets without reading any file.
+
+ Args:
+ hashes: Mapping of path to ``(hash, resolution)``
+ threshold: Maximum Hamming distance
+ """
+ if _USE_RUST and hasattr(_phash, "group_hashes"):
+ try:
+ raw_groups = _phash.group_hashes(
+ [(path, h, res) for path, (h, res) in hashes.items()], threshold
+ )
+ return [
+ DuplicateGroup(paths=g["paths"], hash=g["hash"], best=g["best"])
+ for g in raw_groups
+ ]
+ except Exception as e:
+ logger.error(f"Rust duplicate grouping failed: {e}")
+ logger.info("Falling back to Python implementation")
+
+ return _python_group([(path, h, res) for path, (h, res) in hashes.items()], threshold)
+
+
# ============================================================================
# Pure Python Fallback Implementation
# ============================================================================
@@ -235,8 +294,8 @@ def _python_compute_hash(
try:
from PIL import Image
- img = Image.open(path).convert('L') # Grayscale
- return _python_phash(img, hash_size)
+ with Image.open(path) as source:
+ return _python_phash(source.convert('L'), hash_size) # Grayscale
except Exception as e:
logger.debug(f"Python hash failed for {path}: {e}")
return None
@@ -324,20 +383,20 @@ def _python_find_duplicates(
threshold: int
) -> List[DuplicateGroup]:
"""Pure Python duplicate finder (fallback)."""
- from PIL import Image
-
- # Compute hashes
image_data = []
for path in paths:
h = _python_compute_hash(path)
if h:
- try:
- with Image.open(path) as img:
- res = img.size[0] * img.size[1]
- except Exception:
- res = 0
- image_data.append((path, h, res))
-
+ image_data.append((path, h, _python_resolution(path)))
+
+ return _python_group(image_data, threshold)
+
+
+def _python_group(
+ image_data: List[Tuple[str, str, int]],
+ threshold: int
+) -> List[DuplicateGroup]:
+ """Group ``(path, hash, resolution)`` records by Hamming distance."""
if not image_data:
return []
diff --git a/src/undo_manager.py b/src/undo_manager.py
index d31273d..6e71712 100644
--- a/src/undo_manager.py
+++ b/src/undo_manager.py
@@ -1,168 +1,372 @@
+"""Durable local operation journals and conflict-aware, retryable undo.
+
+A journal is an append-only log, one JSON record per line. A record is either
+a full action (it has an ``id`` and an ``action``) or an update to an earlier
+action (``{"_update": , ...changed fields}``; a ``null`` value removes the
+field). Each state change is one fsynced append, so journaling a session costs
+time proportional to its length rather than to its square. A final line cut
+short by a crash was never durable and is ignored. Journals written by earlier
+versions as a single JSON array remain readable.
+"""
+
+from datetime import datetime
import json
import os
-import shutil
from pathlib import Path
-from datetime import datetime
+import tempfile
+import threading
+import uuid
+
+from src.file_operations import (
+ FileConflictError,
+ fcntl,
+ file_identity,
+ fsync_directory,
+ locked_paths,
+ require_identity,
+ verified_transfer,
+)
from src.logger import logger
JOURNAL_DIR = Path("logs/undo_journals")
+
+# Fields that change after an action is first recorded.
+_MUTABLE_FIELDS = ("state", "output_identity", "restore_identity", "undo_phase", "error")
+
+
+def _line(record):
+ return json.dumps(record, separators=(",", ":")) + "\n"
+
+
+def _update_record(entry):
+ """The current mutable fields of *entry*; absent ones are recorded as removed."""
+ return {"_update": entry["id"], **{key: entry.get(key) for key in _MUTABLE_FIELDS}}
+
+
+def _parse_journal(text):
+ """Return ``(actions, appendable)`` for a journal's text."""
+ if text.lstrip().startswith("["):
+ actions = json.loads(text) # Earlier single-array format.
+ if not isinstance(actions, list) or not all(isinstance(a, dict) for a in actions):
+ raise ValueError("Malformed journal")
+ return actions, False
+
+ actions, by_id = [], {}
+ *complete, tail = text.split("\n")
+ for line in complete:
+ if not line.strip():
+ continue
+ record = json.loads(line)
+ if not isinstance(record, dict):
+ raise ValueError("Malformed journal record")
+ if "_update" in record:
+ entry = by_id.get(record.pop("_update"))
+ if entry is None:
+ raise ValueError("Journal update refers to an unknown action")
+ for key, value in record.items():
+ if value is None:
+ entry.pop(key, None)
+ else:
+ entry[key] = value
+ else:
+ actions.append(record)
+ if "id" in record:
+ by_id[record["id"]] = record
+ # A non-empty tail is a record whose append was interrupted: not durable.
+ appendable = not tail and len(by_id) == len(actions)
+ return actions, appendable
+
+
+def load_journal(path):
+ """Read a journal's actions with every recorded update applied."""
+ return _parse_journal(Path(path).read_text())[0]
+
+
+def _write_journal(path, actions):
+ """Atomically replace a journal; never truncate its only durable copy."""
+ fd, name = tempfile.mkstemp(prefix=".journal-", suffix=".tmp", dir=path.parent)
+ temporary = Path(name)
+ try:
+ with os.fdopen(fd, "w") as stream:
+ stream.writelines(_line(action) for action in actions)
+ stream.flush()
+ os.fsync(stream.fileno())
+ os.replace(temporary, path)
+ fsync_directory(path.parent)
+ finally:
+ temporary.unlink(missing_ok=True)
+
+
+def _append_journal(path, records):
+ """Durably append records to an existing journal."""
+ data = "".join(_line(record) for record in records).encode()
+ fd = os.open(path, os.O_WRONLY | os.O_APPEND | getattr(os, "O_NOFOLLOW", 0))
+ try:
+ while data:
+ data = data[os.write(fd, data):]
+ os.fsync(fd)
+ finally:
+ os.close(fd)
+
+
+def _session_lock(path):
+ fd = os.open(
+ str(path) + ".lock",
+ os.O_CREAT | os.O_RDWR | getattr(os, "O_NOFOLLOW", 0),
+ 0o600,
+ )
+ try:
+ if fcntl:
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ return fd
+ except BaseException:
+ os.close(fd)
+ raise
+
+
class UndoManager:
- def __init__(self):
+ def __init__(self, journal_dir=None):
+ self._journal_dir = Path(journal_dir) if journal_dir is not None else None
self.session_id = None
self.journal_path = None
self.actions = []
- JOURNAL_DIR.mkdir(parents=True, exist_ok=True)
+ self._unsaved = [] # Records not yet durable in the journal file.
+ self._lock = threading.RLock()
+ self._session_fd = None
+
+ def __enter__(self):
+ self.start_session()
+ return self
+
+ def __exit__(self, *exc):
+ self.end_session()
+
+ @property
+ def journal_dir(self):
+ return (self._journal_dir or JOURNAL_DIR).absolute()
def start_session(self):
- """Start a new transaction session."""
- self.session_id = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
- self.journal_path = JOURNAL_DIR / f"journal_{self.session_id}.json"
- self.actions = []
- logger.info(f"Started undo session: {self.session_id}")
+ with self._lock:
+ if self.session_id is not None:
+ raise RuntimeError("An undo session is already active on this manager")
+ self.journal_dir.mkdir(parents=True, exist_ok=True)
+ self.session_id = (
+ datetime.now().strftime("%Y-%m-%d_%H-%M-%S-%f") + "_" + uuid.uuid4().hex
+ )
+ self.journal_path = self.journal_dir / f"journal_{self.session_id}.json"
+ self.actions = []
+ self._unsaved = []
+ self._session_fd = _session_lock(self.journal_path)
+ try:
+ _write_journal(self.journal_path, [])
+ except BaseException:
+ self.end_session()
+ raise
+ return self.session_id
+
+ def _save_journal(self):
+ """Make every recorded change durable; a failure leaves it queued."""
+ if self.journal_path is None:
+ raise RuntimeError("No active journal")
+ if self._unsaved:
+ _append_journal(self.journal_path, self._unsaved)
+ self._unsaved = []
+
+ def prepare_action(self, action, src, dst, source_identity, output_identity):
+ """Record intent before a verified temporary output is published."""
+ with self._lock:
+ if self.session_id is None:
+ raise RuntimeError("No active undo session")
+ entry = {
+ "id": uuid.uuid4().hex,
+ "action": action,
+ "src": str(Path(src).absolute()),
+ "dst": str(Path(dst).absolute()),
+ "source_identity": source_identity,
+ "output_identity": output_identity,
+ "state": "prepared",
+ "timestamp": datetime.now().isoformat(),
+ }
+ self.actions.append(entry)
+ self._unsaved.append(dict(entry))
+ self._save_journal() # An error propagates and prevents publication.
+ return entry
+
+ def cancel_action(self, entry):
+ with self._lock:
+ entry["state"] = "cancelled"
+ self._unsaved.append(_update_record(entry))
+ self._save_journal()
+
+ def complete_action(self, entry, output_identity):
+ with self._lock:
+ entry["output_identity"] = output_identity
+ entry["state"] = "completed"
+ self._unsaved.append(_update_record(entry))
+ self._save_journal()
def log_action(self, action_type, src, dst):
- """Log a file operation.
-
- Args:
- action_type (str): 'move' or 'copy'
- src (str): Source path
- dst (str): Destination path
+ """Compatibility for older callers; new transfers must record intent first.
+
+ Old path-only journals remain readable, but undo refuses them because they
+ cannot prove ownership of the current file. Missing outputs are recorded
+ as unresolved rather than later acquiring an unrelated file's identity.
"""
- if not self.session_id:
- return # No active session
-
- entry = {
- "action": action_type,
- "src": str(src),
- "dst": str(dst),
- "timestamp": datetime.now().isoformat()
- }
- self.actions.append(entry)
-
- # Write to disk immediately for crash safety (append mode would be better in production, but JSON list is simple)
- self._save_journal()
-
- def _cleanup_empty_dirs(self, directory):
- """Recursively delete empty directories up the tree."""
- path = Path(directory)
+ if self.session_id is None:
+ raise RuntimeError("No active undo session")
try:
- # Stop if we reach root or get a permission error
- while path.is_dir() and path != path.parent:
- if not any(path.iterdir()):
- path.rmdir()
- logger.info(f"Cleanup: Deleted empty directory {path}")
- path = path.parent
- else:
- break
- except Exception:
- # Stops bubbling up if duplicate_handler or other process is using the dir, or permission denied
- pass
-
- def _save_journal(self):
+ identity = file_identity(dst)
+ except OSError:
+ identity = None
try:
- with open(self.journal_path, 'w') as f:
- json.dump(self.actions, f, indent=4)
- except Exception as e:
- logger.error(f"Failed to save undo journal: {e}")
+ source_identity = file_identity(src)
+ except OSError:
+ source_identity = None
+ entry = self.prepare_action(action_type, src, dst, source_identity, identity)
+ self.complete_action(entry, identity)
def end_session(self):
- """Close the current session."""
- if self.actions:
- logger.info(f"Ended undo session {self.session_id} with {len(self.actions)} actions.")
- else:
- # Cleanup empty journal
- if self.journal_path and self.journal_path.exists():
- os.remove(self.journal_path)
-
- self.session_id = None
- self.actions = []
- self.journal_path = None
+ with self._lock:
+ try:
+ if self.journal_path and not self.actions:
+ self.journal_path.unlink(missing_ok=True)
+ finally:
+ if self._session_fd is not None:
+ os.close(self._session_fd)
+ self._session_fd = None
+ self.session_id = None
+ self.actions = []
+ self._unsaved = []
+ self.journal_path = None
def list_sessions(self):
- """List available undo sessions."""
- files = sorted(JOURNAL_DIR.glob("journal_*.json"), reverse=True)
sessions = []
- for p in files:
+ for path in sorted(self.journal_dir.glob("journal_*.json"), reverse=True):
+ fd = None
try:
- # filename format: journal_YYYY-MM-DD_HH-MM-SS.json
- # session_id matches the timestamp part
- sid = p.stem.replace("journal_", "")
- with open(p, 'r') as f:
- data = json.load(f)
- count = len(data)
- sessions.append({"id": sid, "path": p, "count": count})
- except Exception:
+ fd = _session_lock(path)
+ actions = load_journal(path)
+ count = sum(
+ a.get("state") not in {"undone", "cancelled"} for a in actions
+ )
+ if count:
+ sessions.append(
+ {
+ "id": path.stem.removeprefix("journal_"),
+ "path": path,
+ "count": count,
+ }
+ )
+ except (OSError, ValueError, TypeError):
continue
+ finally:
+ if fd is not None:
+ os.close(fd)
return sessions
+ @staticmethod
+ def _check_copy_survivor(entry):
+ identity = file_identity(entry["src"])
+ expected = entry.get("source_identity") or entry.get("output_identity")
+ if not expected or any(identity[k] != expected[k] for k in ("sha256", "size")):
+ raise FileConflictError(
+ "The original copy source is missing or changed; retaining the output"
+ )
+
+ def _undo_entry(self, entry, save):
+ action, src, dst = entry["action"], Path(entry["src"]), Path(entry["dst"])
+ expected = entry.get("output_identity")
+ if action not in {"copy", "move"} or not expected:
+ raise FileConflictError(
+ "Journal has no supported, verified output identity; manual review required"
+ )
+ with locked_paths(src, dst):
+ if not os.path.lexists(dst):
+ if entry.get("undo_phase") == "removing":
+ if action == "copy":
+ self._check_copy_survivor(entry)
+ else:
+ require_identity(src, entry["restore_identity"])
+ return
+ if entry.get("state") == "prepared":
+ require_identity(src, entry["source_identity"])
+ return # The intent was written but no final output was published.
+ raise FileConflictError(f"Recorded output is missing: {dst}")
+ require_identity(dst, expected, published=entry.get("state") == "prepared")
+ if action == "copy":
+ self._check_copy_survivor(entry)
+ elif os.path.lexists(src):
+ if entry.get("restore_identity"):
+ require_identity(src, entry["restore_identity"])
+ elif entry.get("state") == "prepared":
+ require_identity(src, entry["source_identity"])
+ else:
+ raise FileConflictError(
+ f"Restore path is occupied; retaining both files: {src}"
+ )
+ else:
+ restored = verified_transfer(dst, src, "copy", collision="error")
+ entry["restore_identity"] = file_identity(restored)
+ save()
+ entry["undo_phase"] = "removing"
+ save() # A retry can distinguish an interrupted undo from a missing file.
+ if action == "copy":
+ self._check_copy_survivor(entry)
+ else:
+ require_identity(
+ src, entry.get("restore_identity") or entry["source_identity"]
+ )
+ require_identity(dst, expected, published=entry.get("state") == "prepared")
+ dst.unlink()
+ fsync_directory(dst.parent)
+
def undo_session(self, session_path):
- """Revert a specific session."""
- logger.info(f"Reverting session from {session_path}")
+ path = Path(session_path).absolute()
+ fd = None
try:
- with open(session_path, 'r') as f:
- actions = json.load(f)
- except Exception as e:
- logger.error(f"Could not read journal file: {e}")
- return False
+ fd = _session_lock(path)
+ actions, appendable = _parse_journal(path.read_text())
- success_count = 0
- fail_count = 0
+ def persist(entry):
+ nonlocal appendable
+ if appendable:
+ _append_journal(path, [_update_record(entry)])
+ return
+ # Earlier array format, or a record cut short by a crash:
+ # rewrite once as a clean log, then append from there on.
+ for action in actions:
+ action.setdefault("id", uuid.uuid4().hex)
+ _write_journal(path, actions)
+ appendable = True
- # Reverse order to undo correctly
- for entry in reversed(actions):
- action = entry.get("action")
- src = entry.get("src") # This was the ORIGINAL source
- dst = entry.get("dst") # This was the destination
+ for entry in reversed(actions):
+ if entry.get("state") in {"undone", "cancelled"}:
+ continue
+
+ def save(entry=entry):
+ persist(entry)
+
+ try:
+ self._undo_entry(entry, save)
+ entry["state"] = "undone"
+ entry.pop("error", None)
+ save()
+ except Exception as exc:
+ logger.error("Undo conflict for %s: %s", entry.get("dst"), exc)
+ entry["error"] = str(exc)
+ save()
+ if any(a.get("state") not in {"undone", "cancelled"} for a in actions):
+ return False
+ os.replace(path, str(path) + ".reverted")
+ fsync_directory(path.parent)
+ return True
+ except (OSError, ValueError, TypeError) as exc:
+ logger.error("Could not revert journal %s: %s", path, exc)
+ return False
+ finally:
+ if fd is not None:
+ os.close(fd)
- try:
- if action == "move":
- # Undo move: Move dst back to src
- if os.path.exists(dst):
- # Ensure src directory exists
- os.makedirs(os.path.dirname(src), exist_ok=True)
- shutil.move(dst, src)
- logger.info(f"Undo Move: {dst} -> {src}")
- success_count += 1
-
- # Cleanup empty directories at destination
- self._cleanup_empty_dirs(os.path.dirname(dst))
- else:
- logger.warning(f"Undo failed: File not found at {dst}")
- fail_count += 1
-
- elif action == "copy":
- # Undo copy: Delete dst
- if os.path.exists(dst):
- os.remove(dst)
- logger.info(f"Undo Copy: Deleted {dst}")
- success_count += 1
-
- # Cleanup empty directories at destination
- self._cleanup_empty_dirs(os.path.dirname(dst))
- else:
- logger.warning(f"Undo failed: File not found at {dst}")
- fail_count += 1
- # Note: we don't strictly need to do anything to 'src' for a copy undo,
- # as it is essentially "delete the copy".
-
- except Exception as e:
- logger.error(f"Error undoing action {entry}: {e}")
- fail_count += 1
-
- print("\nUndo Complete.")
- print(f"Successfully reverted: {success_count} files")
- print(f"Failed to revert: {fail_count} files")
-
- # Rename journal to indicate it's undone (or delete it?)
- # Let's rename it to .undone
- try:
- new_path = str(session_path) + ".reverted"
- os.rename(session_path, new_path)
- logger.info("Marked journal as reverted.")
- except OSError:
- pass
-
- return True
undo_manager = UndoManager()
diff --git a/src/watcher/api.py b/src/watcher/api.py
index 2b1bb47..cac4f66 100644
--- a/src/watcher/api.py
+++ b/src/watcher/api.py
@@ -63,8 +63,13 @@ def update_watcher(config_id: int):
if blocked:
return blocked
- payload = request.get_json(silent=True) or {}
- success = db.update_config(config_id, **payload)
+ payload = request.get_json(silent=True)
+ if not isinstance(payload, dict):
+ return jsonify({"ok": False, "error": "A JSON object is required"}), 400
+ try:
+ success = db.update_config(config_id, **payload)
+ except ValueError as exc:
+ return jsonify({"ok": False, "error": str(exc)}), 400
if not success:
return jsonify({"ok": False, "error": "Watcher not found"}), 404
diff --git a/src/watcher/db.py b/src/watcher/db.py
index 8152d9f..9c0f23c 100644
--- a/src/watcher/db.py
+++ b/src/watcher/db.py
@@ -139,10 +139,21 @@ def add_config(
return cur.lastrowid
+# Column names are interpolated into SQL, so only these may be updated.
+UPDATABLE_FIELDS = frozenset({
+ "label", "watch_path", "recursive", "stability_window_seconds",
+ "ignore_patterns", "pipeline", "on_complete", "on_error", "enabled",
+})
+
+
def update_config(config_id: int, **kwargs: Any) -> bool:
if not kwargs:
return True
-
+
+ unknown = set(kwargs) - UPDATABLE_FIELDS
+ if unknown:
+ raise ValueError(f"Unknown watcher fields: {sorted(map(str, unknown))}")
+
set_clauses = []
values = []
for k, v in kwargs.items():
diff --git a/src/web_app.py b/src/web_app.py
index 0799587..72cf376 100644
--- a/src/web_app.py
+++ b/src/web_app.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import io
+import ipaddress
import os
import subprocess
import sys
@@ -11,17 +12,21 @@
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Callable
+from urllib.parse import urlsplit
from flask import Flask, jsonify, request, send_file, send_from_directory
+from markupsafe import escape
from PIL import Image
from src.compressor import compress_files, get_compression_settings
from src.config import get_threshold, load_config, save_config
+from src.constants import IMAGE_EXTENSIONS
from src.duplicate_handler import scan_for_duplicates_with_progress
from src.logger import logger
from src.organiser import organise_files
from src.phash import get_backend
-from src.undo_manager import undo_manager
+from src.file_operations import verified_transfer
+from src.undo_manager import UndoManager, undo_manager
from src.demo import demo_guard, is_demo_mode
# Classification module
@@ -83,15 +88,29 @@ class JobRecord:
class JobManager:
+ # Finished jobs keep their full result payload, so retain only recent ones.
+ MAX_FINISHED_JOBS = 50
+
def __init__(self) -> None:
self._lock = threading.Lock()
self._jobs: dict[str, JobRecord] = {}
+ def _prune_finished(self) -> None:
+ finished = [
+ job for job in self._jobs.values() if job.status in {"completed", "failed"}
+ ]
+ excess = len(finished) - self.MAX_FINISHED_JOBS
+ if excess > 0:
+ finished.sort(key=lambda job: job.updated_at)
+ for job in finished[:excess]:
+ del self._jobs[job.id]
+
def submit(self, kind: str, task_fn: Callable[..., dict[str, Any]], *args: Any, **kwargs: Any) -> str:
job_id = uuid.uuid4().hex
now = time.time()
with self._lock:
+ self._prune_finished()
self._jobs[job_id] = JobRecord(
id=job_id,
kind=kind,
@@ -166,6 +185,27 @@ def _add_allowed_root(root: Path) -> None:
_allowed_roots.add(root)
+def _demo_media_root() -> Path:
+ return Path(os.environ.get("CLEAN_BACKUP_MEDIA_PATH", "/data/media")).resolve()
+
+
+def _resolve_source_dir(raw_path: str) -> Path:
+ """Resolve a directory a job may read, and remember it as an allowed root.
+
+ The public demo has no per-user isolation, so there it may only read the
+ seeded media directory rather than any directory on the host.
+ """
+ source = Path(raw_path).expanduser().resolve()
+ if is_demo_mode():
+ root = _demo_media_root()
+ if source != root and root not in source.parents:
+ raise PermissionError("The demo can only read its sample media folder")
+ if not source.is_dir():
+ raise ValueError(f"Source directory not found: {source}")
+ _add_allowed_root(source)
+ return source
+
+
def _is_allowed(path: Path) -> bool:
path = path.resolve()
with _allowed_roots_lock:
@@ -235,11 +275,7 @@ def _image_payload(path: Path, is_best: bool) -> dict[str, Any]:
def _scan_duplicates_task(progress: Callable[[int, str], None], source_dir: str, threshold: int) -> dict[str, Any]:
- source = Path(source_dir).expanduser().resolve()
- if not source.exists() or not source.is_dir():
- raise ValueError(f"Source directory not found: {source}")
-
- _add_allowed_root(source)
+ source = _resolve_source_dir(source_dir)
scan_started = time.perf_counter()
scan_stats: dict[str, float | int] = {}
@@ -330,13 +366,8 @@ def _organize_task(
duplicate_threshold: int,
check_name_duplicates: bool,
) -> dict[str, Any]:
- source = Path(source_dir).expanduser().resolve()
+ source = _resolve_source_dir(source_dir)
destination = Path(destination_dir).expanduser().resolve()
-
- if not source.exists() or not source.is_dir():
- raise ValueError(f"Source directory not found: {source}")
-
- _add_allowed_root(source)
_add_allowed_root(destination)
progress(10, "Running organize workflow")
@@ -388,13 +419,8 @@ def _compress_task(
level: int,
file_types: str,
) -> dict[str, Any]:
- source = Path(source_dir).expanduser().resolve()
+ source = _resolve_source_dir(source_dir)
output = Path(output_dir).expanduser().resolve()
-
- if not source.exists() or not source.is_dir():
- raise ValueError(f"Source directory not found: {source}")
-
- _add_allowed_root(source)
_add_allowed_root(output)
progress(10, "Running compression workflow")
@@ -433,7 +459,8 @@ def compression_progress(completed: int, total: int, file_path: Any, success: bo
def _trash_target_for(path: Path) -> Path:
timestamp = int(time.time())
relative = path.as_posix().replace("/", "__")
- return TRASH_ROOT / f"{timestamp}_{relative}"
+ # Long paths would exceed the 255-byte filename limit once flattened.
+ return TRASH_ROOT / f"{timestamp}_{relative[-180:]}"
def _run_picker_command(
@@ -579,11 +606,63 @@ def _pick_folder_native(initial_dir: str | None = None) -> Path | None:
return _pick_folder_tkinter(start_dir)
+_LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
+
+
+def _allowed_hosts() -> set[str]:
+ """Extra hostnames this server may be addressed by, besides loopback and IPs."""
+ names = os.environ.get("CLEAN_BACKUP_ALLOWED_HOSTS", "").split(",")
+ # Render sets this for its public URL; the hosted demo needs no extra setup.
+ names.append(os.environ.get("RENDER_EXTERNAL_HOSTNAME", ""))
+ return {name.strip().lower() for name in names if name.strip()}
+
+
+def _host_is_trusted(hostname: str | None) -> bool:
+ if not hostname:
+ return False
+ hostname = hostname.lower()
+ if hostname in _LOOPBACK_HOSTS or hostname.endswith(".localhost"):
+ return True
+ allowed = _allowed_hosts()
+ if "*" in allowed or hostname in allowed:
+ return True
+ try:
+ # An IP literal cannot be re-pointed by an attacker's DNS record.
+ ipaddress.ip_address(hostname)
+ return True
+ except ValueError:
+ return False
+
+
+@app.before_request
+def _reject_untrusted_requests():
+ """The API has no login, so only the app's own pages may drive it.
+
+ * An unexpected Host header means the browser reached us through someone
+ else's DNS name (DNS rebinding); refuse it.
+ * A state-changing request whose Origin is another site is cross-site
+ request forgery; refuse it. Non-browser clients send no Origin.
+ """
+ if not _host_is_trusted(urlsplit(f"//{request.host}").hostname):
+ return jsonify({"ok": False, "error": "Host not allowed. Set CLEAN_BACKUP_ALLOWED_HOSTS."}), 403
+
+ if request.method in {"GET", "HEAD", "OPTIONS"}:
+ return None
+
+ origin = request.headers.get("Origin")
+ if origin is not None and urlsplit(origin).netloc.lower() != request.host.lower():
+ return jsonify({"ok": False, "error": "Cross-origin request refused"}), 403
+ if origin is None and request.headers.get("Sec-Fetch-Site") == "cross-site":
+ return jsonify({"ok": False, "error": "Cross-origin request refused"}), 403
+ return None
+
+
@app.after_request
def _after_request(response):
- response.headers["Access-Control-Allow-Origin"] = "*"
- response.headers["Access-Control-Allow-Headers"] = "Content-Type"
- response.headers["Access-Control-Allow-Methods"] = "GET,POST,PATCH,DELETE,OPTIONS"
+ # No Access-Control-Allow-Origin: the UI is served from this same origin
+ # (or through the Vite dev proxy), so other sites get no read access.
+ response.headers.setdefault("X-Content-Type-Options", "nosniff")
+ response.headers.setdefault("Referrer-Policy", "no-referrer")
return response
@@ -802,10 +881,14 @@ def api_delete_selected():
deleted_paths: list[str] = []
errors: list[str] = []
- undo_manager.start_session()
+ session_manager = UndoManager()
+ session_manager.start_session()
try:
for item in selected_images:
+ if not isinstance(item, dict):
+ errors.append("Invalid selection entry")
+ continue
raw_path = str(item.get("path", "")).strip()
is_best = bool(item.get("is_best", False))
@@ -822,12 +905,21 @@ def api_delete_selected():
if not file_path.is_file():
errors.append(f"Not a file: {file_path}")
continue
+ # Duplicate review only ever lists images; refuse anything else
+ # that happens to sit under a scanned folder.
+ if file_path.suffix.lower() not in IMAGE_EXTENSIONS:
+ errors.append(f"Not an image: {file_path}")
+ continue
if mode == "trash":
- target = _trash_target_for(file_path)
- target.parent.mkdir(parents=True, exist_ok=True)
- file_path.rename(target)
- undo_manager.log_action("move", str(file_path), str(target))
+ # Verified, journaled move: works across filesystems, never
+ # replaces an earlier trashed file, and is undoable.
+ verified_transfer(
+ file_path,
+ _trash_target_for(file_path),
+ "move",
+ journal=session_manager,
+ )
else:
file_path.unlink()
@@ -835,9 +927,9 @@ def api_delete_selected():
except Exception as exc:
errors.append(str(exc))
- undo_manager.end_session()
+ session_manager.end_session()
except Exception:
- undo_manager.end_session()
+ session_manager.end_session()
raise
return jsonify(
@@ -902,6 +994,10 @@ def api_image():
if not image_path.is_file():
return jsonify({"ok": False, "error": "Not a file"}), 400
+ # Previews are for media only; never hand back arbitrary files from a root.
+ if image_path.suffix.lower() not in IMAGE_EXTENSIONS:
+ return jsonify({"ok": False, "error": "Not a supported image type"}), 415
+
try:
with Image.open(image_path) as img:
out = img.copy()
@@ -922,8 +1018,14 @@ def api_image():
return send_file(buffer, mimetype="image/jpeg")
except Exception:
- # Fallback for files Pillow cannot decode through current codecs.
- return send_file(image_path)
+ # Fallback for image formats Pillow cannot decode (e.g. camera RAW).
+ # Sent as a download so mislabelled content is never rendered inline.
+ return send_file(
+ image_path,
+ mimetype="application/octet-stream",
+ as_attachment=True,
+ download_name=image_path.name,
+ )
@@ -935,10 +1037,7 @@ def _classify_task(
source_dir: str,
run_id: str,
) -> dict[str, Any]:
- source = Path(source_dir).expanduser().resolve()
- if not source.exists() or not source.is_dir():
- raise ValueError(f"Source directory not found: {source}")
- _add_allowed_root(source)
+ source = _resolve_source_dir(source_dir)
config = get_run_config(run_id) or {}
result = run_classify_pipeline(str(source), run_id, config, progress)
@@ -976,11 +1075,9 @@ def api_classify_start():
def _classify_apply_task(progress_cb, run_id, dest_dir, operation):
from src.classify.apply_org import apply_classification
- try:
- return apply_classification(run_id, dest_dir, operation, progress_cb)
- except Exception as e:
- logger.error(f"Classification apply failed: {e}")
- return {"error": str(e)}
+
+ # Errors propagate so the job is reported as failed, not completed.
+ return apply_classification(run_id, dest_dir, operation, progress_cb)
@app.route("/api/classify/apply", methods=["POST", "OPTIONS"])
@@ -1188,8 +1285,8 @@ def api_purge_faces():
@app.route("/api/face-crop", methods=["GET"])
def api_face_crop():
face_id = request.args.get("id", "")
- if not face_id:
- return jsonify({"ok": False, "error": "id is required"}), 400
+ if not face_id.isdecimal():
+ return jsonify({"ok": False, "error": "id must be a face number"}), 400
crop_path = FACE_CACHE_DIR / f"face_{face_id}.jpg"
if crop_path.exists():
@@ -1229,6 +1326,7 @@ def api_resolve_review(review_id: int):
# In-memory OAuth flow cache (keyed by a random state token)
_oauth_flows: dict[str, Any] = {}
+_MAX_PENDING_OAUTH_FLOWS = 16
@app.route("/api/cloud/accounts", methods=["GET"])
@@ -1247,12 +1345,13 @@ def api_gdrive_connect():
# Build the redirect URI pointing back to our callback endpoint
host_url = request.host_url.rstrip("/")
redirect_uri = f"{host_url}/api/cloud/accounts/gdrive/callback"
- auth_url, flow = start_oauth_flow(redirect_uri)
+ auth_url, state, flow = start_oauth_flow(redirect_uri)
- # Store flow in memory keyed by a state token
- state = uuid.uuid4().hex
+ # Keep the pending flow in memory under the state Google will echo back.
+ while len(_oauth_flows) >= _MAX_PENDING_OAUTH_FLOWS:
+ _oauth_flows.pop(next(iter(_oauth_flows)))
_oauth_flows[state] = flow
- return jsonify({"ok": True, "auth_url": f"{auth_url}&state={state}", "state": state})
+ return jsonify({"ok": True, "auth_url": auth_url, "state": state})
except FileNotFoundError as exc:
return jsonify({"ok": False, "error": str(exc)}), 400
except Exception as exc:
@@ -1295,7 +1394,7 @@ def api_gdrive_callback():
)
except Exception as exc:
logger.error("OAuth callback failed: %s", exc)
- return f"❌ Connection failed
{exc}
", 500
+ return f"❌ Connection failed
{escape(str(exc))}
", 500
@app.route("/api/cloud/accounts/", methods=["DELETE", "OPTIONS"])
@@ -1337,22 +1436,24 @@ def api_cloud_sync_config():
from src.cloud.manifest import create_sync_run
+ blocked = demo_guard()
+ if blocked:
+ return blocked
+
payload = request.get_json(silent=True) or {}
- account_id = payload.get("account_id")
- if not account_id:
+ try:
+ account_id = int(payload.get("account_id"))
+ except (TypeError, ValueError):
return jsonify({"ok": False, "error": "account_id is required"}), 400
- run_id = create_sync_run(int(account_id), payload)
+ run_id = create_sync_run(account_id, payload)
return jsonify({"ok": True, "run_id": run_id})
def _cloud_sync_task(progress_cb, run_id):
from src.cloud.sync_pipeline import run_sync
- try:
- return run_sync(run_id, progress_cb)
- except Exception as e:
- logger.error(f"Cloud sync failed: {e}")
- return {"error": str(e)}
+
+ return run_sync(run_id, progress_cb)
@app.route("/api/cloud/sync/start", methods=["POST", "OPTIONS"])
@@ -1365,21 +1466,19 @@ def api_cloud_sync_start():
return blocked
payload = request.get_json(silent=True) or {}
- run_id = payload.get("run_id")
- if not run_id:
+ try:
+ run_id = int(payload.get("run_id"))
+ except (TypeError, ValueError):
return jsonify({"ok": False, "error": "run_id is required"}), 400
- job_id = jobs.submit("cloud_sync", _cloud_sync_task, int(run_id))
+ job_id = jobs.submit("cloud_sync", _cloud_sync_task, run_id)
return jsonify({"ok": True, "job_id": job_id, "run_id": run_id})
def _cloud_undo_task(progress_cb, run_id):
from src.cloud.sync_pipeline import undo_sync
- try:
- return undo_sync(run_id, progress_cb)
- except Exception as e:
- logger.error(f"Cloud sync undo failed: {e}")
- return {"error": str(e)}
+
+ return undo_sync(run_id, progress_cb)
@app.route("/api/cloud/sync//undo", methods=["POST", "OPTIONS"])
@@ -1438,11 +1537,14 @@ def serve_frontend(path: str):
)
-def start_web_gui(host: str = "0.0.0.0", port: int = None, auto_open: bool = True) -> None:
+def start_web_gui(host: str | None = None, port: int | None = None, auto_open: bool = True) -> None:
if port is None:
port = int(os.environ.get("CLEAN_BACKUP_PORT", 8080))
- # Note: host defaults to 0.0.0.0 to allow Docker binding
-
+ # The API has no login: listen on loopback unless explicitly told otherwise
+ # (the Docker image sets CLEAN_BACKUP_HOST=0.0.0.0 inside its own network).
+ if host is None:
+ host = os.environ.get("CLEAN_BACKUP_HOST", "127.0.0.1")
+
# We display 127.0.0.1 in the terminal for clicking convenience
display_host = "127.0.0.1" if host == "0.0.0.0" else host
url = f"http://{display_host}:{port}"
diff --git a/tests/conftest.py b/tests/conftest.py
new file mode 100644
index 0000000..1af9a36
--- /dev/null
+++ b/tests/conftest.py
@@ -0,0 +1,39 @@
+"""Run API tests against disposable state, including module import side effects."""
+
+import importlib
+import sys
+from pathlib import Path
+
+import pytest
+
+
+@pytest.fixture(scope="session")
+def api_module(tmp_path_factory):
+ state = tmp_path_factory.mktemp("clean-backup-api")
+ with pytest.MonkeyPatch.context() as patch:
+ patch.chdir(state)
+ patch.setenv("CLEAN_BACKUP_DB_PATH", str(state / "test.db"))
+ patch.setenv("CLEAN_BACKUP_CONFIG_DIR", str(state / "config"))
+ patch.syspath_prepend(str(Path(__file__).resolve().parents[1]))
+ module = importlib.import_module("src.web_app")
+ yield module
+ # SQLite connections are thread-local; close the main test connection.
+ db = sys.modules["src.classify.db"]
+ connection = getattr(db._local, "conn", None)
+ if connection is not None:
+ connection.close()
+ del db._local.conn
+
+
+@pytest.fixture
+def client(api_module, monkeypatch, tmp_path):
+ monkeypatch.delenv("DEMO_MODE", raising=False)
+ monkeypatch.chdir(tmp_path)
+ (tmp_path / "logs" / "undo_journals").mkdir(parents=True)
+ # Real background jobs and file operations, isolated per test.
+ monkeypatch.setattr(api_module, "jobs", api_module.JobManager())
+ monkeypatch.setattr(api_module, "_allowed_roots", set())
+ monkeypatch.setattr(api_module, "TRASH_ROOT", tmp_path / "trash")
+ api_module.app.config.update(TESTING=True)
+ with api_module.app.test_client() as test_client:
+ yield test_client
diff --git a/tests/test_api_security.py b/tests/test_api_security.py
new file mode 100644
index 0000000..963aa20
--- /dev/null
+++ b/tests/test_api_security.py
@@ -0,0 +1,308 @@
+"""Regression tests for the unauthenticated local API's trust boundaries."""
+
+import stat
+import time
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+from flask import Flask
+from PIL import Image
+
+
+def finished_job(client, response):
+ assert response.status_code == 200, response.get_json()
+ job_id = response.get_json()["job_id"]
+ deadline = time.monotonic() + 30
+ while time.monotonic() < deadline:
+ job = client.get(f"/api/jobs/{job_id}").get_json()["job"]
+ if job["status"] in {"completed", "failed"}:
+ return job
+ time.sleep(0.02)
+ pytest.fail("Background job did not finish within 30 seconds")
+
+
+def scanned_library(client, tmp_path):
+ source = tmp_path / "library"
+ source.mkdir()
+ Image.new("RGB", (64, 48), "#336699").save(source / "a.jpg")
+ Image.new("RGB", (64, 48), "#996633").save(source / "b.jpg")
+ job = finished_job(client, client.post("/api/duplicates/scan", json={"source_dir": str(source)}))
+ assert job["status"] == "completed", job
+ return source
+
+
+# ── Cross-site and DNS-rebinding protection ──────────────────────────────
+
+
+def test_other_sites_get_no_cors_read_access(client):
+ response = client.get("/api/health", headers={"Origin": "https://evil.example"})
+ assert response.status_code == 200
+ assert "Access-Control-Allow-Origin" not in response.headers
+
+
+def test_cross_origin_state_change_is_refused(client, tmp_path):
+ victim = tmp_path / "keep.jpg"
+ Image.new("RGB", (8, 8)).save(victim)
+ response = client.post(
+ "/api/duplicates/delete",
+ json={"selected_images": [{"path": str(victim)}], "mode": "permanent", "confirm_text": "DELETE"},
+ headers={"Origin": "https://evil.example"},
+ )
+ assert response.status_code == 403
+ assert victim.exists()
+
+
+def test_same_origin_state_change_is_accepted(client):
+ response = client.post(
+ "/api/config", json={"phash_threshold": 7}, headers={"Origin": "http://localhost"}
+ )
+ assert response.status_code == 200, response.get_json()
+
+
+@pytest.mark.parametrize("host", ["evil.example", "evil.example:8080", "localhost.evil.example"])
+def test_unexpected_host_header_is_refused(client, host):
+ response = client.get("/api/health", headers={"Host": host})
+ assert response.status_code == 403
+
+
+@pytest.mark.parametrize("host", ["127.0.0.1:8080", "192.168.1.20:8080", "[::1]:8080", "app.localhost"])
+def test_loopback_and_ip_hosts_are_accepted(client, host):
+ assert client.get("/api/health", headers={"Host": host}).status_code == 200
+
+
+def test_configured_hostname_is_accepted(client, monkeypatch):
+ monkeypatch.setenv("CLEAN_BACKUP_ALLOWED_HOSTS", "nas.local, photos.example.org")
+ assert client.get("/api/health", headers={"Host": "nas.local:8080"}).status_code == 200
+ assert client.get("/api/health", headers={"Host": "other.local"}).status_code == 403
+
+
+# ── File disclosure ──────────────────────────────────────────────────────
+
+
+def test_image_endpoint_does_not_serve_non_image_files(client, tmp_path):
+ source = scanned_library(client, tmp_path)
+ secret = source / "id_rsa"
+ secret.write_text("PRIVATE KEY MATERIAL")
+ notes = source / "notes.txt"
+ notes.write_text("private notes")
+
+ for path in (secret, notes):
+ response = client.get("/api/image", query_string={"path": str(path)})
+ assert response.status_code == 415
+ assert b"PRIVATE" not in response.data and b"private notes" not in response.data
+
+ assert client.get("/api/image", query_string={"path": str(source / "a.jpg")}).mimetype == "image/jpeg"
+
+
+def test_undecodable_image_is_only_offered_as_a_download(client, tmp_path):
+ source = scanned_library(client, tmp_path)
+ fake = source / "page.jpg"
+ fake.write_text("")
+ response = client.get("/api/image", query_string={"path": str(fake)})
+ assert response.mimetype == "application/octet-stream"
+ assert response.headers["Content-Disposition"].startswith("attachment")
+ assert response.headers["X-Content-Type-Options"] == "nosniff"
+
+
+def test_demo_mode_cannot_scan_outside_its_media_folder(client, tmp_path, monkeypatch):
+ media = tmp_path / "media"
+ media.mkdir()
+ Image.new("RGB", (32, 32), "red").save(media / "a.jpg")
+ Image.new("RGB", (32, 32), "blue").save(media / "b.jpg")
+ outside = tmp_path / "home"
+ outside.mkdir()
+ (outside / "secret.jpg").write_text("not for visitors")
+ monkeypatch.setenv("DEMO_MODE", "true")
+ monkeypatch.setenv("CLEAN_BACKUP_MEDIA_PATH", str(media))
+
+ job = finished_job(client, client.post("/api/duplicates/scan", json={"source_dir": str(outside)}))
+ assert job["status"] == "failed" and "sample media" in job["error"]
+ assert client.get("/api/image", query_string={"path": str(outside / "secret.jpg")}).status_code == 400
+
+ job = finished_job(client, client.post("/api/duplicates/scan", json={"source_dir": str(media)}))
+ assert job["status"] == "completed", job
+
+
+@pytest.mark.parametrize("face_id", ["../../../etc/passwd", "1/../2", "", "abc"])
+def test_face_crop_requires_a_numeric_id(client, face_id):
+ assert client.get("/api/face-crop", query_string={"id": face_id}).status_code == 400
+
+
+# ── Deletion ─────────────────────────────────────────────────────────────
+
+
+def test_delete_rejects_malformed_entries_without_crashing(client, tmp_path):
+ response = client.post("/api/duplicates/delete", json={"selected_images": ["x", 3, None]})
+ assert response.status_code == 200
+ body = response.get_json()
+ assert body["deleted_count"] == 0 and len(body["errors"]) == 3
+
+
+@pytest.mark.parametrize("mode", ["trash", "permanent"])
+def test_delete_only_accepts_images(client, tmp_path, mode):
+ source = scanned_library(client, tmp_path)
+ document = source / "taxes.pdf"
+ document.write_bytes(b"%PDF-1.7 not a duplicate photo")
+ body = client.post("/api/duplicates/delete", json={
+ "selected_images": [{"path": str(document)}], "mode": mode, "confirm_text": "DELETE",
+ }).get_json()
+ assert body["deleted_count"] == 0 and "Not an image" in body["errors"][0]
+ assert document.exists()
+
+
+def test_trash_never_replaces_an_earlier_trashed_file(client, api_module, tmp_path, monkeypatch):
+ source = scanned_library(client, tmp_path)
+ target = source / "a.jpg"
+ monkeypatch.setattr(api_module.time, "time", lambda: 1_700_000_000) # same second twice
+
+ first = target.read_bytes()
+ assert client.post("/api/duplicates/delete", json={"selected_images": [{"path": str(target)}]}).get_json()["deleted_count"] == 1
+ target.write_bytes(b"a different file that reuses the name")
+ second = target.read_bytes()
+ assert client.post("/api/duplicates/delete", json={"selected_images": [{"path": str(target)}]}).get_json()["deleted_count"] == 1
+
+ trashed = sorted(p.read_bytes() for p in api_module.TRASH_ROOT.iterdir() if not p.name.startswith("."))
+ assert trashed == sorted([first, second])
+ assert not target.exists()
+
+
+def test_trashed_file_can_be_restored_by_undo(client, api_module, tmp_path):
+ source = scanned_library(client, tmp_path)
+ target = source / "b.jpg"
+ original = target.read_bytes()
+ assert client.post("/api/duplicates/delete", json={"selected_images": [{"path": str(target)}]}).get_json()["deleted_count"] == 1
+ assert not target.exists()
+ assert client.post("/api/undo/revert", json={}).get_json()["ok"]
+ assert target.read_bytes() == original
+
+
+# ── SQL identifiers ──────────────────────────────────────────────────────
+
+
+@pytest.fixture
+def watcher_db(api_module):
+ from src.watcher import db
+
+ db.init_db()
+ config_id = db.add_config("Inbox", "/tmp/inbox", True, 2, [], [], "leave", "leave", False)
+ yield db, config_id
+ db.delete_config(config_id)
+
+
+def test_watcher_update_rejects_injected_column_names(watcher_db):
+ db, config_id = watcher_db
+ with pytest.raises(ValueError):
+ db.update_config(config_id, **{"label = 'pwned', watch_path": "/"})
+ config = db.get_config(config_id)
+ assert (config.label, config.watch_path) == ("Inbox", "/tmp/inbox")
+
+ assert db.update_config(config_id, label="Renamed", pipeline=[{"job_type": "dedupe"}])
+ assert db.get_config(config_id).label == "Renamed"
+
+
+def test_watcher_api_reports_unknown_fields_as_a_client_error(watcher_db, monkeypatch):
+ from src.watcher import api
+
+ db, config_id = watcher_db
+ monkeypatch.setattr(api.daemon, "sync_configs", lambda: None)
+ app = Flask(__name__)
+ app.register_blueprint(api.watcher_bp)
+ client = app.test_client()
+
+ injected = client.patch(f"/api/watchers/{config_id}", json={"label = 'pwned' --": 1})
+ assert injected.status_code == 400
+ assert client.patch(f"/api/watchers/{config_id}", json=["not", "an", "object"]).status_code == 400
+ assert client.patch(f"/api/watchers/{config_id}", json={"label": "Fine"}).status_code == 200
+ assert db.get_config(config_id).label == "Fine"
+
+
+def test_sync_run_update_rejects_unknown_columns(api_module):
+ from src.cloud.manifest import update_sync_run
+
+ with pytest.raises(ValueError):
+ update_sync_run(1, **{"status = 'x', account_id": 2})
+
+
+# ── Cloud ────────────────────────────────────────────────────────────────
+
+
+def test_drive_queries_escape_file_names():
+ from src.cloud.provider_gdrive import GoogleDriveProvider, _q
+
+ assert _q("O'Brien.jpg") == r"'O\'Brien.jpg'"
+ assert _q("back\\slash") == r"'back\\slash'"
+
+ queries = []
+
+ class Files:
+ def list(self, q, **_):
+ queries.append(q)
+ return self
+
+ def execute(self):
+ return {"files": []}
+
+ class Service:
+ def files(self):
+ return Files()
+
+ provider = GoogleDriveProvider()
+ provider._service = Service()
+ provider.delete("x' or name contains '.jpg")
+ assert queries == [r"name='x\' or name contains \'.jpg' and 'root' in parents and trashed=false"]
+
+
+def test_oauth_url_carries_exactly_one_state(tmp_path, monkeypatch):
+ import json
+
+ from src.cloud.provider_gdrive import start_oauth_flow
+
+ (tmp_path / "credentials.json").write_text(json.dumps({"web": {
+ "client_id": "test-client.apps.googleusercontent.com",
+ "client_secret": "not-a-real-secret",
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
+ "token_uri": "https://oauth2.googleapis.com/token",
+ "redirect_uris": ["http://localhost:8080/api/cloud/accounts/gdrive/callback"],
+ }}))
+ monkeypatch.chdir(tmp_path)
+
+ url, state, _flow = start_oauth_flow("http://localhost:8080/api/cloud/accounts/gdrive/callback")
+ assert parse_qs(urlsplit(url).query)["state"] == [state]
+
+
+def test_oauth_callback_escapes_error_text(client, api_module):
+ class Flow:
+ def fetch_token(self, **_):
+ raise RuntimeError("")
+
+ api_module._oauth_flows["known-state"] = Flow()
+ response = client.get("/api/cloud/accounts/gdrive/callback", query_string={"state": "known-state"})
+ assert response.status_code == 500
+ assert b"