refactor(memories): unified, immich and synology photo sync through repositories

This commit is contained in:
jubnl
2026-09-23 18:38:36 +02:00
parent 5453836a06
commit bceaf4b134
14 changed files with 857 additions and 128 deletions
+11 -17
View File
@@ -1,14 +1,16 @@
import { Injectable } from '@nestjs/common';
import type { Response } from 'express';
import { InjectRepository } from '@mikro-orm/nestjs';
import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { checkSsrf, safeFetch } from '../../utils/ssrfGuard';
import { AuditService } from '../audit/audit.service';
import { StorageService } from '../storage/storage.service';
import fsPromises from 'node:fs/promises';
import path from 'node:path';
import { DatabaseService } from '../database/database.service';
import { MemoriesAccessService } from './memories-access.service';
import { fail, handleServiceResult, isWithinLocalDayRange, pipeAsset, shiftCalendarDay, sortAssetsByTakenAtDesc, type Selection } from './memories.helpers';
import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository } from '../../db/repositories/Users.repository';
const ALBUM_PAGE_SIZE = 1000;
const ALBUM_MAX_PAGES = 20;
@@ -34,18 +36,18 @@ const SEARCH_MAX_RAW_PAGES = 20;
@Injectable()
export class ImmichService {
constructor(
private readonly db: DatabaseService,
private readonly audit: AuditService,
private readonly access: MemoriesAccessService,
private readonly storage: StorageService,
@InjectRepository(Users) private readonly users: UsersRepository,
) {}
async getImmichCredentials(userId: number) {
const user = this.db.prepare('SELECT immich_url, immich_api_key FROM users WHERE id = ?').get(userId) as any;
const user = await this.users.getImmichCredentials(userId);
if (!user?.immich_url || !user?.immich_api_key) return null;
const apiKey = decrypt_api_key(user.immich_api_key);
if (!apiKey) return null;
return { immich_url: user.immich_url as string, immich_api_key: apiKey };
return { immich_url: user.immich_url, immich_api_key: apiKey };
}
/** Validate that an asset ID is a safe UUID-like string (no path traversal). */
@@ -73,16 +75,16 @@ export class ImmichService {
async getConnectionSettings(userId: number) {
const creds = await this.getImmichCredentials(userId);
const prefs = this.db.prepare('SELECT immich_auto_upload FROM users WHERE id = ?').get(userId) as { immich_auto_upload?: number } | undefined;
const autoUpload = await this.users.getImmichAutoUpload(userId);
return {
immich_url: creds?.immich_url || '',
connected: !!(creds?.immich_url && creds?.immich_api_key),
auto_upload: !!(prefs?.immich_auto_upload),
auto_upload: !!autoUpload,
};
}
async setImmichAutoUpload(userId: number, enabled: boolean): Promise<void> {
this.db.prepare('UPDATE users SET immich_auto_upload = ? WHERE id = ?').run(enabled ? 1 : 0, userId);
await this.users.setImmichAutoUpload(userId, enabled ? 1 : 0);
}
async saveImmichSettings(
@@ -99,11 +101,7 @@ export class ImmichService {
if (!ssrf.allowed) {
return { success: false, error: `Invalid Immich URL: ${ssrf.error}` };
}
this.db.prepare('UPDATE users SET immich_url = ?, immich_api_key = ? WHERE id = ?').run(
immichUrl.trim(),
maybe_encrypt_api_key(immichApiKey),
userId
);
await this.users.setImmichSettings(userId, immichUrl.trim(), maybe_encrypt_api_key(immichApiKey));
if (ssrf.isPrivate) {
await this.audit.writeAudit({
userId,
@@ -117,11 +115,7 @@ export class ImmichService {
};
}
} else {
this.db.prepare('UPDATE users SET immich_url = ?, immich_api_key = ? WHERE id = ?').run(
null,
maybe_encrypt_api_key(immichApiKey),
userId
);
await this.users.setImmichSettings(userId, null, maybe_encrypt_api_key(immichApiKey));
}
return { success: true };
}
+6 -4
View File
@@ -3,11 +3,13 @@ import {
errorResult, ok, type McpContext,
} from '../../nest-mcp';
import { z } from 'zod';
import { InjectRepository } from '@mikro-orm/nestjs';
import { ADDON_IDS } from '../../addons';
import { AddonsService } from '../addons/addons.service';
import { DatabaseService } from '../database/database.service';
import { ImmichService } from './immich.service';
import { SynologyService } from './synology.service';
import { PhotoProviders } from '../../db/entities/PhotoProviders.entity';
import type { PhotoProvidersRepository } from '../../db/repositories/PhotoProviders.repository';
/**
* The photo backends TREK can talk to, named rather than taken as a free
@@ -65,8 +67,8 @@ export class MemoriesMcp {
constructor(
private readonly immich: ImmichService,
private readonly synology: SynologyService,
private readonly db: DatabaseService,
private readonly addons: AddonsService,
@InjectRepository(PhotoProviders) private readonly photoProviders: PhotoProvidersRepository,
) {}
/**
@@ -75,7 +77,7 @@ export class MemoriesMcp {
*/
async enabledProviderIds(): Promise<string[]> {
if (!(await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY))) return [];
return this.db.all<{ id: string }>('SELECT id FROM photo_providers WHERE enabled = 1').map((row) => row.id);
return await this.photoProviders.listEnabledIds();
}
/**
@@ -85,7 +87,7 @@ export class MemoriesMcp {
* themselves never checked it, so this only ever narrows what REST allows.
*/
private async providerRefusal(provider: ProviderId) {
const row = this.db.get<{ enabled: number }>('SELECT enabled FROM photo_providers WHERE id = ?', provider);
const row = await this.photoProviders.findEnabled(provider);
if (!row) return errorResult(`Provider: "${provider}" is not supported`);
if (row.enabled !== 1 || !(await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY)))
return errorResult(`Provider: "${provider}" is not enabled, contact server administrator`);
+8 -2
View File
@@ -31,6 +31,8 @@ import { TrekPhotos } from '../../db/entities/TrekPhotos.entity';
import { TripAlbumLinks } from '../../db/entities/TripAlbumLinks.entity';
import { Trips } from '../../db/entities/Trips.entity';
import { TrekPhotoCacheMeta } from '../../db/entities/TrekPhotoCacheMeta.entity';
import { PhotoProviders } from '../../db/entities/PhotoProviders.entity';
import { Users } from '../../db/entities/Users.entity';
/**
* Memories (photo-providers) domain — mounted at /api/integrations/memories.
@@ -57,12 +59,16 @@ import { TrekPhotoCacheMeta } from '../../db/entities/TrekPhotoCacheMeta.entity'
* (owned elsewhere, reached the same way every cross-domain module in this
* program reaches another domain's entity) for `MemoriesAccessService`'s
* `@InjectRepository` constructor params, and `TrekPhotoCacheMetaRepository`
* for `TrekPhotoCacheService`'s (Plan 3e Task 6).
* for `TrekPhotoCacheService`'s (Plan 3e Task 6). `PhotoProviders` (owned by
* this module) and `Users` (owned elsewhere, reached the same way `Trips`
* is above) are added for `UnifiedMemoriesService`/`ImmichService`/
* `SynologyService`/`MemoriesMcp`'s `@InjectRepository` constructor params
* (Plan 3e Task 7).
*/
@Module({
imports: [
NotificationsModule, AddonsModule, AuditModule, TrekPhotosModule, RealtimeModule, SchedulingModule, StorageModule,
MikroOrmModule.forFeature([TripPhotos, TrekPhotos, TripAlbumLinks, Trips, TrekPhotoCacheMeta]),
MikroOrmModule.forFeature([TripPhotos, TrekPhotos, TripAlbumLinks, Trips, TrekPhotoCacheMeta, PhotoProviders, Users]),
],
controllers: [UnifiedMemoriesController, ImmichMemoriesController, SynologyMemoriesController],
providers: [
+16 -19
View File
@@ -1,9 +1,11 @@
import { Injectable } from '@nestjs/common';
import { Response } from 'express';
import { InjectRepository } from '@mikro-orm/nestjs';
import { decrypt_api_key, encrypt_api_key, maybe_encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { safeFetch, SsrfBlockedError, checkSsrf } from '../../utils/ssrfGuard';
import { DatabaseService } from '../database/database.service';
import { MemoriesAccessService } from './memories-access.service';
import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository, SynologyUserColumn } from '../../db/repositories/Users.repository';
import {
dayStartEpochSeconds,
fail,
@@ -129,24 +131,19 @@ interface SynologyPhotoItem {
@Injectable()
export class SynologyService {
constructor(
private readonly db: DatabaseService,
private readonly access: MemoriesAccessService,
private readonly notifications: NotificationsService,
@InjectRepository(Users) private readonly users: UsersRepository,
) {}
private async _readSynologyUser(userId: number, columns: string[]): Promise<ServiceResult<SynologyUserRecord>> {
private async _readSynologyUser(userId: number, columns: SynologyUserColumn[]): Promise<ServiceResult<SynologyUserRecord>> {
try {
const row = this.db.prepare(`SELECT synology_url, synology_username, synology_password, synology_sid, synology_did, synology_skip_ssl FROM users WHERE id = ?`).get(userId) as SynologyUserRecord | undefined;
const filtered = await this.users.getSynologyFields(userId, columns);
if (!row) {
if (!filtered) {
return fail('User not found', 404);
}
const filtered: SynologyUserRecord = {};
for (const column of columns) {
filtered[column] = row[column];
}
return success(filtered);
} catch {
return fail('Failed to read Synology user data', 500);
@@ -306,11 +303,11 @@ export class SynologyService {
private async _clearSynologySID(userId: number): Promise<void> {
this.db.prepare('UPDATE users SET synology_sid = NULL WHERE id = ?').run(userId);
await this.users.clearSynologySID(userId);
}
private async _clearSynologySession(userId: number): Promise<void> {
this.db.prepare('UPDATE users SET synology_sid = NULL, synology_did = NULL WHERE id = ?').run(userId);
await this.users.clearSynologySession(userId);
}
private _splitPackedSynologyId(rawId: string): { id: string; cacheKey: string; assetId: string } | null {
@@ -349,7 +346,7 @@ export class SynologyService {
return resp as ServiceResult<string>;
}
this.db.prepare('UPDATE users SET synology_sid = ? WHERE id = ?').run(encrypt_api_key(resp.data.sid), userId);
await this.users.setSynologySid(userId, encrypt_api_key(resp.data.sid));
return success(resp.data.sid);
}
@@ -403,12 +400,12 @@ export class SynologyService {
}
try {
this.db.prepare('UPDATE users SET synology_url = ?, synology_username = ?, synology_password = ?, synology_skip_ssl = ? WHERE id = ?').run(
await this.users.setSynologySettings(
userId,
synologyUrl,
synologyUsername,
synologyPassword ? maybe_encrypt_api_key(synologyPassword) : existingEncryptedPassword,
synologySkipSsl ? 1 : 0,
userId,
);
} catch {
return fail('Failed to update Synology settings', 500);
@@ -422,8 +419,8 @@ export class SynologyService {
if ('error' in sid) return success({ connected: false, error: sid.error.message });
if (!sid.data) return success({ connected: false, error: 'Not connected to Synology' });
try {
const user = this.db.prepare('SELECT synology_username FROM users WHERE id = ?').get(userId) as { synology_username?: string } | undefined;
return success({ connected: true, user: { name: user?.synology_username || 'unknown user' } });
const synologyUsername = await this.users.getSynologyUsername(userId);
return success({ connected: true, user: { name: synologyUsername || 'unknown user' } });
} catch (err: unknown) {
return success({ connected: true, user: { name: 'unknown user' } });
}
@@ -443,9 +440,9 @@ export class SynologyService {
// Persist the session so the OTP code is not required again on save.
// The did (device token) allows future re-logins without OTP.
this.db.prepare('UPDATE users SET synology_sid = ? WHERE id = ?').run(encrypt_api_key(resp.data.sid), userId);
await this.users.setSynologySid(userId, encrypt_api_key(resp.data.sid));
if (resp.data.did) {
this.db.prepare('UPDATE users SET synology_did = ? WHERE id = ?').run(encrypt_api_key(resp.data.did), userId);
await this.users.setSynologyDid(userId, encrypt_api_key(resp.data.did));
}
return success({ connected: true, user: { name: synologyUsername } });
@@ -1,6 +1,6 @@
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import { ADDON_IDS } from '../../addons';
import { broadcast } from '../../websocket';
import { encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { AddonsService } from '../addons/addons.service';
import { DatabaseService } from '../database/database.service';
@@ -18,6 +18,17 @@ import {
} from './memories.helpers';
import { NotificationsService } from '../notifications/notifications.service';
import { UnitOfWork } from '../database/unit-of-work';
import { RealtimeService } from '../realtime/realtime.service';
import { PhotoProviders } from '../../db/entities/PhotoProviders.entity';
import type { PhotoProvidersRepository } from '../../db/repositories/PhotoProviders.repository';
import { TripPhotos } from '../../db/entities/TripPhotos.entity';
import type { TripPhotosRepository } from '../../db/repositories/TripPhotos.repository';
import { TripAlbumLinks } from '../../db/entities/TripAlbumLinks.entity';
import type { TripAlbumLinksRepository } from '../../db/repositories/TripAlbumLinks.repository';
import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { Trips } from '../../db/entities/Trips.entity';
import type { TripsRepository } from '../../db/repositories/Trips.repository';
/**
* The provider-agnostic trip photo surface: which photos a trip shows, which
@@ -36,6 +47,12 @@ export class UnifiedMemoriesService {
private readonly notifications: NotificationsService,
private readonly addons: AddonsService,
private readonly uow: UnitOfWork,
private readonly realtime: RealtimeService,
@InjectRepository(PhotoProviders) private readonly photoProviders: PhotoProvidersRepository,
@InjectRepository(TripPhotos) private readonly tripPhotos: TripPhotosRepository,
@InjectRepository(TripAlbumLinks) private readonly tripAlbumLinks: TripAlbumLinksRepository,
@InjectRepository(Users) private readonly users: UsersRepository,
@InjectRepository(Trips) private readonly trips: TripsRepository,
) {}
private async _providers(): Promise<Array<{id: string; enabled: boolean}>> {
@@ -43,7 +60,7 @@ export class UnifiedMemoriesService {
// surface lives inside journeys. Covers rows left enabled from before
// updateAddon cascaded the journey disable.
const journeyOn = await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY);
const rows = this.db.prepare('SELECT id, enabled FROM photo_providers').all() as Array<{id: string; enabled: number}>;
const rows = await this.photoProviders.listAll();
return rows.map(r => ({ id: r.id, enabled: journeyOn && r.enabled === 1 }));
}
@@ -76,17 +93,7 @@ export class UnifiedMemoriesService {
return fail('No photo providers enabled', 400);
}
const photos = this.db.prepare(`
SELECT tp.photo_id, tkp.asset_id, tkp.provider, tp.user_id, tp.shared, tp.added_at,
u.username, u.avatar
FROM trip_photos tp
JOIN trek_photos tkp ON tkp.id = tp.photo_id
JOIN users u ON tp.user_id = u.id
WHERE tp.trip_id = ?
AND (tp.user_id = ? OR tp.shared = 1)
AND tkp.provider IN (${enabledProviders.map(() => '?').join(',')})
ORDER BY tp.added_at ASC
`).all(tripId, userId, ...enabledProviders);
const photos = await this.tripPhotos.listForTrip(tripId, userId, enabledProviders);
return success(photos);
} catch (error) {
@@ -108,23 +115,7 @@ export class UnifiedMemoriesService {
}
try {
const links = this.db.prepare(`
SELECT tal.id,
tal.trip_id,
tal.user_id,
tal.provider,
tal.album_id,
tal.album_name,
tal.sync_enabled,
tal.last_synced_at,
tal.created_at,
u.username
FROM trip_album_links tal
JOIN users u ON tal.user_id = u.id
WHERE tal.trip_id = ?
AND tal.provider IN (${enabledProviders.map(() => '?').join(',')})
ORDER BY tal.created_at ASC
`).all(tripId, ...enabledProviders);
const links = await this.tripAlbumLinks.listForTrip(tripId, enabledProviders);
return success(links);
} catch (error) {
@@ -142,10 +133,14 @@ export class UnifiedMemoriesService {
}
try {
const photoId = await this.photos.getOrCreate(provider, assetId, userId, passphrase);
const result = this.db.prepare(
'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, photo_id, shared, album_link_id) VALUES (?, ?, ?, ?, ?)'
).run(tripId, userId, photoId, shared ? 1 : 0, albumLinkId || null);
return success(result.changes > 0);
const added = await this.tripPhotos.insertIgnore({
trip_id: tripId,
user_id: userId,
photo_id: photoId,
shared: shared ? 1 : 0,
album_link_id: albumLinkId || null,
});
return success(added);
}
catch (error) {
return mapDbError(error, 'Failed to add photo to trip');
@@ -189,7 +184,7 @@ export class UnifiedMemoriesService {
}
await this._notifySharedTripPhotos(tripId, userId, added);
broadcast(tripId, 'memories:updated', { userId }, sid);
this.realtime.broadcast(tripId, 'memories:updated', { userId }, sid);
return success({ added, shared });
}
@@ -207,16 +202,10 @@ export class UnifiedMemoriesService {
}
try {
this.db.prepare(`
UPDATE trip_photos
SET shared = ?
WHERE trip_id = ?
AND user_id = ?
AND photo_id = ?
`).run(shared ? 1 : 0, tripId, userId, photoId);
await this.tripPhotos.setShared(tripId, userId, photoId, shared ? 1 : 0);
await this._notifySharedTripPhotos(tripId, userId, 1);
broadcast(tripId, 'memories:updated', { userId }, sid);
this.realtime.broadcast(tripId, 'memories:updated', { userId }, sid);
return success(true);
} catch (error) {
return mapDbError(error, 'Failed to update photo sharing');
@@ -235,15 +224,10 @@ export class UnifiedMemoriesService {
}
try {
this.db.prepare(`
DELETE FROM trip_photos
WHERE trip_id = ?
AND user_id = ?
AND photo_id = ?
`).run(tripId, userId, photoId);
await this.tripPhotos.deleteForUserPhoto(tripId, userId, photoId);
await this.photos.deleteIfOrphan(photoId);
broadcast(tripId, 'memories:updated', { userId }, sid);
this.realtime.broadcast(tripId, 'memories:updated', { userId }, sid);
return success(true);
} catch (error) {
@@ -279,11 +263,16 @@ export class UnifiedMemoriesService {
try {
const encryptedPassphrase = passphrase ? encrypt_api_key(passphrase) : null;
const result = this.db.prepare(
'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name, passphrase) VALUES (?, ?, ?, ?, ?, ?)'
).run(tripId, userId, provider, albumId, albumName, encryptedPassphrase);
const added = await this.tripAlbumLinks.insertIgnore({
trip_id: tripId,
user_id: userId,
provider,
album_id: albumId,
album_name: albumName,
passphrase: encryptedPassphrase,
});
if (result.changes === 0) {
if (!added) {
return fail('Album already linked', 409);
}
@@ -300,17 +289,14 @@ export class UnifiedMemoriesService {
}
try {
const linkedPhotos = this.db.prepare('SELECT photo_id FROM trip_photos WHERE trip_id = ? AND album_link_id = ?')
.all(tripId, linkId) as Array<{ photo_id: number }>;
const linkedPhotoIds = await this.tripPhotos.listPhotoIdsForAlbumLink(tripId, linkId);
await this.uow.transactional(async () => {
this.db.prepare('DELETE FROM trip_photos WHERE trip_id = ? AND album_link_id = ?')
.run(tripId, linkId);
this.db.prepare('DELETE FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?')
.run(linkId, tripId, userId);
await this.tripPhotos.deleteForAlbumLink(tripId, linkId);
await this.tripAlbumLinks.deleteScoped(linkId, tripId, userId);
});
for (const { photo_id } of linkedPhotos) {
for (const photo_id of linkedPhotoIds) {
await this.photos.deleteIfOrphan(photo_id);
}
@@ -332,12 +318,11 @@ export class UnifiedMemoriesService {
if (added <= 0) return success(undefined);
try {
const actorRow = this.db.prepare('SELECT username, email FROM users WHERE id = ?').get(actorUserId) as { username: string | null, email: string | null };
const actorRow = await this.users.findUsernameEmail(actorUserId);
const tripInfo = this.db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined;
const tripTitle = await this.trips.getTitle(tripId);
this.notifications.send({ event: 'photos_shared', actorId: actorUserId, scope: 'trip', targetId: Number(tripId), params: { trip: tripInfo?.title || 'Untitled', actor: actorRow?.email || 'Unknown', count: String(added), tripId: String(tripId) } }).catch(() => {});
this.notifications.send({ event: 'photos_shared', actorId: actorUserId, scope: 'trip', targetId: Number(tripId), params: { trip: tripTitle || 'Untitled', actor: actorRow?.email || 'Unknown', count: String(added), tripId: String(tripId) } }).catch(() => {});
return success(undefined);
} catch {
return fail('Failed to send notifications', 500);