import fs from 'fs'; import path from 'path'; const UPLOADS_DIR = path.join(process.cwd(), 'data', 'uploads'); if (!fs.existsSync(UPLOADS_DIR)) { fs.mkdirSync(UPLOADS_DIR, { recursive: true }); } export interface ImmichUploadResult { url: string; immichAssetId?: string; syncedToImmich: boolean; albumSynced?: boolean; error?: string; } export interface ImmichAlbum { id: string; albumName: string; assetCount?: number; description?: string; } /** * Normalizes and determines correct MIME-type and extension for image uploads */ function resolveMimeAndExt(base64OrBuffer: string, providedFilename?: string, providedMime?: string): { mimeType: string; extension: string } { if (providedMime && providedMime.startsWith('image/')) { const sub = providedMime.split('/')[1].toLowerCase(); const ext = sub === 'jpeg' || sub === 'jpg' ? 'jpg' : sub === 'png' ? 'png' : sub === 'webp' ? 'webp' : sub === 'heic' ? 'heic' : sub; const standardMime = ext === 'jpg' ? 'image/jpeg' : providedMime; return { mimeType: standardMime, extension: ext }; } if (base64OrBuffer.startsWith('data:image/')) { const match = base64OrBuffer.match(/^data:(image\/[a-zA-Z0-9.+_-]+);base64,/); if (match && match[1]) { const rawMime = match[1].toLowerCase(); const sub = rawMime.split('/')[1]; const ext = sub === 'jpeg' || sub === 'jpg' ? 'jpg' : sub; const standardMime = ext === 'jpg' ? 'image/jpeg' : rawMime; return { mimeType: standardMime, extension: ext }; } } if (providedFilename) { const extMatch = providedFilename.match(/\.([a-zA-Z0-9]+)$/); if (extMatch) { const ext = extMatch[1].toLowerCase(); if (ext === 'jpg' || ext === 'jpeg') return { mimeType: 'image/jpeg', extension: 'jpg' }; if (ext === 'png') return { mimeType: 'image/png', extension: 'png' }; if (ext === 'webp') return { mimeType: 'image/webp', extension: 'webp' }; if (ext === 'heic' || ext === 'heif') return { mimeType: 'image/heic', extension: 'heic' }; } } return { mimeType: 'image/jpeg', extension: 'jpg' }; } /** * Saves original photo locally in full uncompressed quality and syncs it to Immich instance (optionally into a dedicated album). */ export async function saveAndSyncPhoto( base64OrBuffer: string, filename?: string, immichUrl?: string, immichApiKey?: string, immichAlbumId?: string, options?: { mimeType?: string; fileCreatedAt?: string; } ): Promise { try { let buffer: Buffer; const { mimeType, extension } = resolveMimeAndExt(base64OrBuffer, filename, options?.mimeType); if (base64OrBuffer.startsWith('data:')) { const commaIdx = base64OrBuffer.indexOf(','); const base64Data = commaIdx >= 0 ? base64OrBuffer.substring(commaIdx + 1) : base64OrBuffer; buffer = Buffer.from(base64Data, 'base64'); } else { buffer = Buffer.from(base64OrBuffer, 'base64'); } const cleanBaseName = filename ? path.parse(filename).name.replace(/[^a-zA-Z0-9_-]/g, '_') : 'photo'; const uniqueFileName = `${Date.now()}-${cleanBaseName}.${extension}`; const localFilePath = path.join(UPLOADS_DIR, uniqueFileName); // Write exact binary buffer to disk (100% original quality preserved, no recompression) fs.writeFileSync(localFilePath, buffer); const localUrl = `/api/uploads/${uniqueFileName}`; let immichAssetId: string | undefined; let syncedToImmich = false; let albumSynced = false; // If Immich is configured, upload original binary asset to Immich API if (immichUrl && immichApiKey) { try { const cleanImmichUrl = immichUrl.replace(/\/+$/, ''); const formData = new FormData(); // Use Node Blob with strict standard MIME type const blob = new Blob([buffer], { type: mimeType }); const uploadFilename = filename || uniqueFileName; formData.append('assetData', blob, uploadFilename); formData.append('deviceAssetId', `${Date.now()}-${uploadFilename}`); formData.append('deviceId', 'wedding-hub-pwa'); formData.append('fileCreatedAt', options?.fileCreatedAt || new Date().toISOString()); formData.append('fileModifiedAt', new Date().toISOString()); formData.append('isFavorite', 'false'); const uploadRes = await fetch(`${cleanImmichUrl}/api/assets`, { method: 'POST', headers: { 'x-api-key': immichApiKey, Accept: 'application/json', }, body: formData, }); if (uploadRes.ok) { const immichData = await uploadRes.json(); immichAssetId = immichData.id; syncedToImmich = true; // If a specific Immich Album is targeted, add this asset to that album if (immichAssetId && immichAlbumId && immichAlbumId.trim() !== '') { try { const targetAlbumId = immichAlbumId.trim(); let albumRes = await fetch(`${cleanImmichUrl}/api/albums/${targetAlbumId}/assets`, { method: 'PUT', headers: { 'x-api-key': immichApiKey, 'Content-Type': 'application/json', Accept: 'application/json', }, body: JSON.stringify({ ids: [immichAssetId], }), }); if (!albumRes.ok) { // Fallback for Immich API variants albumRes = await fetch(`${cleanImmichUrl}/api/albums/${targetAlbumId}/assets`, { method: 'POST', headers: { 'x-api-key': immichApiKey, 'Content-Type': 'application/json', Accept: 'application/json', }, body: JSON.stringify({ ids: [immichAssetId], }), }); } if (albumRes.ok) { albumSynced = true; } else { console.warn(`Immich album sync responded with ${albumRes.status}`); } } catch (albumErr) { console.warn('Failed to attach asset to Immich album:', albumErr); } } } else { const errText = await uploadRes.text().catch(() => ''); console.warn(`Immich asset upload failed (${uploadRes.status}):`, errText); } } catch (immichErr: any) { console.warn('Immich sync network error:', immichErr?.message || immichErr); } } return { url: localUrl, immichAssetId, syncedToImmich, albumSynced, }; } catch (err: any) { console.error('Error saving uploaded photo:', err); return { url: base64OrBuffer.startsWith('data:') ? base64OrBuffer : '', syncedToImmich: false, error: err?.message, }; } } /** * Fetches list of all albums from Immich instance */ export async function getImmichAlbums(immichUrl: string, immichApiKey: string): Promise { try { const cleanUrl = immichUrl.replace(/\/+$/, ''); const res = await fetch(`${cleanUrl}/api/albums`, { method: 'GET', headers: { 'x-api-key': immichApiKey, Accept: 'application/json', }, }); if (!res.ok) { throw new Error(`Immich returned HTTP ${res.status}`); } const data = await res.json(); if (Array.isArray(data)) { return data.map((a: any) => ({ id: a.id, albumName: a.albumName || a.title || 'Безымянный альбом', assetCount: a.assetCount ?? a.assets?.length ?? 0, description: a.description, })); } return []; } catch (err: any) { console.warn('Failed to fetch Immich albums:', err.message); throw err; } } /** * Creates a dedicated wedding album in Immich */ export async function createImmichAlbum( immichUrl: string, immichApiKey: string, albumName: string, description?: string ): Promise { const cleanUrl = immichUrl.replace(/\/+$/, ''); const res = await fetch(`${cleanUrl}/api/albums`, { method: 'POST', headers: { 'x-api-key': immichApiKey, 'Content-Type': 'application/json', Accept: 'application/json', }, body: JSON.stringify({ albumName, description: description || 'Свадебные фотографии гостей и интерактивных конкурсов Wedding Hub', }), }); if (!res.ok) { const errText = await res.text().catch(() => ''); throw new Error(`Ошибка создания альбома в Immich (${res.status}): ${errText}`); } const data = await res.json(); return { id: data.id, albumName: data.albumName || albumName, description: data.description, }; } /** * Validates connection to Immich */ export async function testImmichConnection(immichUrl: string, immichApiKey: string): Promise<{ success: boolean; message: string; version?: string; albumCount?: number }> { try { const cleanUrl = immichUrl.replace(/\/+$/, ''); // Test auth by fetching albums const res = await fetch(`${cleanUrl}/api/albums`, { method: 'GET', headers: { 'x-api-key': immichApiKey, Accept: 'application/json', }, }); if (res.status === 401 || res.status === 403) { return { success: false, message: 'Неверный API ключ Immich (401/403)' }; } if (!res.ok) { return { success: false, message: `Immich ответил с кодом ошибки ${res.status}` }; } const albums = await res.json(); return { success: true, message: 'Подключение к Immich успешно установлено!', albumCount: Array.isArray(albums) ? albums.length : 0, }; } catch (err: any) { return { success: false, message: `Не удалось связаться с сервером Immich: ${err.message || 'Ошибка сети'}`, }; } }