Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

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

Mauriceb2ba89fe4fb2
diff --git a/server/src/nest/memories/immich.service.ts b/server/src/nest/memories/immich.service.ts
index 583bcb053..c1b1b807b 100644
--- a/server/src/nest/memories/immich.service.ts
+++ b/server/src/nest/memories/immich.service.ts
@@ -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';
}
}
diff --git a/server/tests/unit/nest/immich.service.test.ts b/server/tests/unit/nest/immich.service.test.ts
index 89b2a2a48..4f299c7cb 100644
--- a/server/tests/unit/nest/immich.service.test.ts
+++ b/server/tests/unit/nest/immich.service.test.ts
@@ -988,16 +988,15 @@ describe('streamImmichAsset', () => {
expect(urls[2]).toContain('/api/assets/v1/video/playback');
});
- it('IMMICH-041f: a public view plays a video with a location only from the transcode, never the original file', async () => {
- await seedUser(13, 'https://immich.example', 'owner-key');
+ describe('a public video', () => {
const located = { exifInfo: { latitude: 38.1, longitude: 13.1, fileSizeInByte: 5000 } };
const playback = (total: number) => ({
...upstream({ status: 206, contentType: 'video/mp4' }),
headers: { get: (h: string) => (h === 'content-range' ? `bytes 0-0/${total}` : null) },
});
- const serve = (asset: unknown, total: number) =>
+ const serve = (id: string, asset: unknown, total: number) =>
safeFetch.mockImplementation(async (url: string, init: { headers: Record<string, string> }) => {
- if (url.endsWith('/api/assets/v1')) return upstream({ json: asset });
+ if (url.endsWith(`/api/assets/${id}`)) return upstream({ json: asset });
if (init.headers.Range === 'bytes=0-0') return playback(total);
return upstream({ contentType: 'video/mp4', body: 'video' });
});
@@ -1005,29 +1004,75 @@ describe('streamImmichAsset', () => {
safeFetch.mock.calls.some(
(call) => call[1].headers.Range !== 'bytes=0-0' && String(call[0]).includes('/video/playback'),
);
- const publicVideo = async () => {
+ const checks = () =>
+ safeFetch.mock.calls.filter(
+ (call) => call[1].headers.Range === 'bytes=0-0' || !String(call[0]).includes('/video/playback'),
+ ).length;
+ const publicVideo = async (id: string, range?: string) => {
const res = makeRes();
- await svc.streamImmichAsset(res as never, USER, 'v1', 'original', 13, { mediaType: 'video', publicView: true });
+ await svc.streamImmichAsset(res as never, USER, id, 'original', 13, {
+ mediaType: 'video',
+ publicView: true,
+ range,
+ });
return res;
};
- serve(located, 5000);
- expect((await publicVideo()).status).toHaveBeenCalledWith(404);
- expect(played()).toBe(false);
+ beforeEach(async () => {
+ await seedUser(13, 'https://immich.example', 'owner-key');
+ });
- safeFetch.mockClear();
- serve(located, 3200);
- await publicVideo();
- expect(played()).toBe(true);
+ it('IMMICH-041f: plays a video with a location only from the transcode, never the original file', async () => {
+ serve('v1', located, 5000);
+ expect((await publicVideo('v1')).status).toHaveBeenCalledWith(404);
+ expect(played()).toBe(false);
- safeFetch.mockClear();
- serve({ exifInfo: { latitude: null, longitude: null, fileSizeInByte: 5000 } }, 5000);
- await publicVideo();
- expect(played()).toBe(true);
+ safeFetch.mockClear();
+ serve('v2', located, 3200);
+ await publicVideo('v2');
+ expect(played()).toBe(true);
- safeFetch.mockClear();
- serve({}, 3200);
- expect((await publicVideo()).status).toHaveBeenCalledWith(404);
+ safeFetch.mockClear();
+ serve('v3', { exifInfo: { latitude: null, longitude: null, fileSizeInByte: 5000 } }, 5000);
+ await publicVideo('v3');
+ expect(played()).toBe(true);
+
+ safeFetch.mockClear();
+ serve('v4', {}, 3200);
+ expect((await publicVideo('v4')).status).toHaveBeenCalledWith(404);
+ });
+
+ it('IMMICH-041g: a seek reuses the verdict instead of asking Immich again', async () => {
+ serve('v10', located, 3200);
+ await publicVideo('v10');
+ await publicVideo('v10', 'bytes=1000-');
+ await publicVideo('v10', 'bytes=2000-');
+
+ expect(checks()).toBe(2);
+ expect(safeFetch.mock.calls.length - checks()).toBe(3);
+
+ safeFetch.mockClear();
+ serve('v11', located, 5000);
+ expect((await publicVideo('v11')).status).toHaveBeenCalledWith(404);
+ expect((await publicVideo('v11', 'bytes=1000-')).status).toHaveBeenCalledWith(404);
+ expect(checks()).toBe(2);
+ expect(played()).toBe(false);
+ });
+
+ it('IMMICH-041h: an Immich that fails or times out answers 502 for that request, not 404, and is asked again', async () => {
+ safeFetch.mockResolvedValue(upstream({ ok: false, status: 503 }));
+ const busy = await publicVideo('v20');
+ expect(busy.status).toHaveBeenCalledWith(502);
+ expect(played()).toBe(false);
+
+ safeFetch.mockRejectedValue(new Error('The operation was aborted due to timeout'));
+ expect((await publicVideo('v20', 'bytes=1000-')).status).toHaveBeenCalledWith(502);
+
+ safeFetch.mockReset();
+ serve('v20', located, 3200);
+ await publicVideo('v20', 'bytes=1000-');
+ expect(played()).toBe(true);
+ });
});
});