From 78008787b6210f57d18c37140b10db368508e7c7 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 1 Sep 2026 14:10:32 -0500 Subject: [PATCH] docs: add project overview, architecture, roadmap, and deployment specs --- README.md | 64 ++++++++++++++++++++++- docs/architecture.md | 117 +++++++++++++++++++++++++++++++++++++++++++ docs/deployment.md | 93 ++++++++++++++++++++++++++++++++++ docs/overview.md | 48 ++++++++++++++++++ docs/roadmap.md | 73 +++++++++++++++++++++++++++ 5 files changed, 394 insertions(+), 1 deletion(-) create mode 100644 docs/architecture.md create mode 100644 docs/deployment.md create mode 100644 docs/overview.md create mode 100644 docs/roadmap.md diff --git a/README.md b/README.md index 736f758..2c6fbb1 100644 --- a/README.md +++ b/README.md @@ -1 +1,63 @@ -# MagNetFlix +# 🎬 MagNetFlix + +> Automated, secure movie fetching and library organization pipeline via gRPC, Transmission, and Traefik/Authelia SSO. + +--- + +## πŸ“– Table of Contents + +- [Overview](docs/overview.md) - Project mission, key features, and user workflow. +- [Architecture](docs/architecture.md) - System design, BFF pattern, gRPC contracts, and data flow. +- [Development Rules & Agent Guidelines](AGENTS.md) - Coding standards, monorepo conventions, and toolchain rules. +- [Roadmap](docs/roadmap.md) - Milestone-by-milestone development plan. +- [Deployment Guide](docs/deployment.md) - Docker Compose, Traefik integration, and Authelia SSO setup. + +--- + +## ⚑ Quick Start + +```bash +# Enter hermetic dev shell (Nix) +nix develop + +# Or install dependencies with uv workspace +uv sync + +# Generate protobuf stubs +make generate + +# Start full local stack with docker compose +docker compose up -d +``` + +--- + +## πŸ“ Repository Structure + +```text +. +β”œβ”€β”€ AGENTS.md # Development guidelines & rules for AI/human contributors +β”œβ”€β”€ Makefile # High-level build & generation commands +β”œβ”€β”€ README.md # Project landing page +β”œβ”€β”€ buf.gen.yaml # Buf remote plugin generation config +β”œβ”€β”€ buf.yaml # Buf module definition +β”œβ”€β”€ docker-compose.yml # Local development & production compose stack +β”œβ”€β”€ docs/ # Detailed system documentation +β”‚ β”œβ”€β”€ architecture.md # Architecture & component interactions +β”‚ β”œβ”€β”€ deployment.md # Traefik & Authelia deployment guide +β”‚ β”œβ”€β”€ overview.md # Feature overview & workflow +β”‚ └── roadmap.md # Development milestones +β”œβ”€β”€ proto/ # Protocol Buffer definitions +β”‚ └── magnetflix/v1/ +β”‚ └── pipeline.proto +└── services/ + β”œβ”€β”€ bff/ # FastAPI Web Gateway / HTML Form / Authelia SSO + β”‚ β”œβ”€β”€ Dockerfile + β”‚ β”œβ”€β”€ pyproject.toml + β”‚ └── src/bff/ + └── worker/ # gRPC Pipeline Worker & Transmission Coordinator + β”œβ”€β”€ Dockerfile + β”œβ”€β”€ alembic/ + β”œβ”€β”€ pyproject.toml + └── src/worker/ +``` diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..06457c4 --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,117 @@ +# πŸ›οΈ MagNetFlix β€” Architecture & System Design + +MagNetFlix uses a **Backend-For-Frontend (BFF)** pattern paired with an internal **gRPC Worker** pipeline service to decouple public web endpoints from disk I/O and media processing. + +--- + +## πŸ“ High-Level Architecture + +```mermaid +flowchart TB + subgraph Edge ["🌐 Public Edge (Protected)"] + Browser["User Browser"] -->|HTTPS| Traefik["Traefik Reverse Proxy"] + Traefik <-->|Forward Auth| Authelia["Authelia SSO"] + end + + subgraph InternalServices ["πŸ›‘οΈ Internal Services (Docker Network)"] + Traefik -->|HTTP + Remote-User| BFF["FastAPI BFF Gateway"] + + subgraph WorkerApp ["Worker Service"] + BFF -->|gRPC / Stream| Worker["gRPC Pipeline Server"] + Worker --> DB[("SQLite 3 (WAL Mode)\nAudit & State Store")] + Worker --> Sanitizer["Media Sanitizer & Allowlist"] + Worker --> MetaService["TMDB Metadata Client"] + Worker --> StorageMgr["Library Relocator & Renamer"] + end + + Worker --> Torrent["Transmission Daemon"] + end + + subgraph Volumes ["πŸ’Ύ Storage Mounts"] + Torrent --> StagingDir[("/data/staging/ (Scratch Disk)")] + StorageMgr --> FinalMedia[("/media/movies (Jellyfin/Plex Library)")] + end +``` + +--- + +## πŸ”„ Job State Machine & Lifecycle Rules + +The pipeline worker operates strictly as a finite state machine with terminal failure handling. + +```mermaid +stateDiagram-v2 + [*] --> QUEUED: SubmitDownload() + QUEUED --> DOWNLOADING: Transmission starts torrent + DOWNLOADING --> SCANNING: Torrent reaches 100% + DOWNLOADING --> FAILED: Torrent error / stalled timeout + + SCANNING --> VERIFYING_METADATA: Sanitizer validates payload + SCANNING --> FAILED: Disallowed files / no valid video + + VERIFYING_METADATA --> ORGANIZING: TMDB match verified + VERIFYING_METADATA --> FAILED: Title/year mismatch or lookup failed + + ORGANIZING --> COMPLETED: Files relocated & renamed + ORGANIZING --> FAILED: Disk full / permission error + + COMPLETED --> [*] + FAILED --> [*] +``` + +### Transition & Failure Invariants +1. **Linear Progression**: `QUEUED` βž” `DOWNLOADING` βž” `SCANNING` βž” `VERIFYING_METADATA` βž” `ORGANIZING` βž” `COMPLETED`. +2. **Terminal Failure**: Any failure at any phase transitions the job directly to `FAILED` with a populated `error_message`. +3. **Crash & Restart Recovery**: Upon worker startup, any orphaned non-terminal jobs (`QUEUED`, `DOWNLOADING`, `SCANNING`, `VERIFYING_METADATA`, `ORGANIZING`) in the SQLite database are automatically transitioned to `FAILED` with reason `"Worker restarted during execution"`. Retrying requires a new submission. +4. **Duplicate Rejection (Idempotency)**: + - A submission is rejected if a non-terminal job for the same `imdb_id` is currently active in the database. + - A submission is rejected if `/media/movies/*[imdbid-{imdb_id}]` already exists in the destination library. + +--- + +## πŸ›‘οΈ Security & Media Sanitizer Specification + +The sanitizer enforces a strict file-system boundary before files are touched or moved: + +1. **Path Traversal & Symlink Check**: Rejects any archive or torrent payload containing symbolic links, hard links, or paths escaping the staging root (`..`). +2. **File Allowlist**: + - **Allowed Video**: `.mkv`, `.mp4`, `.avi`, `.webm` + - **Allowed Subtitles**: `.srt`, `.vtt`, `.sub`, `.ass` + - **Forbidden / Quarantine**: `.exe`, `.bat`, `.cmd`, `.sh`, `.scr`, `.vbs`, `.lnk`, `.iso`, `.zip`, `.rar`, etc. +3. **Multiple Video Selection (Largest File Rule)**: + - Files containing `sample` in the filename or with size `< 100MB` are discarded. + - If multiple video files remain, the **single largest video file** is selected as the primary feature film. A warning is logged listing ignored video files. + - If 0 eligible video files remain, the job transitions to `FAILED`. + +--- + +## 🎬 Metadata Authority & Verification Criteria + +- **Authority**: **The Movie Database (TMDB) API** using the `/find/{imdb_id}?external_source=imdb_id` endpoint. +- **Verification Criteria**: + - The canonical title and release year are fetched from TMDB. + - A normalized token comparison is performed between the TMDB movie title/year and the torrent folder name / primary video filename. + - If there is zero token overlap between the metadata title/year and the torrent name, the job transitions to `FAILED` (`"Torrent payload does not appear to match TMDB metadata"`). + +--- + +## πŸ“‚ Storage Paths & Naming Convention + +- **Canonical Staging Path**: `/data/staging//` +- **Canonical Library Destination**: + ```text + /media/movies/ (<Year>) [imdbid-<IMDbID>]/<Title> (<Year>).<ext> + /media/movies/<Title> (<Year>) [imdbid-<IMDbID>]/<Title> (<Year>).en.srt + ``` +- **Cleanup**: The `/data/staging/<job_id>/` folder is purged immediately upon successful completion or terminal failure. + +--- + +## πŸ” Security Boundaries & Health Endpoints + +### Authentication Trust Boundary +- The FastAPI BFF trusts `Remote-User` and `Remote-Email` headers **strictly because it is reachable exclusively through the authenticated Traefik reverse proxy**. Direct ingress from outside the Docker network is prohibited. + +### Health & Readiness Probes +- **BFF**: `GET /healthz` (Verifies FastAPI liveness + gRPC worker channel connectivity). +- **Worker**: gRPC standard health checking protocol (`grpc.health.v1.Health`) + Transmission RPC ping. diff --git a/docs/deployment.md b/docs/deployment.md new file mode 100644 index 0000000..1b98cf1 --- /dev/null +++ b/docs/deployment.md @@ -0,0 +1,93 @@ +# πŸš€ MagNetFlix β€” Deployment & Traefik Integration + +This guide details how **MagNetFlix** integrates into the home server stack at `/home/kiskaadee/Deployments/` with **Traefik Reverse Proxy** and **Authelia SSO**. + +--- + +## 🐳 Docker Compose Architecture + +MagNetFlix runs as a multi-container stack attached to the shared `traefik_network`: + +```yaml +services: + # 1. FastAPI Web Gateway & Form UI + bff: + build: + context: . + dockerfile: services/bff/Dockerfile + restart: unless-stopped + environment: + - GRPC_WORKER_HOST=worker:50051 + - APP_ENV=production + networks: + - traefik_network + - magnetflix_internal + labels: + - "traefik.enable=true" + - "traefik.http.routers.magnetflix.rule=Host(`addmovie.arch-services.mywire.org`)" + - "traefik.http.routers.magnetflix.entrypoints=websecure" + - "traefik.http.routers.magnetflix.tls.certresolver=letsencrypt" + - "traefik.http.routers.magnetflix.middlewares=authelia@docker" + - "traefik.http.services.magnetflix.loadbalancer.server.port=8000" + + # 2. gRPC Pipeline Worker & Mover + worker: + build: + context: . + dockerfile: services/worker/Dockerfile + restart: unless-stopped + environment: + - TRANSMISSION_HOST=transmission + - TRANSMISSION_PORT=9091 + - DATABASE_URL=sqlite:////data/magnetflix.sqlite3 + - STAGING_DIR=/data/staging + - MEDIA_DIR=/media/movies + volumes: + - ./data:/data + - /mnt/storage/media/movies:/media/movies + networks: + - magnetflix_internal + + # 3. Transmission Torrent Daemon + transmission: + image: lscr.io/linuxserver/transmission:latest + restart: unless-stopped + environment: + - PUID=1000 + - PGID=1000 + - TZ=America/Chicago + volumes: + - ./config/transmission:/config + - ./data/staging:/downloads + networks: + - magnetflix_internal + +networks: + traefik_network: + external: true + magnetflix_internal: + driver: bridge +``` + +--- + +## πŸ” Authelia SSO Integration + +When a user visits `addmovie.arch-services.mywire.org`: +1. Traefik triggers the `authelia@docker` forward-auth middleware. +2. If unauthenticated, Authelia redirects the user to the login portal. +3. Upon authentication, Authelia injects headers into the forwarded request: + - `Remote-User`: Username of the logged-in user. + - `Remote-Email`: Email address. + - `Remote-Groups`: Group memberships (e.g. `admins`, `family`). +4. FastAPI extracts `request.headers.get("Remote-User")` and passes it to the gRPC worker for audit logging. + +--- + +## πŸ“‚ Storage Volumes Configuration + +| Mount Path | Type | Purpose | +| :--- | :--- | :--- | +| `/data/magnetflix.sqlite3` | Persistent Volume | SQLite DB with WAL mode for jobs and audit log. | +| `/data/staging` | Fast Scratch Disk | Staging folder where Transmission downloads files. | +| `/media/movies` | Media Storage | Final target destination mounted to Jellyfin/Plex. | diff --git a/docs/overview.md b/docs/overview.md new file mode 100644 index 0000000..f3f861e --- /dev/null +++ b/docs/overview.md @@ -0,0 +1,48 @@ +# 🌟 MagNetFlix β€” Overview + +**MagNetFlix** is a self-hosted, automated media acquisition pipeline. It bridges the gap between web-based movie requests and structured, verified media storage in a secure, audited environment. + +--- + +## 🎯 The Problem & Mission + +When self-hosting a media server (Jellyfin/Plex): +1. Adding movies manually requires downloading torrents, monitoring client progress, manually checking for malicious/garbage files, and renaming folders to match IMDb/TMDB conventions. +2. In multi-user setups, tracking who requested what and keeping track of download failures is difficult without a dedicated audit log. + +**MagNetFlix** solves this with an end-to-end automated workflow: +- **Input**: A simple web form protected by **Authelia SSO** accepting an **IMDb ID** and a **Magnet URI**. +- **Processing**: A background **gRPC worker** handles downloading via Transmission into a sandboxed staging directory. +- **Safety**: Recursively scans and purges all non-media/dangerous executable files. +- **Organization**: Fetches official metadata for the IMDb ID, verifies movie details, and places renamed media files into your library structure. +- **Observability**: Live status tracking and persistent audit logs. + +--- + +## 🎬 User Workflow + +```mermaid +sequenceDiagram + autonumber + actor User as Authenticated User + participant Traefik as Traefik (SSO Protected) + participant BFF as FastAPI (BFF Gateway) + participant Worker as gRPC Pipeline Worker + participant Engine as Transmission Daemon + participant Media as Jellyfin / Plex Library + + User->>Traefik: GET addmovie.arch-services.mywire.org + Traefik->>User: Renders MagNetFlix Web Form + User->>Traefik: Submit form (magnet URI + IMDb ID: tt1375666) + Traefik->>BFF: POST /api/v1/downloads (includes Remote-User header) + BFF->>Worker: gRPC SubmitDownload(magnet, imdb_id, user) + Worker-->>BFF: Acknowledged (Job ID: job-42) + BFF-->>User: Enqueued! Showing live progress + Worker->>Engine: Start torrent download in /tmp/staging/job-42 + Engine-->>Worker: Download Completed + Worker->>Worker: Run Security Whitelist Scan (Purge .exe/.bat) + Worker->>Worker: Verify IMDb metadata & rename files + Worker->>Media: Move to /media/movies/Inception (2010) [imdbid-tt1375666]/ + Worker-->>BFF: Status: COMPLETED + BFF-->>User: Notification: Movie ready in library! +``` diff --git a/docs/roadmap.md b/docs/roadmap.md new file mode 100644 index 0000000..9163d10 --- /dev/null +++ b/docs/roadmap.md @@ -0,0 +1,73 @@ +# πŸ—ΊοΈ MagNetFlix β€” Development Roadmap + +This roadmap breaks down the construction of **MagNetFlix** into clear, incremental milestones with testing embedded in each stage. + +--- + +## 🎯 Milestones Overview + +```mermaid +gantt + title MagNetFlix Implementation Phases + dateFormat YYYY-MM-DD + section Phase 1 + Workspace & Protobuf Contract :p1, 2026-09-01, 2d + section Phase 2 + Worker Engine & Pipeline Modules :p2, after p1, 4d + Worker Unit & Component Tests :p2_test, after p2, 2d + section Phase 3 + FastAPI BFF & Web UI (SSE) :p3, after p2_test, 3d + BFF & gRPC Integration Tests :p3_test, after p3, 2d + section Phase 4 + Traefik SSO & Docker Compose :p4, after p3_test, 2d + End-to-End Verification :p4_test, after p4, 1d +``` + +--- + +## πŸ“Œ Phase 1: Repository Foundation & Protobuf Contracts +- [x] Initialize `uv` workspace with `services/bff` and `services/worker`. +- [x] Configure `buf.yaml` and `buf.gen.yaml` with Python & gRPC stubs generation. +- [x] Define `proto/magnetflix/v1/pipeline.proto` with pagination, `updated_at`, and streaming snapshot semantics. +- [x] Create developer guidelines (`AGENTS.md` and `CLAUDE.md`). + +--- + +## πŸ“Œ Phase 2: Pipeline Worker & Security Engine +- [ ] Set up SQLite with WAL mode via SQLAlchemy 2.0 and Alembic migrations. +- [ ] Implement Transmission daemon RPC client wrapper. +- [ ] Implement isolated scratch staging (`/data/staging/<job_id>`). +- [ ] Build **Media Sanitizer & Allowlist**: + - Symlink & path traversal blocker. + - Video & subtitle extension whitelist. + - Sample file discard (<100MB / "sample") & largest video file selector. +- [ ] Build **TMDB Metadata Verifier**: Fetch title/year from TMDB via IMDb ID and perform token overlap verification. +- [ ] Build **Library Relocator**: Move verified video and `.srt` files into final Jellyfin/Plex structure. +- [ ] **Phase 2 Tests**: + - `tests/test_sanitizer.py`: Unit tests for allowlist, traversal, and largest video file selection. + - `tests/test_metadata.py`: Unit tests for TMDB client and token matching logic. + - `tests/test_state_machine.py`: Unit tests for linear transitions, failure transitions, and restart recovery. + - `tests/test_transmission.py`: Mocked Transmission RPC client tests. + +--- + +## πŸ“Œ Phase 3: BFF Gateway & Live Dashboard +- [ ] Build FastAPI application with Pydantic v2 schemas. +- [ ] Add Authelia SSO header middleware (`Remote-User`, `Remote-Email`). +- [ ] Implement gRPC client wrapper in BFF. +- [ ] Build clean HTML form (PicoCSS / Tailwind) for adding movies. +- [ ] Implement Server-Sent Events (SSE) route `/api/v1/movies/events` connected to gRPC streaming updates. +- [ ] Build live progress dashboard showing active and completed downloads. +- [ ] **Phase 3 Tests**: + - `tests/test_bff_routes.py`: FastAPI route and header extraction tests. + - `tests/test_grpc_integration.py`: End-to-end gRPC communication between BFF and Worker. + - `tests/test_sse_stream.py`: SSE stream snapshot and event emission tests. + +--- + +## πŸ“Œ Phase 4: Containerization & Traefik Integration +- [ ] Create multi-stage `Dockerfile` for `bff` and `worker`. +- [ ] Create production-ready `docker-compose.yml` including Transmission daemon and shared volumes. +- [ ] Configure Traefik labels for `addmovie.arch-services.mywire.org` with Authelia middleware. +- [ ] Configure health and readiness probes (`/healthz`, gRPC health service). +- [ ] **Phase 4 Tests**: Full end-to-end dry-run with a public domain torrent.