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 shared journey from streaming an Immich video original with its location

Maurice1c6bdb41298f
diff --git a/server/src/nest/memories/immich.service.ts b/server/src/nest/memories/immich.service.ts
index cc1bc4da9..583bcb053 100644
--- a/server/src/nest/memories/immich.service.ts
+++ b/server/src/nest/memories/immich.service.ts
@@ -21,6 +21,7 @@ import { PROVIDER_SELECT_ALL_MAX_PAGES } from '@trek/shared';
import type { Response } from 'express';
import fsPromises from 'node:fs/promises';
import path from 'node:path';
+import { z } from 'zod';
const ALBUM_PAGE_SIZE = 1000;
const ALBUM_MAX_PAGES = 20;
@@ -72,6 +73,17 @@ export interface ImmichCreds {
* the only thing the switch relaxes: the SSRF guard and the DNS pinning still
* run on every hop.
*/
+/** What a public video's playback check reads of an Immich asset. */
+const videoExifSchema = z.object({
+ exifInfo: z
+ .object({
+ latitude: z.number().nullish(),
+ longitude: z.number().nullish(),
+ fileSizeInByte: z.number().nullish(),
+ })
+ .nullish(),
+});
+
function tlsOptions(allowInsecureTls: boolean): SafeFetchOptions {
return { rejectUnauthorized: !allowInsecureTls };
}
@@ -530,6 +542,10 @@ 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;
+ }
const headers: Record<string, string> = { 'x-api-key': creds.immich_api_key };
let url: string;
let timeout: number | undefined;
@@ -565,6 +581,41 @@ export class ImmichService {
);
}
+ /**
+ * 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.
+ */
+ private async playbackWithoutLocation(creds: ImmichCreds, assetId: string): Promise<boolean> {
+ const tls = tlsOptions(creds.allow_insecure_tls);
+ const key = { 'x-api-key': creds.immich_api_key };
+ try {
+ const info = await safeFetch(
+ `${creds.immich_url}/api/assets/${assetId}`,
+ { headers: { ...key, Accept: 'application/json' }, signal: AbortSignal.timeout(10000) },
+ { ...tls, maxBytes: 1024 * 1024 },
+ );
+ if (!info.ok) return false;
+ const exifInfo = videoExifSchema.safeParse(await info.json()).data?.exifInfo;
+ if (!exifInfo) return false;
+ if (exifInfo.latitude == null && exifInfo.longitude == null) return true;
+ 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;
+ 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;
+ } catch {
+ return false;
+ }
+ }
+
// ── Albums ──────────────────────────────────────────────────────────────────
async listAlbums(userId: number): Promise<{ albums?: any[]; error?: string; status?: number }> {
diff --git a/server/tests/unit/nest/immich.service.test.ts b/server/tests/unit/nest/immich.service.test.ts
index d47bc4bdf..89b2a2a48 100644
--- a/server/tests/unit/nest/immich.service.test.ts
+++ b/server/tests/unit/nest/immich.service.test.ts
@@ -980,16 +980,55 @@ describe('streamImmichAsset', () => {
await svc.streamImmichAsset(makeRes() as never, USER, 'a1', 'original', 13, { publicView: true });
await svc.streamImmichAsset(makeRes() as never, USER, 'a1', 'original', 13);
- await svc.streamImmichAsset(makeRes() as never, USER, 'v1', 'original', 13, {
- mediaType: 'video',
- publicView: true,
- });
+ await svc.streamImmichAsset(makeRes() as never, USER, 'v1', 'original', 13, { mediaType: 'video' });
const urls = safeFetch.mock.calls.map((call) => String(call[0]));
expect(urls[0]).toContain('/api/assets/a1/thumbnail?size=preview');
expect(urls[1]).toContain('/api/assets/a1/thumbnail?size=fullsize');
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');
+ 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) =>
+ safeFetch.mockImplementation(async (url: string, init: { headers: Record<string, string> }) => {
+ if (url.endsWith('/api/assets/v1')) return upstream({ json: asset });
+ if (init.headers.Range === 'bytes=0-0') return playback(total);
+ return upstream({ contentType: 'video/mp4', body: 'video' });
+ });
+ const played = () =>
+ safeFetch.mock.calls.some(
+ (call) => call[1].headers.Range !== 'bytes=0-0' && String(call[0]).includes('/video/playback'),
+ );
+ const publicVideo = async () => {
+ const res = makeRes();
+ await svc.streamImmichAsset(res as never, USER, 'v1', 'original', 13, { mediaType: 'video', publicView: true });
+ return res;
+ };
+
+ serve(located, 5000);
+ expect((await publicVideo()).status).toHaveBeenCalledWith(404);
+ expect(played()).toBe(false);
+
+ safeFetch.mockClear();
+ serve(located, 3200);
+ await publicVideo();
+ expect(played()).toBe(true);
+
+ safeFetch.mockClear();
+ serve({ exifInfo: { latitude: null, longitude: null, fileSizeInByte: 5000 } }, 5000);
+ await publicVideo();
+ expect(played()).toBe(true);
+
+ safeFetch.mockClear();
+ serve({}, 3200);
+ expect((await publicVideo()).status).toHaveBeenCalledWith(404);
+ });
});
describe('collectAlbumSelection', () => {