← Back to index

document_type: "user_manual" service: "MOMENTRY_CORE" title: "TMDb Enrichment 使用指南" date: "2026-05-17" version: "V1.0" status: "active" owner: "M5" created_by: "OpenCode"


TMDb Enrichment 使用指南

項目 內容
目標讀者 developer
預備知識 需有 API Key

Base URL

Environment URL Purpose
Playground (Dev) http://localhost:3003 Development and testing
Production http://localhost:3002 Production deployment
External (M5) https://m5api.momentry.ddns.net Remote access

Variables

All examples in this documentation use these environment variables:

API="http://localhost:3003"
KEY="your-api-key-here"

Authentication

All endpoints under /api/v1/* require authentication. The following endpoints are public (no auth needed):

Three Authentication Modes

The system supports three authentication methods, checked in priority order by the middleware:

Middleware priority:
  1. Session Cookie (Portal/browser)
  2. JWT Bearer (API clients: n8n, CLI)
  3. API Key Header (legacy compatibility)
  4. API Key Query Param (?api_key=)
Mode Transport Expiry Scope Best for
Session Cookie Cookie: session_id=<uuid> 24h per-browser session Portal (browser)
JWT Authorization: Bearer <token> 1h per-login token API clients (n8n, CLI, scripts)
API Key X-API-Key: <key> 90d fixed key for automation Legacy scripts, WordPress

Login

Default accounts & API keys:

Username Password API Key Role
admin admin — admin
demo demo muser_demo_key_32chars_abcdef1234567890 user

The demo API key is set via MOMENTRY_DEMO_API_KEY env var and can be used in place of JWT for marcom integrations:

# Using API key instead of JWT
curl -s "$API/api/v1/files/scan" -H "X-API-Key: muser_demo_key_32chars_abcdef1234567890"
# Login as admin
curl -s -X POST "$API/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username": "admin", "password": "admin"}'

# Login as demo user
curl -s -X POST "$API/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username": "demo", "password": "demo"}'

Success Response

{
  "success": true,
  "jwt": "eyJhbGciOiJIUzI1NiIs...",
  "api_key": "muser_...",
  "user": {
    "username": "admin",
    "role": "admin"
  },
  "expires_at": "2026-05-18T13:00:00Z"
}
Field Type Description
jwt string JWT access token. Use as Authorization: Bearer <jwt>. Expires in 1 hour.
api_key string Legacy API key. Use as X-API-Key: <key>. Good for 90 days.
user.username string Username
user.role string Role: admin, user, or readonly
expires_at string ISO8601 timestamp of JWT expiration

The login endpoint also sets a Set-Cookie header for browser-based clients:

Set-Cookie: session_id=<uuid>; Path=/api; HttpOnly; SameSite=Strict; Max-Age=86400

Error Response (401)

{
  "success": false,
  "message": "Invalid username or password"
}

Using JWT

JWT is preferred for API clients (n8n, CLI scripts, WordPress). It is validated by the middleware without a database lookup (stateless).

# Login and capture JWT
JWT=$(curl -s -X POST "$API/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin"}' | python3 -c "import json,sys;print(json.load(sys.stdin)['jwt'])")

# Use JWT for all subsequent requests
curl -H "Authorization: Bearer $JWT" "$API/api/v1/files/scan"
curl -H "Authorization: Bearer $JWT" "$API/api/v1/resource/tmdb"

JWT is short-lived (1 hour). When it expires, request a new one via login.


Using Session Cookie (Browser)

Browser-based clients (Portal) get a session cookie automatically after login. The browser sends the cookie with every request—no manual header needed.

# Login captures the session cookie from Set-Cookie header
curl -v -X POST "$API/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin"}' 2>&1 | grep "Set-Cookie"

# Browser automatically sends: Cookie: session_id=<uuid>
# No manual header needed for subsequent requests

The session cookie is HttpOnly (not accessible from JavaScript) and SameSite=Strict (protected against CSRF).


Using Legacy API Key

curl -H "X-API-Key: $KEY" "$API/api/v1/files/scan"

# Also accepted via Bearer header (non-JWT format) or query parameter:
curl -H "Authorization: Bearer $KEY" "$API/api/v1/files/scan"
curl "$API/api/v1/files/scan?api_key=$KEY"

API keys are validated via SHA256 hash lookup in the database. They are long-lived (90 days) and intended for automation.

Obtaining an API Key (CLI)

momentry api-key create "My API Key" --key-type user

Logout

# Logout using the session cookie (browser)
curl -X POST "$API/api/v1/auth/logout" \
  -H "Cookie: session_id=<uuid>"

What logout does

Auth mode Effect
Session Cookie Session deleted from database. Same cookie returns 401 on subsequent requests.
JWT JWT remains valid until expiry. (JWT is stateless — logout adds JWT to a blacklist only if API key mode is used.)
API Key API key remains valid. (Legacy keys are shared across sessions — revoking would break other clients.)

Example: full session lifecycle

# 1. Login
SESSION_ID=$(curl -s -D - -X POST "$API/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username":"admin","password":"admin"}' | grep "Set-Cookie" | sed 's/.*session_id=\([^;]*\).*/\1/')

# 2. Use session (works)
curl -s -o /dev/null -w "HTTP %{http_code}\n" "$API/api/v1/resource/tmdb" \
  -H "Cookie: session_id=$SESSION_ID"
# → HTTP 200

# 3. Logout
curl -s -X POST "$API/api/v1/auth/logout" \
  -H "Cookie: session_id=$SESSION_ID"
# → {"success": true}

# 4. Use session again (rejected)
curl -s -o /dev/null -w "HTTP %{http_code}\n" "$API/api/v1/resource/tmdb" \
  -H "Cookie: session_id=$SESSION_ID"
# → HTTP 401

Authentication Flow Summary

Login Request
     │
     ▼
┌──────────────────┐
│  1. Check users  │ ← users table (argon2 password verify)
│     table        │
└──────┬───────────┘
       │
   ┌───┴───┐
   │ match │
   └───┬───┘
       │
       ▼
┌──────────────────┐
│  2. Create JWT   │ ← 1h expiry, signed with JWT_SECRET
├──────────────────┤
│  3. Create       │ ← 24h expiry, stored in sessions table
│     session      │
├──────────────────┤
│  4. Set-Cookie   │ ← HttpOnly, SameSite=Strict, Path=/api
├──────────────────┤
│  5. Return       │ ← JWT + api_key + user info to client
└──────────────────┘
Protected Request
     │
     ▼
┌──────────────────────┐
│  Middleware checks:  │
│                      │
│  1. Cookie session?  │ → DB lookup session → get api_key → verify
│                      │
│  2. JWT Bearer?      │ → verify JWT signature → decode claims
│                      │
│  3. X-API-Key?       │ → SHA256 hash → DB lookup → verify
│                      │
│  4. ?api_key=?       │ → same as #3
│                      │
│  5. None → 401       │
└──────────────────────┘

Error Responses

HTTP When
401 Missing or invalid authentication
401 Session expired or logged out
401 JWT expired
401 API key revoked or inactive

Related


File Registration

POST /api/v1/files/register

Auth: Required Scope: file-level

Register a video file for processing. Returns the file's metadata and UUID.

New in v0.1.2: Registration now automatically triggers the processing pipeline — no need to call POST /api/v1/file/:uuid/process separately. The system will: 1. Register the file and run ffprobe 2. Auto-run offline TMDb probe (reads local identity files, no API calls) 3. Create a monitor job for the worker 4. Worker starts all 10 processors (Cut → ASR → ASRX → YOLO → OCR → Face → Pose → VisualChunk → Story → 5W1H)

If the file already exists (same content hash), returns the existing record with already_exists: true.

Request Parameters

Field Type Required Default Description
file_path string Yes — Path to video file on disk
pattern string No — Regex pattern for batch register (requires file_path to be a directory)
user_id integer No — User ID to associate with registration
content_hash string No — Pre-computed SHA-256 hash (skips computation)

Example

# Register a single file
curl -s -X POST "$API/api/v1/files/register" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $KEY" \
  -d '{"file_path": "/path/to/video.mp4"}'

# Batch register files matching a pattern in a directory
curl -s -X POST "$API/api/v1/files/register" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $KEY" \
  -d '{"file_path": "/path/to/dir", "pattern": ".*\\.mp4$"}'

Response (200)

{
  "success": true,
  "file_uuid": "3a6c1865...",
  "file_name": "video.mp4",
  "file_path": "/path/to/video.mp4",
  "file_type": "video",
  "duration": 120.5,
  "width": 1920,
  "height": 1080,
  "fps": 24.0,
  "total_frames": 2892,
  "already_exists": false,
  "message": "File registered successfully"
}
Field Type Description
success boolean Always true on 200
file_uuid string 32-char hex UUID of the registered file
file_name string File name (auto-renamed if name conflict)
file_path string Canonical path on disk
file_type string "video", "audio", or "unknown"
duration float Duration in seconds
width integer Video width in pixels
height integer Video height in pixels
fps float Frames per second
total_frames integer Total frame count
already_exists boolean True if same content was already registered
message string Human-readable status

Error Responses

HTTP When
401 Missing or invalid API key
400 Invalid request body
404 File path does not exist

GET /api/v1/files/scan

Auth: Required Scope: file-level

Scan the filesystem directory and list all media files, showing which are registered, processing, or unregistered.

Query Parameters

Field Type Required Default Description
page integer No 1 Page number (1-based)
page_size integer No all Items per page (alias: limit)
limit integer No all Max items (alias for page_size)
pattern string No — Regex filter on file name (e.g., .*\\.mp4$)
sort_by string No name Sort field: name, size, modified, status
sort_order string No asc Sort direction: asc or desc

Example

# Full scan
curl -s "$API/api/v1/files/scan" -H "X-API-Key: $KEY" | jq '{total, registered_count, unregistered_count}'

# Paginated (page 1, 5 per page)
curl -s "$API/api/v1/files/scan?page=1&page_size=5" -H "X-API-Key: $KEY" | jq '{page, total_pages, files: [.files[].file_name]}'

# Regex filter: only mp4 files
curl -s "$API/api/v1/files/scan?pattern=.*\\.mp4$" -H "X-API-Key: $KEY" | jq '{filtered_total, files: [.files[].file_name]}'

# Sort by file size (largest first)
curl -s "$API/api/v1/files/scan?sort_by=size&sort_order=desc&page_size=5" -H "X-API-Key: $KEY" | jq '[.files[] | {file_name, file_size}]'

# Sort by modified time (most recent first)
curl -s "$API/api/v1/files/scan?sort_by=modified&sort_order=desc&page_size=5" -H "X-API-Key: $KEY" | jq '[.files[] | {file_name, modified_time}]'

# Sort by status
curl -s "$API/api/v1/files/scan?sort_by=status&page_size=5" -H "X-API-Key: $KEY" | jq '[.files[] | {file_name, status}]'

Response (200)

{
  "files": [
    {
      "file_name": "video.mp4",
      "file_size": 12345678,
      "is_registered": true,
      "file_uuid": "3a6c1865...",
      "status": "completed",
      "registration_time": "2026-05-16T12:00:00Z",
      "job_id": 42
    }
  ],
  "total": 107,
  "filtered_total": 80,
  "page": 1,
  "page_size": 20,
  "total_pages": 4,
  "registered_count": 26,
  "unregistered_count": 81
}
Field Type Description
files array Array of file info objects (paginated)
files[].file_name string File name
files[].relative_path string Path relative to scan root
files[].file_path string Absolute path on disk
files[].file_size integer File size in bytes
files[].modified_time string Last modified timestamp (ISO8601)
files[].is_registered boolean Whether file is registered in DB
files[].file_uuid string 32-char hex UUID (only if registered)
files[].status string "completed", "processing", "registered", "unregistered", or null
files[].registration_time string DB registration timestamp (only if registered)
files[].job_id integer Processing job ID (only if a job exists)
total integer Total files found on disk (unfiltered)
filtered_total integer Files matching regex filter
page integer Current page number
page_size integer Items per page
total_pages integer Total pages
registered_count integer Files registered in DB
unregistered_count integer Files not yet registered

Notes

Feature Behavior
Regex Case-insensitive ((?i) prefix auto-applied). Applied to file_name.
Sort order Default (sort_by=name): registered files first, then alphabetically. sort_by=status: alphabetical by status string.
Pagination page_size and limit are aliases. Default: show all results.
Processing order pattern regex filter → sort_by/sort_order → page/page_size slice.

TMDb Enrichment

⚠️ External resource: TMDb requires internet access, violating Momentry's local-only principle. All core processing (ASR, YOLO, Face, OCR, Pose, embeddings) runs fully offline. TMDb enrichment is optional and gated behind TMDB_API_KEY + MOMENTRY_TMDB_PROBE_ENABLED.

Overview

TMDb enrichment is an optional identity enrichment step that can be run after Pipeline face detection completes. The workflow is:

  1. Prefetch (requires internet): Download movie cast data from TMDb API → cache to {file_uuid}.tmdb.json
  2. Probe: Read local cache → create identities for all cast members (source='tmdb') + save identity.json + download profile image to {OUTPUT}/identities/{uuid}/profile.jpg
  3. Match: The worker automatically matches video faces against TMDb identities when MOMENTRY_TMDB_PROBE_ENABLED=true

POST /api/v1/agents/tmdb/prefetch

Auth: Required Scope: file-level

Fetch TMDb cast data for a registered file and cache it locally. This is the only step requiring internet access.

Request Parameters

Field Type Required Description
file_uuid string Yes File UUID to enrich

Example

curl -s -X POST "$API/api/v1/agents/tmdb/prefetch" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $KEY" \
  -d '{"file_uuid": "'"$FILE_UUID"'"}'

Response (200)

{"success": true, "file_uuid": "...", "cache_path": "/output/...tmdb.json"}

POST /api/v1/file/:file_uuid/tmdb-probe

Auth: Required Scope: file-level

Read local TMDb cache and create/update identities. Requires prefetch to have been run first.

Example

curl -s -X POST "$API/api/v1/file/$FILE_UUID/tmdb-probe" \
  -H "X-API-Key: $KEY" | jq '{identities_created, movie_title}'

Response (200 — identities created)

{"success": true, "identities_created": 15, "movie_title": "Charade"}

Response (200 — no cache)

{"success": false, "message": "No TMDb cache found. Run tmdb-prefetch first."}

GET /api/v1/resource/tmdb

Auth: Required Scope: system-level

View TMDb resource status including configuration, identity counts, and cache file count.

Example

curl -s "$API/api/v1/resource/tmdb" -H "X-API-Key: $KEY" \
  | jq '{identities_seeded, cache_files}'

POST /api/v1/resource/tmdb/check

Auth: Required Scope: system-level

Ping the TMDb API to verify connectivity and measure latency.

Example

curl -s -X POST "$API/api/v1/resource/tmdb/check" \
  -H "X-API-Key: $KEY" | jq '.status'

Response

{
  "api_key_configured": true,
  "enabled": false,
  "api_reachable": true,
  "api_latency_ms": 120
}