← Back to index

document_type: "user_manual" service: "MOMENTRY_CORE" title: "Momentry Core API 教育訓練手冊" date: "2026-05-17" version: "V1.5" status: "active" owner: "M5" created_by: "OpenCode"


Momentry Core API 教育訓練手冊

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

About This Manual

This training manual is designed for the Marcom team to understand and use the Momentry Core API.

Demo Credentials

API Key: muser_68600856036340bcafc01930eb4bd839_1774418104_97221b69

SFTPGo (for video upload):

Item Value
SFTP Host sftpgo.momentry.ddns.net
SFTP Port 2022
Username demo
Password demopassword123
Web UI https://sftpgo.momentry.ddns.net

Quick Examples

List all videos:

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

Search:

curl -s -X POST "$API/api/v1/search" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $KEY" \
  -d '{"query": "example", "limit": 5}'

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.

Search APIs

Standard Search

POST /api/v1/search

Auth: Required Scope: file-level

Semantic/vector search across indexed video chunks. Returns matching chunks with scores.

Request Parameters

Field Type Required Default Description
query string Yes — Search text
file_uuid string No — Restrict search to a specific file
limit integer No 10 Max results
page integer No 1 Page number (1-based)
page_size integer No limit Items per page (alias: page_size)
mode string No smart Search mode: "vector" or "smart"

Example

# Search across all files
curl -s -X POST "$API/api/v1/search" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $KEY" \
  -d '{"query": "charade", "limit": 5}'

# Search within a specific file
curl -s -X POST "$API/api/v1/search" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $KEY" \
  -d '{"query": "charade", "file_uuid": "'"$FILE_UUID"'"}'

# Paginated search
curl -s -X POST "$API/api/v1/search" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $KEY" \
  -d '{"query": "charade", "page": 1, "page_size": 3}'

Response (200)

{
  "results": [
    {
      "uuid": "3a6c1865...",
      "chunk_id": "sentence_0012",
      "chunk_type": "sentence",
      "start_time": 48.8,
      "end_time": 55.4,
      "text": "charade is a classic film...",
      "score": 0.92
    }
  ],
  "query": "charade",
  "total": 15,
  "page": 1,
  "page_size": 3
}

> Results are deduplicated by `chunk_id` (highest score wins) before pagination.

| Field | Type | Description |
|-------|------|-------------|
| `results` | array | Array of matched chunks (deduplicated) |
| `results[].uuid` | string | File UUID |
| `results[].chunk_id` | string | Chunk identifier |
| `results[].chunk_type` | string | `"sentence"`, `"cut"`, `"trace"`, `"visual"` |
| `results[].start_time` | float | Start time in seconds |
| `results[].end_time` | float | End time in seconds |
| `results[].text` | string | Chunk text content |
| `results[].score` | float | Similarity score (0.0–1.0) |
| `query` | string | Original search query |
| `total` | integer | Total matching results |
| `page` | integer | Current page number |
| `page_size` | integer | Items per page |

#### Error Responses

| HTTP | When |
|------|------|
| `401` | Missing or invalid API key |

---

### `POST /api/v1/search/hybrid`

**Auth**: Required
**Scope**: file-level

Hybrid search combining vector similarity score and BM25 text score into a combined score.

#### Request Parameters

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `query` | string | Yes | — | Search text |
| `file_uuid` | string | No | — | Restrict search to a specific file |
| `limit` | integer | No | 10 | Max results |
| `page` | integer | No | 1 | Page number (1-based) |
| `page_size` | integer | No | `limit` | Items per page |
| `vector_weight` | float | No | 0.5 | Weight for vector score (0.0–1.0) |
| `bm25_weight` | float | No | 0.5 | Weight for BM25 score (0.0–1.0) |

#### Response

```json
{
  "results": [
    {
      "uuid": "3a6c1865...",
      "chunk_id": "sentence_0012",
      "chunk_type": "sentence",
      "start_time": 48.8,
      "end_time": 55.4,
      "text": "charade is a classic film...",
      "vector_score": 0.85,
      "bm25_score": 0.72,
      "combined_score": 0.79
    }
  ],
  "query": "charade"
}
Field Type Description
results[].vector_score float Vector similarity score
results[].bm25_score float BM25 text score
results[].combined_score float Weighted combination of both scores

POST /api/v1/search/bm25

Auth: Required Scope: file-level

BM25 full-text keyword search. Good for exact term matching. Returns results with BM25 score only.

Request Parameters

Same as standard search: query, file_uuid, limit.

Response

Returns the same structure as standard search, with score representing the BM25 relevance score.


N8N Search

N8N-format search endpoints. Response format is optimized for n8n workflow consumption.

Method Endpoint Description
POST /api/v1/n8n/search N8N-format vector search
POST /api/v1/n8n/search/bm25 N8N-format BM25 search
POST /api/v1/n8n/search/hybrid N8N-format hybrid search
POST /api/v1/n8n/search/smart N8N-format smart search

Request Parameters

Field Type Required Default Description
query string Yes — Search text
file_uuid string No — Restrict to specific file
types string[] No ["chunk"] Search types: chunk, frame, person
filters object No — Filter criteria (confidence, object class, speaker, etc.)
page integer No 1 Page number
page_size integer No 20 Items per page
time_range float[2] No — Time range [start, end] in seconds

Example

curl -s -X POST "$API/api/v1/n8n/search" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: $KEY" \
  -d '{"query": "charade", "limit": 5}'

Response (200)

{
  "query": "charade",
  "results": [
    {
      "type": "chunk",
      "chunk_id": "sentence_0012",
      "chunk_type": "sentence",
      "file_uuid": "3a6c1865...",
      "start_time": 48.8,
      "end_time": 55.4,
      "text": "charade is a classic film...",
      "score": 0.92
    }
  ],
  "total": 15,
  "page": 1,
  "page_size": 20,
  "took_ms": 42
}
Field Type Description
results array Array of search results
results[].type string Result type: "chunk", "frame", or "person"
results[].chunk_id string Chunk identifier
results[].chunk_type string Chunk type
results[].file_uuid string File UUID
results[].start_time float Start time in seconds
results[].end_time float End time in seconds
results[].text string Content text
results[].score float Relevance score
total integer Total matching results
page integer Current page
page_size integer Items per page
took_ms integer Query execution time in milliseconds

Identity Text Search

Two paths for searching identities by text.

Path A: GET /api/v1/search/identity_text

Search chunk text content and return associated identities (if any).

Auth: Required Scope: file-level

Field Type Required Description
file_uuid string Yes File UUID to search within
q string Yes Text search query
limit integer No Max results (default 50)
page integer No 1
page_size integer No limit
curl -s "$API/api/v1/search/identity_text?file_uuid=$FILE_UUID&q=charade&page=1&page_size=5" \
  -H "X-API-Key: $KEY"
Response
{
  "success": true,
  "total": 0,
  "page": 1,
  "page_size": 5,
  "limit": 50,
  "results": []
}

Each result (IdentityTextHit):

{
  "file_uuid": "3a6c1865...",
  "chunk_id": "sentence_0012",
  "start_time": 48.8,
  "end_time": 55.4,
  "text_content": "charade is a classic film...",
  "identity_id": 42,
  "identity_name": "Cary Grant",
  "identity_source": "tmdb",
  "trace_id": 10
}
Field Type Description
file_uuid string File UUID
chunk_id string Chunk identifier
start_time float Start time in seconds
end_time float End time in seconds
text_content string Chunk text content
identity_id integer Identity ID (null if no identity matched)
identity_name string Identity name (null if no identity matched)
identity_source string Identity origin. .json = established from identity.json files on disk (unified format for all sources). tmdb = from .json via TMDb enrichment probe, then matched against faces. auto = pipeline face matching result; only stranger identities are auto-created. user_defined = manual. merged = merged identities.
trace_id integer Face trace ID (null if no trace matched)

Path B: POST /api/v1/identities/search

Search identity names and return associated face detection text.

Auth: Required Scope: identity-level

Field Type Required Description
q string Yes Identity name search
file_uuid string No Restrict to specific file
limit integer No Max results (default 50)
curl -s -X POST "$API/api/v1/identities/search" \
  -H "X-API-Key: $KEY" \
  -d '{"q": "Cary Grant"}'

Visual Chunk Search

Search video frames by visual content (object detection results).

Method Endpoint Description
POST /api/v1/search/visual Search visual chunks by criteria (object classes, density)
POST /api/v1/search/visual/class Search by specific object class
POST /api/v1/search/visual/density Search by spatial density range
POST /api/v1/search/visual/stats Get visual detection statistics
POST /api/v1/search/visual/combination Search by object class combination

Request Parameters (Visual Search)

Field Type Required Description
file_uuid string Yes File UUID
criteria.required_classes string[] No Required object classes (e.g., ["person", "car"])
criteria.min_confidence float No Minimum confidence threshold
criteria.min_spatial_density float No Minimum spatial density
criteria.max_spatial_density float No Maximum spatial density

Example

curl -s -X POST "$API/api/v1/search/visual" \
  -H "X-API-Key: $KEY" \
  -H "Content-Type: application/json" \
  -d '{"file_uuid": "'"$FILE_UUID"'", "criteria": {"required_classes": ["person", "car"]}}'

Response

{
  "chunks": [
    {
      "file_uuid": "3a6c1865...",
      "chunk_id": "visual_001",
      "chunk_type": "visual",
      "detections": [
        {"class": "person", "confidence": 0.95, "bbox": [100, 200, 150, 350]}
      ],
      "start_time": 120.5,
      "end_time": 125.3
    }
  ],
  "total": 42
}
Field Type Description
chunks array Array of matching visual chunks
chunks[].file_uuid string File UUID
chunks[].chunk_id string Chunk identifier
chunks[].detections array Object detections in this chunk
total integer Total matching chunks