feat: add video streaming proxy and webhook cache invalidation
- Add /api/video/[id] route with Range header support for seeking - Add /api/webhook route for Immich event-driven cache invalidation - Add streamVideo() to ImmichClient with 206 Partial Content support - Support album description overrides in gallery.yaml - Add videoUrl() helper to lib/urls.ts - Export cache.delete() and cache.clear() methods
This commit is contained in:
66
app/api/video/[id]/route.ts
Normal file
66
app/api/video/[id]/route.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Video proxy route — streams Immich video assets to the browser
|
||||
* without exposing the Immich server or API key.
|
||||
*
|
||||
* Supports HTTP Range requests (required for <video> seeking in browsers).
|
||||
*
|
||||
* Usage: GET /api/video/:token
|
||||
* GET /api/video/:token (with Range header for seeking)
|
||||
* The :token is an encoded asset ID (not a raw UUID).
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { immich } from '@/lib/immich';
|
||||
import { decodeAssetId } from '@/lib/tokens';
|
||||
import { getConfig } from '@/lib/config';
|
||||
import { checkRateLimit, getClientIp } from '@/lib/rate-limit';
|
||||
|
||||
export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
// ── Rate limiting ──────────────────────────────────
|
||||
const ip = getClientIp(request);
|
||||
const { success, remaining, resetAt } = checkRateLimit(`video:${ip}`, getConfig().rateLimitRpm);
|
||||
|
||||
if (!success) {
|
||||
const retryAfter = Math.ceil((resetAt - Date.now()) / 1000);
|
||||
console.warn(`[Video API] ⚠️ Rate limit exceeded for IP: ${ip}. Retry after ${retryAfter}s`);
|
||||
return NextResponse.json({ error: 'Too many requests' }, { status: 429 });
|
||||
}
|
||||
|
||||
const { id: token } = await params;
|
||||
|
||||
// Decode the opaque token back to an Immich asset ID
|
||||
const assetId = decodeAssetId(token);
|
||||
if (!assetId) {
|
||||
console.error(`[Video API] ❌ Invalid token: ${token.substring(0, 10)}...`);
|
||||
return NextResponse.json({ error: 'Invalid token' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Forward Range header from browser (needed for <video> seeking)
|
||||
const rangeHeader = request.headers.get('range');
|
||||
|
||||
const result = await immich.streamVideo(assetId, rangeHeader);
|
||||
if (!result) {
|
||||
console.error(`[Video API] ❌ Asset not found in Immich: ${assetId}`);
|
||||
return NextResponse.json({ error: 'Asset not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': result.contentType,
|
||||
// Videos are immutable once uploaded — cache aggressively
|
||||
'Cache-Control': 'public, max-age=31536000, immutable',
|
||||
'Accept-Ranges': 'bytes',
|
||||
'X-RateLimit-Remaining': String(remaining),
|
||||
};
|
||||
|
||||
if (result.contentLength) {
|
||||
headers['Content-Length'] = result.contentLength;
|
||||
}
|
||||
if (result.contentRange) {
|
||||
headers['Content-Range'] = result.contentRange;
|
||||
}
|
||||
|
||||
return new NextResponse(result.stream, {
|
||||
status: result.status,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
102
app/api/webhook/route.ts
Normal file
102
app/api/webhook/route.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* Webhook endpoint — receives album update events from Immich and
|
||||
* invalidates the corresponding in-memory cache entries.
|
||||
*
|
||||
* Security: requests must include an HMAC-SHA256 signature in the
|
||||
* `x-immich-signature` header, computed as:
|
||||
*
|
||||
* HMAC-SHA256(WEBHOOK_SECRET, raw request body)
|
||||
*
|
||||
* If WEBHOOK_SECRET is not set, the endpoint returns 501.
|
||||
*
|
||||
* Supported Immich event types:
|
||||
* - album.updated → invalidates the specific album
|
||||
* - album.assetAdded → invalidates the specific album
|
||||
* - album.assetRemoved → invalidates the specific album
|
||||
* - * → any other event clears the full cache
|
||||
*
|
||||
* POST /api/webhook
|
||||
*/
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { createHmac, timingSafeEqual } from 'crypto';
|
||||
import { immich } from '@/lib/immich';
|
||||
import { env } from '@/lib/env';
|
||||
import { checkRateLimit, getClientIp } from '@/lib/rate-limit';
|
||||
|
||||
// Tight rate limit — webhooks should come from one trusted source only
|
||||
const WEBHOOK_RPM = 60;
|
||||
|
||||
/** Album-scoped Immich webhook events. */
|
||||
const ALBUM_EVENTS = new Set(['album.updated', 'album.assetAdded', 'album.assetRemoved']);
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
// ── Feature guard ──────────────────────────────────
|
||||
if (!env.WEBHOOK_SECRET) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Webhook is not configured. Set WEBHOOK_SECRET in your environment.' },
|
||||
{ status: 501 },
|
||||
);
|
||||
}
|
||||
|
||||
// ── Rate limiting ──────────────────────────────────
|
||||
const ip = getClientIp(request);
|
||||
const { success } = checkRateLimit(`webhook:${ip}`, WEBHOOK_RPM);
|
||||
if (!success) {
|
||||
return NextResponse.json({ error: 'Too many requests' }, { status: 429 });
|
||||
}
|
||||
|
||||
// ── Read body (needed for HMAC verification) ───────
|
||||
let rawBody: string;
|
||||
try {
|
||||
rawBody = await request.text();
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Failed to read request body' }, { status: 400 });
|
||||
}
|
||||
|
||||
// ── Signature verification ─────────────────────────
|
||||
const signature = request.headers.get('x-immich-signature');
|
||||
if (!signature) {
|
||||
console.warn('[Webhook] ⚠️ Missing x-immich-signature header');
|
||||
return NextResponse.json({ error: 'Missing signature' }, { status: 401 });
|
||||
}
|
||||
|
||||
const expected = createHmac('sha256', env.WEBHOOK_SECRET).update(rawBody).digest('hex');
|
||||
|
||||
let signatureValid = false;
|
||||
try {
|
||||
signatureValid = timingSafeEqual(Buffer.from(signature, 'hex'), Buffer.from(expected, 'hex'));
|
||||
} catch {
|
||||
// Buffer lengths differ → invalid hex or wrong length
|
||||
signatureValid = false;
|
||||
}
|
||||
|
||||
if (!signatureValid) {
|
||||
console.warn(`[Webhook] ⚠️ Invalid signature from ${ip}`);
|
||||
return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });
|
||||
}
|
||||
|
||||
// ── Parse payload ──────────────────────────────────
|
||||
let payload: { event?: string; albumId?: string } = {};
|
||||
try {
|
||||
payload = JSON.parse(rawBody);
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON payload' }, { status: 400 });
|
||||
}
|
||||
|
||||
const { event, albumId } = payload;
|
||||
|
||||
if (!event) {
|
||||
return NextResponse.json({ error: 'Missing event field in payload' }, { status: 400 });
|
||||
}
|
||||
|
||||
// ── Cache invalidation ─────────────────────────────
|
||||
if (ALBUM_EVENTS.has(event) && albumId && typeof albumId === 'string') {
|
||||
immich.invalidateAlbum(albumId);
|
||||
return NextResponse.json({ ok: true, invalidated: albumId });
|
||||
}
|
||||
|
||||
// Any unrecognised event → full cache clear
|
||||
immich.invalidateAll();
|
||||
return NextResponse.json({ ok: true, invalidated: 'all' });
|
||||
}
|
||||
@@ -25,6 +25,7 @@ subpages:
|
||||
- "album-uuid-5"
|
||||
- "album-uuid-6":
|
||||
title: "Private Project #7"
|
||||
description: "Shot on 35mm film in Vienna, spring 2025." # Optional: shown below album title
|
||||
password: "scrypt:..." # Recommended: secure hash (generated via logs)
|
||||
|
||||
# ── Subpage with Sections ──────────────────────────────────────────
|
||||
|
||||
@@ -44,6 +44,10 @@ class MemoryCache {
|
||||
});
|
||||
}
|
||||
|
||||
delete(key: string): void {
|
||||
this.store.delete(key);
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.store.clear();
|
||||
}
|
||||
|
||||
@@ -21,11 +21,15 @@ export interface SubpageObjectValue {
|
||||
subtitle?: string;
|
||||
password?: string;
|
||||
grid?: Partial<GridConfig>;
|
||||
albums?: Array<string | Record<string, string | { title: string; password?: string }>>;
|
||||
albums?: Array<
|
||||
string | Record<string, string | { title: string; description?: string; password?: string }>
|
||||
>;
|
||||
sections?: Array<{
|
||||
title: string;
|
||||
description?: string;
|
||||
albums: Array<string | Record<string, string | { title: string; password?: string }>>;
|
||||
albums: Array<
|
||||
string | Record<string, string | { title: string; description?: string; password?: string }>
|
||||
>;
|
||||
}>;
|
||||
}
|
||||
|
||||
@@ -91,6 +95,7 @@ export interface AppConfig {
|
||||
map: boolean;
|
||||
transitions: boolean;
|
||||
albumOverrides: Record<string, string>;
|
||||
albumDescriptions: Record<string, string>;
|
||||
albumPasswords: Record<string, string>;
|
||||
cacheTtl: number;
|
||||
rateLimitRpm: number;
|
||||
@@ -100,18 +105,26 @@ export interface AppConfig {
|
||||
|
||||
export interface GalleryYaml {
|
||||
hero?: string | string[];
|
||||
albums?: string[];
|
||||
albums?: Array<
|
||||
string | Record<string, string | { title: string; description?: string; password?: string }>
|
||||
>;
|
||||
subpages?:
|
||||
| Record<string, string[] | Array<string | Record<string, string>>>
|
||||
| Array<{
|
||||
name: string;
|
||||
title?: string;
|
||||
subtitle?: string;
|
||||
albums?: Array<string | Record<string, string | { title: string; password?: string }>>;
|
||||
albums?: Array<
|
||||
| string
|
||||
| Record<string, string | { title: string; description?: string; password?: string }>
|
||||
>;
|
||||
sections?: Array<{
|
||||
title: string;
|
||||
description?: string;
|
||||
albums: Array<string | Record<string, string | { title: string; password?: string }>>;
|
||||
albums: Array<
|
||||
| string
|
||||
| Record<string, string | { title: string; description?: string; password?: string }>
|
||||
>;
|
||||
}>;
|
||||
password?: string;
|
||||
grid?: {
|
||||
|
||||
@@ -108,6 +108,52 @@ class ImmichClient {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream a video from Immich with optional Range header forwarding.
|
||||
* Range support is required for `<video>` seeking in browsers.
|
||||
*/
|
||||
async streamVideo(
|
||||
assetId: string,
|
||||
rangeHeader?: string | null,
|
||||
): Promise<{
|
||||
stream: ReadableStream;
|
||||
contentType: string;
|
||||
contentLength: string | null;
|
||||
contentRange: string | null;
|
||||
status: 200 | 206;
|
||||
} | null> {
|
||||
if (this.config.needsSetup || !this.config.immich.apiUrl) return null;
|
||||
|
||||
const endpoint = `/assets/${encodeURIComponent(assetId)}/video/playback`;
|
||||
const url = `${this.config.immich.apiUrl}${endpoint}`;
|
||||
try {
|
||||
const headers: Record<string, string> = {
|
||||
'x-api-key': this.config.immich.apiKey,
|
||||
};
|
||||
if (rangeHeader) {
|
||||
headers['Range'] = rangeHeader;
|
||||
}
|
||||
|
||||
const res = await fetch(url, { headers });
|
||||
|
||||
if ((!res.ok && res.status !== 206) || !res.body) {
|
||||
console.error(`[Immich] Failed to stream video ${assetId}: ${res.status}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
stream: res.body,
|
||||
contentType: res.headers.get('Content-Type') || 'video/mp4',
|
||||
contentLength: res.headers.get('Content-Length'),
|
||||
contentRange: res.headers.get('Content-Range'),
|
||||
status: res.status === 206 ? 206 : 200,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`[Immich] Video stream error for ${assetId}:`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream a binary response from Immich (for image proxying).
|
||||
*/
|
||||
@@ -169,9 +215,11 @@ class ImmichClient {
|
||||
.filter((album) => allowedIds.has(album.id))
|
||||
.map((album) => {
|
||||
const name = this.config.albumOverrides[album.id] ?? album.albumName;
|
||||
const description = this.config.albumDescriptions[album.id] ?? album.description ?? '';
|
||||
return {
|
||||
...album,
|
||||
albumName: name,
|
||||
description,
|
||||
slug: slugify(name),
|
||||
};
|
||||
});
|
||||
@@ -296,7 +344,9 @@ class ImmichClient {
|
||||
album.assets = (album.assets || []).filter((a) => !a.isTrashed);
|
||||
|
||||
const name = this.config.albumOverrides[album.id] ?? album.albumName;
|
||||
const description = this.config.albumDescriptions[album.id] ?? album.description ?? '';
|
||||
album.albumName = name;
|
||||
album.description = description;
|
||||
album.slug = slugify(name);
|
||||
|
||||
cache.set(cacheKey, album, this.config.cacheTtl);
|
||||
@@ -368,6 +418,25 @@ class ImmichClient {
|
||||
return promise;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate the cache for a specific album (by Immich UUID) and the
|
||||
* shared albums-list entry. Called by the webhook handler after an
|
||||
* album.updated / album.assetAdded event from Immich.
|
||||
*/
|
||||
invalidateAlbum(albumId: string): void {
|
||||
cache.delete(`album-${albumId}`);
|
||||
cache.delete('albums-list');
|
||||
console.log(`[Immich] 🔄 Cache invalidated for album ${albumId}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate all album caches at once (e.g. on a full sync event).
|
||||
*/
|
||||
invalidateAll(): void {
|
||||
cache.clear();
|
||||
console.log('[Immich] 🔄 Full cache cleared via webhook');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the Immich server is reachable.
|
||||
*/
|
||||
|
||||
@@ -24,6 +24,13 @@ export function exifUrl(assetId: string): string {
|
||||
return `/api/exif/${encodeAssetId(assetId)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a public video proxy URL for an asset.
|
||||
*/
|
||||
export function videoUrl(assetId: string): string {
|
||||
return `/api/video/${encodeAssetId(assetId)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Placeholder data derived from an asset's ThumbHash.
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user