feat(photos): ask the provider where and when, and stop the album path dropping it

Second half of the capture-metadata foundation (#1614).

The album paths were the asymmetry: Immich's search has always carried
exifInfo.latitude/longitude, but the album mapping quietly left them out, and
the Synology album listing never asked for the gps block at all. So a photo
picked out of an album could never be placed on a map, and the distance sort
that PR #1632 added silently had nothing to sort by. Both now carry the pair.

For the add itself the client only sends an asset id. Widening that contract
would have meant trusting the client for something the provider can be asked
for directly, and would have left the MCP path and every already-imported photo
without it — so PhotoCaptureBackfillService asks afterwards instead, detached,
skipping rows that already know both so an album import is not one provider
call per photo. A slow or unreachable provider cannot hold up the add, and a
photo without capture metadata stays the normal case.
This commit is contained in:
Maurice
2026-08-18 20:16:39 +02:00
committed by Maurice
parent 6185cf96b6
commit 359c3afc21
8 changed files with 271 additions and 91 deletions
+19 -1
View File
@@ -22,6 +22,7 @@ import fs from 'node:fs';
import crypto from 'node:crypto';
import type { User } from '../../types';
import { JourneyService } from './journey.service';
import { PhotoCaptureBackfillService } from '../memories/photo-capture-backfill.service';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { ADDON_IDS } from '../../addons';
@@ -120,7 +121,20 @@ const VIDEO_UPLOAD = {
@UseGuards(AddonGuard, JwtAuthGuard)
@RequireAddon(ADDON_IDS.JOURNEY, 'Journey')
export class JourneyController {
constructor(private readonly journey: JourneyService) {}
constructor(
private readonly journey: JourneyService,
private readonly captureBackfill: PhotoCaptureBackfillService,
) {}
// The add call carries only an asset id, so when and where the picture was taken
// are fetched from the provider afterwards rather than trusted from the client
// (#1614). Detached: a slow or unreachable provider must not hold up the add.
private backfillCapture(photos: unknown[], userId: number): void {
const ids = photos
.map(p => (p as { photo_id?: number } | null)?.photo_id)
.filter((id): id is number => typeof id === 'number');
this.captureBackfill.schedule(ids, userId);
}
// ── Static prefix routes (before /:id) ──────────────────────────────────
@Get()
@@ -211,6 +225,7 @@ export class JourneyController {
const photo = this.journey.addProviderPhoto(Number(entryId), user.id, String(body.provider), String(id), body.caption as string | undefined, pp, mt);
if (photo) added.push(photo);
});
this.backfillCapture(added, user.id);
return { photos: added, added: added.length };
}
if (!body.provider || !body.asset_id) {
@@ -220,6 +235,7 @@ export class JourneyController {
if (!photo) {
throw new HttpException({ error: 'Not allowed or duplicate' }, 403);
}
this.backfillCapture([photo], user.id);
return photo;
}
@@ -325,6 +341,7 @@ export class JourneyController {
const photo = this.journey.addProviderPhotoToGallery(Number(id), user.id, String(body.provider), String(aid), undefined, pp, mt);
if (photo) added.push(photo);
});
this.backfillCapture(added, user.id);
return { photos: added, added: added.length };
}
if (!body.provider || !body.asset_id) {
@@ -334,6 +351,7 @@ export class JourneyController {
if (!photo) {
throw new HttpException({ error: 'Not allowed or duplicate' }, 403);
}
this.backfillCapture([photo], user.id);
return photo;
}
@@ -519,6 +519,11 @@ export class ImmichService {
takenAt: a.fileCreatedAt || a.createdAt,
city: a.exifInfo?.city || null,
country: a.exifInfo?.country || null,
// The search path has always carried these; dropping them here meant a
// photo picked out of an album could never be placed on a map, and the
// distance sort silently had nothing to sort by (#1614).
lat: typeof a.exifInfo?.latitude === 'number' ? a.exifInfo.latitude : null,
lng: typeof a.exifInfo?.longitude === 'number' ? a.exifInfo.longitude : null,
mediaType: a.type === 'VIDEO' ? 'video' : 'image',
}));
return { assets };
+3 -1
View File
@@ -5,6 +5,7 @@ import { ImmichService } from './immich.service';
import { SynologyService } from './synology.service';
import { UnifiedMemoriesService } from './unified-memories.service';
import { PhotoResolverService } from './photo-resolver.service';
import { PhotoCaptureBackfillService } from './photo-capture-backfill.service';
import { ThumbnailService } from './thumbnail.service';
import { TrekPhotoCacheService } from './trek-photo-cache.service';
import { TrekPhotoCacheJob } from './trek-photo-cache.job';
@@ -52,6 +53,7 @@ import { NotificationsModule } from '../notifications/notifications.module';
SynologyService,
UnifiedMemoriesService,
PhotoResolverService,
PhotoCaptureBackfillService,
ThumbnailService,
TrekPhotoCacheService,
TrekPhotoCacheJob,
@@ -64,6 +66,6 @@ import { NotificationsModule } from '../notifications/notifications.module';
inject: [ImmichPhotoProvider, SynologyPhotoProvider],
},
],
exports: [MemoriesAccessService, PhotoResolverService, ImmichService, SynologyService, PhotoProviderRegistry],
exports: [MemoriesAccessService, PhotoResolverService, PhotoCaptureBackfillService, ImmichService, SynologyService, PhotoProviderRegistry],
})
export class MemoriesModule {}
@@ -0,0 +1,53 @@
import { Injectable } from '@nestjs/common';
import { PhotoResolverService } from './photo-resolver.service';
import { TrekPhotosRepository } from '../photos/trek-photos.repository';
/**
* Ask the provider when and where a photo was taken, and record it (#1614).
*
* The picker already sees these values, but the add call carries only the asset
* id — widening that contract would have meant trusting the client for something
* the provider can be asked for directly, and would have left the MCP path, the
* album sync and every already-imported photo without them.
*
* Runs detached and never throws: a provider that is slow, unreachable or simply
* does not know must not fail the add the user is waiting on. A photo without
* capture metadata is the normal case, not an error — it just will not appear on
* the map.
*/
@Injectable()
export class PhotoCaptureBackfillService {
constructor(
private readonly resolver: PhotoResolverService,
private readonly photos: TrekPhotosRepository,
) {}
/** Fire-and-forget for a batch that was just added. */
schedule(trekPhotoIds: number[], userId: number): void {
if (!trekPhotoIds.length) return;
void this.run(trekPhotoIds, userId);
}
/** Awaitable form, so tests do not have to chase a floating promise. */
async run(trekPhotoIds: number[], userId: number): Promise<void> {
for (const id of trekPhotoIds) {
try {
const photo = this.photos.resolve(id);
// A row that already knows both has nothing to gain, and a provider call
// per photo is the expensive part of an album import.
if (!photo || (photo.taken_at && photo.lat != null && photo.lng != null)) continue;
const info = await this.resolver.getPhotoInfo(id, userId);
if (!info.success) continue;
this.photos.recordCaptureMetadata(id, {
takenAt: info.data.takenAt ?? null,
lat: info.data.lat ?? null,
lng: info.data.lng ?? null,
});
} catch (err) {
console.error(`[Photos] capture backfill failed for ${id}:`, err instanceof Error ? err.message : err);
}
}
}
}
+6 -2
View File
@@ -507,8 +507,10 @@ export class SynologyService {
while (true) {
const params: ApiCallParams = passphrase
? { api: 'SYNO.Foto.Browse.Item', method: 'list', version: 1, passphrase, offset, limit: pageSize, additional: ['thumbnail'] }
: { api: 'SYNO.Foto.Browse.Item', method: 'list', version: 1, album_id: Number(albumId), offset, limit: pageSize, additional: ['thumbnail'] };
// 'gps' costs nothing extra on the same call and is the only way a
// photo picked from an album can ever reach the map (#1614).
? { api: 'SYNO.Foto.Browse.Item', method: 'list', version: 1, passphrase, offset, limit: pageSize, additional: ['thumbnail', 'gps'] }
: { api: 'SYNO.Foto.Browse.Item', method: 'list', version: 1, album_id: Number(albumId), offset, limit: pageSize, additional: ['thumbnail', 'gps'] };
const result = await this._requestSynologyApi<{ list: SynologyPhotoItem[] }>(userId, params);
if (!result.success) return result as ServiceResult<AssetsList>;
const items = result.data.list || [];
@@ -520,6 +522,8 @@ export class SynologyService {
const assets = allItems.map(item => ({
id: String(item.additional?.thumbnail?.cache_key || item.id || ''),
takenAt: item.time ? new Date(item.time * 1000).toISOString() : '',
lat: typeof item.additional?.gps?.latitude === 'number' ? item.additional.gps.latitude : null,
lng: typeof item.additional?.gps?.longitude === 'number' ? item.additional.gps.longitude : null,
})).filter(a => a.id);
return success({ assets, total: assets.length, hasMore: false });
+5
View File
@@ -398,6 +398,11 @@ export interface TrekPhoto {
media_type?: string | null;
/** Optional video duration in milliseconds. */
duration_ms?: number | null;
/** When the picture was taken, as the provider or its EXIF reported it (#1614). */
taken_at?: string | null;
/** Capture coordinates. Stored as a pair or not at all. */
lat?: number | null;
lng?: number | null;
created_at: string;
}