0b3ab76405
Immich connections stay server-side with an encrypted API key, albums can be imported, and photos are only sent back when an event's push button is pressed: originals upload once, edited photos re-render, and edits hashes plus checksums skip anything already in Immich. This also lands the accompanying editor, cloud and administration work that was still uncommitted. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com>
1541 lines
50 KiB
JavaScript
1541 lines
50 KiB
JavaScript
/**
|
|
* Immich integration — opt-in, per account.
|
|
*
|
|
* Each user connects their own Immich server and API key from the Immich sync
|
|
* panel; nothing exists for a user until they save a connection and enable it.
|
|
* The integration then provides three things:
|
|
*
|
|
* - pull: import an album into a Luminary event, recording each source asset;
|
|
* - push: on demand only, render an edit (or the original) and upload it as a
|
|
* new Immich asset, copying album, stack, favourite and sidecar
|
|
* associations from the imported original.
|
|
*
|
|
* The API key is sealed at rest and never returned to the browser. All network
|
|
* access is server-side, so the key is not exposed to page scripts either.
|
|
*/
|
|
|
|
import crypto from 'node:crypto';
|
|
import fs from 'node:fs';
|
|
import fsp from 'node:fs/promises';
|
|
import { Readable, Transform } from 'node:stream';
|
|
import { pipeline } from 'node:stream/promises';
|
|
import { MAX_UPLOAD, RAW_PREVIEW_EDGE } from './config.mjs';
|
|
import {
|
|
allImmichSettings,
|
|
deleteImmichSettingsRecord,
|
|
getEvent,
|
|
getPhoto,
|
|
immichAlbumByAlbum,
|
|
immichAlbumFor,
|
|
immichAlbumForEvent,
|
|
immichAlbumLinks,
|
|
immichAssetForPhoto,
|
|
immichAssetsForEvent,
|
|
immichMetaFor,
|
|
immichPendingForEvent,
|
|
immichPushAssetsForPhoto,
|
|
immichPushDoneForPhoto,
|
|
immichPushFor,
|
|
immichSettingsFor,
|
|
kv,
|
|
patchPhotoMeta,
|
|
photoIdsForEvent,
|
|
saveImmichMeta,
|
|
removeImmichAsset,
|
|
saveEvent,
|
|
saveImmichAlbum,
|
|
saveImmichAsset,
|
|
saveImmichPush,
|
|
saveImmichSettingsRecord,
|
|
savePhoto,
|
|
setImmichSyncState,
|
|
} from './db.mjs';
|
|
import { decodeRaw, isRawName } from './raw.mjs';
|
|
import { jpegInfo, makeThumb, toJpegProxy } from './imaging.mjs';
|
|
import { findOriginal, findPreview, originalTarget, writePreview, writeThumb } from './storage.mjs';
|
|
import { quotaState } from './quota.mjs';
|
|
import { open, seal } from './secrets.mjs';
|
|
|
|
const REQUEST_TIMEOUT_MS = 20_000;
|
|
const DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;
|
|
const MAX_JOB_HISTORY = 20;
|
|
const MAX_JOB_ERRORS = 5;
|
|
const SYNC_TICK_MS = 5 * 60 * 1000;
|
|
|
|
const MIME_BY_EXT = {
|
|
jpg: 'image/jpeg',
|
|
jpeg: 'image/jpeg',
|
|
png: 'image/png',
|
|
webp: 'image/webp',
|
|
gif: 'image/gif',
|
|
avif: 'image/avif',
|
|
tif: 'image/tiff',
|
|
tiff: 'image/tiff',
|
|
heic: 'image/heic',
|
|
heif: 'image/heif',
|
|
};
|
|
|
|
const BROWSER_IMAGE_EXT = new Set(['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif']);
|
|
|
|
/* ------------------------------------------------------------------ settings */
|
|
|
|
const versionCache = new Map();
|
|
const SHARED_OWNER_ID = '__shared__';
|
|
const SHARED_SETTINGS_KEY = 'immich.shared';
|
|
|
|
/** The server-wide connection saved from Administration → Immich. */
|
|
function sharedSettingsRow() {
|
|
const saved = kv.get(SHARED_SETTINGS_KEY);
|
|
if (!saved || typeof saved !== 'object') return null;
|
|
return {
|
|
ownerId: SHARED_OWNER_ID,
|
|
serverUrl: String(saved.serverUrl ?? ''),
|
|
apiKey: String(saved.apiKey ?? ''),
|
|
enabled: Boolean(saved.enabled),
|
|
autoSync: false,
|
|
syncMinutes: 60,
|
|
trashOriginal: Boolean(saved.trashOriginal),
|
|
syncMetadata: saved.syncMetadata !== false,
|
|
lastSyncAt: saved.lastSyncAt ?? null,
|
|
lastError: saved.lastError ?? null,
|
|
createdAt: saved.createdAt ?? Date.now(),
|
|
};
|
|
}
|
|
|
|
function openedSettings(ownerId) {
|
|
// A connection configured by an administrator applies to every account.
|
|
// Per-account settings remain as a fallback for installations without one.
|
|
const shared = sharedSettingsRow();
|
|
const row = shared ?? (ownerId === SHARED_OWNER_ID ? null : immichSettingsFor(ownerId));
|
|
if (!row) return null;
|
|
let apiKey = row.apiKey;
|
|
if (apiKey) {
|
|
try {
|
|
apiKey = open(apiKey);
|
|
} catch (err) {
|
|
console.error(`[luminary] could not decrypt the Immich key for ${ownerId}:`, err.message);
|
|
apiKey = '';
|
|
}
|
|
}
|
|
return { ...row, apiKey };
|
|
}
|
|
|
|
export function normalizeImmichUrl(input) {
|
|
const raw = String(input ?? '').trim();
|
|
if (!raw) throw new Error('Enter the address of your Immich server');
|
|
let url;
|
|
try {
|
|
url = new URL(raw);
|
|
} catch {
|
|
throw new Error('Enter a full address, for example http://192.168.1.10:2283');
|
|
}
|
|
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
throw new Error('Immich must be reachable over http or https');
|
|
}
|
|
if (url.username || url.password) {
|
|
throw new Error('Put the API key in the key field, not in the server address');
|
|
}
|
|
url.search = '';
|
|
url.hash = '';
|
|
let pathname = url.pathname.replace(/\/+$/, '');
|
|
if (/\/api$/i.test(pathname)) pathname = pathname.slice(0, -4);
|
|
url.pathname = pathname;
|
|
return `${url.origin}${pathname}`;
|
|
}
|
|
|
|
/** Safe for the browser: never includes the API key. */
|
|
export function immichStatusFor(ownerId) {
|
|
const row = openedSettings(ownerId);
|
|
let url = row?.serverUrl ?? '';
|
|
let valid = true;
|
|
try {
|
|
if (url) url = normalizeImmichUrl(url);
|
|
} catch {
|
|
valid = false;
|
|
}
|
|
const hasKey = Boolean(row?.apiKey);
|
|
const configured = Boolean(valid && url && hasKey);
|
|
return {
|
|
configured,
|
|
enabled: Boolean(configured && row?.enabled),
|
|
managed: Boolean(sharedSettingsRow()),
|
|
url,
|
|
hasKey,
|
|
autoSync: Boolean(row?.autoSync),
|
|
syncMinutes: Number(row?.syncMinutes ?? 60),
|
|
trashOriginal: Boolean(row?.trashOriginal),
|
|
syncMetadata: Boolean(row?.syncMetadata ?? true),
|
|
lastSyncAt: row?.lastSyncAt ?? null,
|
|
lastError: row?.lastError ?? null,
|
|
version: versionCache.get(ownerId) ?? versionCache.get(SHARED_OWNER_ID) ?? null,
|
|
albumCount: immichAlbumLinks(ownerId).length,
|
|
};
|
|
}
|
|
|
|
export function immichConfigured(ownerId) {
|
|
return immichStatusFor(ownerId).configured;
|
|
}
|
|
|
|
export function saveImmichUserSettings(ownerId, input = {}) {
|
|
const current = openedSettings(ownerId);
|
|
const url = normalizeImmichUrl(input.url !== undefined ? input.url : current?.serverUrl ?? '');
|
|
const apiKey = String(
|
|
(input.apiKey && String(input.apiKey).trim()) || current?.apiKey || '',
|
|
).trim();
|
|
if (!apiKey) throw new Error('Paste an Immich API key');
|
|
if (apiKey.length < 8) throw new Error('That API key looks too short');
|
|
|
|
const record = {
|
|
ownerId,
|
|
serverUrl: url,
|
|
apiKey: seal(apiKey),
|
|
enabled: input.enabled === undefined ? (current?.enabled ?? true) : Boolean(input.enabled),
|
|
autoSync:
|
|
input.autoSync === undefined ? (current?.autoSync ?? false) : Boolean(input.autoSync),
|
|
syncMinutes: Math.max(
|
|
15,
|
|
Math.min(1440, Number(input.syncMinutes ?? current?.syncMinutes ?? 60) || 60),
|
|
),
|
|
trashOriginal:
|
|
input.trashOriginal === undefined
|
|
? (current?.trashOriginal ?? false)
|
|
: Boolean(input.trashOriginal),
|
|
syncMetadata:
|
|
input.syncMetadata === undefined ? (current?.syncMetadata ?? true) : Boolean(input.syncMetadata),
|
|
lastSyncAt: current?.lastSyncAt ?? null,
|
|
lastError: null,
|
|
createdAt: current?.createdAt ?? Date.now(),
|
|
};
|
|
saveImmichSettingsRecord(record);
|
|
if (!current || input.apiKey || url !== current.serverUrl) versionCache.delete(ownerId);
|
|
return immichStatusFor(ownerId);
|
|
}
|
|
|
|
export function saveImmichAdminSettings(input = {}) {
|
|
const current = openedSettings(SHARED_OWNER_ID);
|
|
const url = normalizeImmichUrl(input.url !== undefined ? input.url : current?.serverUrl ?? '');
|
|
const apiKey = String(
|
|
(input.apiKey && String(input.apiKey).trim()) || current?.apiKey || '',
|
|
).trim();
|
|
if (!apiKey) throw new Error('Paste an Immich API key');
|
|
if (apiKey.length < 8) throw new Error('That API key looks too short');
|
|
|
|
const previous = kv.get(SHARED_SETTINGS_KEY) ?? {};
|
|
kv.set(SHARED_SETTINGS_KEY, {
|
|
serverUrl: url,
|
|
apiKey: seal(apiKey),
|
|
enabled: input.enabled === undefined ? (current?.enabled ?? true) : Boolean(input.enabled),
|
|
trashOriginal:
|
|
input.trashOriginal === undefined
|
|
? (current?.trashOriginal ?? false)
|
|
: Boolean(input.trashOriginal),
|
|
syncMetadata:
|
|
input.syncMetadata === undefined ? (current?.syncMetadata ?? true) : Boolean(input.syncMetadata),
|
|
lastSyncAt: current?.lastSyncAt ?? null,
|
|
lastError: null,
|
|
createdAt: previous.createdAt ?? Date.now(),
|
|
});
|
|
if (!current || input.apiKey || url !== current.serverUrl) versionCache.delete(SHARED_OWNER_ID);
|
|
return immichStatusFor(SHARED_OWNER_ID);
|
|
}
|
|
|
|
export function disconnectImmichAdmin() {
|
|
kv.set(SHARED_SETTINGS_KEY, null);
|
|
versionCache.delete(SHARED_OWNER_ID);
|
|
return immichStatusFor(SHARED_OWNER_ID);
|
|
}
|
|
|
|
export function immichAdminStatus() {
|
|
return immichStatusFor(SHARED_OWNER_ID);
|
|
}
|
|
|
|
export function immichAdminPing() {
|
|
return immichPing(SHARED_OWNER_ID);
|
|
}
|
|
|
|
export function disconnectImmich(ownerId) {
|
|
deleteImmichSettingsRecord(ownerId);
|
|
versionCache.delete(ownerId);
|
|
return immichStatusFor(ownerId);
|
|
}
|
|
|
|
function credentials(ownerId) {
|
|
const row = openedSettings(ownerId);
|
|
if (!row?.serverUrl || !row.apiKey) {
|
|
throw new Error('Connect your Immich server in the Immich sync panel first');
|
|
}
|
|
return { url: normalizeImmichUrl(row.serverUrl), apiKey: row.apiKey, settings: row };
|
|
}
|
|
|
|
/* ---------------------------------------------------------------------- api */
|
|
|
|
function messageFromBody(body, status) {
|
|
const raw = body?.message ?? body?.error;
|
|
if (Array.isArray(raw)) return raw.join('; ');
|
|
if (typeof raw === 'string' && raw.trim()) return raw.trim();
|
|
return `Immich request failed (${status})`;
|
|
}
|
|
|
|
async function apiRequest(ownerId, path, init = {}) {
|
|
const { url, apiKey } = credentials(ownerId);
|
|
const controller = new AbortController();
|
|
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
|
|
try {
|
|
const res = await fetch(`${url}/api${path}`, {
|
|
...init,
|
|
headers: {
|
|
accept: 'application/json',
|
|
'x-api-key': apiKey,
|
|
...(init.headers ?? {}),
|
|
},
|
|
signal: controller.signal,
|
|
});
|
|
const text = await res.text();
|
|
let body = null;
|
|
try {
|
|
body = text ? JSON.parse(text) : null;
|
|
} catch {
|
|
body = text;
|
|
}
|
|
if (!res.ok) {
|
|
if (res.status === 401 || res.status === 403) {
|
|
throw new Error(
|
|
'Immich rejected the API key or it lacks permission. Check album.read, albumAsset.create, asset.read, asset.download and asset.upload.',
|
|
);
|
|
}
|
|
throw new Error(messageFromBody(body, res.status));
|
|
}
|
|
return body;
|
|
} catch (err) {
|
|
if (err instanceof Error && err.name === 'AbortError') {
|
|
throw new Error('The Immich server did not respond in time');
|
|
}
|
|
if (err instanceof TypeError) {
|
|
throw new Error(`Could not reach Immich at ${url}`);
|
|
}
|
|
throw err;
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
|
|
async function immichVersion(ownerId) {
|
|
const body = await apiRequest(ownerId, '/server/version');
|
|
let major = 0;
|
|
let minor = 0;
|
|
let patch = 0;
|
|
let version = 'unknown';
|
|
if (typeof body === 'string') {
|
|
version = body;
|
|
const parts = body.split('.').map(Number);
|
|
[major = 0, minor = 0, patch = 0] = parts;
|
|
} else if (body && typeof body === 'object') {
|
|
major = Number(body.major ?? 0) || 0;
|
|
minor = Number(body.minor ?? 0) || 0;
|
|
patch = Number(body.patch ?? 0) || 0;
|
|
version = String(body.version ?? (major ? `${major}.${minor}.${patch}` : 'unknown'));
|
|
}
|
|
if (major) versionCache.set(ownerId, version);
|
|
return { major, minor, patch, version };
|
|
}
|
|
|
|
function normalizeAlbum(album) {
|
|
return {
|
|
id: String(album.id),
|
|
name: String(album.albumName ?? album.name ?? 'Untitled album'),
|
|
assetCount: Number(album.assetCount ?? album.assets?.length ?? 0) || 0,
|
|
updatedAt: album.updatedAt ? Date.parse(album.updatedAt) || null : null,
|
|
startDate: album.startDate ? Date.parse(album.startDate) || null : null,
|
|
endDate: album.endDate ? Date.parse(album.endDate) || null : null,
|
|
thumbnailAssetId: album.albumThumbnailAssetId ?? null,
|
|
};
|
|
}
|
|
|
|
export async function listImmichAlbums(ownerId) {
|
|
const body = await apiRequest(ownerId, '/albums');
|
|
const items = Array.isArray(body) ? body : Array.isArray(body?.albums) ? body.albums : [];
|
|
return items
|
|
.filter((album) => album && album.id)
|
|
.map(normalizeAlbum)
|
|
.sort(
|
|
(a, b) =>
|
|
(b.updatedAt ?? 0) - (a.updatedAt ?? 0) ||
|
|
a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }),
|
|
);
|
|
}
|
|
|
|
/** Creates an Immich album for an event and records it as that event's gallery. */
|
|
export async function createImmichAlbumForEvent({ ownerId, eventId, name }) {
|
|
const settings = openedSettings(ownerId);
|
|
if (!settings?.enabled) {
|
|
throw new Error('Immich sync is not enabled for this account');
|
|
}
|
|
const event = getEvent(eventId);
|
|
if (!event) throw new Error('No such event');
|
|
if (event.immich || immichAlbumForEvent(eventId)) {
|
|
throw new Error('This event already has an Immich gallery');
|
|
}
|
|
|
|
const { url } = credentials(ownerId);
|
|
const albumName = String(name || event.name || 'Luminary event').trim().slice(0, 120);
|
|
const created = await apiRequest(ownerId, '/albums', {
|
|
method: 'POST',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({ albumName, description: 'Created from Luminary' }),
|
|
});
|
|
const albumId = created?.id ? String(created.id) : '';
|
|
if (!albumId) throw new Error('Immich did not return the new album');
|
|
|
|
const now = Date.now();
|
|
saveImmichAlbum({
|
|
eventId,
|
|
ownerId,
|
|
serverUrl: url,
|
|
albumId,
|
|
albumName,
|
|
assetCount: 0,
|
|
kind: 'gallery',
|
|
lastSyncAt: now,
|
|
createdAt: now,
|
|
});
|
|
const updated = {
|
|
...event,
|
|
immich: { albumId, albumName, serverUrl: url, lastSyncAt: now },
|
|
};
|
|
saveEvent(updated, event.order ?? event.createdAt ?? now, ownerId);
|
|
return { album: normalizeAlbum(created), event: updated };
|
|
}
|
|
|
|
export async function immichPing(ownerId) {
|
|
const version = await immichVersion(ownerId);
|
|
const albums = await listImmichAlbums(ownerId);
|
|
const { url } = credentials(ownerId);
|
|
return {
|
|
ok: true,
|
|
url,
|
|
version: version.version,
|
|
major: version.major,
|
|
albumCount: albums.length,
|
|
};
|
|
}
|
|
|
|
/* -------------------------------------------------------------------- albums */
|
|
|
|
async function searchAlbumAssets(ownerId, albumId) {
|
|
const body = await apiRequest(ownerId, '/search/metadata', {
|
|
method: 'POST',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({ albumIds: [albumId], size: 1000, page: 1, withExif: true }),
|
|
});
|
|
if (Array.isArray(body?.assets?.items)) return body.assets.items;
|
|
if (Array.isArray(body?.items)) return body.items;
|
|
return [];
|
|
}
|
|
|
|
async function fetchImmichAlbum(ownerId, albumId) {
|
|
let album = await apiRequest(ownerId, `/albums/${encodeURIComponent(albumId)}`);
|
|
if (!album || typeof album !== 'object') {
|
|
throw new Error('Immich returned an unexpected album response');
|
|
}
|
|
let assets = Array.isArray(album.assets) ? album.assets : [];
|
|
|
|
if (!assets.length) {
|
|
const full = await apiRequest(
|
|
ownerId,
|
|
`/albums/${encodeURIComponent(albumId)}?withoutAssets=false`,
|
|
).catch(() => null);
|
|
if (full && typeof full === 'object') {
|
|
album = { ...album, ...full };
|
|
if (Array.isArray(full.assets)) assets = full.assets;
|
|
}
|
|
}
|
|
|
|
const expected = Number(album.assetCount ?? 0) || 0;
|
|
if (expected && assets.length < expected) {
|
|
const items = await searchAlbumAssets(ownerId, albumId).catch(() => []);
|
|
if (items.length > assets.length) assets = items;
|
|
}
|
|
return { album, assets, expected };
|
|
}
|
|
|
|
function assetFileName(asset) {
|
|
const name = String(asset.originalFileName ?? '').trim();
|
|
if (name) return name;
|
|
const fromPath = String(asset.originalPath ?? '').split('/').pop()?.trim();
|
|
if (fromPath) return fromPath;
|
|
return `${asset.id}.jpg`;
|
|
}
|
|
|
|
function assetTakenAt(asset) {
|
|
const value = asset.fileCreatedAt || asset.exifInfo?.dateTimeOriginal || asset.createdAt;
|
|
const ms = value ? Date.parse(value) : NaN;
|
|
return Number.isFinite(ms) ? ms : undefined;
|
|
}
|
|
|
|
function assetMeta(asset) {
|
|
const exif = asset.exifInfo ?? {};
|
|
const camera = [exif.make, exif.model].filter(Boolean).join(' ').trim();
|
|
const iso = Number(exif.iso) || undefined;
|
|
const aperture = Number(exif.fNumber) || undefined;
|
|
const focal = Number(exif.focalLength) || undefined;
|
|
const shutter = exif.exposureTime ? String(exif.exposureTime) : undefined;
|
|
return {
|
|
...(camera ? { camera } : {}),
|
|
...(exif.lensModel ? { lens: String(exif.lensModel) } : {}),
|
|
...(iso ? { iso } : {}),
|
|
...(aperture ? { aperture } : {}),
|
|
...(shutter ? { shutter } : {}),
|
|
...(focal ? { focal } : {}),
|
|
};
|
|
}
|
|
|
|
function extensionOf(name) {
|
|
const raw = String(name ?? '');
|
|
const dot = raw.lastIndexOf('.');
|
|
const ext = dot > 0 ? raw.slice(dot + 1).toLowerCase() : '';
|
|
return /^[a-z0-9]{1,10}$/.test(ext) ? ext : 'jpg';
|
|
}
|
|
|
|
async function downloadImmichAsset(ownerId, assetId, target) {
|
|
const { url, apiKey } = credentials(ownerId);
|
|
const controller = new AbortController();
|
|
const timer = setTimeout(() => controller.abort(), DOWNLOAD_TIMEOUT_MS);
|
|
const temp = `${target}.part-${crypto.randomBytes(6).toString('hex')}`;
|
|
let size = 0;
|
|
|
|
try {
|
|
const res = await fetch(`${url}/api/assets/${encodeURIComponent(assetId)}/original`, {
|
|
headers: { 'x-api-key': apiKey },
|
|
signal: controller.signal,
|
|
});
|
|
if (!res.ok || !res.body) {
|
|
throw new Error(`Immich could not send this file (${res.status})`);
|
|
}
|
|
|
|
const counter = new Transform({
|
|
transform(chunk, _encoding, callback) {
|
|
size += chunk.length;
|
|
if (size > MAX_UPLOAD) {
|
|
callback(new Error('This file is larger than the upload limit'));
|
|
return;
|
|
}
|
|
callback(null, chunk);
|
|
},
|
|
});
|
|
|
|
await pipeline(Readable.fromWeb(res.body), counter, fs.createWriteStream(temp, { flags: 'wx' }));
|
|
await fsp.rename(temp, target);
|
|
return size;
|
|
} catch (err) {
|
|
await fsp.rm(temp, { force: true }).catch(() => undefined);
|
|
if (err instanceof Error && err.name === 'AbortError') {
|
|
throw new Error('The Immich download timed out');
|
|
}
|
|
throw err;
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
|
|
async function prepareImportedFile({ photoId, fileName, raw, target, exifSize }) {
|
|
if (raw) {
|
|
const decoded = await decodeRaw(await fsp.readFile(target));
|
|
await writePreview(photoId, decoded.jpeg, decoded.ext);
|
|
const info = await jpegInfo(decoded.jpeg);
|
|
const thumb = await makeThumb(decoded.jpeg, 512);
|
|
if (thumb) await writeThumb(photoId, thumb);
|
|
return {
|
|
mime: 'image/jpeg',
|
|
width: info?.width || decoded.width || exifSize?.width || 0,
|
|
height: info?.height || decoded.height || exifSize?.height || 0,
|
|
previewUrl: `/api/photos/${photoId}/preview`,
|
|
thumbUrl: `/api/photos/${photoId}/thumb`,
|
|
decode: decoded.engine,
|
|
};
|
|
}
|
|
|
|
const ext = extensionOf(fileName);
|
|
const buffer = await fsp.readFile(target);
|
|
const info = await jpegInfo(buffer);
|
|
|
|
let previewUrl;
|
|
let previewBuffer;
|
|
if (!BROWSER_IMAGE_EXT.has(ext)) {
|
|
const proxy = await toJpegProxy(buffer, RAW_PREVIEW_EDGE);
|
|
if (proxy) {
|
|
await writePreview(photoId, proxy.data, proxy.ext);
|
|
previewUrl = `/api/photos/${photoId}/preview`;
|
|
previewBuffer = proxy.data;
|
|
}
|
|
}
|
|
|
|
const thumb = await makeThumb(previewBuffer ?? buffer, 512);
|
|
if (thumb) await writeThumb(photoId, thumb);
|
|
|
|
return {
|
|
mime: MIME_BY_EXT[ext] ?? 'application/octet-stream',
|
|
width: info?.width || exifSize?.width || 0,
|
|
height: info?.height || exifSize?.height || 0,
|
|
previewUrl,
|
|
thumbUrl: `/api/photos/${photoId}/thumb`,
|
|
};
|
|
}
|
|
|
|
/* --------------------------------------------------------------------- jobs */
|
|
|
|
const jobs = new Map();
|
|
|
|
function pruneJobs() {
|
|
if (jobs.size <= MAX_JOB_HISTORY) return;
|
|
const finished = [...jobs.values()]
|
|
.filter((job) => job.state !== 'running')
|
|
.sort((a, b) => (a.finishedAt ?? a.startedAt) - (b.finishedAt ?? b.startedAt));
|
|
while (jobs.size > MAX_JOB_HISTORY && finished.length) {
|
|
jobs.delete(finished.shift().id);
|
|
}
|
|
}
|
|
|
|
function runningJobFor(ownerId) {
|
|
for (const job of jobs.values()) {
|
|
if (job.ownerId === ownerId && job.state === 'running') return job;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function publicJob(job) {
|
|
return {
|
|
id: job.id,
|
|
albumId: job.albumId,
|
|
albumName: job.albumName,
|
|
eventId: job.eventId,
|
|
state: job.state,
|
|
scheduled: Boolean(job.scheduled),
|
|
total: job.total,
|
|
done: job.done,
|
|
skipped: job.skipped,
|
|
failed: job.failed,
|
|
bytes: job.bytes,
|
|
message: job.message,
|
|
errors: job.errors.slice(),
|
|
startedAt: job.startedAt,
|
|
finishedAt: job.finishedAt,
|
|
};
|
|
}
|
|
|
|
export function immichJobFor(id, user) {
|
|
const job = jobs.get(id);
|
|
if (!job) return null;
|
|
if (job.ownerId !== user.id && user.role !== 'admin') return null;
|
|
return publicJob(job);
|
|
}
|
|
|
|
function makeJob(ownerId, albumId, scheduled) {
|
|
pruneJobs();
|
|
const job = {
|
|
id: crypto.randomUUID(),
|
|
ownerId,
|
|
albumId,
|
|
albumName: '',
|
|
eventId: null,
|
|
scheduled: Boolean(scheduled),
|
|
state: 'running',
|
|
total: 0,
|
|
done: 0,
|
|
skipped: 0,
|
|
failed: 0,
|
|
bytes: 0,
|
|
message: '',
|
|
errors: [],
|
|
startedAt: Date.now(),
|
|
finishedAt: null,
|
|
};
|
|
job.completion = new Promise((resolve) => {
|
|
job.settle = resolve;
|
|
});
|
|
jobs.set(job.id, job);
|
|
|
|
void runImport(job)
|
|
.catch((err) => {
|
|
job.state = 'error';
|
|
job.message = err instanceof Error ? err.message : 'The import could not be completed';
|
|
job.finishedAt = Date.now();
|
|
})
|
|
.finally(() => job.settle(job));
|
|
|
|
return job;
|
|
}
|
|
|
|
export function startImmichImport({ albumId, ownerId }) {
|
|
const status = immichStatusFor(ownerId);
|
|
if (!status.configured) {
|
|
throw new Error('Connect your Immich server in the Immich sync panel first');
|
|
}
|
|
if (!status.enabled) {
|
|
throw new Error('Turn on Immich sync in the Immich sync panel first');
|
|
}
|
|
if (typeof albumId !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(albumId)) {
|
|
throw new Error('Choose an Immich album to import');
|
|
}
|
|
const gallery = immichAlbumByAlbum(ownerId, albumId);
|
|
if (gallery?.kind === 'gallery') {
|
|
throw new Error('This album is an event gallery. Its edits are uploaded from Luminary.');
|
|
}
|
|
if (runningJobFor(ownerId)) {
|
|
throw new Error('An Immich import is already running for this account. Wait for it to finish.');
|
|
}
|
|
return publicJob(makeJob(ownerId, albumId, false));
|
|
}
|
|
|
|
async function runImport(job) {
|
|
await immichVersion(job.ownerId);
|
|
const { album, assets, expected } = await fetchImmichAlbum(job.ownerId, job.albumId);
|
|
const syncMeta = Boolean(openedSettings(job.ownerId)?.syncMetadata);
|
|
job.albumName = String(album.albumName ?? 'Untitled album');
|
|
|
|
const images = assets.filter(
|
|
(asset) => asset && asset.id && (!asset.type || asset.type === 'IMAGE') && !asset.isTrashed,
|
|
);
|
|
job.total = images.length;
|
|
if (expected && images.length < expected) {
|
|
job.message = `Immich reported ${expected} items; ${images.length} images were available to import.`;
|
|
}
|
|
|
|
const { url } = credentials(job.ownerId);
|
|
const existingLink = immichAlbumFor(job.ownerId, url, job.albumId);
|
|
const eventId = existingLink?.eventId ?? `immich-${crypto.randomUUID()}`;
|
|
job.eventId = eventId;
|
|
|
|
const existingEvent = existingLink ? getEvent(eventId) : null;
|
|
const known = new Map(immichAssetsForEvent(eventId).map((row) => [row.assetId, row]));
|
|
const now = Date.now();
|
|
|
|
let nextOrder = 0;
|
|
for (const row of known.values()) {
|
|
const photo = getPhoto(row.photoId);
|
|
if (photo) nextOrder = Math.max(nextOrder, (photo.order ?? 0) + 1);
|
|
}
|
|
|
|
let newestTaken = existingEvent?.date ?? 0;
|
|
let budget = quotaState(job.ownerId).remaining;
|
|
|
|
for (const asset of images) {
|
|
const previous = known.get(String(asset.id));
|
|
if (previous) {
|
|
const existingPhoto = getPhoto(previous.photoId);
|
|
if (existingPhoto) {
|
|
if (syncMeta) {
|
|
const saved = immichMetaFor(previous.photoId);
|
|
const stamp = asset.updatedAt ? Date.parse(asset.updatedAt) || 0 : 0;
|
|
if (!saved || !stamp || stamp !== saved.remoteUpdatedAt) {
|
|
await reconcileImmichMetadata({
|
|
photoId: previous.photoId,
|
|
ownerId: job.ownerId,
|
|
remoteAsset: asset,
|
|
}).catch(() => undefined);
|
|
}
|
|
}
|
|
job.skipped += 1;
|
|
continue;
|
|
}
|
|
removeImmichAsset(eventId, previous.assetId);
|
|
known.delete(previous.assetId);
|
|
}
|
|
|
|
if (budget <= 0) {
|
|
job.message = 'The account storage quota is full; the remaining photos were not imported.';
|
|
break;
|
|
}
|
|
|
|
const fileName = assetFileName(asset);
|
|
const raw = isRawName(fileName);
|
|
const photoId = `im-${crypto.randomUUID()}`;
|
|
const target = originalTarget(photoId, extensionOf(fileName));
|
|
const exif = asset.exifInfo ?? {};
|
|
const exifWidth = Number(exif.exifImageWidth ?? 0) || 0;
|
|
const exifHeight = Number(exif.exifImageHeight ?? 0) || 0;
|
|
const exifSize = exifWidth && exifHeight ? { width: exifWidth, height: exifHeight } : null;
|
|
const takenAt = assetTakenAt(asset);
|
|
const pulled = syncMeta ? await importAssetMetadata(job.ownerId, asset) : null;
|
|
|
|
try {
|
|
const size = await downloadImmichAsset(job.ownerId, String(asset.id), target);
|
|
const prepared = await prepareImportedFile({
|
|
photoId,
|
|
fileName,
|
|
raw,
|
|
target,
|
|
exifSize,
|
|
});
|
|
|
|
savePhoto(
|
|
{
|
|
id: photoId,
|
|
eventId,
|
|
order: nextOrder,
|
|
name: fileName,
|
|
width: prepared.width,
|
|
height: prepared.height,
|
|
size,
|
|
mime: prepared.mime,
|
|
addedAt: Date.now(),
|
|
takenAt,
|
|
meta: assetMeta(asset),
|
|
thumb: '',
|
|
thumbUrl: prepared.thumbUrl,
|
|
rating: pulled?.meta.rating ?? 0,
|
|
flag: pulled?.meta.flag ?? 'none',
|
|
color: '',
|
|
keywords: pulled?.meta.keywords ?? [],
|
|
edits: {},
|
|
history: [],
|
|
raw,
|
|
...(raw && prepared.decode ? { decode: prepared.decode } : {}),
|
|
...(prepared.previewUrl ? { previewUrl: prepared.previewUrl } : {}),
|
|
immich: {
|
|
albumId: job.albumId,
|
|
assetId: String(asset.id),
|
|
checksum: String(asset.checksum ?? ''),
|
|
},
|
|
},
|
|
Date.now(),
|
|
job.ownerId,
|
|
);
|
|
saveImmichAsset({
|
|
eventId,
|
|
assetId: String(asset.id),
|
|
photoId,
|
|
ownerId: job.ownerId,
|
|
albumId: job.albumId,
|
|
checksum: String(asset.checksum ?? ''),
|
|
fileName,
|
|
});
|
|
if (pulled) {
|
|
rememberImmichMeta({
|
|
photoId,
|
|
ownerId: job.ownerId,
|
|
assetId: String(asset.id),
|
|
local: {
|
|
rating: pulled.meta.rating,
|
|
flag: pulled.meta.flag,
|
|
keywords: pulled.meta.keywords ?? [],
|
|
},
|
|
remote: pulled.meta,
|
|
});
|
|
}
|
|
|
|
nextOrder += 1;
|
|
job.done += 1;
|
|
job.bytes += size;
|
|
budget -= size;
|
|
if (takenAt) newestTaken = Math.max(newestTaken, takenAt);
|
|
} catch (err) {
|
|
job.failed += 1;
|
|
if (job.errors.length < MAX_JOB_ERRORS) {
|
|
job.errors.push(
|
|
`${fileName}: ${err instanceof Error ? err.message : 'could not be imported'}`,
|
|
);
|
|
}
|
|
await fsp.rm(target, { force: true }).catch(() => undefined);
|
|
}
|
|
}
|
|
|
|
const record = {
|
|
...(existingEvent ?? {
|
|
id: eventId,
|
|
name: job.albumName,
|
|
createdAt: now,
|
|
date: newestTaken || now,
|
|
notes: `Imported from Immich (${url})`,
|
|
}),
|
|
id: eventId,
|
|
name: existingEvent?.name || job.albumName,
|
|
date: newestTaken || existingEvent?.date || now,
|
|
immich: {
|
|
albumId: job.albumId,
|
|
albumName: job.albumName,
|
|
serverUrl: url,
|
|
lastSyncAt: Date.now(),
|
|
},
|
|
};
|
|
saveEvent(record, existingEvent?.order ?? existingEvent?.createdAt ?? now, job.ownerId);
|
|
saveImmichAlbum({
|
|
eventId,
|
|
ownerId: job.ownerId,
|
|
serverUrl: url,
|
|
albumId: job.albumId,
|
|
albumName: job.albumName,
|
|
assetCount: images.length,
|
|
lastSyncAt: Date.now(),
|
|
createdAt: existingLink?.createdAt ?? now,
|
|
});
|
|
setImmichSyncState(job.ownerId, Date.now(), null);
|
|
|
|
if (job.failed) {
|
|
job.message = `${job.failed} file${job.failed === 1 ? '' : 's'} could not be imported.`;
|
|
} else if (!job.message) {
|
|
job.message = job.done
|
|
? `Imported ${job.done} new photo${job.done === 1 ? '' : 's'}.`
|
|
: 'Everything in this album is already in the library.';
|
|
}
|
|
job.state = 'done';
|
|
job.finishedAt = Date.now();
|
|
}
|
|
|
|
/** Links already created by this account, keyed for the album picker. */
|
|
export function immichLinksForOwner(ownerId) {
|
|
return immichAlbumLinks(ownerId);
|
|
}
|
|
|
|
/**
|
|
* Photos in an event that are not in its Immich gallery yet. Only local
|
|
* bookkeeping is read here, so the caller can plan a backfill without
|
|
* touching Immich.
|
|
*/
|
|
export function immichPendingPhotos({ eventId, ownerId }) {
|
|
const settings = openedSettings(ownerId);
|
|
if (!settings?.enabled) {
|
|
throw new Error('Immich sync is not enabled for this account');
|
|
}
|
|
const event = getEvent(eventId);
|
|
if (!event) throw new Error('No such event');
|
|
if (!event.immich && !immichAlbumForEvent(eventId)) {
|
|
throw new Error('This event has no Immich gallery yet');
|
|
}
|
|
const pending = immichPendingForEvent(eventId, ownerId);
|
|
return { pending, total: pending.length };
|
|
}
|
|
|
|
/**
|
|
* The manual push plan for one event: originals Immich has never seen, plus the
|
|
* current edit of any photo whose edits changed since the last push. This only
|
|
* reads local bookkeeping - the client renders and uploads each entry.
|
|
*/
|
|
export function immichEventQueue({ eventId, ownerId }) {
|
|
const settings = openedSettings(ownerId);
|
|
if (!settings?.enabled) {
|
|
throw new Error('Immich sync is not enabled for this account');
|
|
}
|
|
const event = getEvent(eventId);
|
|
if (!event) throw new Error('No such event');
|
|
if (!immichAlbumForEvent(eventId)) {
|
|
throw new Error('This event has no Immich gallery');
|
|
}
|
|
|
|
const queue = [];
|
|
for (const photoId of photoIdsForEvent(eventId, ownerId)) {
|
|
const photo = getPhoto(photoId);
|
|
if (!photo || photo.deletedAt) continue;
|
|
const link = immichAssetForPhoto(photoId);
|
|
const pushed = immichPushDoneForPhoto(photoId);
|
|
if (!photo.copyOf && !link && !pushed) {
|
|
queue.push({ photoId, name: photo.name, mode: 'original' });
|
|
continue;
|
|
}
|
|
// Virtual copies have no bytes of their own, so they are always rendered.
|
|
if (pushed && !photo.copyOf && pushed.edits_hash === editsHash(photo)) continue;
|
|
queue.push({ photoId, name: photo.name, mode: 'edit' });
|
|
}
|
|
return { queue, total: queue.length };
|
|
}
|
|
|
|
/* --------------------------------------------------------------------- push */
|
|
|
|
/** Identifies the edit version, so a repeat push can skip unchanged photos. */
|
|
function editsHash(photo) {
|
|
return crypto.createHash('sha1').update(JSON.stringify(photo?.edits ?? null)).digest('base64');
|
|
}
|
|
|
|
function fileStamp(photo) {
|
|
const ms = Number(photo.takenAt ?? photo.addedAt ?? Date.now());
|
|
return new Date(Number.isFinite(ms) ? ms : Date.now()).toISOString();
|
|
}
|
|
|
|
function outputName(photo) {
|
|
const base = String(photo.name || 'photo').replace(/\.[^.]+$/, '') || 'photo';
|
|
return `${base}-luminary.jpg`;
|
|
}
|
|
|
|
/* ------------------------------------------------------------------ metadata */
|
|
|
|
function normalizeKeywords(list) {
|
|
const seen = new Set();
|
|
const out = [];
|
|
for (const value of list ?? []) {
|
|
const word = String(value ?? '').trim();
|
|
if (!word) continue;
|
|
const key = word.toLowerCase();
|
|
if (seen.has(key)) continue;
|
|
seen.add(key);
|
|
out.push(word.slice(0, 64));
|
|
if (out.length >= 100) break;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** Immich stars + favourite/rejected map onto Luminary rating + flag. */
|
|
function remoteMetadata(asset) {
|
|
const raw = Number(asset?.rating ?? asset?.exifInfo?.rating);
|
|
const rating = Number.isFinite(raw) ? Math.trunc(raw) : 0;
|
|
const tags = Array.isArray(asset?.tags)
|
|
? normalizeKeywords(asset.tags.map((tag) => tag?.value ?? tag?.name))
|
|
: null;
|
|
return {
|
|
rating: rating < 0 ? 0 : Math.min(5, rating),
|
|
flag: rating < 0 ? 'reject' : asset?.isFavorite ? 'pick' : 'none',
|
|
keywords: tags,
|
|
updatedAt: asset?.updatedAt ? Date.parse(asset.updatedAt) || 0 : 0,
|
|
};
|
|
}
|
|
|
|
function localMetadata(photo) {
|
|
return {
|
|
rating: Math.max(0, Math.min(5, Math.trunc(Number(photo.rating) || 0))),
|
|
flag: photo.flag === 'pick' || photo.flag === 'reject' ? photo.flag : 'none',
|
|
keywords: normalizeKeywords(photo.keywords),
|
|
};
|
|
}
|
|
|
|
function metadataFingerprint(meta) {
|
|
return JSON.stringify([meta.rating, meta.flag, meta.keywords ?? null]);
|
|
}
|
|
|
|
function immichRating(local, major) {
|
|
if (local.flag === 'reject') return -1;
|
|
if (local.rating > 0) return local.rating;
|
|
// v3 rejects 0 as a rating; older servers use 0 for unrated.
|
|
return major >= 3 ? null : 0;
|
|
}
|
|
|
|
function rememberImmichMeta({ photoId, ownerId, assetId, local, remote }) {
|
|
saveImmichMeta({
|
|
photoId,
|
|
ownerId,
|
|
assetId,
|
|
localFingerprint: metadataFingerprint(local),
|
|
remoteFingerprint: metadataFingerprint(remote),
|
|
remoteUpdatedAt: remote.updatedAt ?? null,
|
|
lastSyncedAt: Date.now(),
|
|
lastError: null,
|
|
});
|
|
}
|
|
|
|
/** Uses the album payload when it already carries tags, otherwise asks for the asset. */
|
|
async function importAssetMetadata(ownerId, asset) {
|
|
if (Array.isArray(asset?.tags)) return { asset, meta: remoteMetadata(asset) };
|
|
const detail = await apiRequest(ownerId, `/assets/${encodeURIComponent(String(asset.id))}`).catch(
|
|
() => null,
|
|
);
|
|
return detail ? { asset: detail, meta: remoteMetadata(detail) } : { asset, meta: remoteMetadata(asset) };
|
|
}
|
|
|
|
function tagKey(tag) {
|
|
return String(tag?.value ?? tag?.name ?? '').trim().toLowerCase();
|
|
}
|
|
|
|
/**
|
|
* Immich has no batch tag-remove across tags, so removals walk the tags that are
|
|
* currently on the source asset. Adding uses the upsert endpoint then tags both
|
|
* the original and any pushed edits.
|
|
*/
|
|
async function syncAssetTags(ownerId, assetIds, wanted, currentTags) {
|
|
if (!assetIds.length) return;
|
|
const wantedList = normalizeKeywords(wanted);
|
|
const wantedKeys = new Set(wantedList.map((word) => word.toLowerCase()));
|
|
const current = Array.isArray(currentTags) ? currentTags : [];
|
|
const currentKeys = new Set(current.map(tagKey));
|
|
|
|
for (const tag of current) {
|
|
if (!tag?.id || wantedKeys.has(tagKey(tag))) continue;
|
|
await apiRequest(ownerId, `/tags/${encodeURIComponent(tag.id)}/assets`, {
|
|
method: 'DELETE',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({ ids: assetIds }),
|
|
});
|
|
}
|
|
|
|
const missing = wantedList.filter((word) => !currentKeys.has(word.toLowerCase()));
|
|
if (!missing.length) return;
|
|
const upserted = await apiRequest(ownerId, '/tags', {
|
|
method: 'PUT',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({ tags: missing }),
|
|
});
|
|
const list = Array.isArray(upserted) ? upserted : Array.isArray(upserted?.tags) ? upserted.tags : [];
|
|
const byKey = new Map(list.map((tag) => [tagKey(tag), tag]));
|
|
for (const word of missing) {
|
|
const tag = byKey.get(word.toLowerCase());
|
|
if (!tag?.id) continue;
|
|
await apiRequest(ownerId, `/tags/${encodeURIComponent(tag.id)}/assets`, {
|
|
method: 'PUT',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({ ids: assetIds }),
|
|
});
|
|
}
|
|
}
|
|
|
|
async function writeMetadataToAssets(ownerId, assetIds, local, currentTags) {
|
|
const ids = [...new Set(assetIds.filter(Boolean))];
|
|
if (!ids.length) return;
|
|
const version = await immichVersion(ownerId);
|
|
await apiRequest(ownerId, '/assets', {
|
|
method: 'PUT',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({
|
|
ids,
|
|
rating: immichRating(local, version.major),
|
|
isFavorite: local.flag === 'pick',
|
|
}),
|
|
});
|
|
await syncAssetTags(ownerId, ids, local.keywords, currentTags);
|
|
}
|
|
|
|
function remoteMetadataPatch(remote) {
|
|
return {
|
|
rating: remote.rating,
|
|
flag: remote.flag,
|
|
...(remote.keywords ? { keywords: remote.keywords } : {}),
|
|
};
|
|
}
|
|
|
|
/** Push the local rating/flag/keywords for a photo to its source and pushed edits. */
|
|
export async function pushImmichPhotoMetadata({ photoId, ownerId, local }) {
|
|
const settings = openedSettings(ownerId);
|
|
if (!settings?.enabled) throw new Error('Immich sync is not enabled for this account');
|
|
if (!settings.syncMetadata) return { ok: true, action: 'disabled' };
|
|
|
|
const photo = getPhoto(photoId);
|
|
if (!photo) throw new Error('No such photo');
|
|
const link = immichAssetForPhoto(photoId);
|
|
if (!link) {
|
|
throw new Error('This photo was not imported from Immich, so there is no original to update');
|
|
}
|
|
|
|
const desired = localMetadata({ ...photo, ...(local ?? {}) });
|
|
const detail = await importAssetMetadata(ownerId, { id: link.assetId });
|
|
await writeMetadataToAssets(
|
|
ownerId,
|
|
[link.assetId, ...immichPushAssetsForPhoto(photoId)],
|
|
desired,
|
|
detail.asset?.tags ?? [],
|
|
);
|
|
// Keep the stored record aligned so a later reconcile does not treat the
|
|
// pre-save value as a fresh local edit and push it back.
|
|
patchPhotoMeta(photoId, desired);
|
|
rememberImmichMeta({
|
|
photoId,
|
|
ownerId,
|
|
assetId: link.assetId,
|
|
local: desired,
|
|
remote: { ...desired, updatedAt: Date.now() },
|
|
});
|
|
return { ok: true, action: 'push' };
|
|
}
|
|
|
|
/**
|
|
* Reconciles one imported photo. A local edit wins when both sides changed; a
|
|
* remote-only change is written back to the stored photo without reordering it.
|
|
*/
|
|
export async function reconcileImmichMetadata({ photoId, ownerId, remoteAsset }) {
|
|
const settings = openedSettings(ownerId);
|
|
if (!settings?.enabled || !settings.syncMetadata) return { action: 'skipped' };
|
|
|
|
const photo = getPhoto(photoId);
|
|
const link = immichAssetForPhoto(photoId);
|
|
if (!photo || !link) return { action: 'skipped' };
|
|
|
|
let asset = remoteAsset;
|
|
if (!asset || !Array.isArray(asset.tags)) {
|
|
asset = await apiRequest(ownerId, `/assets/${encodeURIComponent(link.assetId)}`).catch(
|
|
() => asset,
|
|
);
|
|
}
|
|
if (!asset) return { action: 'skipped' };
|
|
|
|
const remote = remoteMetadata(asset);
|
|
const local = localMetadata(photo);
|
|
const saved = immichMetaFor(photoId);
|
|
const localFp = metadataFingerprint(local);
|
|
const remoteFp = metadataFingerprint(remote);
|
|
const localChanged = saved
|
|
? localFp !== saved.localFingerprint
|
|
: local.rating > 0 || local.flag !== 'none' || local.keywords.length > 0;
|
|
const remoteChanged = saved
|
|
? remoteFp !== saved.remoteFingerprint
|
|
: remote.rating > 0 || remote.flag !== 'none' || (remote.keywords?.length ?? 0) > 0;
|
|
|
|
if (localChanged) {
|
|
await writeMetadataToAssets(
|
|
ownerId,
|
|
[link.assetId, ...immichPushAssetsForPhoto(photoId)],
|
|
local,
|
|
asset.tags ?? [],
|
|
);
|
|
rememberImmichMeta({
|
|
photoId,
|
|
ownerId,
|
|
assetId: link.assetId,
|
|
local,
|
|
remote: { ...local, updatedAt: Date.now() },
|
|
});
|
|
return { action: 'push' };
|
|
}
|
|
|
|
if (remoteChanged) {
|
|
const next = patchPhotoMeta(photoId, remoteMetadataPatch(remote));
|
|
rememberImmichMeta({
|
|
photoId,
|
|
ownerId,
|
|
assetId: link.assetId,
|
|
local: localMetadata(next),
|
|
remote,
|
|
});
|
|
return { action: 'pull', photo: next };
|
|
}
|
|
|
|
rememberImmichMeta({ photoId, ownerId, assetId: link.assetId, local, remote });
|
|
return { action: 'none' };
|
|
}
|
|
|
|
export async function pushImmichPhoto({ photoId, ownerId, jpeg }) {
|
|
const settings = openedSettings(ownerId);
|
|
if (!settings?.enabled) {
|
|
throw new Error('Immich sync is not enabled for this account');
|
|
}
|
|
credentials(ownerId);
|
|
|
|
const photo = getPhoto(photoId);
|
|
if (!photo) throw new Error('No such photo');
|
|
const link = immichAssetForPhoto(photoId);
|
|
const gallery = immichAlbumForEvent(photo.eventId);
|
|
if (!link && !gallery) {
|
|
throw new Error(
|
|
'This photo was not imported from Immich and its event has no Immich gallery to send it to',
|
|
);
|
|
}
|
|
|
|
const checksum = crypto.createHash('sha1').update(jpeg).digest('base64');
|
|
const previous = immichPushFor(photoId, checksum);
|
|
if (previous?.state === 'done' && previous.newAssetId) {
|
|
let warning = '';
|
|
if (settings.syncMetadata && link) {
|
|
try {
|
|
await pushImmichPhotoMetadata({ photoId, ownerId, local: localMetadata(photo) });
|
|
} catch (err) {
|
|
warning = `The edit is already in Immich, but metadata did not sync: ${
|
|
err instanceof Error ? err.message : 'unknown error'
|
|
}`;
|
|
}
|
|
}
|
|
return {
|
|
ok: true,
|
|
assetId: previous.newAssetId,
|
|
alreadyPushed: true,
|
|
trashed: previous.trashedSource,
|
|
associations: {},
|
|
warning,
|
|
};
|
|
}
|
|
|
|
const version = await immichVersion(ownerId);
|
|
const form = new FormData();
|
|
form.append('assetData', new Blob([jpeg], { type: 'image/jpeg' }), outputName(photo));
|
|
form.append('fileCreatedAt', fileStamp(photo));
|
|
form.append('fileModifiedAt', new Date().toISOString());
|
|
if (version.major > 0 && version.major < 3) {
|
|
// Immich v3 removed the device identity fields from the upload contract.
|
|
form.append('deviceAssetId', `luminary-${photoId}-${checksum.slice(0, 8)}`);
|
|
form.append('deviceId', 'luminary');
|
|
}
|
|
|
|
let newAssetId;
|
|
try {
|
|
const uploaded = await apiRequest(ownerId, '/assets', {
|
|
method: 'POST',
|
|
headers: { 'x-immich-checksum': checksum },
|
|
body: form,
|
|
});
|
|
// Immich answers a byte-identical upload with a trashed placeholder and
|
|
// points at the asset it kept. Recording the placeholder would leave the
|
|
// photo out of the album (and look pushed forever), so keep the survivor.
|
|
newAssetId = uploaded?.duplicateId || uploaded?.id;
|
|
if (!newAssetId) throw new Error('Immich did not return the uploaded asset');
|
|
} catch (err) {
|
|
saveImmichPush({
|
|
id: crypto.randomUUID(),
|
|
ownerId,
|
|
photoId,
|
|
sourceAssetId: link?.assetId ?? '',
|
|
newAssetId: null,
|
|
checksum,
|
|
editsHash: editsHash(photo),
|
|
state: 'error',
|
|
trashedSource: false,
|
|
error: err instanceof Error ? err.message : 'upload failed',
|
|
createdAt: Date.now(),
|
|
});
|
|
throw err;
|
|
}
|
|
|
|
const associations = { albums: false, stack: false, favorite: false, sidecar: false };
|
|
const failures = [];
|
|
try {
|
|
if (link && version.major >= 3) {
|
|
await apiRequest(ownerId, '/assets/copy', {
|
|
method: 'PUT',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({
|
|
sourceId: link.assetId,
|
|
targetId: newAssetId,
|
|
albums: true,
|
|
stack: true,
|
|
sidecar: true,
|
|
favorite: true,
|
|
sharedLinks: true,
|
|
}),
|
|
});
|
|
associations.albums = true;
|
|
associations.stack = true;
|
|
associations.favorite = true;
|
|
associations.sidecar = true;
|
|
} else if (link && version.major > 0) {
|
|
await apiRequest(ownerId, `/assets/${encodeURIComponent(newAssetId)}/copy`, {
|
|
method: 'PUT',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({
|
|
sourceId: link.assetId,
|
|
albums: true,
|
|
stack: true,
|
|
sidecar: true,
|
|
}),
|
|
});
|
|
associations.albums = true;
|
|
associations.stack = true;
|
|
associations.sidecar = true;
|
|
}
|
|
} catch {
|
|
if (link) failures.push('album, stack and favourite associations');
|
|
}
|
|
|
|
// The destination album must not be lost; adding it is idempotent, so do it
|
|
// even when the copy endpoint claimed success. An event gallery is added as
|
|
// well, which lets plain Luminary uploads publish into that gallery.
|
|
const albumIds = [...new Set([link?.albumId, gallery?.albumId].filter(Boolean))];
|
|
for (const albumId of albumIds) {
|
|
try {
|
|
await apiRequest(ownerId, `/albums/${encodeURIComponent(albumId)}/assets`, {
|
|
method: 'PUT',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({ ids: [newAssetId] }),
|
|
});
|
|
associations.albums = true;
|
|
} catch (err) {
|
|
failures.push(
|
|
`the album could not be updated (${err instanceof Error ? err.message : 'unknown error'})`,
|
|
);
|
|
}
|
|
}
|
|
|
|
let metaWarning = '';
|
|
if (settings.syncMetadata) {
|
|
try {
|
|
const local = localMetadata(photo);
|
|
if (link) {
|
|
const detail = await importAssetMetadata(ownerId, { id: link.assetId });
|
|
await writeMetadataToAssets(
|
|
ownerId,
|
|
[link.assetId, newAssetId],
|
|
local,
|
|
detail.asset?.tags ?? [],
|
|
);
|
|
rememberImmichMeta({
|
|
photoId,
|
|
ownerId,
|
|
assetId: link.assetId,
|
|
local,
|
|
remote: { ...local, updatedAt: Date.now() },
|
|
});
|
|
} else {
|
|
await writeMetadataToAssets(ownerId, [newAssetId], local, []);
|
|
}
|
|
} catch (err) {
|
|
metaWarning = `The edit is in Immich, but ratings, flags or tags did not sync: ${
|
|
err instanceof Error ? err.message : 'unknown error'
|
|
}`;
|
|
}
|
|
}
|
|
|
|
let trashed = false;
|
|
let warning = '';
|
|
if (settings.trashOriginal && link) {
|
|
try {
|
|
await apiRequest(ownerId, '/assets', {
|
|
method: 'DELETE',
|
|
headers: { 'content-type': 'application/json' },
|
|
body: JSON.stringify({ ids: [link.assetId], force: false }),
|
|
});
|
|
trashed = true;
|
|
} catch (err) {
|
|
warning = `The edit is in Immich, but the original could not be moved to trash: ${
|
|
err instanceof Error ? err.message : 'unknown error'
|
|
}`;
|
|
}
|
|
}
|
|
|
|
saveImmichPush({
|
|
id: crypto.randomUUID(),
|
|
ownerId,
|
|
photoId,
|
|
sourceAssetId: link?.assetId ?? '',
|
|
newAssetId,
|
|
checksum,
|
|
editsHash: editsHash(photo),
|
|
state: 'done',
|
|
trashedSource: trashed,
|
|
error: null,
|
|
createdAt: Date.now(),
|
|
});
|
|
|
|
return {
|
|
ok: true,
|
|
assetId: newAssetId,
|
|
alreadyPushed: false,
|
|
trashed,
|
|
associations,
|
|
warning:
|
|
warning ||
|
|
metaWarning ||
|
|
(failures.length ? `Some metadata was not copied: ${failures.join('; ')}` : ''),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Adds a photo's original to its event's Immich gallery. Local imports use
|
|
* this so the whole set lands in the gallery without a manual send; the
|
|
* existing checksum record keeps a retry from uploading it twice.
|
|
*/
|
|
export async function publishImmichOriginal({ photoId, ownerId }) {
|
|
const settings = openedSettings(ownerId);
|
|
if (!settings?.enabled) {
|
|
throw new Error('Immich sync is not enabled for this account');
|
|
}
|
|
const photo = getPhoto(photoId);
|
|
if (!photo) throw new Error('No such photo');
|
|
if (!immichAlbumForEvent(photo.eventId)) {
|
|
throw new Error('This event has no Immich gallery');
|
|
}
|
|
|
|
const existing = immichAssetForPhoto(photoId);
|
|
if (existing) {
|
|
// The photo already exists in Immich; uploading the original again would
|
|
// create a duplicate rather than adding anything to the gallery.
|
|
return {
|
|
ok: true,
|
|
assetId: existing.assetId,
|
|
alreadyPushed: true,
|
|
skipped: true,
|
|
trashed: false,
|
|
associations: {},
|
|
warning: '',
|
|
};
|
|
}
|
|
|
|
const alreadyUploaded = immichPushDoneForPhoto(photoId);
|
|
if (alreadyUploaded) {
|
|
// An edit or an earlier original is already in Immich; uploading the
|
|
// original again would create a duplicate instead of adding anything.
|
|
return {
|
|
ok: true,
|
|
assetId: alreadyUploaded.new_asset_id,
|
|
alreadyPushed: true,
|
|
skipped: true,
|
|
trashed: false,
|
|
associations: {},
|
|
warning: '',
|
|
};
|
|
}
|
|
|
|
const original = findOriginal(photoId);
|
|
// Raws whose bytes were lost still have a server preview; sending that keeps
|
|
// the photo in the gallery instead of failing the whole push.
|
|
const preview = original ? null : findPreview(photoId);
|
|
if (!original && !preview) {
|
|
throw new Error('The original is not on the server, so it cannot be added to Immich');
|
|
}
|
|
const source = original ?? preview;
|
|
const bytes = await fsp.readFile(source);
|
|
const ext = source.split('.').pop()?.toLowerCase() ?? '';
|
|
let jpeg = bytes;
|
|
if (!['jpg', 'jpeg'].includes(ext) || bytes[0] !== 0xff || bytes[1] !== 0xd8) {
|
|
if (isRawName(source) || isRawName(photo.name)) {
|
|
const decoded = await decodeRaw(bytes);
|
|
jpeg = decoded?.jpeg;
|
|
} else {
|
|
const proxy = await toJpegProxy(bytes, 0);
|
|
jpeg = proxy?.data;
|
|
}
|
|
}
|
|
if (!jpeg || jpeg.length < 4 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8) {
|
|
throw new Error('The original could not be prepared as a JPEG for Immich');
|
|
}
|
|
const result = await pushImmichPhoto({ photoId, ownerId, jpeg });
|
|
if (original) return result;
|
|
const note = 'the raw original is missing on the server, so its preview was sent';
|
|
return { ...result, warning: result.warning ? `${result.warning} · ${note}` : note };
|
|
}
|
|
|
|
/* ---------------------------------------------------------------- scheduler */
|
|
|
|
export function startImmichWorker() {
|
|
const tick = () => {
|
|
void syncDueAccounts().catch((err) =>
|
|
console.error(`[luminary] Immich sync worker: ${err.message}`),
|
|
);
|
|
};
|
|
const timer = setInterval(tick, SYNC_TICK_MS);
|
|
timer.unref?.();
|
|
// Give the server a moment to settle before the first pass.
|
|
setTimeout(tick, 15_000).unref?.();
|
|
}
|
|
|
|
export async function syncDueAccounts() {
|
|
const now = Date.now();
|
|
for (const row of allImmichSettings()) {
|
|
if (!row.enabled || !row.autoSync || !row.serverUrl || !row.apiKey) continue;
|
|
if (runningJobFor(row.ownerId)) continue;
|
|
|
|
const settings = openedSettings(row.ownerId);
|
|
if (!settings?.apiKey) continue;
|
|
|
|
const interval = Math.max(15, Number(settings.syncMinutes) || 60) * 60_000;
|
|
if (settings.lastSyncAt && now - settings.lastSyncAt < interval) continue;
|
|
|
|
const links = immichAlbumLinks(row.ownerId);
|
|
if (!links.length) continue;
|
|
|
|
if (quotaState(row.ownerId).remaining <= 0) {
|
|
setImmichSyncState(row.ownerId, now, 'Storage quota is full; automatic sync was skipped.');
|
|
continue;
|
|
}
|
|
|
|
let lastError = null;
|
|
for (const link of links) {
|
|
if (link.kind === 'gallery') continue;
|
|
if (link.lastSyncAt && now - link.lastSyncAt < interval) continue;
|
|
if (runningJobFor(row.ownerId)) {
|
|
lastError = 'Automatic sync stopped because another import started.';
|
|
break;
|
|
}
|
|
let job;
|
|
try {
|
|
job = makeJob(row.ownerId, link.albumId, true);
|
|
} catch (err) {
|
|
lastError = err instanceof Error ? err.message : 'Could not start automatic sync';
|
|
break;
|
|
}
|
|
await job.completion;
|
|
if (job.state === 'error') lastError = job.message;
|
|
}
|
|
setImmichSyncState(row.ownerId, Date.now(), lastError);
|
|
}
|
|
}
|