The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
M1: Media Library — import, yt-dlp download, sha256 dedupe, thumbnails
OsintMeThat16161ba67535
diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelteindex b57d9eb..7e22150 100644--- a/frontend/src/tools/MediaLibrary.svelte+++ b/frontend/src/tools/MediaLibrary.svelte@@ -1,13 +1,403 @@<script>+ import { api } from '../lib/api.js';+ import { caseState, uiState, ensureCase, reloadCase, toast } from '../lib/state.svelte.js';import Icon from '../components/Icon.svelte';++ const KIND_ICONS = { image: 'image', video: 'video', audio: 'audio', file: 'file' };++ let items = $state([]);+ let loadedFor = $state(null);+ let url = $state('');+ let dragOver = $state(false);+ let jobs = $state([]); // active download jobs: {id, url, progress}+ let fileInput;++ $effect(() => {+ const id = caseState.current?.id;+ if (id !== loadedFor) {+ loadedFor = id;+ items = [];+ if (id) refresh(id);+ }+ });++ async function refresh(id = caseState.current?.id) {+ if (id) items = await api.get(`/api/cases/${id}/media`);+ }++ async function importFiles(fileList) {+ const files = [...fileList];+ if (!files.length) return;+ const c = await ensureCase();+ let added = 0;+ let dups = 0;+ for (const file of files) {+ const form = new FormData();+ form.append('file', file);+ try {+ const res = await api.post(`/api/cases/${c.id}/media/upload`, form);+ res.duplicate ? dups++ : added++;+ } catch (e) {+ toast(`${file.name}: ${e.message}`, 'danger');+ }+ }+ await Promise.all([refresh(), reloadCase()]);+ if (added) toast(`${added} file${added > 1 ? 's' : ''} added to the case`, 'ok');+ if (dups) toast(`${dups} duplicate${dups > 1 ? 's' : ''} skipped (same SHA-256)`, 'warn');+ }++ async function download() {+ const target = url.trim();+ if (!target) return;+ url = '';+ const c = await ensureCase();+ try {+ const { job_id } = await api.post(`/api/cases/${c.id}/media/download`, { url: target });+ jobs.push({ id: job_id, url: target, progress: {} });+ poll(job_id);+ } catch (e) {+ toast(e.message, 'danger');+ }+ }++ async function poll(jobId) {+ const job = jobs.find((j) => j.id === jobId);+ if (!job) return;+ try {+ const status = await api.get(`/api/jobs/${jobId}`);+ job.progress = status.progress ?? {};+ if (status.status === 'running') {+ setTimeout(() => poll(jobId), 700);+ return;+ }+ jobs = jobs.filter((j) => j.id !== jobId);+ if (status.status === 'done') {+ toast(+ status.result?.duplicate+ ? 'Already in the case (same SHA-256)'+ : `Downloaded: ${status.result?.item?.filename}`,+ status.result?.duplicate ? 'warn' : 'ok'+ );+ await Promise.all([refresh(), reloadCase()]);+ } else {+ toast(`Download failed: ${status.error}`, 'danger', 6000);+ }+ } catch (e) {+ jobs = jobs.filter((j) => j.id !== jobId);+ toast(e.message, 'danger');+ }+ }++ async function remove(item) {+ await api.del(+ `/api/cases/${caseState.current.id}/media?path=${encodeURIComponent(item.path)}`+ );+ await Promise.all([refresh(), reloadCase()]);+ toast(`Removed ${item.filename}`, 'info');+ }++ function sendToComposer(item) {+ if (!uiState.composeQueue.includes(item.path)) {+ uiState.composeQueue.push(item.path);+ }+ uiState.tool = 'proof';+ }++ function fmtSize(bytes) {+ if (bytes >= 1 << 30) return (bytes / (1 << 30)).toFixed(1) + ' GB';+ if (bytes >= 1 << 20) return (bytes / (1 << 20)).toFixed(1) + ' MB';+ if (bytes >= 1 << 10) return (bytes / (1 << 10)).toFixed(0) + ' KB';+ return bytes + ' B';+ }++ function onDrop(e) {+ e.preventDefault();+ dragOver = false;+ importFiles(e.dataTransfer.files);+ }</script>-<div class="tool">+<div+ class="tool"+ role="region"+ aria-label="Media Library"+ ondragover={(e) => {+ e.preventDefault();+ dragOver = true;+ }}+ ondragleave={(e) => {+ if (e.currentTarget === e.target) dragOver = false;+ }}+ ondrop={onDrop}+>+ <div class="tool-header">+ <h2>Media Library</h2>+ <span class="sub">import files or download by URL — hashed & filed in the case</span>+ <div class="spacer"></div>+ <form+ class="dl-form"+ onsubmit={(e) => {+ e.preventDefault();+ download();+ }}+ >+ <input+ class="input"+ placeholder="https://x.com/… https://t.me/… https://youtube.com/…"+ bind:value={url}+ />+ <button type="submit" class="btn btn-primary" disabled={!url.trim()}>+ <Icon name="download" size={15} /> Download+ </button>+ </form>+ <button class="btn" onclick={() => fileInput.click()}>+ <Icon name="upload" size={15} /> Import+ </button>+ <input+ type="file"+ multiple+ hidden+ bind:this={fileInput}+ onchange={(e) => {+ importFiles(e.target.files);+ e.target.value = '';+ }}+ />+ </div>+<div class="tool-body">- <div class="empty" style="height: 100%">- <div class="empty-icon"><Icon name="media" size={40} /></div>- <h3>MediaLibrary</h3>- <p>Coming in this milestone.</p>- </div>+ {#each jobs as job (job.id)}+ <div class="job card fade-up">+ <Icon name="download" size={15} />+ <span class="job-url mono">{job.url}</span>+ <div class="bar">+ <div+ class="fill"+ class:indeterminate={job.progress.percent == null}+ style:width={job.progress.percent != null ? job.progress.percent + '%' : '40%'}+ ></div>+ </div>+ <span class="job-meta">+ {#if job.progress.stage === 'processing'}processing…{:else if job.progress.percent != null}{job.progress.percent}%+ {job.progress.speed ?? ''}{:else}starting…{/if}+ </span>+ </div>+ {/each}++ {#if !items.length && !jobs.length}+ <div class="empty" style="height: 100%">+ <div class="empty-icon"><Icon name="media" size={42} /></div>+ <h3>No media yet</h3>+ <p>+ Drop files anywhere on this page, or paste a URL from X, Telegram, TikTok, YouTube…+ Every file is SHA-256 hashed and its origin recorded.+ </p>+ </div>+ {:else}+ <div class="grid">+ {#each items as item (item.path)}+ <div class="media-card card fade-up">+ <div class="thumb">+ {#if item.thumbnail}+ <img+ src={`/files/${caseState.current.id}/${item.thumbnail}`}+ alt={item.filename}+ loading="lazy"+ />+ {:else}+ <Icon name={KIND_ICONS[item.kind] ?? 'file'} size={34} />+ {/if}+ <span class="kind badge">{item.kind}</span>+ </div>+ <div class="body">+ <span class="name" title={item.filename}>{item.filename}</span>+ <span class="meta">+ {fmtSize(item.size)} ·+ <span class="mono" title={item.sha256}>{item.sha256.slice(0, 8)}</span>+ {#if item.source?.type === 'download'}+ · <a href={item.source.webpage_url ?? item.source.url} target="_blank" rel="noreferrer">source</a>+ {/if}+ </span>+ </div>+ <div class="actions">+ <a+ class="btn btn-ghost btn-sm"+ href={`/files/${caseState.current.id}/${item.path}`}+ target="_blank"+ rel="noreferrer"+ title="Open file"+ >+ <Icon name="external" size={14} />+ </a>+ {#if item.kind === 'image'}+ <button+ class="btn btn-ghost btn-sm"+ title="Send to Proof Composer"+ onclick={() => sendToComposer(item)}+ >+ <Icon name="proof" size={14} />+ </button>+ {/if}+ <button class="btn btn-ghost btn-sm del" title="Delete" onclick={() => remove(item)}>+ <Icon name="trash" size={14} />+ </button>+ </div>+ </div>+ {/each}+ </div>+ {/if}</div>++ {#if dragOver}+ <div class="drop-overlay">+ <div class="drop-box">+ <Icon name="upload" size={40} />+ <span>Drop to add to the case</span>+ </div>+ </div>+ {/if}</div>++<style>+ .tool {+ position: relative;+ }+ .spacer {+ flex: 1;+ }+ .dl-form {+ display: flex;+ gap: 8px;+ width: min(480px, 40vw);+ }+ .job {+ display: flex;+ align-items: center;+ gap: 12px;+ margin: 14px 20px 0;+ padding: 10px 14px;+ color: var(--text-2);+ }+ .job-url {+ font-size: var(--fs-xs);+ max-width: 260px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .bar {+ flex: 1;+ height: 6px;+ border-radius: 3px;+ background: var(--bg-3);+ overflow: hidden;+ }+ .fill {+ height: 100%;+ background: var(--accent);+ border-radius: 3px;+ transition: width 0.4s var(--ease);+ }+ .fill.indeterminate {+ animation: slide 1.2s infinite var(--ease);+ }+ @keyframes slide {+ from {+ transform: translateX(-100%);+ }+ to {+ transform: translateX(350%);+ }+ }+ .job-meta {+ font-size: var(--fs-xs);+ color: var(--text-3);+ min-width: 90px;+ text-align: right;+ }+ .grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(210px, 1fr));+ gap: 14px;+ padding: 18px 20px;+ }+ .media-card {+ overflow: hidden;+ display: flex;+ flex-direction: column;+ transition: border-color 0.15s var(--ease), transform 0.15s var(--ease);+ }+ .media-card:hover {+ border-color: var(--border-strong);+ transform: translateY(-1px);+ }+ .thumb {+ position: relative;+ aspect-ratio: 16 / 10;+ background: var(--bg-2);+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--text-3);+ }+ .thumb img {+ width: 100%;+ height: 100%;+ object-fit: cover;+ }+ .kind {+ position: absolute;+ top: 8px;+ left: 8px;+ background: rgba(11, 15, 23, 0.75);+ backdrop-filter: blur(4px);+ }+ .body {+ padding: 10px 12px 6px;+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ }+ .name {+ font-size: var(--fs-sm);+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .meta {+ font-size: var(--fs-xs);+ color: var(--text-3);+ }+ .actions {+ display: flex;+ gap: 2px;+ padding: 4px 8px 8px;+ }+ .del {+ margin-left: auto;+ }+ .drop-overlay {+ position: absolute;+ inset: 0;+ background: rgba(11, 15, 23, 0.8);+ display: flex;+ align-items: center;+ justify-content: center;+ z-index: 50;+ pointer-events: none;+ }+ .drop-box {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 12px;+ padding: 44px 64px;+ border: 2px dashed var(--accent);+ border-radius: var(--r-lg);+ color: var(--accent);+ font-weight: 700;+ background: var(--accent-soft);+ }+</style>diff --git a/src/ozimut/api/files.py b/src/ozimut/api/files.pynew file mode 100644index 0000000..5c024c3--- /dev/null+++ b/src/ozimut/api/files.py@@ -0,0 +1,27 @@+"""Serve case files (media, thumbnails, satellite crops, proofs) to the UI.++Only paths inside a case directory are reachable (Case.resolve_inside refuses+traversal), and the server itself binds to localhost only.+"""++from __future__ import annotations++from fastapi import APIRouter, HTTPException+from fastapi.responses import FileResponse++from ..workspace import CaseError+from .cases import get_case++router = APIRouter(prefix="/files", tags=["files"])++[email protected]("/{case_id}/{rel_path:path}")+def case_file(case_id: str, rel_path: str) -> FileResponse:+ case = get_case(case_id)+ try:+ path = case.resolve_inside(rel_path)+ except CaseError as exc:+ raise HTTPException(status_code=403, detail=str(exc)) from exc+ if not path.is_file():+ raise HTTPException(status_code=404, detail="file not found")+ return FileResponse(path)diff --git a/src/ozimut/api/media.py b/src/ozimut/api/media.pynew file mode 100644index 0000000..2a75895--- /dev/null+++ b/src/ozimut/api/media.py@@ -0,0 +1,78 @@+"""REST API for the Media Library: upload, URL download (async job), list, delete."""++from __future__ import annotations++from typing import Any++from fastapi import APIRouter, HTTPException, UploadFile+from pydantic import BaseModel, HttpUrl++from .. import jobs+from ..engine import media as media_engine+from ..workspace import CaseError+from .cases import get_case++router = APIRouter(prefix="/api", tags=["media"])+++class DownloadIn(BaseModel):+ url: HttpUrl+++class DeleteIn(BaseModel):+ path: str++[email protected]("/cases/{case_id}/media")+def list_media(case_id: str) -> list[dict[str, Any]]:+ return media_engine.list_media(get_case(case_id))++[email protected]("/cases/{case_id}/media/upload")+async def upload(case_id: str, file: UploadFile) -> dict[str, Any]:+ case = get_case(case_id)+ result = media_engine.import_stream(case, file.filename or "file", file.file)+ return result++[email protected]("/cases/{case_id}/media/download")+def download(case_id: str, body: DownloadIn) -> dict[str, str]:+ case = get_case(case_id)+ url = str(body.url)++ def work(set_progress):+ def hook(d):+ if d.get("status") == "downloading":+ total = d.get("total_bytes") or d.get("total_bytes_estimate") or 0+ done = d.get("downloaded_bytes") or 0+ set_progress(+ {+ "percent": round(done * 100 / total, 1) if total else None,+ "speed": d.get("_speed_str", "").strip() or None,+ }+ )+ elif d.get("status") == "finished":+ set_progress({"percent": 100, "stage": "processing"})++ return media_engine.download_url(case, url, progress_hook=hook)++ job_id = jobs.start("download", work)+ return {"job_id": job_id}++[email protected]("/jobs/{job_id}")+def job_status(job_id: str) -> dict[str, Any]:+ job = jobs.get(job_id)+ if not job:+ raise HTTPException(status_code=404, detail="job not found")+ return job++[email protected]("/cases/{case_id}/media")+def delete_media(case_id: str, path: str) -> dict[str, str]:+ case = get_case(case_id)+ try:+ media_engine.delete_media(case, path)+ except CaseError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"status": "deleted"}diff --git a/src/ozimut/engine/__init__.py b/src/ozimut/engine/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/src/ozimut/engine/media.py b/src/ozimut/engine/media.pynew file mode 100644index 0000000..15a9af1--- /dev/null+++ b/src/ozimut/engine/media.py@@ -0,0 +1,238 @@+"""Media engine: import local files, download by URL (yt-dlp), hash, thumbnail.++Every media item gets a *sidecar* JSON (``<name>.ozimut.json``) recording how it+entered the case — source, timestamps, hashes (spec §3.6 honest output) — and a+``media`` entity in ``case.json``.+"""++from __future__ import annotations++import hashlib+import json+import mimetypes+import re+import shutil+import subprocess+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, BinaryIO++from PIL import Image++from ..workspace import Case++THUMB_DIR = ".thumbs"+THUMB_MAX = 512+SIDECAR_SUFFIX = ".ozimut.json"+++def _now() -> str:+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")+++def sha256_file(path: Path) -> str:+ digest = hashlib.sha256()+ with path.open("rb") as fh:+ for chunk in iter(lambda: fh.read(1 << 20), b""):+ digest.update(chunk)+ return digest.hexdigest()+++def media_kind(filename: str) -> str:+ mime = mimetypes.guess_type(filename)[0] or ""+ for kind in ("image", "video", "audio"):+ if mime.startswith(kind):+ return kind+ return "file"+++def safe_filename(name: str) -> str:+ name = Path(name).name # strip any path component+ name = re.sub(r"[^\w.\- ]+", "_", name).strip(" .") or "file"+ return name[:150]+++def unique_path(directory: Path, filename: str) -> Path:+ """Return a non-colliding path in directory for filename."""+ stem, suffix = Path(filename).stem, Path(filename).suffix+ candidate = directory / filename+ counter = 1+ while candidate.exists():+ candidate = directory / f"{stem}-{counter}{suffix}"+ counter += 1+ return candidate+++def ffmpeg_available() -> bool:+ return shutil.which("ffmpeg") is not None+++def make_thumbnail(media_path: Path, thumb_path: Path) -> bool:+ """Best-effort thumbnail. Images via Pillow, videos via ffmpeg if present."""+ thumb_path.parent.mkdir(exist_ok=True)+ kind = media_kind(media_path.name)+ try:+ if kind == "image":+ with Image.open(media_path) as img:+ img = img.convert("RGB")+ img.thumbnail((THUMB_MAX, THUMB_MAX))+ img.save(thumb_path, "JPEG", quality=82)+ return True+ if kind == "video" and ffmpeg_available():+ subprocess.run(+ [+ "ffmpeg", "-y", "-loglevel", "error",+ "-ss", "1", "-i", str(media_path),+ "-frames:v", "1", "-vf", f"scale={THUMB_MAX}:-2",+ str(thumb_path),+ ],+ check=True,+ timeout=30,+ capture_output=True,+ )+ return thumb_path.exists()+ except Exception:+ thumb_path.unlink(missing_ok=True)+ return False+++def _sidecar_path(media_path: Path) -> Path:+ return media_path.with_name(media_path.name + SIDECAR_SUFFIX)+++def _write_sidecar(media_path: Path, data: dict[str, Any]) -> None:+ _sidecar_path(media_path).write_text(+ json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"+ )+++def _register(case: Case, media_path: Path, source: dict[str, Any]) -> dict[str, Any]:+ """Hash + sidecar + thumbnail + media entity. Dedupes on sha256."""+ digest = sha256_file(media_path)++ existing = case.find_entity(attr="sha256", value=digest)+ if existing:+ media_path.unlink() # identical bytes already in the case+ return {"duplicate": True, "entity": existing, "item": read_item(case, existing["attrs"]["path"])}++ rel_path = f"media/{media_path.name}"+ thumb = case.subdir("media") / THUMB_DIR / (media_path.name + ".jpg")+ has_thumb = make_thumbnail(media_path, thumb)++ sidecar = {+ "filename": media_path.name,+ "kind": media_kind(media_path.name),+ "sha256": digest,+ "size": media_path.stat().st_size,+ "added_at": _now(),+ "source": source,+ "thumbnail": f"media/{THUMB_DIR}/{media_path.name}.jpg" if has_thumb else None,+ }+ _write_sidecar(media_path, sidecar)++ entity = case.add_entity(+ "media",+ media_path.name,+ attrs={"path": rel_path, "sha256": digest, **({"source_url": source["url"]} if source.get("url") else {})},+ by="media-library",+ source=source.get("url"),+ )+ return {"duplicate": False, "entity": entity, "item": {**sidecar, "path": rel_path}}+++def import_stream(case: Case, filename: str, stream: BinaryIO) -> dict[str, Any]:+ """Import an uploaded file into the case."""+ media_dir = case.subdir("media")+ dest = unique_path(media_dir, safe_filename(filename))+ with dest.open("wb") as out:+ shutil.copyfileobj(stream, out)+ return _register(case, dest, {"type": "upload", "original_name": filename})+++def download_url(case: Case, url: str, progress_hook=None) -> dict[str, Any]:+ """Download a URL via yt-dlp into the case. Blocking — run in a worker."""+ import yt_dlp++ media_dir = case.subdir("media")+ tmp_dir = media_dir / ".dl"+ tmp_dir.mkdir(exist_ok=True)++ ydl_opts = {+ "outtmpl": str(tmp_dir / "%(title).120B [%(id)s].%(ext)s"),+ "noplaylist": True,+ "quiet": True,+ "no_warnings": True,+ "restrictfilenames": False,+ }+ if not ffmpeg_available():+ # without ffmpeg yt-dlp cannot merge separate audio+video streams+ ydl_opts["format"] = "best[acodec!=none][vcodec!=none]/best"+ if progress_hook:+ ydl_opts["progress_hooks"] = [progress_hook]++ with yt_dlp.YoutubeDL(ydl_opts) as ydl:+ info = ydl.extract_info(url, download=True)+ downloaded = Path(ydl.prepare_filename(info))++ if not downloaded.exists(): # extension may differ after post-processing+ candidates = sorted(tmp_dir.glob(f"*[{info['id']}]*"), key=lambda p: p.stat().st_mtime)+ if not candidates:+ raise RuntimeError("yt-dlp reported success but no file was produced")+ downloaded = candidates[-1]++ dest = unique_path(media_dir, safe_filename(downloaded.name))+ shutil.move(str(downloaded), str(dest))+ shutil.rmtree(tmp_dir, ignore_errors=True)++ source = {+ "type": "download",+ "url": url,+ "downloader": f"yt-dlp",+ "title": info.get("title"),+ "uploader": info.get("uploader") or info.get("channel"),+ "upload_date": info.get("upload_date"),+ "webpage_url": info.get("webpage_url", url),+ "extractor": info.get("extractor"),+ "duration": info.get("duration"),+ }+ return _register(case, dest, source)+++def read_item(case: Case, rel_path: str) -> dict[str, Any] | None:+ media_path = case.resolve_inside(rel_path)+ sidecar = _sidecar_path(media_path)+ if not sidecar.exists():+ return None+ data = json.loads(sidecar.read_text(encoding="utf-8"))+ data["path"] = rel_path+ return data+++def list_media(case: Case) -> list[dict[str, Any]]:+ media_dir = case.subdir("media")+ items = []+ for sidecar in sorted(media_dir.glob(f"*{SIDECAR_SUFFIX}")):+ media_name = sidecar.name[: -len(SIDECAR_SUFFIX)]+ if not (media_dir / media_name).exists():+ continue+ data = json.loads(sidecar.read_text(encoding="utf-8"))+ data["path"] = f"media/{media_name}"+ items.append(data)+ items.sort(key=lambda d: d.get("added_at") or "", reverse=True)+ return items+++def delete_media(case: Case, rel_path: str) -> None:+ media_path = case.resolve_inside(rel_path)+ sidecar = _sidecar_path(media_path)+ data = None+ if sidecar.exists():+ data = json.loads(sidecar.read_text(encoding="utf-8"))+ media_path.unlink(missing_ok=True)+ sidecar.unlink(missing_ok=True)+ if data and data.get("thumbnail"):+ case.resolve_inside(data["thumbnail"]).unlink(missing_ok=True)+ # remove the matching media entity (matched by case-relative path)+ entity = case.find_entity(attr="path", value=rel_path)+ if entity:+ case.remove_entity(entity["id"])diff --git a/src/ozimut/jobs.py b/src/ozimut/jobs.pynew file mode 100644index 0000000..37f9c7e--- /dev/null+++ b/src/ozimut/jobs.py@@ -0,0 +1,44 @@+"""Tiny in-memory job registry for long-running work (downloads, …).++POST endpoints start a job in a thread and return its id; the UI polls+GET /api/jobs/{id}. Local single-user app — no persistence needed.+"""++from __future__ import annotations++import threading+import uuid+from typing import Any, Callable++_jobs: dict[str, dict[str, Any]] = {}+_lock = threading.Lock()+++def start(kind: str, work: Callable[[Callable[[dict[str, Any]], None]], Any]) -> str:+ """Run `work(set_progress)` in a thread; returns the job id."""+ job_id = uuid.uuid4().hex[:12]+ with _lock:+ _jobs[job_id] = {"id": job_id, "kind": kind, "status": "running", "progress": {}}++ def set_progress(progress: dict[str, Any]) -> None:+ with _lock:+ if job_id in _jobs:+ _jobs[job_id]["progress"] = progress++ def runner() -> None:+ try:+ result = work(set_progress)+ with _lock:+ _jobs[job_id].update(status="done", result=result)+ except Exception as exc: # surfaced to the UI, not swallowed+ with _lock:+ _jobs[job_id].update(status="error", error=str(exc))++ threading.Thread(target=runner, daemon=True).start()+ return job_id+++def get(job_id: str) -> dict[str, Any] | None:+ with _lock:+ job = _jobs.get(job_id)+ return dict(job) if job else Nonediff --git a/src/ozimut/server.py b/src/ozimut/server.pyindex 62b7ea4..961f8c6 100644--- a/src/ozimut/server.py+++ b/src/ozimut/server.py@@ -18,9 +18,11 @@ def create_app() -> FastAPI:app = FastAPI(title="Ozimut", version=__version__, docs_url="/api/docs")- from .api import cases+ from .api import cases, files, mediaapp.include_router(cases.router)+ app.include_router(media.router)+ app.include_router(files.router)@app.get("/api/health")def health() -> dict[str, str]:@@ -32,8 +34,8 @@ def create_app() -> FastAPI:@app.get("/{path:path}", include_in_schema=False)def spa(path: str): # SPA fallback: serve index.html for app routes- candidate = STATIC_DIR / path- if path and candidate.is_file() and candidate.is_relative_to(STATIC_DIR):+ candidate = (STATIC_DIR / path).resolve()+ if path and candidate.is_file() and candidate.is_relative_to(STATIC_DIR.resolve()):return FileResponse(candidate)return FileResponse(STATIC_DIR / "index.html")diff --git a/tests/test_media_api.py b/tests/test_media_api.pynew file mode 100644index 0000000..04991db--- /dev/null+++ b/tests/test_media_api.py@@ -0,0 +1,85 @@+"""Media Library: upload, dedupe, listing, file serving, deletion."""++import io+import time++from PIL import Image+++def _png_bytes(color=(200, 30, 30), size=(64, 48)) -> bytes:+ buf = io.BytesIO()+ Image.new("RGB", size, color).save(buf, "PNG")+ return buf.getvalue()+++def _upload(client, cid, name, data):+ return client.post(+ f"/api/cases/{cid}/media/upload", files={"file": (name, io.BytesIO(data), "image/png")}+ )+++def test_upload_and_list(client):+ cid = client.post("/api/cases", json={"name": "Media"}).json()["id"]++ res = _upload(client, cid, "frame one.png", _png_bytes()).json()+ assert res["duplicate"] is False+ item = res["item"]+ assert item["kind"] == "image"+ assert len(item["sha256"]) == 64+ assert item["thumbnail"] # Pillow thumbnail for images always works++ listed = client.get(f"/api/cases/{cid}/media").json()+ assert [m["filename"] for m in listed] == ["frame one.png"]++ # media entity was filed with provenance+ case = client.get(f"/api/cases/{cid}").json()+ assert case["entities"][0]["type"] == "media"+ assert case["entities"][0]["provenance"]["by"] == "media-library"++ # the file and its thumbnail are served+ assert client.get(f"/files/{cid}/{item['path']}").status_code == 200+ assert client.get(f"/files/{cid}/{item['thumbnail']}").status_code == 200+++def test_duplicate_detection(client):+ cid = client.post("/api/cases", json={"name": "Dup"}).json()["id"]+ data = _png_bytes(color=(1, 2, 3))+ first = _upload(client, cid, "a.png", data).json()+ second = _upload(client, cid, "b.png", data).json()+ assert second["duplicate"] is True+ assert second["entity"]["id"] == first["entity"]["id"]+ assert len(client.get(f"/api/cases/{cid}/media").json()) == 1+++def test_delete_media_removes_entity(client):+ cid = client.post("/api/cases", json={"name": "Del"}).json()["id"]+ item = _upload(client, cid, "x.png", _png_bytes()).json()["item"]+ client.delete(f"/api/cases/{cid}/media", params={"path": item["path"]})+ assert client.get(f"/api/cases/{cid}/media").json() == []+ assert client.get(f"/api/cases/{cid}").json()["entities"] == []+ assert client.get(f"/files/{cid}/{item['path']}").status_code == 404+++def test_path_traversal_refused(client):+ cid = client.post("/api/cases", json={"name": "Sec"}).json()["id"]+ # percent-encoded so the HTTP client doesn't normalize it away:+ # the decoded rel_path reaching the route is "../../etc/passwd"+ res = client.get(f"/files/{cid}/%2e%2e/%2e%2e/%2e%2e/etc/passwd")+ assert res.status_code in (403, 404)+ assert b"root:" not in res.content+++def test_download_job_bad_url(client):+ cid = client.post("/api/cases", json={"name": "Job"}).json()["id"]+ job_id = client.post(+ f"/api/cases/{cid}/media/download",+ json={"url": "https://localhost:1/nothing-here"},+ ).json()["job_id"]++ for _ in range(100):+ job = client.get(f"/api/jobs/{job_id}").json()+ if job["status"] != "running":+ break+ time.sleep(0.1)+ assert job["status"] == "error"+ assert job["error"]