fix(immich): keep a public video's location check across its range requests

The verdict is held for five minutes per owner and asset, so a seek no longer asks Immich twice before it streams, and an Immich that times out or fails answers 502 instead of 404. A located video Immich did not transcode still never plays.
This commit is contained in:
Maurice
2026-11-23 17:18:25 +01:00
parent eb32eb1690
commit b2ba89fe4f
2 changed files with 115 additions and 31 deletions
+50 -11
View File
@@ -84,6 +84,18 @@ const videoExifSchema = z.object({
.nullish(),
});
/** How long a public video's playback verdict holds, so every Range request of one viewing asks Immich once. */
const PLAYBACK_VERDICT_TTL_MS = 5 * 60_000;
const PLAYBACK_VERDICT_MAX = 500;
/** A public video plays (`clear`), stays hidden (`located`), or Immich did not answer this time (`unknown`). */
type PlaybackVerdict = 'clear' | 'located' | 'unknown';
/** An Immich answer that may be different on the next try. */
function transient(status: number): boolean {
return status >= 500 || status === 429;
}
function tlsOptions(allowInsecureTls: boolean): SafeFetchOptions {
return { rejectUnauthorized: !allowInsecureTls };
}
@@ -97,6 +109,8 @@ function tlsOptions(allowInsecureTls: boolean): SafeFetchOptions {
*/
@Injectable()
export class ImmichService {
private readonly playbackVerdicts = new Map<string, { verdict: PlaybackVerdict; until: number }>();
constructor(
private readonly audit: AuditService,
private readonly access: MemoriesAccessService,
@@ -542,9 +556,12 @@ export class ImmichService {
}
const isVideo = opts?.mediaType === 'video';
if (kind === 'original' && isVideo && opts?.publicView && !(await this.playbackWithoutLocation(creds, assetId))) {
handleServiceResult(response, fail('Not found', 404));
return;
if (kind === 'original' && isVideo && opts?.publicView) {
const verdict = await this.publicPlayback(effectiveUserId, creds, assetId);
if (verdict !== 'clear') {
handleServiceResult(response, verdict === 'unknown' ? fail('Upstream error', 502) : fail('Not found', 404));
return;
}
}
const headers: Record<string, string> = { 'x-api-key': creds.immich_api_key };
let url: string;
@@ -581,13 +598,35 @@ export class ImmichService {
);
}
/**
* The playback verdict of a public video, kept for a few minutes per owner
* and asset, since a player sends a Range request for every seek and chunk.
* Only an answer Immich actually gave is kept.
*/
private async publicPlayback(userId: number, creds: ImmichCreds, assetId: string): Promise<PlaybackVerdict> {
const key = `${userId}:${creds.immich_url}:${assetId}`;
const now = Date.now();
const kept = this.playbackVerdicts.get(key);
if (kept && kept.until > now) return kept.verdict;
this.playbackVerdicts.delete(key);
const verdict = await this.playbackWithoutLocation(creds, assetId);
if (verdict === 'unknown') return verdict;
if (this.playbackVerdicts.size >= PLAYBACK_VERDICT_MAX) {
const oldest = this.playbackVerdicts.keys().next().value;
if (oldest !== undefined) this.playbackVerdicts.delete(oldest);
}
this.playbackVerdicts.set(key, { verdict, until: now + PLAYBACK_VERDICT_TTL_MS });
return verdict;
}
/**
* Whether Immich plays a video back without its recorded location: the asset
* has none, or Immich serves its own transcode, which it writes without the
* metadata, rather than the original file (told apart by the file's size).
* Anything Immich does not answer counts as no.
* An answer Immich refused or did not understand counts as located; one it
* failed to give in time, or a server error, as unknown.
*/
private async playbackWithoutLocation(creds: ImmichCreds, assetId: string): Promise<boolean> {
private async playbackWithoutLocation(creds: ImmichCreds, assetId: string): Promise<PlaybackVerdict> {
const tls = tlsOptions(creds.allow_insecure_tls);
const key = { 'x-api-key': creds.immich_api_key };
try {
@@ -596,23 +635,23 @@ export class ImmichService {
{ headers: { ...key, Accept: 'application/json' }, signal: AbortSignal.timeout(10000) },
{ ...tls, maxBytes: 1024 * 1024 },
);
if (!info.ok) return false;
if (!info.ok) return transient(info.status) ? 'unknown' : 'located';
const exifInfo = videoExifSchema.safeParse(await info.json()).data?.exifInfo;
if (!exifInfo) return false;
if (exifInfo.latitude == null && exifInfo.longitude == null) return true;
if (!exifInfo) return 'located';
if (exifInfo.latitude == null && exifInfo.longitude == null) return 'clear';
const probe = await safeFetch(
`${creds.immich_url}/api/assets/${assetId}/video/playback`,
{ headers: { ...key, Range: 'bytes=0-0' }, signal: AbortSignal.timeout(10000) },
{ ...tls, maxBytes: 1024 * 1024 },
);
void probe.body?.cancel().catch(() => undefined);
if (!probe.ok) return false;
if (!probe.ok) return transient(probe.status) ? 'unknown' : 'located';
const total =
/\/(\d+)$/.exec(probe.headers.get('content-range') ?? '')?.[1] ?? probe.headers.get('content-length');
const original = Number(exifInfo.fileSizeInByte);
return total !== null && original > 0 && Number(total) > 0 && Number(total) !== original;
return total !== null && original > 0 && Number(total) > 0 && Number(total) !== original ? 'clear' : 'located';
} catch {
return false;
return 'unknown';
}
}