From 1e44b25a0c6d1c2e99ef75de07685f69a6ff7830 Mon Sep 17 00:00:00 2001 From: micro92 Date: Thu, 2 Apr 2026 20:59:02 -0400 Subject: [PATCH 001/117] Add Accomodation to PDF --- client/src/components/PDF/TripPDF.tsx | 71 +++++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 4 deletions(-) diff --git a/client/src/components/PDF/TripPDF.tsx b/client/src/components/PDF/TripPDF.tsx index c83cc4b..57412d2 100644 --- a/client/src/components/PDF/TripPDF.tsx +++ b/client/src/components/PDF/TripPDF.tsx @@ -2,7 +2,7 @@ import { createElement } from 'react' import { getCategoryIcon } from '../shared/categoryIcons' import { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark } from 'lucide-react' -import { mapsApi } from '../../api/client' +import { accommodationsApi, mapsApi } from '../../api/client' import type { Trip, Day, Place, Category, AssignmentsMap, DayNotesMap } from '../../types' const NOTE_ICON_MAP = { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark } @@ -115,6 +115,8 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor const sorted = [...(days || [])].sort((a, b) => a.day_number - b.day_number) const range = longDateRange(sorted, loc) const coverImg = safeImg(trip?.cover_image) + //retrieve accomodations for the trip to display on the day sections and prefetch their photos if needed + const accomodations = await accommodationsApi.list(trip.id); // Pre-fetch place photos from Google const photoMap = await fetchPlacePhotos(assignments) @@ -223,7 +225,45 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor ${place.notes ? `
${escHtml(place.notes)}
` : ''} ` - }).join('') + }).join('') + + const accomodationsForDay = accomodations.accommodations?.filter(a => + days.some(d => d.id >= a.start_day_id && d.id <= a.end_day_id && d.id === day?.id) + ).sort((a, b) => a.start_day_id - b.start_day_id); + + const accomodationDetails = accomodationsForDay.map(item => { + + const isCheckIn = day.id === item.start_day_id; + const isCheckOut = day.id === item.end_day_id; + const accomoAction = isCheckIn ? '🛎️ '+tr('reservations.meta.checkIn') + : isCheckOut ? '🧳 '+tr('reservations.meta.checkOut') + : '🏨 '+tr('reservations.meta.linkAccommodation') + + const accomoEmoji = isCheckIn ? '🛎️' + : isCheckOut ? '🧳' + : '' + + const accomoTime = isCheckIn ? item.check_in || 'N/A' + : isCheckOut ? item.check_out || 'N/A' + : '' + + return ` +
+
${escHtml(accomoAction)}
+ ${accomoTime ? `
${accomoEmoji} ${accomoTime}
` : ''} + +
🏨 ${escHtml(item.place_name)}
+ ${item.place_address ? `
📌 ${escHtml(item.place_address)}
` : ''} + ${item.notes ? `
📝 ${escHtml(item.notes)}
` : ''} + ${isCheckIn && item.confirmation ? `
🔑 ${escHtml(item.confirmation)}
` : ''} +
+ ` + }).join(''); + + const accomodationsHtml = accomodationDetails ? + `
+
${accomodationDetails}
+
` : ''; return `
@@ -233,8 +273,8 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor ${day.date ? `${shortDate(day.date, loc)}` : ''} ${cost ? `${cost}` : ''}
-
${itemsHtml}
- ` +
${accomodationsHtml}${itemsHtml}
+ ` }).join('') const html = ` @@ -317,6 +357,29 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor .day-cost { font-size: 9px; font-weight: 600; color: rgba(255,255,255,0.65); } .day-body { padding: 12px 28px 6px; } + /* Accomodation info */ + .day-accomodations-overview { font-size: 12px; } + .day-accomodations { display: flex; flex-direction: row; justify-content: space-between; } + .day-accomodations.single { justify-content: center; } + + .day-accomodation { + width: 50%; + margin:10px; + padding:10px; + border:2px solid #e2e8f0; + border-radius: 12px; + justify-content: center; + display: flex; + flex-direction: column; + } + + .day-accomodation-action { + font-size: 18px; + font-weight: 600; + text-align: center; + margin-bottom: 4px; + } + /* ── Place card ────────────────────────────────── */ .place-card { display: flex; align-items: stretch; From 5be2e9b26811013484a81e77797e4acb9790f220 Mon Sep 17 00:00:00 2001 From: Maurice Date: Thu, 2 Apr 2026 17:19:24 +0200 Subject: [PATCH 002/117] add Discord community badge to README --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 572d849..8248ee6 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@

+ Discord License: AGPL v3 Docker Pulls GitHub Stars From 8e9f8784dc67f6f5a795b26fe139dc1e96e8470c Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 02:54:35 +0200 Subject: [PATCH 003/117] refactor(memories): generalize photo providers and decouple from immich --- client/src/api/authUrl.ts | 2 +- client/src/components/Admin/AddonManager.tsx | 133 +++++++-- .../src/components/Memories/MemoriesPanel.tsx | 195 +++++++++--- client/src/pages/SettingsPage.tsx | 279 +++++++++++++----- client/src/pages/TripPlannerPage.tsx | 4 +- client/src/store/addonStore.ts | 16 + server/src/db/migrations.ts | 114 +++++++ server/src/db/schema.ts | 25 ++ server/src/db/seeds.ts | 28 ++ server/src/index.ts | 69 ++++- server/src/routes/admin.ts | 87 +++++- server/src/routes/immich.ts | 168 ++++++----- server/src/routes/memories.ts | 182 ++++++++++++ 13 files changed, 1076 insertions(+), 226 deletions(-) create mode 100644 server/src/routes/memories.ts diff --git a/client/src/api/authUrl.ts b/client/src/api/authUrl.ts index 203ceb3..ed92729 100644 --- a/client/src/api/authUrl.ts +++ b/client/src/api/authUrl.ts @@ -1,4 +1,4 @@ -export async function getAuthUrl(url: string, purpose: 'download' | 'immich'): Promise { +export async function getAuthUrl(url: string, purpose: string): Promise { if (!url) return url try { const resp = await fetch('/api/auth/resource-token', { diff --git a/client/src/components/Admin/AddonManager.tsx b/client/src/components/Admin/AddonManager.tsx index 3050258..b45f9f0 100644 --- a/client/src/components/Admin/AddonManager.tsx +++ b/client/src/components/Admin/AddonManager.tsx @@ -15,7 +15,17 @@ interface Addon { name: string description: string icon: string + type: string enabled: boolean + config?: Record +} + +interface ProviderOption { + key: string + label: string + description: string + enabled: boolean + toggle: () => Promise } interface AddonIconProps { @@ -34,7 +44,7 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking } const dark = dm === true || dm === 'dark' || (dm === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) const toast = useToast() const refreshGlobalAddons = useAddonStore(s => s.loadAddons) - const [addons, setAddons] = useState([]) + const [addons, setAddons] = useState([]) const [loading, setLoading] = useState(true) useEffect(() => { @@ -53,7 +63,7 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking } } } - const handleToggle = async (addon) => { + const handleToggle = async (addon: Addon) => { const newEnabled = !addon.enabled // Optimistic update setAddons(prev => prev.map(a => a.id === addon.id ? { ...a, enabled: newEnabled } : a)) @@ -68,9 +78,44 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking } } } + const isPhotoProviderAddon = (addon: Addon) => { + return addon.type === 'photo_provider' + } + + const isPhotosAddon = (addon: Addon) => { + const haystack = `${addon.id} ${addon.name} ${addon.description}`.toLowerCase() + return addon.type === 'trip' && (addon.icon === 'Image' || haystack.includes('photo') || haystack.includes('memories')) + } + + const handleTogglePhotoProvider = async (providerAddon: Addon) => { + const enableProvider = !providerAddon.enabled + const prev = addons + + setAddons(current => current.map(a => a.id === providerAddon.id ? { ...a, enabled: enableProvider } : a)) + + try { + await adminApi.updateAddon(providerAddon.id, { enabled: enableProvider }) + refreshGlobalAddons() + toast.success(t('admin.addons.toast.updated')) + } catch { + setAddons(prev) + toast.error(t('admin.addons.toast.error')) + } + } + const tripAddons = addons.filter(a => a.type === 'trip') const globalAddons = addons.filter(a => a.type === 'global') + const photoProviderAddons = addons.filter(isPhotoProviderAddon) const integrationAddons = addons.filter(a => a.type === 'integration') + const photosAddon = tripAddons.find(isPhotosAddon) + const providerOptions: ProviderOption[] = photoProviderAddons.map((provider) => ({ + key: provider.id, + label: provider.name, + description: provider.description, + enabled: provider.enabled, + toggle: () => handleTogglePhotoProvider(provider), + })) + const photosDerivedEnabled = providerOptions.some(p => p.enabled) if (loading) { return ( @@ -108,7 +153,42 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking } {tripAddons.map(addon => (

- + + {photosAddon && addon.id === photosAddon.id && providerOptions.length > 0 && ( +
+
+ {providerOptions.map(provider => ( +
+
+
{provider.label}
+
{provider.description}
+
+
+ + {provider.enabled ? t('admin.addons.enabled') : t('admin.addons.disabled')} + + +
+
+ ))} +
+
+ )} {addon.id === 'packing' && addon.enabled && onToggleBagTracking && (
@@ -171,8 +251,10 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking } interface AddonRowProps { addon: Addon - onToggle: (addonId: string) => void + onToggle: (addon: Addon) => void t: (key: string) => string + statusOverride?: boolean + hideToggle?: boolean } function getAddonLabel(t: (key: string) => string, addon: Addon): { name: string; description: string } { @@ -187,9 +269,12 @@ function getAddonLabel(t: (key: string) => string, addon: Addon): { name: string } } -function AddonRow({ addon, onToggle, t }: AddonRowProps) { +function AddonRow({ addon, onToggle, t, nameOverride, descriptionOverride, statusOverride, hideToggle }: AddonRowProps & { nameOverride?: string; descriptionOverride?: string }) { const isComingSoon = false const label = getAddonLabel(t, addon) + const displayName = nameOverride || label.name + const displayDescription = descriptionOverride || label.description + const enabledState = statusOverride ?? addon.enabled return (
{/* Icon */} @@ -200,7 +285,7 @@ function AddonRow({ addon, onToggle, t }: AddonRowProps) { {/* Info */}
- {label.name} + {displayName} {isComingSoon && ( Coming Soon @@ -210,28 +295,30 @@ function AddonRow({ addon, onToggle, t }: AddonRowProps) { {addon.type === 'global' ? t('admin.addons.type.global') : addon.type === 'integration' ? t('admin.addons.type.integration') : t('admin.addons.type.trip')}
-

{label.description}

+

{displayDescription}

{/* Toggle */}
- - {isComingSoon ? t('admin.addons.disabled') : addon.enabled ? t('admin.addons.enabled') : t('admin.addons.disabled')} + + {isComingSoon ? t('admin.addons.disabled') : enabledState ? t('admin.addons.enabled') : t('admin.addons.disabled')} - + {!hideToggle && ( + + )}
) diff --git a/client/src/components/Memories/MemoriesPanel.tsx b/client/src/components/Memories/MemoriesPanel.tsx index 9dd1ed4..b288487 100644 --- a/client/src/components/Memories/MemoriesPanel.tsx +++ b/client/src/components/Memories/MemoriesPanel.tsx @@ -1,27 +1,36 @@ import { useState, useEffect, useCallback } from 'react' import { Camera, Plus, Share2, EyeOff, Eye, X, Check, Search, ArrowUpDown, MapPin, Filter, Link2, RefreshCw, Unlink, FolderOpen } from 'lucide-react' -import apiClient from '../../api/client' +import apiClient, { addonsApi } from '../../api/client' import { useAuthStore } from '../../store/authStore' import { useTranslation } from '../../i18n' import { getAuthUrl } from '../../api/authUrl' import { useToast } from '../shared/Toast' -function ImmichImg({ baseUrl, style, loading }: { baseUrl: string; style?: React.CSSProperties; loading?: 'lazy' | 'eager' }) { +interface PhotoProvider { + id: string + name: string + icon?: string + config?: Record +} + +function ProviderImg({ baseUrl, provider, style, loading }: { baseUrl: string; provider: string; style?: React.CSSProperties; loading?: 'lazy' | 'eager' }) { const [src, setSrc] = useState('') useEffect(() => { - getAuthUrl(baseUrl, 'immich').then(setSrc) - }, [baseUrl]) + getAuthUrl(baseUrl, provider).then(setSrc).catch(() => {}) + }, [baseUrl, provider]) return src ? : null } // ── Types ─────────────────────────────────────────────────────────────────── interface TripPhoto { - immich_asset_id: string + asset_id: string + provider: string user_id: number username: string shared: number added_at: string + city?: string | null } interface ImmichAsset { @@ -45,6 +54,8 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const currentUser = useAuthStore(s => s.user) const [connected, setConnected] = useState(false) + const [availableProviders, setAvailableProviders] = useState([]) + const [selectedProvider, setSelectedProvider] = useState('') const [loading, setLoading] = useState(true) // Trip photos (saved selections) @@ -67,49 +78,61 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const [showAlbumPicker, setShowAlbumPicker] = useState(false) const [albums, setAlbums] = useState<{ id: string; albumName: string; assetCount: number }[]>([]) const [albumsLoading, setAlbumsLoading] = useState(false) - const [albumLinks, setAlbumLinks] = useState<{ id: number; immich_album_id: string; album_name: string; user_id: number; username: string; sync_enabled: number; last_synced_at: string | null }[]>([]) + const [albumLinks, setAlbumLinks] = useState<{ id: number; provider: string; album_id: string; album_name: string; user_id: number; username: string; sync_enabled: number; last_synced_at: string | null }[]>([]) const [syncing, setSyncing] = useState(null) + const pickerIntegrationBase = selectedProvider ? `/integrations/${selectedProvider}` : '' const loadAlbumLinks = async () => { try { - const res = await apiClient.get(`/integrations/immich/trips/${tripId}/album-links`) + const res = await apiClient.get(`/integrations/memories/trips/${tripId}/album-links`) setAlbumLinks(res.data.links || []) } catch { setAlbumLinks([]) } } - const openAlbumPicker = async () => { - setShowAlbumPicker(true) + const loadAlbums = async (provider: string = selectedProvider) => { + if (!provider) return setAlbumsLoading(true) try { - const res = await apiClient.get('/integrations/immich/albums') + const res = await apiClient.get(`/integrations/${provider}/albums`) setAlbums(res.data.albums || []) - } catch { setAlbums([]); toast.error(t('memories.error.loadAlbums')) } - finally { setAlbumsLoading(false) } + } catch { + setAlbums([]) + toast.error(t('memories.error.loadAlbums')) + } finally { + setAlbumsLoading(false) + } + } + + const openAlbumPicker = async () => { + setShowAlbumPicker(true) + await loadAlbums(selectedProvider) } const linkAlbum = async (albumId: string, albumName: string) => { try { - await apiClient.post(`/integrations/immich/trips/${tripId}/album-links`, { album_id: albumId, album_name: albumName }) + await apiClient.post(`${pickerIntegrationBase}/trips/${tripId}/album-links`, { album_id: albumId, album_name: albumName }) setShowAlbumPicker(false) await loadAlbumLinks() // Auto-sync after linking - const linksRes = await apiClient.get(`/integrations/immich/trips/${tripId}/album-links`) - const newLink = (linksRes.data.links || []).find((l: any) => l.immich_album_id === albumId) + const linksRes = await apiClient.get(`/integrations/memories/trips/${tripId}/album-links`) + const newLink = (linksRes.data.links || []).find((l: any) => l.album_id === albumId && l.provider === selectedProvider) if (newLink) await syncAlbum(newLink.id) } catch { toast.error(t('memories.error.linkAlbum')) } } const unlinkAlbum = async (linkId: number) => { try { - await apiClient.delete(`/integrations/immich/trips/${tripId}/album-links/${linkId}`) + await apiClient.delete(`/integrations/memories/trips/${tripId}/album-links/${linkId}`) loadAlbumLinks() } catch { toast.error(t('memories.error.unlinkAlbum')) } } - const syncAlbum = async (linkId: number) => { + const syncAlbum = async (linkId: number, provider?: string) => { + const targetProvider = provider || selectedProvider + if (!targetProvider) return setSyncing(linkId) try { - await apiClient.post(`/integrations/immich/trips/${tripId}/album-links/${linkId}/sync`) + await apiClient.post(`/integrations/${targetProvider}/trips/${tripId}/album-links/${linkId}/sync`) await loadAlbumLinks() await loadPhotos() } catch { toast.error(t('memories.error.syncAlbum')) } @@ -138,7 +161,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const loadPhotos = async () => { try { - const photosRes = await apiClient.get(`/integrations/immich/trips/${tripId}/photos`) + const photosRes = await apiClient.get(`/integrations/memories/trips/${tripId}/photos`) setTripPhotos(photosRes.data.photos || []) } catch { setTripPhotos([]) @@ -148,9 +171,35 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const loadInitial = async () => { setLoading(true) try { - const statusRes = await apiClient.get('/integrations/immich/status') - setConnected(statusRes.data.connected) + const addonsRes = await addonsApi.enabled().catch(() => ({ addons: [] as any[] })) + const enabledAddons = addonsRes?.addons || [] + const photoProviders = enabledAddons.filter((a: any) => a.type === 'photo_provider' && a.enabled) + + // Test connection status for each enabled provider + const statusResults = await Promise.all( + photoProviders.map(async (provider: any) => { + const statusUrl = (provider.config as Record)?.status_get as string + if (!statusUrl) return { provider, connected: false } + try { + const res = await apiClient.get(statusUrl) + return { provider, connected: !!res.data?.connected } + } catch { + return { provider, connected: false } + } + }) + ) + + const connectedProviders = statusResults + .filter(r => r.connected) + .map(r => ({ id: r.provider.id, name: r.provider.name, icon: r.provider.icon, config: r.provider.config })) + + setAvailableProviders(connectedProviders) + setConnected(connectedProviders.length > 0) + if (connectedProviders.length > 0 && !selectedProvider) { + setSelectedProvider(connectedProviders[0].id) + } } catch { + setAvailableProviders([]) setConnected(false) } await loadPhotos() @@ -170,10 +219,26 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa await loadPickerPhotos(!!(startDate && endDate)) } + useEffect(() => { + if (showPicker) { + loadPickerPhotos(pickerDateFilter) + } + }, [selectedProvider]) + + useEffect(() => { + loadAlbumLinks() + }, [tripId]) + + useEffect(() => { + if (showAlbumPicker) { + loadAlbums(selectedProvider) + } + }, [showAlbumPicker, selectedProvider, tripId]) + const loadPickerPhotos = async (useDate: boolean) => { setPickerLoading(true) try { - const res = await apiClient.post('/integrations/immich/search', { + const res = await apiClient.post(`${pickerIntegrationBase}/search`, { from: useDate && startDate ? startDate : undefined, to: useDate && endDate ? endDate : undefined, }) @@ -203,7 +268,8 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const executeAddPhotos = async () => { setShowConfirmShare(false) try { - await apiClient.post(`/integrations/immich/trips/${tripId}/photos`, { + await apiClient.post(`/integrations/memories/trips/${tripId}/photos`, { + provider: selectedProvider, asset_ids: [...selectedIds], shared: true, }) @@ -214,28 +280,37 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa // ── Remove photo ────────────────────────────────────────────────────────── - const removePhoto = async (assetId: string) => { + const removePhoto = async (photo: TripPhoto) => { try { - await apiClient.delete(`/integrations/immich/trips/${tripId}/photos/${assetId}`) - setTripPhotos(prev => prev.filter(p => p.immich_asset_id !== assetId)) + await apiClient.delete(`/integrations/memories/trips/${tripId}/photos`, { + data: { + asset_id: photo.asset_id, + provider: photo.provider, + }, + }) + setTripPhotos(prev => prev.filter(p => !(p.provider === photo.provider && p.asset_id === photo.asset_id))) } catch { toast.error(t('memories.error.removePhoto')) } } // ── Toggle sharing ──────────────────────────────────────────────────────── - const toggleSharing = async (assetId: string, shared: boolean) => { + const toggleSharing = async (photo: TripPhoto, shared: boolean) => { try { - await apiClient.put(`/integrations/immich/trips/${tripId}/photos/${assetId}/sharing`, { shared }) + await apiClient.put(`/integrations/memories/trips/${tripId}/photos/sharing`, { + shared, + asset_id: photo.asset_id, + provider: photo.provider, + }) setTripPhotos(prev => prev.map(p => - p.immich_asset_id === assetId ? { ...p, shared: shared ? 1 : 0 } : p + p.provider === photo.provider && p.asset_id === photo.asset_id ? { ...p, shared: shared ? 1 : 0 } : p )) } catch { toast.error(t('memories.error.toggleSharing')) } } // ── Helpers ─────────────────────────────────────────────────────────────── - const thumbnailBaseUrl = (assetId: string, userId: number) => - `/api/integrations/immich/assets/${assetId}/thumbnail?userId=${userId}` + const thumbnailBaseUrl = (photo: TripPhoto) => + `/api/integrations/${photo.provider}/assets/${photo.asset_id}/thumbnail?userId=${photo.user_id}` const ownPhotos = tripPhotos.filter(p => p.user_id === currentUser?.id) const othersPhotos = tripPhotos.filter(p => p.user_id !== currentUser?.id && p.shared) @@ -286,10 +361,40 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa // ── Photo Picker Modal ──────────────────────────────────────────────────── + const ProviderTabs = () => { + if (availableProviders.length < 2) return null + return ( +
+ {availableProviders.map(provider => ( + + ))} +
+ ) + } + // ── Album Picker Modal ────────────────────────────────────────────────── if (showAlbumPicker) { - const linkedIds = new Set(albumLinks.map(l => l.immich_album_id)) + const linkedIds = new Set(albumLinks.map(l => l.album_id)) return (
@@ -297,6 +402,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa

{t('memories.selectAlbum')}

+ @@ -630,18 +741,18 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa {allVisible.map(photo => { const isOwn = photo.user_id === currentUser?.id return ( -
{ - setLightboxId(photo.immich_asset_id); setLightboxUserId(photo.user_id); setLightboxInfo(null) + setLightboxId(photo.asset_id); setLightboxUserId(photo.user_id); setLightboxInfo(null) setLightboxOriginalSrc('') - getAuthUrl(`/api/integrations/immich/assets/${photo.immich_asset_id}/original?userId=${photo.user_id}`, 'immich').then(setLightboxOriginalSrc) + getAuthUrl(`/api/integrations/${photo.provider}/assets/${photo.asset_id}/original?userId=${photo.user_id}`, photo.provider).then(setLightboxOriginalSrc).catch(() => {}) setLightboxInfoLoading(true) - apiClient.get(`/integrations/immich/assets/${photo.immich_asset_id}/info?userId=${photo.user_id}`) + apiClient.get(`/integrations/${photo.provider}/assets/${photo.asset_id}/info?userId=${photo.user_id}`) .then(r => setLightboxInfo(r.data)).catch(() => {}).finally(() => setLightboxInfoLoading(false)) }}> - {/* Other user's avatar */} @@ -672,7 +783,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa {isOwn && (
- - + + {connected && ( + + + {t('memories.connected')} + + )} +
+
+ + ) + } + // Map settings const [mapTileUrl, setMapTileUrl] = useState(settings.map_tile_url || '') const [defaultLat, setDefaultLat] = useState(settings.default_lat || 48.8566) @@ -673,45 +832,7 @@ export default function SettingsPage(): React.ReactElement { - {/* Immich — only when Memories addon is enabled */} - {memoriesEnabled && ( -
-
-
- - { setImmichUrl(e.target.value); setImmichTestPassed(false) }} - placeholder="https://immich.example.com" - className="w-full px-3 py-2.5 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-300" /> -
-
- - { setImmichApiKey(e.target.value); setImmichTestPassed(false) }} - placeholder={immichConnected ? '••••••••' : 'API Key'} - className="w-full px-3 py-2.5 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-300" /> -
-
- - - {immichConnected && ( - - - {t('memories.connected')} - - )} -
-
-
- )} + {activePhotoProviders.map(provider => renderPhotoProviderSection(provider as PhotoProviderAddon))} {/* MCP Configuration — only when MCP addon is enabled */} {mcpEnabled &&
diff --git a/client/src/pages/TripPlannerPage.tsx b/client/src/pages/TripPlannerPage.tsx index 47918bd..256714a 100644 --- a/client/src/pages/TripPlannerPage.tsx +++ b/client/src/pages/TripPlannerPage.tsx @@ -78,7 +78,9 @@ export default function TripPlannerPage(): React.ReactElement | null { addonsApi.enabled().then(data => { const map = {} data.addons.forEach(a => { map[a.id] = true }) - setEnabledAddons({ packing: !!map.packing, budget: !!map.budget, documents: !!map.documents, collab: !!map.collab, memories: !!map.memories }) + // Check if any photo provider is enabled (for memories tab to show) + const hasPhotoProviders = data.addons.some(a => a.type === 'photo_provider' && a.enabled) + setEnabledAddons({ packing: !!map.packing, budget: !!map.budget, documents: !!map.documents, collab: !!map.collab, memories: !!map.memories || hasPhotoProviders }) }).catch(() => {}) authApi.getAppConfig().then(config => { if (config.allowed_file_types) setAllowedFileTypes(config.allowed_file_types) diff --git a/client/src/store/addonStore.ts b/client/src/store/addonStore.ts index d0fce97..8ef6798 100644 --- a/client/src/store/addonStore.ts +++ b/client/src/store/addonStore.ts @@ -4,9 +4,22 @@ import { addonsApi } from '../api/client' interface Addon { id: string name: string + description?: string type: string icon: string enabled: boolean + config?: Record + fields?: Array<{ + key: string + label: string + input_type: string + placeholder?: string | null + required: boolean + secret: boolean + settings_key?: string | null + payload_key?: string | null + sort_order: number + }> } interface AddonState { @@ -30,6 +43,9 @@ export const useAddonStore = create((set, get) => ({ }, isEnabled: (id: string) => { + if (id === 'memories') { + return get().addons.some(a => a.type === 'photo_provider' && a.enabled) + } return get().addons.some(a => a.id === id && a.enabled) }, })) diff --git a/server/src/db/migrations.ts b/server/src/db/migrations.ts index c2f1271..8e01979 100644 --- a/server/src/db/migrations.ts +++ b/server/src/db/migrations.ts @@ -518,6 +518,120 @@ function runMigrations(db: Database.Database): void { CREATE INDEX IF NOT EXISTS idx_notifications_recipient_created ON notifications(recipient_id, created_at DESC); `); }, + () => { + // Normalize trip_photos to provider-based schema used by current routes + const tripPhotosExists = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'trip_photos'").get(); + if (!tripPhotosExists) { + db.exec(` + CREATE TABLE trip_photos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + asset_id TEXT NOT NULL, + provider TEXT NOT NULL DEFAULT 'immich', + shared INTEGER NOT NULL DEFAULT 1, + added_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(trip_id, user_id, asset_id, provider) + ); + CREATE INDEX IF NOT EXISTS idx_trip_photos_trip ON trip_photos(trip_id); + `); + } else { + const columns = db.prepare("PRAGMA table_info('trip_photos')").all() as Array<{ name: string }>; + const names = new Set(columns.map(c => c.name)); + const assetSource = names.has('asset_id') ? 'asset_id' : (names.has('immich_asset_id') ? 'immich_asset_id' : null); + if (assetSource) { + const providerExpr = names.has('provider') + ? "CASE WHEN provider IS NULL OR provider = '' THEN 'immich' ELSE provider END" + : "'immich'"; + const sharedExpr = names.has('shared') ? 'COALESCE(shared, 1)' : '1'; + const addedAtExpr = names.has('added_at') ? 'COALESCE(added_at, CURRENT_TIMESTAMP)' : 'CURRENT_TIMESTAMP'; + + db.exec(` + CREATE TABLE trip_photos_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + asset_id TEXT NOT NULL, + provider TEXT NOT NULL DEFAULT 'immich', + shared INTEGER NOT NULL DEFAULT 1, + added_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(trip_id, user_id, asset_id, provider) + ); + `); + + db.exec(` + INSERT OR IGNORE INTO trip_photos_new (trip_id, user_id, asset_id, provider, shared, added_at) + SELECT trip_id, user_id, ${assetSource}, ${providerExpr}, ${sharedExpr}, ${addedAtExpr} + FROM trip_photos + WHERE ${assetSource} IS NOT NULL AND TRIM(${assetSource}) != '' + `); + + db.exec('DROP TABLE trip_photos'); + db.exec('ALTER TABLE trip_photos_new RENAME TO trip_photos'); + db.exec('CREATE INDEX IF NOT EXISTS idx_trip_photos_trip ON trip_photos(trip_id)'); + } + } + }, + () => { + // Normalize trip_album_links to provider + album_id schema used by current routes + const linksExists = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'trip_album_links'").get(); + if (!linksExists) { + db.exec(` + CREATE TABLE trip_album_links ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + provider TEXT NOT NULL, + album_id TEXT NOT NULL, + album_name TEXT NOT NULL DEFAULT '', + sync_enabled INTEGER NOT NULL DEFAULT 1, + last_synced_at DATETIME, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(trip_id, user_id, provider, album_id) + ); + CREATE INDEX IF NOT EXISTS idx_trip_album_links_trip ON trip_album_links(trip_id); + `); + } else { + const columns = db.prepare("PRAGMA table_info('trip_album_links')").all() as Array<{ name: string }>; + const names = new Set(columns.map(c => c.name)); + const albumIdSource = names.has('album_id') ? 'album_id' : (names.has('immich_album_id') ? 'immich_album_id' : null); + if (albumIdSource) { + const providerExpr = names.has('provider') + ? "CASE WHEN provider IS NULL OR provider = '' THEN 'immich' ELSE provider END" + : "'immich'"; + const albumNameExpr = names.has('album_name') ? "COALESCE(album_name, '')" : "''"; + const syncEnabledExpr = names.has('sync_enabled') ? 'COALESCE(sync_enabled, 1)' : '1'; + const lastSyncedExpr = names.has('last_synced_at') ? 'last_synced_at' : 'NULL'; + const createdAtExpr = names.has('created_at') ? 'COALESCE(created_at, CURRENT_TIMESTAMP)' : 'CURRENT_TIMESTAMP'; + + db.exec(` + CREATE TABLE trip_album_links_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + provider TEXT NOT NULL, + album_id TEXT NOT NULL, + album_name TEXT NOT NULL DEFAULT '', + sync_enabled INTEGER NOT NULL DEFAULT 1, + last_synced_at DATETIME, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(trip_id, user_id, provider, album_id) + ); + `); + + db.exec(` + INSERT OR IGNORE INTO trip_album_links_new (trip_id, user_id, provider, album_id, album_name, sync_enabled, last_synced_at, created_at) + SELECT trip_id, user_id, ${providerExpr}, ${albumIdSource}, ${albumNameExpr}, ${syncEnabledExpr}, ${lastSyncedExpr}, ${createdAtExpr} + FROM trip_album_links + WHERE ${albumIdSource} IS NOT NULL AND TRIM(${albumIdSource}) != '' + `); + + db.exec('DROP TABLE trip_album_links'); + db.exec('ALTER TABLE trip_album_links_new RENAME TO trip_album_links'); + db.exec('CREATE INDEX IF NOT EXISTS idx_trip_album_links_trip ON trip_album_links(trip_id)'); + } + } + }, ]; if (currentVersion < migrations.length) { diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index 8506253..8fe5739 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -222,6 +222,31 @@ function createTables(db: Database.Database): void { sort_order INTEGER DEFAULT 0 ); + CREATE TABLE IF NOT EXISTS photo_providers ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + description TEXT, + icon TEXT DEFAULT 'Image', + enabled INTEGER DEFAULT 0, + config TEXT DEFAULT '{}', + sort_order INTEGER DEFAULT 0 + ); + + CREATE TABLE IF NOT EXISTS photo_provider_fields ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + provider_id TEXT NOT NULL REFERENCES photo_providers(id) ON DELETE CASCADE, + field_key TEXT NOT NULL, + label TEXT NOT NULL, + input_type TEXT NOT NULL DEFAULT 'text', + placeholder TEXT, + required INTEGER DEFAULT 0, + secret INTEGER DEFAULT 0, + settings_key TEXT, + payload_key TEXT, + sort_order INTEGER DEFAULT 0, + UNIQUE(provider_id, field_key) + ); + -- Vacay addon tables CREATE TABLE IF NOT EXISTS vacay_plans ( id INTEGER PRIMARY KEY AUTOINCREMENT, diff --git a/server/src/db/seeds.ts b/server/src/db/seeds.ts index 8e0d9c6..f875794 100644 --- a/server/src/db/seeds.ts +++ b/server/src/db/seeds.ts @@ -92,6 +92,34 @@ function seedAddons(db: Database.Database): void { ]; const insertAddon = db.prepare('INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)'); for (const a of defaultAddons) insertAddon.run(a.id, a.name, a.description, a.type, a.icon, a.enabled, a.sort_order); + + const providerRows = [ + { + id: 'immich', + name: 'Immich', + description: 'Immich photo provider', + icon: 'Image', + enabled: 0, + sort_order: 0, + config: JSON.stringify({ + settings_get: '/integrations/immich/settings', + settings_put: '/integrations/immich/settings', + status_get: '/integrations/immich/status', + test_post: '/integrations/immich/test', + }), + }, + ]; + const insertProvider = db.prepare('INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, config, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)'); + for (const p of providerRows) insertProvider.run(p.id, p.name, p.description, p.icon, p.enabled, p.config, p.sort_order); + + const providerFields = [ + { provider_id: 'immich', field_key: 'immich_url', label: 'Immich URL', input_type: 'url', placeholder: 'https://immich.example.com', required: 1, secret: 0, settings_key: 'immich_url', payload_key: 'immich_url', sort_order: 0 }, + { provider_id: 'immich', field_key: 'immich_api_key', label: 'API Key', input_type: 'password', placeholder: 'API Key', required: 1, secret: 1, settings_key: null, payload_key: 'immich_api_key', sort_order: 1 }, + ]; + const insertProviderField = db.prepare('INSERT OR IGNORE INTO photo_provider_fields (provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); + for (const f of providerFields) { + insertProviderField.run(f.provider_id, f.field_key, f.label, f.input_type, f.placeholder, f.required, f.secret, f.settings_key, f.payload_key, f.sort_order); + } console.log('Default addons seeded'); } catch (err: unknown) { console.error('Error seeding addons:', err instanceof Error ? err.message : err); diff --git a/server/src/index.ts b/server/src/index.ts index 5508542..533d92c 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -207,8 +207,71 @@ import { authenticate as addonAuth } from './middleware/auth'; import {db as addonDb} from './db/database'; import { Addon } from './types'; app.get('/api/addons', addonAuth, (req: Request, res: Response) => { - const addons = addonDb.prepare('SELECT id, name, type, icon, enabled FROM addons WHERE enabled = 1 ORDER BY sort_order').all() as Pick[]; - res.json({ addons: addons.map(a => ({ ...a, enabled: !!a.enabled })) }); + const addons = addonDb.prepare('SELECT id, name, type, icon, enabled, config, sort_order FROM addons WHERE enabled = 1 ORDER BY sort_order').all() as Array & { sort_order: number }>; + const photoProviders = addonDb.prepare(` + SELECT id, name, description, icon, enabled, config, sort_order + FROM photo_providers + WHERE enabled = 1 + ORDER BY sort_order + `).all() as Array<{ id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number }>; + const providerIds = photoProviders.map(p => p.id); + const providerFields = providerIds.length > 0 + ? addonDb.prepare(` + SELECT provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order + FROM photo_provider_fields + WHERE provider_id IN (${providerIds.map(() => '?').join(',')}) + ORDER BY sort_order, id + `).all(...providerIds) as Array<{ + provider_id: string; + field_key: string; + label: string; + input_type: string; + placeholder?: string | null; + required: number; + secret: number; + settings_key?: string | null; + payload_key?: string | null; + sort_order: number; + }> + : []; + const fieldsByProvider = new Map(); + for (const field of providerFields) { + const arr = fieldsByProvider.get(field.provider_id) || []; + arr.push(field); + fieldsByProvider.set(field.provider_id, arr); + } + + const combined = [ + ...addons, + ...photoProviders.map(p => ({ + id: p.id, + name: p.name, + type: 'photo_provider', + icon: p.icon, + enabled: p.enabled, + config: p.config, + fields: (fieldsByProvider.get(p.id) || []).map(f => ({ + key: f.field_key, + label: f.label, + input_type: f.input_type, + placeholder: f.placeholder || '', + required: !!f.required, + secret: !!f.secret, + settings_key: f.settings_key || null, + payload_key: f.payload_key || null, + sort_order: f.sort_order, + })), + sort_order: p.sort_order, + })), + ].sort((a, b) => a.sort_order - b.sort_order || a.id.localeCompare(b.id)); + + res.json({ + addons: combined.map(a => ({ + ...a, + enabled: !!a.enabled, + config: JSON.parse(a.config || '{}'), + })), + }); }); // Addon routes @@ -218,6 +281,8 @@ import atlasRoutes from './routes/atlas'; app.use('/api/addons/atlas', atlasRoutes); import immichRoutes from './routes/immich'; app.use('/api/integrations/immich', immichRoutes); +import memoriesRoutes from './routes/memories'; +app.use('/api/integrations/memories', memoriesRoutes); app.use('/api/maps', mapsRoutes); app.use('/api/weather', weatherRoutes); diff --git a/server/src/routes/admin.ts b/server/src/routes/admin.ts index 56a9136..8770f79 100644 --- a/server/src/routes/admin.ts +++ b/server/src/routes/admin.ts @@ -264,12 +264,91 @@ router.delete('/packing-templates/:templateId/items/:itemId', (req: Request, res // ── Addons ───────────────────────────────────────────────────────────────── router.get('/addons', (_req: Request, res: Response) => { - res.json({ addons: svc.listAddons() }); + const addons = db.prepare('SELECT * FROM addons ORDER BY sort_order, id').all() as Addon[]; + const providers = db.prepare(` + SELECT id, name, description, icon, enabled, config, sort_order + FROM photo_providers + ORDER BY sort_order, id + `).all() as Array<{ id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number }>; + const fields = db.prepare(` + SELECT provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order + FROM photo_provider_fields + ORDER BY sort_order, id + `).all() as Array<{ + provider_id: string; + field_key: string; + label: string; + input_type: string; + placeholder?: string | null; + required: number; + secret: number; + settings_key?: string | null; + payload_key?: string | null; + sort_order: number; + }>; + const fieldsByProvider = new Map(); + for (const field of fields) { + const arr = fieldsByProvider.get(field.provider_id) || []; + arr.push(field); + fieldsByProvider.set(field.provider_id, arr); + } + + res.json({ + addons: [ + ...addons.map(a => ({ ...a, enabled: !!a.enabled, config: JSON.parse(a.config || '{}') })), + ...providers.map(p => ({ + id: p.id, + name: p.name, + description: p.description, + type: 'photo_provider', + icon: p.icon, + enabled: !!p.enabled, + config: JSON.parse(p.config || '{}'), + fields: (fieldsByProvider.get(p.id) || []).map(f => ({ + key: f.field_key, + label: f.label, + input_type: f.input_type, + placeholder: f.placeholder || '', + required: !!f.required, + secret: !!f.secret, + settings_key: f.settings_key || null, + payload_key: f.payload_key || null, + sort_order: f.sort_order, + })), + sort_order: p.sort_order, + })), + ], + }); }); router.put('/addons/:id', (req: Request, res: Response) => { - const result = svc.updateAddon(req.params.id, req.body); - if ('error' in result) return res.status(result.status!).json({ error: result.error }); + const addon = db.prepare('SELECT * FROM addons WHERE id = ?').get(req.params.id) as Addon | undefined; + const provider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(req.params.id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number } | undefined; + if (!addon && !provider) return res.status(404).json({ error: 'Addon not found' }); + const { enabled, config } = req.body; + if (addon) { + if (enabled !== undefined) db.prepare('UPDATE addons SET enabled = ? WHERE id = ?').run(enabled ? 1 : 0, req.params.id); + if (config !== undefined) db.prepare('UPDATE addons SET config = ? WHERE id = ?').run(JSON.stringify(config), req.params.id); + } else { + if (enabled !== undefined) db.prepare('UPDATE photo_providers SET enabled = ? WHERE id = ?').run(enabled ? 1 : 0, req.params.id); + if (config !== undefined) db.prepare('UPDATE photo_providers SET config = ? WHERE id = ?').run(JSON.stringify(config), req.params.id); + } + const updatedAddon = db.prepare('SELECT * FROM addons WHERE id = ?').get(req.params.id) as Addon | undefined; + const updatedProvider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(req.params.id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number } | undefined; + const updated = updatedAddon + ? { ...updatedAddon, enabled: !!updatedAddon.enabled, config: JSON.parse(updatedAddon.config || '{}') } + : updatedProvider + ? { + id: updatedProvider.id, + name: updatedProvider.name, + description: updatedProvider.description, + type: 'photo_provider', + icon: updatedProvider.icon, + enabled: !!updatedProvider.enabled, + config: JSON.parse(updatedProvider.config || '{}'), + sort_order: updatedProvider.sort_order, + } + : null; const authReq = req as AuthRequest; writeAudit({ userId: authReq.user.id, @@ -278,7 +357,7 @@ router.put('/addons/:id', (req: Request, res: Response) => { ip: getClientIp(req), details: result.auditDetails, }); - res.json({ addon: result.addon }); + res.json({ addon: updated }); }); // ── MCP Tokens ───────────────────────────────────────────────────────────── diff --git a/server/src/routes/immich.ts b/server/src/routes/immich.ts index 198b6e8..7ed3dd4 100644 --- a/server/src/routes/immich.ts +++ b/server/src/routes/immich.ts @@ -62,13 +62,41 @@ router.put('/settings', authenticate, async (req: Request, res: Response) => { router.get('/status', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - res.json(await getConnectionStatus(authReq.user.id)); + const creds = getImmichCredentials(authReq.user.id); + if (!creds) { + return res.json({ connected: false, error: 'Not configured' }); + } + try { + const resp = await fetch(`${creds.immich_url}/api/users/me`, { + headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, + signal: AbortSignal.timeout(10000), + }); + if (!resp.ok) return res.json({ connected: false, error: `HTTP ${resp.status}` }); + const data = await resp.json() as { name?: string; email?: string }; + res.json({ connected: true, user: { name: data.name, email: data.email } }); + } catch (err: unknown) { + res.json({ connected: false, error: err instanceof Error ? err.message : 'Connection failed' }); + } }); +// Test connection with saved credentials router.post('/test', authenticate, async (req: Request, res: Response) => { - const { immich_url, immich_api_key } = req.body; - if (!immich_url || !immich_api_key) return res.json({ connected: false, error: 'URL and API key required' }); - res.json(await testConnection(immich_url, immich_api_key)); + const authReq = req as AuthRequest; + const creds = getImmichCredentials(authReq.user.id); + if (!creds) return res.json({ connected: false, error: 'No credentials configured' }); + const ssrf = await checkSsrf(creds.immich_url); + if (!ssrf.allowed) return res.json({ connected: false, error: ssrf.error ?? 'Invalid Immich URL' }); + try { + const resp = await fetch(`${creds.immich_url}/api/users/me`, { + headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, + signal: AbortSignal.timeout(10000), + }); + if (!resp.ok) return res.json({ connected: false, error: `HTTP ${resp.status}` }); + const data = await resp.json() as { name?: string; email?: string }; + res.json({ connected: true, user: { name: data.name, email: data.email } }); + } catch (err: unknown) { + res.json({ connected: false, error: err instanceof Error ? err.message : 'Connection failed' }); + } }); // ── Browse Immich Library (for photo picker) ─────────────────────────────── @@ -88,55 +116,6 @@ router.post('/search', authenticate, async (req: Request, res: Response) => { res.json({ assets: result.assets }); }); -// ── Trip Photos (selected by user) ──────────────────────────────────────── - -router.get('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { tripId } = req.params; - if (!canAccessTrip(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); - res.json({ photos: listTripPhotos(tripId, authReq.user.id) }); -}); - -router.post('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { tripId } = req.params; - if (!canAccessTrip(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); - const { asset_ids, shared = true } = req.body; - - if (!Array.isArray(asset_ids) || asset_ids.length === 0) { - return res.status(400).json({ error: 'asset_ids required' }); - } - - const added = addTripPhotos(tripId, authReq.user.id, asset_ids, shared); - res.json({ success: true, added }); - broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); - - // Notify trip members about shared photos - if (shared && added > 0) { - import('../services/notifications').then(({ notifyTripMembers }) => { - const tripInfo = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; - notifyTripMembers(Number(tripId), authReq.user.id, 'photos_shared', { trip: tripInfo?.title || 'Untitled', actor: authReq.user.email, count: String(added) }).catch(() => {}); - }); - } -}); - -router.delete('/trips/:tripId/photos/:assetId', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - if (!canAccessTrip(req.params.tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); - removeTripPhoto(req.params.tripId, authReq.user.id, req.params.assetId); - res.json({ success: true }); - broadcast(req.params.tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); -}); - -router.put('/trips/:tripId/photos/:assetId/sharing', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - if (!canAccessTrip(req.params.tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); - const { shared } = req.body; - togglePhotoSharing(req.params.tripId, authReq.user.id, req.params.assetId, shared); - res.json({ success: true }); - broadcast(req.params.tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); -}); - // ── Asset Details ────────────────────────────────────────────────────────── router.get('/assets/:assetId/info', authenticate, async (req: Request, res: Response) => { @@ -176,15 +155,27 @@ router.get('/assets/:assetId/original', authFromQuery, async (req: Request, res: router.get('/albums', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - const result = await listAlbums(authReq.user.id); - if (result.error) return res.status(result.status!).json({ error: result.error }); - res.json({ albums: result.albums }); -}); + const creds = getImmichCredentials(authReq.user.id); + if (!creds) return res.status(400).json({ error: 'Immich not configured' }); -router.get('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - if (!canAccessTrip(req.params.tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); - res.json({ links: listAlbumLinks(req.params.tripId) }); + try { + const resp = await fetch(`${creds.immich_url}/api/albums`, { + headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, + signal: AbortSignal.timeout(10000), + }); + if (!resp.ok) return res.status(resp.status).json({ error: 'Failed to fetch albums' }); + const albums = (await resp.json() as any[]).map((a: any) => ({ + id: a.id, + albumName: a.albumName, + assetCount: a.assetCount || 0, + startDate: a.startDate, + endDate: a.endDate, + albumThumbnailAssetId: a.albumThumbnailAssetId, + })); + res.json({ albums }); + } catch { + res.status(502).json({ error: 'Could not reach Immich' }); + } }); router.post('/trips/:tripId/album-links', authenticate, async (req: Request, res: Response) => { @@ -193,25 +184,54 @@ router.post('/trips/:tripId/album-links', authenticate, async (req: Request, res if (!canAccessTrip(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); const { album_id, album_name } = req.body; if (!album_id) return res.status(400).json({ error: 'album_id required' }); - const result = createAlbumLink(tripId, authReq.user.id, album_id, album_name); - if (!result.success) return res.status(400).json({ error: result.error }); - res.json({ success: true }); -}); -router.delete('/trips/:tripId/album-links/:linkId', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - deleteAlbumLink(req.params.linkId, req.params.tripId, authReq.user.id); - res.json({ success: true }); + try { + db.prepare( + 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)' + ).run(tripId, authReq.user.id, 'immich', album_id, album_name || ''); + res.json({ success: true }); + } catch (err: any) { + res.status(400).json({ error: 'Album already linked' }); + } }); router.post('/trips/:tripId/album-links/:linkId/sync', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId, linkId } = req.params; - const result = await syncAlbumAssets(tripId, linkId, authReq.user.id); - if (result.error) return res.status(result.status!).json({ error: result.error }); - res.json({ success: true, added: result.added, total: result.total }); - if (result.added! > 0) { - broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); + + const link = db.prepare("SELECT * FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ? AND provider = 'immich'") + .get(linkId, tripId, authReq.user.id) as any; + if (!link) return res.status(404).json({ error: 'Album link not found' }); + + const creds = getImmichCredentials(authReq.user.id); + if (!creds) return res.status(400).json({ error: 'Immich not configured' }); + + try { + const resp = await fetch(`${creds.immich_url}/api/albums/${link.album_id}`, { + headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, + signal: AbortSignal.timeout(15000), + }); + if (!resp.ok) return res.status(resp.status).json({ error: 'Failed to fetch album' }); + const albumData = await resp.json() as { assets?: any[] }; + const assets = (albumData.assets || []).filter((a: any) => a.type === 'IMAGE'); + + const insert = db.prepare( + "INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, 'immich', 1)" + ); + let added = 0; + for (const asset of assets) { + const r = insert.run(tripId, authReq.user.id, asset.id); + if (r.changes > 0) added++; + } + + db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); + + res.json({ success: true, added, total: assets.length }); + if (added > 0) { + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); + } + } catch { + res.status(502).json({ error: 'Could not reach Immich' }); } }); diff --git a/server/src/routes/memories.ts b/server/src/routes/memories.ts new file mode 100644 index 0000000..d84925d --- /dev/null +++ b/server/src/routes/memories.ts @@ -0,0 +1,182 @@ +import express, { Request, Response } from 'express'; +import { db, canAccessTrip } from '../db/database'; +import { authenticate } from '../middleware/auth'; +import { broadcast } from '../websocket'; +import { AuthRequest } from '../types'; + +const router = express.Router(); + + +router.get('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + + if (!canAccessTrip(tripId, authReq.user.id)) { + return res.status(404).json({ error: 'Trip not found' }); + } + + const photos = db.prepare(` + SELECT tp.asset_id, tp.provider, tp.user_id, tp.shared, tp.added_at, + u.username, u.avatar + FROM trip_photos tp + JOIN users u ON tp.user_id = u.id + WHERE tp.trip_id = ? + AND (tp.user_id = ? OR tp.shared = 1) + ORDER BY tp.added_at ASC + `).all(tripId, authReq.user.id) as any[]; + + res.json({ photos }); +}); + +router.get('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + + if (!canAccessTrip(tripId, authReq.user.id)) { + return res.status(404).json({ error: 'Trip not found' }); + } + + const links = 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 = ? + ORDER BY tal.created_at ASC + `).all(tripId); + + res.json({ links }); +}); + +router.delete('/trips/:tripId/album-links/:linkId', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId, linkId } = req.params; + + if (!canAccessTrip(tripId, authReq.user.id)) { + return res.status(404).json({ error: 'Trip not found' }); + } + + db.prepare('DELETE FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') + .run(linkId, tripId, authReq.user.id); + + res.json({ success: true }); + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); +}); + +router.post('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + const provider = String(req.body?.provider || '').toLowerCase(); + const { shared = true } = req.body; + const assetIdsRaw = req.body?.asset_ids; + + if (!canAccessTrip(tripId, authReq.user.id)) { + return res.status(404).json({ error: 'Trip not found' }); + } + + if (!provider) { + return res.status(400).json({ error: 'provider is required' }); + } + + if (!Array.isArray(assetIdsRaw) || assetIdsRaw.length === 0) { + return res.status(400).json({ error: 'asset_ids required' }); + } + + const insert = db.prepare( + 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, ?, ?)' + ); + + let added = 0; + for (const raw of assetIdsRaw) { + const assetId = String(raw || '').trim(); + if (!assetId) continue; + const result = insert.run(tripId, authReq.user.id, assetId, provider, shared ? 1 : 0); + if (result.changes > 0) added++; + } + + res.json({ success: true, added }); + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); + + if (shared && added > 0) { + import('../services/notifications').then(({ notifyTripMembers }) => { + const tripInfo = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; + notifyTripMembers(Number(tripId), authReq.user.id, 'photos_shared', { + trip: tripInfo?.title || 'Untitled', + actor: authReq.user.username || authReq.user.email, + count: String(added), + }).catch(() => {}); + }); + } +}); + +router.delete('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + const provider = String(req.body?.provider || '').toLowerCase(); + const assetId = String(req.body?.asset_id || ''); + + if (!assetId) { + return res.status(400).json({ error: 'asset_id is required' }); + } + + if (!provider) { + return res.status(400).json({ error: 'provider is required' }); + } + + if (!canAccessTrip(tripId, authReq.user.id)) { + return res.status(404).json({ error: 'Trip not found' }); + } + + db.prepare(` + DELETE FROM trip_photos + WHERE trip_id = ? + AND user_id = ? + AND asset_id = ? + AND provider = ? + `).run(tripId, authReq.user.id, assetId, provider); + + res.json({ success: true }); + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); +}); + +router.put('/trips/:tripId/photos/sharing', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + const provider = String(req.body?.provider || '').toLowerCase(); + const assetId = String(req.body?.asset_id || ''); + const { shared } = req.body; + + if (!assetId) { + return res.status(400).json({ error: 'asset_id is required' }); + } + + if (!provider) { + return res.status(400).json({ error: 'provider is required' }); + } + + if (!canAccessTrip(tripId, authReq.user.id)) { + return res.status(404).json({ error: 'Trip not found' }); + } + + db.prepare(` + UPDATE trip_photos + SET shared = ? + WHERE trip_id = ? + AND user_id = ? + AND asset_id = ? + AND provider = ? + `).run(shared ? 1 : 0, tripId, authReq.user.id, assetId, provider); + + res.json({ success: true }); + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); +}); + +export default router; From 78a91ccb95873552d49b99302bbf38432f1b3854 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 02:58:22 +0200 Subject: [PATCH 004/117] feat(integrations): add synology photos support --- server/src/db/migrations.ts | 59 +++ server/src/db/schema.ts | 4 + server/src/db/seeds.ts | 17 + server/src/index.ts | 2 + server/src/routes/auth.ts | 10 +- server/src/routes/synology.ts | 610 +++++++++++++++++++++++++ server/src/services/ephemeralTokens.ts | 1 + 7 files changed, 700 insertions(+), 3 deletions(-) create mode 100644 server/src/routes/synology.ts diff --git a/server/src/db/migrations.ts b/server/src/db/migrations.ts index 8e01979..d14d4a8 100644 --- a/server/src/db/migrations.ts +++ b/server/src/db/migrations.ts @@ -632,6 +632,65 @@ function runMigrations(db: Database.Database): void { } } }, + () => { + // Add Synology credential columns for existing databases + try { db.exec('ALTER TABLE users ADD COLUMN synology_url TEXT'); } catch (err: any) { if (!err.message?.includes('duplicate column name')) throw err; } + try { db.exec('ALTER TABLE users ADD COLUMN synology_username TEXT'); } catch (err: any) { if (!err.message?.includes('duplicate column name')) throw err; } + try { db.exec('ALTER TABLE users ADD COLUMN synology_password TEXT'); } catch (err: any) { if (!err.message?.includes('duplicate column name')) throw err; } + try { db.exec('ALTER TABLE users ADD COLUMN synology_sid TEXT'); } catch (err: any) { if (!err.message?.includes('duplicate column name')) throw err; } + }, + () => { + // Seed Synology Photos provider and fields in existing databases + try { + db.prepare(` + INSERT INTO photo_providers (id, name, description, icon, enabled, config, sort_order) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + name = excluded.name, + description = excluded.description, + icon = excluded.icon, + enabled = excluded.enabled, + config = excluded.config, + sort_order = excluded.sort_order + `).run( + 'synologyphotos', + 'Synology Photos', + 'Synology Photos integration with separate account settings', + 'Image', + 0, + JSON.stringify({ + settings_get: '/integrations/synologyphotos/settings', + settings_put: '/integrations/synologyphotos/settings', + status_get: '/integrations/synologyphotos/status', + test_get: '/integrations/synologyphotos/status', + }), + 1, + ); + } catch (err: any) { + if (!err.message?.includes('no such table')) throw err; + } + try { + const insertField = db.prepare(` + INSERT INTO photo_provider_fields + (provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(provider_id, field_key) DO UPDATE SET + label = excluded.label, + input_type = excluded.input_type, + placeholder = excluded.placeholder, + required = excluded.required, + secret = excluded.secret, + settings_key = excluded.settings_key, + payload_key = excluded.payload_key, + sort_order = excluded.sort_order + `); + insertField.run('synologyphotos', 'synology_url', 'Server URL', 'url', 'https://synology.example.com', 1, 0, 'synology_url', 'synology_url', 0); + insertField.run('synologyphotos', 'synology_username', 'Username', 'text', 'Username', 1, 0, 'synology_username', 'synology_username', 1); + insertField.run('synologyphotos', 'synology_password', 'Password', 'password', 'Password', 1, 1, null, 'synology_password', 2); + } catch (err: any) { + if (!err.message?.includes('no such table')) throw err; + } + }, ]; if (currentVersion < migrations.length) { diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index 8fe5739..9e243b6 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -18,6 +18,10 @@ function createTables(db: Database.Database): void { mfa_enabled INTEGER DEFAULT 0, mfa_secret TEXT, mfa_backup_codes TEXT, + synology_url TEXT, + synology_username TEXT, + synology_password TEXT, + synology_sid TEXT, must_change_password INTEGER DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP diff --git a/server/src/db/seeds.ts b/server/src/db/seeds.ts index f875794..8035d21 100644 --- a/server/src/db/seeds.ts +++ b/server/src/db/seeds.ts @@ -108,6 +108,20 @@ function seedAddons(db: Database.Database): void { test_post: '/integrations/immich/test', }), }, + { + id: 'synologyphotos', + name: 'Synology Photos', + description: 'Synology Photos integration with separate account settings', + icon: 'Image', + enabled: 0, + sort_order: 1, + config: JSON.stringify({ + settings_get: '/integrations/synologyphotos/settings', + settings_put: '/integrations/synologyphotos/settings', + status_get: '/integrations/synologyphotos/status', + test_get: '/integrations/synologyphotos/status', + }), + }, ]; const insertProvider = db.prepare('INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, config, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)'); for (const p of providerRows) insertProvider.run(p.id, p.name, p.description, p.icon, p.enabled, p.config, p.sort_order); @@ -115,6 +129,9 @@ function seedAddons(db: Database.Database): void { const providerFields = [ { provider_id: 'immich', field_key: 'immich_url', label: 'Immich URL', input_type: 'url', placeholder: 'https://immich.example.com', required: 1, secret: 0, settings_key: 'immich_url', payload_key: 'immich_url', sort_order: 0 }, { provider_id: 'immich', field_key: 'immich_api_key', label: 'API Key', input_type: 'password', placeholder: 'API Key', required: 1, secret: 1, settings_key: null, payload_key: 'immich_api_key', sort_order: 1 }, + { provider_id: 'synologyphotos', field_key: 'synology_url', label: 'Server URL', input_type: 'url', placeholder: 'https://synology.example.com', required: 1, secret: 0, settings_key: 'synology_url', payload_key: 'synology_url', sort_order: 0 }, + { provider_id: 'synologyphotos', field_key: 'synology_username', label: 'Username', input_type: 'text', placeholder: 'Username', required: 1, secret: 0, settings_key: 'synology_username', payload_key: 'synology_username', sort_order: 1 }, + { provider_id: 'synologyphotos', field_key: 'synology_password', label: 'Password', input_type: 'password', placeholder: 'Password', required: 1, secret: 1, settings_key: null, payload_key: 'synology_password', sort_order: 2 }, ]; const insertProviderField = db.prepare('INSERT OR IGNORE INTO photo_provider_fields (provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); for (const f of providerFields) { diff --git a/server/src/index.ts b/server/src/index.ts index 533d92c..d1d682d 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -281,6 +281,8 @@ import atlasRoutes from './routes/atlas'; app.use('/api/addons/atlas', atlasRoutes); import immichRoutes from './routes/immich'; app.use('/api/integrations/immich', immichRoutes); +const synologyRoutes = require('./routes/synology').default; +app.use('/api/integrations/synologyphotos', synologyRoutes); import memoriesRoutes from './routes/memories'; app.use('/api/integrations/memories', memoriesRoutes); diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.ts index eb7463d..29aadd4 100644 --- a/server/src/routes/auth.ts +++ b/server/src/routes/auth.ts @@ -315,9 +315,13 @@ router.post('/ws-token', authenticate, (req: Request, res: Response) => { // Short-lived single-use token for direct resource URLs router.post('/resource-token', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; - const result = createResourceToken(authReq.user.id, req.body.purpose); - if (result.error) return res.status(result.status!).json({ error: result.error }); - res.json({ token: result.token }); + const { purpose } = req.body as { purpose?: string }; + if (purpose !== 'download' && purpose !== 'immich' && purpose !== 'synologyphotos') { + return res.status(400).json({ error: 'Invalid purpose' }); + } + const token = createEphemeralToken(authReq.user.id, purpose); + if (!token) return res.status(503).json({ error: 'Service unavailable' }); + res.json({ token }); }); export default router; diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts new file mode 100644 index 0000000..9e98fcf --- /dev/null +++ b/server/src/routes/synology.ts @@ -0,0 +1,610 @@ +import express, { NextFunction, Request, Response } from 'express'; +import { Readable } from 'node:stream'; +import { pipeline } from 'node:stream/promises'; +import { db, canAccessTrip } from '../db/database'; +import { authenticate } from '../middleware/auth'; +import { broadcast } from '../websocket'; +import { AuthRequest } from '../types'; +import { maybe_encrypt_api_key, decrypt_api_key } from '../services/apiKeyCrypto'; +import { consumeEphemeralToken } from '../services/ephemeralTokens'; + +const router = express.Router(); + +function copyProxyHeaders(resp: Response, upstream: globalThis.Response, headerNames: string[]): void { + for (const headerName of headerNames) { + const value = upstream.headers.get(headerName); + if (value) { + resp.set(headerName, value); + } + } +} + +// Helper: Get Synology credentials from users table +function getSynologyCredentials(userId: number) { + try { + const user = db.prepare('SELECT synology_url, synology_username, synology_password FROM users WHERE id = ?').get(userId) as any; + if (!user?.synology_url || !user?.synology_username || !user?.synology_password) return null; + return { + synology_url: user.synology_url as string, + synology_username: user.synology_username as string, + synology_password: decrypt_api_key(user.synology_password) as string, + }; + } catch { + return null; + } +} + +// Helper: Get cached SID from settings or users table +function getCachedSynologySID(userId: number) { + try { + const row = db.prepare('SELECT synology_sid FROM users WHERE id = ?').get(userId) as any; + return row?.synology_sid || null; + } catch { + return null; + } +} + +// Helper: Cache SID in users table +function cacheSynologySID(userId: number, sid: string) { + try { + db.prepare('UPDATE users SET synology_sid = ? WHERE id = ?').run(sid, userId); + } catch (err) { + // Ignore if columns don't exist yet + } +} + +// Helper: Get authenticated session + +interface SynologySession { + success: boolean; + sid?: string; + error?: { code: number; message?: string }; +} + +async function getSynologySession(userId: number): Promise { + // Check for cached SID + const cachedSid = getCachedSynologySID(userId); + if (cachedSid) { + return { success: true, sid: cachedSid }; + } + + const creds = getSynologyCredentials(userId); + // Login with credentials + if (!creds) { + return { success: false, error: { code: 400, message: 'Invalid Synology credentials' } }; + } + const endpoint = prepareSynologyEndpoint(creds.synology_url); + + const body = new URLSearchParams({ + api: 'SYNO.API.Auth', + method: 'login', + version: '3', + account: creds.synology_username, + passwd: creds.synology_password, + }); + + const resp = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + }, + body, + signal: AbortSignal.timeout(30000), + }); + + if (!resp.ok) { + return { success: false, error: { code: resp.status, message: 'Failed to authenticate with Synology' } }; + } + + const data = await resp.json() as { success: boolean; data?: { sid?: string } }; + + if (data.success && data.data?.sid) { + const sid = data.data.sid; + cacheSynologySID(userId, sid); + return { success: true, sid }; + } + + return { success: false, error: { code: 500, message: 'Failed to get Synology session' } }; +} + +// Helper: Clear cached SID + +function clearSynologySID(userId: number): void { + try { + db.prepare('UPDATE users SET synology_sid = NULL WHERE id = ?').run(userId); + } catch { + // Ignore if columns don't exist yet + } +} + +interface ApiCallParams { + api: string; + method: string; + version?: number; + [key: string]: any; +} + +interface SynologyApiResponse { + success: boolean; + data?: T; + error?: { code: number, message?: string }; +} + +function prepareSynologyEndpoint(url: string): string { + url = url.replace(/\/$/, ''); + if (!/^https?:\/\//.test(url)) { + url = `https://${url}`; + } + return `${url}/photo/webapi/entry.cgi`; +} + +function splitPackedSynologyId(rawId: string): { id: string; cacheKey: string; assetId: string } { + const id = rawId.split('_')[0]; + return { id: id, cacheKey: rawId, assetId: rawId }; +} + +function transformSynologyPhoto(item: any): any { + const address = item.additional?.address || {}; + return { + id: item.additional?.thumbnail?.cache_key, + takenAt: item.time ? new Date(item.time * 1000).toISOString() : null, + city: address.city || null, + country: address.country || null, + }; +} + +async function callSynologyApi(userId: number, params: ApiCallParams): Promise> { + try { + const creds = getSynologyCredentials(userId); + if (!creds) { + return { success: false, error: { code: 400, message: 'Synology not configured' } }; + } + const endpoint = prepareSynologyEndpoint(creds.synology_url); + + + const body = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value === undefined || value === null) continue; + body.append(key, typeof value === 'object' ? JSON.stringify(value) : String(value)); + } + + const sid = await getSynologySession(userId); + if (!sid.success || !sid.sid) { + return { success: false, error: sid.error || { code: 500, message: 'Failed to get Synology session' } }; + } + body.append('_sid', sid.sid); + + const resp = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + }, + body, + signal: AbortSignal.timeout(30000), + }); + + + if (!resp.ok) { + const text = await resp.text(); + return { success: false, error: { code: resp.status, message: text } }; + } + + const result = await resp.json() as SynologyApiResponse; + if (!result.success && result.error?.code === 119) { + clearSynologySID(userId); + return callSynologyApi(userId, params); + } + return result; + } catch (err) { + return { success: false, error: { code: -1, message: err instanceof Error ? err.message : 'Unknown error' } }; + } +} + +// Settings +router.get('/settings', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const creds = getSynologyCredentials(authReq.user.id); + res.json({ + synology_url: creds?.synology_url || '', + synology_username: creds?.synology_username || '', + connected: !!(creds?.synology_url && creds?.synology_username), + }); +}); + +router.put('/settings', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { synology_url, synology_username, synology_password } = req.body; + + const url = String(synology_url || '').trim(); + const username = String(synology_username || '').trim(); + const password = String(synology_password || '').trim(); + + if (!url || !username) { + return res.status(400).json({ error: 'URL and username are required' }); + } + + const existing = db.prepare('SELECT synology_password FROM users WHERE id = ?').get(authReq.user.id) as { synology_password?: string | null } | undefined; + const existingEncryptedPassword = existing?.synology_password || null; + + // First-time setup requires password; later updates may keep existing password. + if (!password && !existingEncryptedPassword) { + return res.status(400).json({ error: 'Password is required' }); + } + + try { + db.prepare('UPDATE users SET synology_url = ?, synology_username = ?, synology_password = ? WHERE id = ?').run( + url, + username, + password ? maybe_encrypt_api_key(password) : existingEncryptedPassword, + authReq.user.id + ); + } catch (err) { + return res.status(400).json({ error: 'Failed to save settings' }); + } + + clearSynologySID(authReq.user.id); + res.json({ success: true }); +}); + +// Status +router.get('/status', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + + try { + const sid = await getSynologySession(authReq.user.id); + if (!sid.success || !sid.sid) { + return res.json({ connected: false, error: 'Authentication failed' }); + } + + const user = db.prepare('SELECT synology_username FROM users WHERE id = ?').get(authReq.user.id) as any; + res.json({ connected: true, user: { username: user.synology_username } }); + } catch (err: unknown) { + res.json({ connected: false, error: err instanceof Error ? err.message : 'Connection failed' }); + } +}); + +// Album linking parity with Immich +router.get('/albums', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + try { + const result = await callSynologyApi<{ list: any[] }>(authReq.user.id, { + api: 'SYNO.Foto.Browse.Album', + method: 'list', + version: 4, + offset: 0, + limit: 100, + }); + + if (!result.success || !result.data) { + return res.status(502).json({ error: result.error?.message || 'Failed to fetch albums' }); + } + + const albums = (result.data.list || []).map((a: any) => ({ + id: String(a.id), + albumName: a.name || '', + assetCount: a.item_count || 0, + })); + + res.json({ albums }); + } catch (err: unknown) { + res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology' }); + } +}); + +router.post('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + if (!canAccessTrip(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); + const { album_id, album_name } = req.body; + if (!album_id) return res.status(400).json({ error: 'album_id required' }); + + try { + db.prepare( + 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)' + ).run(tripId, authReq.user.id, 'synologyphotos', String(album_id), album_name || ''); + res.json({ success: true }); + } catch { + res.status(400).json({ error: 'Album already linked' }); + } +}); + +router.post('/trips/:tripId/album-links/:linkId/sync', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId, linkId } = req.params; + + const link = db.prepare("SELECT * FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ? AND provider = 'synologyphotos'") + .get(linkId, tripId, authReq.user.id) as any; + if (!link) return res.status(404).json({ error: 'Album link not found' }); + + try { + const allItems: any[] = []; + const pageSize = 1000; + let offset = 0; + + while (true) { + const result = await callSynologyApi<{ list: any[] }>(authReq.user.id, { + api: 'SYNO.Foto.Browse.Item', + method: 'list', + version: 1, + album_id: Number(link.album_id), + offset, + limit: pageSize, + additional: ['thumbnail'], + }); + + if (!result.success || !result.data) { + return res.status(502).json({ error: result.error?.message || 'Failed to fetch album' }); + } + + const items = result.data.list || []; + allItems.push(...items); + if (items.length < pageSize) break; + offset += pageSize; + } + + const insert = db.prepare( + "INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, 'synologyphotos', 1)" + ); + + let added = 0; + for (const item of allItems) { + const transformed = transformSynologyPhoto(item); + const assetId = String(transformed?.id || '').trim(); + if (!assetId) continue; + const r = insert.run(tripId, authReq.user.id, assetId); + if (r.changes > 0) added++; + } + + db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); + + res.json({ success: true, added, total: allItems.length }); + if (added > 0) { + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); + } + } catch (err: unknown) { + res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology' }); + } +}); + +// Search +router.post('/search', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + let { from, to, offset = 0, limit = 300 } = req.body; + + try { + const params: any = { + api: 'SYNO.Foto.Search.Search', + method: 'list_item', + version: 1, + offset, + limit, + keyword: '.', + additional: ['thumbnail', 'address'], + }; + + if (from || to) { + if (from) { + params.start_time = Math.floor(new Date(from).getTime() / 1000); + } + if (to) { + params.end_time = Math.floor(new Date(to).getTime() / 1000) + 86400; // Include entire end day + } + } + + + const result = await callSynologyApi<{ list: any[]; total: number }>(authReq.user.id, params); + + if (!result.success || !result.data) { + return res.status(502).json({ error: result.error?.message || 'Failed to fetch album photos' }); + } + + const allItems = (result.data.list || []); + const total = allItems.length; + + const assets = allItems.map((item: any) => transformSynologyPhoto(item)); + + res.json({ + assets, + total, + hasMore: total == limit, + }); + } catch (err: unknown) { + res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology' }); + } +}); + +// Proxy Synology Assets + +// Asset info endpoint (returns metadata, not image) +router.get('/assets/:photoId/info', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { photoId } = req.params; + const parsedId = splitPackedSynologyId(photoId); + const { userId } = req.query; + + const targetUserId = userId ? Number(userId) : authReq.user.id; + + try { + const result = await callSynologyApi(targetUserId, { + api: 'SYNO.Foto.Browse.Item', + method: 'get', + version: 2, + id: Number(parsedId.id), + additional: ['thumbnail', 'resolution', 'exif', 'gps', 'address', 'orientation', 'description'], + }); + if (!result.success || !result.data) { + return res.status(404).json({ error: 'Photo not found' }); + } + + + const exif = result.data.additional?.exif || {}; + const address = result.data.additional?.address || {}; + const gps = result.data.additional?.gps || {}; + res.json({ + id: result.data.id, + takenAt: result.data.time ? new Date(result.data.time * 1000).toISOString() : null, + width: result.data.additional?.resolution?.width || null, + height: result.data.additional?.resolution?.height || null, + camera: exif.model || null, + lens: exif.lens_model || null, + focalLength: exif.focal_length ? `${exif.focal_length}mm` : null, + aperture: exif.f_number ? `f/${exif.f_number}` : null, + shutter: exif.exposure_time || null, + iso: exif.iso_speed_ratings || null, + city: address.city || null, + state: address.state || null, + country: address.country || null, + lat: gps.latitude || null, + lng: gps.longitude || null, + orientation: result.data.additional?.orientation || null, + description: result.data.additional?.description || null, + fileSize: result.data.filesize || null, + fileName: result.data.filename || null, + }); + } catch (err: unknown) { + res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology'}); + } +}); + +// Middleware: Accept ephemeral token from query param for tags +function authFromQuery(req: Request, res: Response, next: NextFunction) { + const queryToken = req.query.token as string | undefined; + if (queryToken) { + const userId = consumeEphemeralToken(queryToken, 'synologyphotos'); + if (!userId) return res.status(401).send('Invalid or expired token'); + const user = db.prepare('SELECT id, username, email, role, mfa_enabled FROM users WHERE id = ?').get(userId) as any; + if (!user) return res.status(401).send('User not found'); + (req as AuthRequest).user = user; + return next(); + } + return (authenticate as any)(req, res, next); +} + +router.get('/assets/:photoId/thumbnail', authFromQuery, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { photoId } = req.params; + const parsedId = splitPackedSynologyId(photoId); + const { userId, cacheKey, size = 'sm' } = req.query; + + const targetUserId = userId ? Number(userId) : authReq.user.id; + + const creds = getSynologyCredentials(targetUserId); + if (!creds) { + return res.status(404).send('Not found'); + } + + try { + const sid = await getSynologySession(authReq.user.id); + if (!sid.success && !sid.sid) { + return res.status(401).send('Authentication failed'); + } + + let resolvedCacheKey = cacheKey ? String(cacheKey) : parsedId.cacheKey; + if (!resolvedCacheKey) { + const row = db.prepare(` + SELECT asset_id FROM trip_photos + WHERE user_id = ? AND (asset_id = ? OR asset_id = ? OR asset_id LIKE ? OR asset_id LIKE ?) + ORDER BY id DESC LIMIT 1 + `).get(targetUserId, parsedId.assetId, parsedId.id, `${parsedId.id}_%`, `${parsedId.id}::%`) as { asset_id?: string } | undefined; + const packed = row?.asset_id || ''; + if (packed) { + resolvedCacheKey = splitPackedSynologyId(packed).cacheKey; + } + } + if (!resolvedCacheKey) return res.status(404).send('Missing cache key for thumbnail'); + + const params = new URLSearchParams({ + api: 'SYNO.Foto.Thumbnail', + method: 'get', + version: '2', + mode: 'download', + id: String(parsedId.id), + type: 'unit', + size: String(size), + cache_key: resolvedCacheKey, + _sid: sid.sid, + }); + const url = prepareSynologyEndpoint(creds.synology_url) + '?' + params.toString(); + const resp = await fetch(url, { + signal: AbortSignal.timeout(30000), + }); + + if (!resp.ok) { + return res.status(resp.status).send('Failed'); + } + + res.status(resp.status); + copyProxyHeaders(res, resp, ['content-type', 'cache-control', 'content-length', 'content-disposition']); + res.set('Content-Type', resp.headers.get('content-type') || 'image/jpeg'); + res.set('Cache-Control', resp.headers.get('cache-control') || 'public, max-age=86400'); + + if (!resp.body) { + return res.end(); + } + + await pipeline(Readable.fromWeb(resp.body), res); + } catch (err: unknown) { + if (res.headersSent) { + return; + } + res.status(502).send('Proxy error: ' + (err instanceof Error ? err.message : String(err))); + } +}); + + +router.get('/assets/download', authFromQuery, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { userId, cacheKey, unitIds } = req.query; + + const targetUserId = userId ? Number(userId) : authReq.user.id; + + const creds = getSynologyCredentials(targetUserId); + if (!creds) { + return res.status(404).send('Not found'); + } + + try { + const sid = await getSynologySession(authReq.user.id); + if (!sid.success && !sid.sid) { + return res.status(401).send('Authentication failed'); + } + + const params = new URLSearchParams({ + api: 'SYNO.Foto.Download', + method: 'download', + version: '2', + cache_key: String(cacheKey), + unit_id: "[" + String(unitIds) + "]", + _sid: sid.sid, + }); + + const url = prepareSynologyEndpoint(creds.synology_url) + '?' + params.toString(); + const resp = await fetch(url, { + signal: AbortSignal.timeout(30000), + }); + + if (!resp.ok) { + const body = await resp.text(); + return res.status(resp.status).send('Failed: ' + body); + } + + res.status(resp.status); + copyProxyHeaders(res, resp, ['content-type', 'cache-control', 'content-length', 'content-disposition']); + res.set('Content-Type', resp.headers.get('content-type') || 'application/octet-stream'); + res.set('Cache-Control', resp.headers.get('cache-control') || 'public, max-age=86400'); + + if (!resp.body) { + return res.end(); + } + + await pipeline(Readable.fromWeb(resp.body), res); + } catch (err: unknown) { + if (res.headersSent) { + return; + } + res.status(502).send('Proxy error: ' + (err instanceof Error ? err.message : String(err))); + } +}); + + +export default router; diff --git a/server/src/services/ephemeralTokens.ts b/server/src/services/ephemeralTokens.ts index 0d1c12b..f880951 100644 --- a/server/src/services/ephemeralTokens.ts +++ b/server/src/services/ephemeralTokens.ts @@ -4,6 +4,7 @@ const TTL: Record = { ws: 30_000, download: 60_000, immich: 60_000, + synologyphotos: 60_000, }; const MAX_STORE_SIZE = 10_000; From f7c965bc6bfb900f0c392d5dc5277b2be60318c1 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 03:08:15 +0200 Subject: [PATCH 005/117] returning test connectioon button to original intend --- server/src/db/migrations.ts | 2 +- server/src/db/seeds.ts | 2 +- server/src/routes/immich.ts | 15 ++++++------ server/src/routes/synology.ts | 44 +++++++++++++++++++++++++++++++++++ 4 files changed, 54 insertions(+), 9 deletions(-) diff --git a/server/src/db/migrations.ts b/server/src/db/migrations.ts index d14d4a8..20f160d 100644 --- a/server/src/db/migrations.ts +++ b/server/src/db/migrations.ts @@ -662,7 +662,7 @@ function runMigrations(db: Database.Database): void { settings_get: '/integrations/synologyphotos/settings', settings_put: '/integrations/synologyphotos/settings', status_get: '/integrations/synologyphotos/status', - test_get: '/integrations/synologyphotos/status', + test_post: '/integrations/synologyphotos/test', }), 1, ); diff --git a/server/src/db/seeds.ts b/server/src/db/seeds.ts index 8035d21..ef849d9 100644 --- a/server/src/db/seeds.ts +++ b/server/src/db/seeds.ts @@ -119,7 +119,7 @@ function seedAddons(db: Database.Database): void { settings_get: '/integrations/synologyphotos/settings', settings_put: '/integrations/synologyphotos/settings', status_get: '/integrations/synologyphotos/status', - test_get: '/integrations/synologyphotos/status', + test_post: '/integrations/synologyphotos/test', }), }, ]; diff --git a/server/src/routes/immich.ts b/server/src/routes/immich.ts index 7ed3dd4..dd02468 100644 --- a/server/src/routes/immich.ts +++ b/server/src/routes/immich.ts @@ -79,16 +79,17 @@ router.get('/status', authenticate, async (req: Request, res: Response) => { } }); -// Test connection with saved credentials +// Test connection with provided credentials only router.post('/test', authenticate, async (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const creds = getImmichCredentials(authReq.user.id); - if (!creds) return res.json({ connected: false, error: 'No credentials configured' }); - const ssrf = await checkSsrf(creds.immich_url); + const { immich_url, immich_api_key } = req.body as { immich_url?: string; immich_api_key?: string }; + const url = String(immich_url || '').trim(); + const apiKey = String(immich_api_key || '').trim(); + if (!url || !apiKey) return res.json({ connected: false, error: 'URL and API key required' }); + const ssrf = await checkSsrf(url); if (!ssrf.allowed) return res.json({ connected: false, error: ssrf.error ?? 'Invalid Immich URL' }); try { - const resp = await fetch(`${creds.immich_url}/api/users/me`, { - headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, + const resp = await fetch(`${url}/api/users/me`, { + headers: { 'x-api-key': apiKey, 'Accept': 'application/json' }, signal: AbortSignal.timeout(10000), }); if (!resp.ok) return res.json({ connected: false, error: `HTTP ${resp.status}` }); diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index 9e98fcf..c1e868e 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -7,6 +7,7 @@ import { broadcast } from '../websocket'; import { AuthRequest } from '../types'; import { maybe_encrypt_api_key, decrypt_api_key } from '../services/apiKeyCrypto'; import { consumeEphemeralToken } from '../services/ephemeralTokens'; +import { checkSsrf } from '../utils/ssrfGuard'; const router = express.Router(); @@ -263,6 +264,49 @@ router.get('/status', authenticate, async (req: Request, res: Response) => { } }); +// Test connection with provided credentials only +router.post('/test', authenticate, async (req: Request, res: Response) => { + const { synology_url, synology_username, synology_password } = req.body as { synology_url?: string; synology_username?: string; synology_password?: string }; + + const url = String(synology_url || '').trim(); + const username = String(synology_username || '').trim(); + const password = String(synology_password || '').trim(); + + if (!url || !username || !password) { + return res.json({ connected: false, error: 'URL, username, and password are required' }); + } + + const ssrf = await checkSsrf(url); + if (!ssrf.allowed) return res.json({ connected: false, error: ssrf.error ?? 'Invalid Synology URL' }); + + try { + const endpoint = prepareSynologyEndpoint(url); + const body = new URLSearchParams({ + api: 'SYNO.API.Auth', + method: 'login', + version: '3', + account: username, + passwd: password, + }); + + const resp = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + }, + body, + signal: AbortSignal.timeout(30000), + }); + + if (!resp.ok) return res.json({ connected: false, error: `HTTP ${resp.status}` }); + const data = await resp.json() as { success: boolean; data?: { sid?: string } }; + if (!data.success || !data.data?.sid) return res.json({ connected: false, error: 'Authentication failed' }); + return res.json({ connected: true, user: { username } }); + } catch (err: unknown) { + return res.json({ connected: false, error: err instanceof Error ? err.message : 'Connection failed' }); + } +}); + // Album linking parity with Immich router.get('/albums', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; From 4b8cfc78b8a49017db210e9df2f803e4dbc39480 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 03:20:45 +0200 Subject: [PATCH 006/117] fixing selection of photos from multiple sources at once --- .../src/components/Memories/MemoriesPanel.tsx | 45 +++++++++++++------ server/src/routes/memories.ts | 32 ++++++++----- 2 files changed, 52 insertions(+), 25 deletions(-) diff --git a/client/src/components/Memories/MemoriesPanel.tsx b/client/src/components/Memories/MemoriesPanel.tsx index b288487..8787dd7 100644 --- a/client/src/components/Memories/MemoriesPanel.tsx +++ b/client/src/components/Memories/MemoriesPanel.tsx @@ -33,11 +33,12 @@ interface TripPhoto { city?: string | null } -interface ImmichAsset { +interface Asset { id: string takenAt: string city: string | null country: string | null + provider: string } interface MemoriesPanelProps { @@ -63,7 +64,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa // Photo picker const [showPicker, setShowPicker] = useState(false) - const [pickerPhotos, setPickerPhotos] = useState([]) + const [pickerPhotos, setPickerPhotos] = useState([]) const [pickerLoading, setPickerLoading] = useState(false) const [selectedIds, setSelectedIds] = useState>(new Set()) @@ -238,11 +239,16 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const loadPickerPhotos = async (useDate: boolean) => { setPickerLoading(true) try { - const res = await apiClient.post(`${pickerIntegrationBase}/search`, { + const provider = availableProviders.find(p => p.id === selectedProvider) + if (!provider) { + setPickerPhotos([]) + return + } + const res = await apiClient.post(`/integrations/${provider.id}/search`, { from: useDate && startDate ? startDate : undefined, to: useDate && endDate ? endDate : undefined, }) - setPickerPhotos(res.data.assets || []) + setPickerPhotos((res.data.assets || []).map((asset: Asset) => ({ ...asset, provider: provider.id }))) } catch { setPickerPhotos([]) toast.error(t('memories.error.loadPhotos')) @@ -268,9 +274,17 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const executeAddPhotos = async () => { setShowConfirmShare(false) try { + const groupedByProvider = new Map() + for (const key of selectedIds) { + const [provider, assetId] = key.split('::') + if (!provider || !assetId) continue + const list = groupedByProvider.get(provider) || [] + list.push(assetId) + groupedByProvider.set(provider, list) + } + await apiClient.post(`/integrations/memories/trips/${tripId}/photos`, { - provider: selectedProvider, - asset_ids: [...selectedIds], + selections: [...groupedByProvider.entries()].map(([provider, asset_ids]) => ({ provider, asset_ids })), shared: true, }) setShowPicker(false) @@ -312,6 +326,8 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const thumbnailBaseUrl = (photo: TripPhoto) => `/api/integrations/${photo.provider}/assets/${photo.asset_id}/thumbnail?userId=${photo.user_id}` + const makePickerKey = (provider: string, assetId: string): string => `${provider}::${assetId}` + const ownPhotos = tripPhotos.filter(p => p.user_id === currentUser?.id) const othersPhotos = tripPhotos.filter(p => p.user_id !== currentUser?.id && p.shared) const allVisibleRaw = [...ownPhotos, ...othersPhotos] @@ -461,8 +477,8 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa if (showPicker) { const alreadyAdded = new Set( tripPhotos - .filter(p => p.user_id === currentUser?.id && p.provider === selectedProvider) - .map(p => p.asset_id) + .filter(p => p.user_id === currentUser?.id) + .map(p => makePickerKey(p.provider, p.asset_id)) ) return ( @@ -537,7 +553,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa
) : (() => { // Group photos by month - const byMonth: Record = {} + const byMonth: Record = {} for (const asset of pickerPhotos) { const d = asset.takenAt ? new Date(asset.takenAt) : null const key = d ? `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}` : 'unknown' @@ -555,11 +571,12 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa
{byMonth[month].map(asset => { - const isSelected = selectedIds.has(asset.id) - const isAlready = alreadyAdded.has(asset.id) + const pickerKey = makePickerKey(asset.provider, asset.id) + const isSelected = selectedIds.has(pickerKey) + const isAlready = alreadyAdded.has(pickerKey) return ( -
!isAlready && togglePickerSelect(asset.id)} +
!isAlready && togglePickerSelect(pickerKey)} style={{ position: 'relative', aspectRatio: '1', borderRadius: 8, overflow: 'hidden', cursor: isAlready ? 'default' : 'pointer', @@ -567,7 +584,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa outline: isSelected ? '3px solid var(--text-primary)' : 'none', outlineOffset: -3, }}> - {isSelected && (
{ const authReq = req as AuthRequest; const { tripId } = req.params; - const provider = String(req.body?.provider || '').toLowerCase(); const { shared = true } = req.body; + const selectionsRaw = Array.isArray(req.body?.selections) ? req.body.selections : null; + const provider = String(req.body?.provider || '').toLowerCase(); const assetIdsRaw = req.body?.asset_ids; if (!canAccessTrip(tripId, authReq.user.id)) { return res.status(404).json({ error: 'Trip not found' }); } - if (!provider) { - return res.status(400).json({ error: 'provider is required' }); - } + const selections = selectionsRaw && selectionsRaw.length > 0 + ? selectionsRaw + .map((selection: any) => ({ + provider: String(selection?.provider || '').toLowerCase(), + asset_ids: Array.isArray(selection?.asset_ids) ? selection.asset_ids : [], + })) + .filter((selection: { provider: string; asset_ids: unknown[] }) => selection.provider && selection.asset_ids.length > 0) + : (provider && Array.isArray(assetIdsRaw) && assetIdsRaw.length > 0 + ? [{ provider, asset_ids: assetIdsRaw }] + : []); - if (!Array.isArray(assetIdsRaw) || assetIdsRaw.length === 0) { - return res.status(400).json({ error: 'asset_ids required' }); + if (selections.length === 0) { + return res.status(400).json({ error: 'selections required' }); } const insert = db.prepare( @@ -95,11 +103,13 @@ router.post('/trips/:tripId/photos', authenticate, (req: Request, res: Response) ); let added = 0; - for (const raw of assetIdsRaw) { - const assetId = String(raw || '').trim(); - if (!assetId) continue; - const result = insert.run(tripId, authReq.user.id, assetId, provider, shared ? 1 : 0); - if (result.changes > 0) added++; + for (const selection of selections) { + for (const raw of selection.asset_ids) { + const assetId = String(raw || '').trim(); + if (!assetId) continue; + const result = insert.run(tripId, authReq.user.id, assetId, selection.provider, shared ? 1 : 0); + if (result.changes > 0) added++; + } } res.json({ success: true, added }); From c4236d673741168538741ef084eba6c33441f2de Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 03:29:13 +0200 Subject: [PATCH 007/117] fixing path for asset in full res --- server/src/routes/synology.ts | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index c1e868e..7312eaa 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -528,7 +528,7 @@ router.get('/assets/:photoId/thumbnail', authFromQuery, async (req: Request, res const authReq = req as AuthRequest; const { photoId } = req.params; const parsedId = splitPackedSynologyId(photoId); - const { userId, cacheKey, size = 'sm' } = req.query; + const { userId, size = 'sm' } = req.query; const targetUserId = userId ? Number(userId) : authReq.user.id; @@ -543,29 +543,15 @@ router.get('/assets/:photoId/thumbnail', authFromQuery, async (req: Request, res return res.status(401).send('Authentication failed'); } - let resolvedCacheKey = cacheKey ? String(cacheKey) : parsedId.cacheKey; - if (!resolvedCacheKey) { - const row = db.prepare(` - SELECT asset_id FROM trip_photos - WHERE user_id = ? AND (asset_id = ? OR asset_id = ? OR asset_id LIKE ? OR asset_id LIKE ?) - ORDER BY id DESC LIMIT 1 - `).get(targetUserId, parsedId.assetId, parsedId.id, `${parsedId.id}_%`, `${parsedId.id}::%`) as { asset_id?: string } | undefined; - const packed = row?.asset_id || ''; - if (packed) { - resolvedCacheKey = splitPackedSynologyId(packed).cacheKey; - } - } - if (!resolvedCacheKey) return res.status(404).send('Missing cache key for thumbnail'); - const params = new URLSearchParams({ api: 'SYNO.Foto.Thumbnail', method: 'get', version: '2', mode: 'download', - id: String(parsedId.id), + id: parsedId.id, type: 'unit', size: String(size), - cache_key: resolvedCacheKey, + cache_key: parsedId.cacheKey, _sid: sid.sid, }); const url = prepareSynologyEndpoint(creds.synology_url) + '?' + params.toString(); @@ -596,9 +582,11 @@ router.get('/assets/:photoId/thumbnail', authFromQuery, async (req: Request, res }); -router.get('/assets/download', authFromQuery, async (req: Request, res: Response) => { +router.get('/assets/:photoId/original', authFromQuery, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - const { userId, cacheKey, unitIds } = req.query; + const { photoId } = req.params; + const parsedId = splitPackedSynologyId(photoId || ''); + const { userId} = req.query; const targetUserId = userId ? Number(userId) : authReq.user.id; @@ -617,8 +605,8 @@ router.get('/assets/download', authFromQuery, async (req: Request, res: Response api: 'SYNO.Foto.Download', method: 'download', version: '2', - cache_key: String(cacheKey), - unit_id: "[" + String(unitIds) + "]", + cache_key: parsedId.cacheKey, + unit_id: `[${parsedId.id}]`, _sid: sid.sid, }); From c20d0256c855bc795da6d2683147c28177d14e2e Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 03:47:44 +0200 Subject: [PATCH 008/117] fixing metada --- server/src/routes/synology.ts | 47 +++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index 7312eaa..71fed86 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -472,38 +472,41 @@ router.get('/assets/:photoId/info', authenticate, async (req: Request, res: Resp const result = await callSynologyApi(targetUserId, { api: 'SYNO.Foto.Browse.Item', method: 'get', - version: 2, - id: Number(parsedId.id), - additional: ['thumbnail', 'resolution', 'exif', 'gps', 'address', 'orientation', 'description'], + version: 5, + id: `[${parsedId.id}]`, + additional: ['resolution', 'exif', 'gps', 'address', 'orientation', 'description'], }); if (!result.success || !result.data) { return res.status(404).json({ error: 'Photo not found' }); } - - const exif = result.data.additional?.exif || {}; - const address = result.data.additional?.address || {}; - const gps = result.data.additional?.gps || {}; + const metadata = result.data.list[0]; + console.log(metadata); + const exif = metadata.additional?.exif || {}; + const address = metadata.additional?.address || {}; + const gps = metadata.additional?.gps || {}; res.json({ - id: result.data.id, - takenAt: result.data.time ? new Date(result.data.time * 1000).toISOString() : null, - width: result.data.additional?.resolution?.width || null, - height: result.data.additional?.resolution?.height || null, - camera: exif.model || null, - lens: exif.lens_model || null, - focalLength: exif.focal_length ? `${exif.focal_length}mm` : null, - aperture: exif.f_number ? `f/${exif.f_number}` : null, - shutter: exif.exposure_time || null, - iso: exif.iso_speed_ratings || null, + id: photoId, + takenAt: metadata.time ? new Date(metadata.time * 1000).toISOString() : null, city: address.city || null, - state: address.state || null, country: address.country || null, + state: address.state || null, + camera: exif.camera || null, + lens: exif.lens || null, + focalLength: exif.focal_length || null, + aperture: exif.aperture || null, + shutter: exif.exposure_time || null, + iso: exif.iso || null, lat: gps.latitude || null, lng: gps.longitude || null, - orientation: result.data.additional?.orientation || null, - description: result.data.additional?.description || null, - fileSize: result.data.filesize || null, - fileName: result.data.filename || null, + orientation: metadata.additional?.orientation || null, + description: metadata.additional?.description || null, + filename: metadata.filename || null, + filesize: metadata.filesize || null, + width: metadata.additional?.resolution?.width || null, + height: metadata.additional?.resolution?.height || null, + fileSize: metadata.filesize || null, + fileName: metadata.filename || null, }); } catch (err: unknown) { res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology'}); From cf968969d0d4d5c91185453bfa3903b5c9f61973 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 02:54:35 +0200 Subject: [PATCH 009/117] refactor(memories): generalize photo providers and decouple from immich --- client/src/api/authUrl.ts | 2 +- client/src/components/Admin/AddonManager.tsx | 133 +++++++-- .../src/components/Memories/MemoriesPanel.tsx | 195 +++++++++--- client/src/pages/SettingsPage.tsx | 279 +++++++++++++----- client/src/pages/TripPlannerPage.tsx | 4 +- client/src/store/addonStore.ts | 16 + server/src/db/migrations.ts | 114 +++++++ server/src/db/schema.ts | 25 ++ server/src/db/seeds.ts | 28 ++ server/src/index.ts | 69 ++++- server/src/routes/admin.ts | 7 +- server/src/routes/immich.ts | 2 - server/src/routes/memories.ts | 182 ++++++++++++ 13 files changed, 901 insertions(+), 155 deletions(-) create mode 100644 server/src/routes/memories.ts diff --git a/client/src/api/authUrl.ts b/client/src/api/authUrl.ts index 203ceb3..ed92729 100644 --- a/client/src/api/authUrl.ts +++ b/client/src/api/authUrl.ts @@ -1,4 +1,4 @@ -export async function getAuthUrl(url: string, purpose: 'download' | 'immich'): Promise { +export async function getAuthUrl(url: string, purpose: string): Promise { if (!url) return url try { const resp = await fetch('/api/auth/resource-token', { diff --git a/client/src/components/Admin/AddonManager.tsx b/client/src/components/Admin/AddonManager.tsx index 3050258..b45f9f0 100644 --- a/client/src/components/Admin/AddonManager.tsx +++ b/client/src/components/Admin/AddonManager.tsx @@ -15,7 +15,17 @@ interface Addon { name: string description: string icon: string + type: string enabled: boolean + config?: Record +} + +interface ProviderOption { + key: string + label: string + description: string + enabled: boolean + toggle: () => Promise } interface AddonIconProps { @@ -34,7 +44,7 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking } const dark = dm === true || dm === 'dark' || (dm === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) const toast = useToast() const refreshGlobalAddons = useAddonStore(s => s.loadAddons) - const [addons, setAddons] = useState([]) + const [addons, setAddons] = useState([]) const [loading, setLoading] = useState(true) useEffect(() => { @@ -53,7 +63,7 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking } } } - const handleToggle = async (addon) => { + const handleToggle = async (addon: Addon) => { const newEnabled = !addon.enabled // Optimistic update setAddons(prev => prev.map(a => a.id === addon.id ? { ...a, enabled: newEnabled } : a)) @@ -68,9 +78,44 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking } } } + const isPhotoProviderAddon = (addon: Addon) => { + return addon.type === 'photo_provider' + } + + const isPhotosAddon = (addon: Addon) => { + const haystack = `${addon.id} ${addon.name} ${addon.description}`.toLowerCase() + return addon.type === 'trip' && (addon.icon === 'Image' || haystack.includes('photo') || haystack.includes('memories')) + } + + const handleTogglePhotoProvider = async (providerAddon: Addon) => { + const enableProvider = !providerAddon.enabled + const prev = addons + + setAddons(current => current.map(a => a.id === providerAddon.id ? { ...a, enabled: enableProvider } : a)) + + try { + await adminApi.updateAddon(providerAddon.id, { enabled: enableProvider }) + refreshGlobalAddons() + toast.success(t('admin.addons.toast.updated')) + } catch { + setAddons(prev) + toast.error(t('admin.addons.toast.error')) + } + } + const tripAddons = addons.filter(a => a.type === 'trip') const globalAddons = addons.filter(a => a.type === 'global') + const photoProviderAddons = addons.filter(isPhotoProviderAddon) const integrationAddons = addons.filter(a => a.type === 'integration') + const photosAddon = tripAddons.find(isPhotosAddon) + const providerOptions: ProviderOption[] = photoProviderAddons.map((provider) => ({ + key: provider.id, + label: provider.name, + description: provider.description, + enabled: provider.enabled, + toggle: () => handleTogglePhotoProvider(provider), + })) + const photosDerivedEnabled = providerOptions.some(p => p.enabled) if (loading) { return ( @@ -108,7 +153,42 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking }
{tripAddons.map(addon => (
- + + {photosAddon && addon.id === photosAddon.id && providerOptions.length > 0 && ( +
+
+ {providerOptions.map(provider => ( +
+
+
{provider.label}
+
{provider.description}
+
+
+ + {provider.enabled ? t('admin.addons.enabled') : t('admin.addons.disabled')} + + +
+
+ ))} +
+
+ )} {addon.id === 'packing' && addon.enabled && onToggleBagTracking && (
@@ -171,8 +251,10 @@ export default function AddonManager({ bagTrackingEnabled, onToggleBagTracking } interface AddonRowProps { addon: Addon - onToggle: (addonId: string) => void + onToggle: (addon: Addon) => void t: (key: string) => string + statusOverride?: boolean + hideToggle?: boolean } function getAddonLabel(t: (key: string) => string, addon: Addon): { name: string; description: string } { @@ -187,9 +269,12 @@ function getAddonLabel(t: (key: string) => string, addon: Addon): { name: string } } -function AddonRow({ addon, onToggle, t }: AddonRowProps) { +function AddonRow({ addon, onToggle, t, nameOverride, descriptionOverride, statusOverride, hideToggle }: AddonRowProps & { nameOverride?: string; descriptionOverride?: string }) { const isComingSoon = false const label = getAddonLabel(t, addon) + const displayName = nameOverride || label.name + const displayDescription = descriptionOverride || label.description + const enabledState = statusOverride ?? addon.enabled return (
{/* Icon */} @@ -200,7 +285,7 @@ function AddonRow({ addon, onToggle, t }: AddonRowProps) { {/* Info */}
- {label.name} + {displayName} {isComingSoon && ( Coming Soon @@ -210,28 +295,30 @@ function AddonRow({ addon, onToggle, t }: AddonRowProps) { {addon.type === 'global' ? t('admin.addons.type.global') : addon.type === 'integration' ? t('admin.addons.type.integration') : t('admin.addons.type.trip')}
-

{label.description}

+

{displayDescription}

{/* Toggle */}
- - {isComingSoon ? t('admin.addons.disabled') : addon.enabled ? t('admin.addons.enabled') : t('admin.addons.disabled')} + + {isComingSoon ? t('admin.addons.disabled') : enabledState ? t('admin.addons.enabled') : t('admin.addons.disabled')} - + {!hideToggle && ( + + )}
) diff --git a/client/src/components/Memories/MemoriesPanel.tsx b/client/src/components/Memories/MemoriesPanel.tsx index 9dd1ed4..b288487 100644 --- a/client/src/components/Memories/MemoriesPanel.tsx +++ b/client/src/components/Memories/MemoriesPanel.tsx @@ -1,27 +1,36 @@ import { useState, useEffect, useCallback } from 'react' import { Camera, Plus, Share2, EyeOff, Eye, X, Check, Search, ArrowUpDown, MapPin, Filter, Link2, RefreshCw, Unlink, FolderOpen } from 'lucide-react' -import apiClient from '../../api/client' +import apiClient, { addonsApi } from '../../api/client' import { useAuthStore } from '../../store/authStore' import { useTranslation } from '../../i18n' import { getAuthUrl } from '../../api/authUrl' import { useToast } from '../shared/Toast' -function ImmichImg({ baseUrl, style, loading }: { baseUrl: string; style?: React.CSSProperties; loading?: 'lazy' | 'eager' }) { +interface PhotoProvider { + id: string + name: string + icon?: string + config?: Record +} + +function ProviderImg({ baseUrl, provider, style, loading }: { baseUrl: string; provider: string; style?: React.CSSProperties; loading?: 'lazy' | 'eager' }) { const [src, setSrc] = useState('') useEffect(() => { - getAuthUrl(baseUrl, 'immich').then(setSrc) - }, [baseUrl]) + getAuthUrl(baseUrl, provider).then(setSrc).catch(() => {}) + }, [baseUrl, provider]) return src ? : null } // ── Types ─────────────────────────────────────────────────────────────────── interface TripPhoto { - immich_asset_id: string + asset_id: string + provider: string user_id: number username: string shared: number added_at: string + city?: string | null } interface ImmichAsset { @@ -45,6 +54,8 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const currentUser = useAuthStore(s => s.user) const [connected, setConnected] = useState(false) + const [availableProviders, setAvailableProviders] = useState([]) + const [selectedProvider, setSelectedProvider] = useState('') const [loading, setLoading] = useState(true) // Trip photos (saved selections) @@ -67,49 +78,61 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const [showAlbumPicker, setShowAlbumPicker] = useState(false) const [albums, setAlbums] = useState<{ id: string; albumName: string; assetCount: number }[]>([]) const [albumsLoading, setAlbumsLoading] = useState(false) - const [albumLinks, setAlbumLinks] = useState<{ id: number; immich_album_id: string; album_name: string; user_id: number; username: string; sync_enabled: number; last_synced_at: string | null }[]>([]) + const [albumLinks, setAlbumLinks] = useState<{ id: number; provider: string; album_id: string; album_name: string; user_id: number; username: string; sync_enabled: number; last_synced_at: string | null }[]>([]) const [syncing, setSyncing] = useState(null) + const pickerIntegrationBase = selectedProvider ? `/integrations/${selectedProvider}` : '' const loadAlbumLinks = async () => { try { - const res = await apiClient.get(`/integrations/immich/trips/${tripId}/album-links`) + const res = await apiClient.get(`/integrations/memories/trips/${tripId}/album-links`) setAlbumLinks(res.data.links || []) } catch { setAlbumLinks([]) } } - const openAlbumPicker = async () => { - setShowAlbumPicker(true) + const loadAlbums = async (provider: string = selectedProvider) => { + if (!provider) return setAlbumsLoading(true) try { - const res = await apiClient.get('/integrations/immich/albums') + const res = await apiClient.get(`/integrations/${provider}/albums`) setAlbums(res.data.albums || []) - } catch { setAlbums([]); toast.error(t('memories.error.loadAlbums')) } - finally { setAlbumsLoading(false) } + } catch { + setAlbums([]) + toast.error(t('memories.error.loadAlbums')) + } finally { + setAlbumsLoading(false) + } + } + + const openAlbumPicker = async () => { + setShowAlbumPicker(true) + await loadAlbums(selectedProvider) } const linkAlbum = async (albumId: string, albumName: string) => { try { - await apiClient.post(`/integrations/immich/trips/${tripId}/album-links`, { album_id: albumId, album_name: albumName }) + await apiClient.post(`${pickerIntegrationBase}/trips/${tripId}/album-links`, { album_id: albumId, album_name: albumName }) setShowAlbumPicker(false) await loadAlbumLinks() // Auto-sync after linking - const linksRes = await apiClient.get(`/integrations/immich/trips/${tripId}/album-links`) - const newLink = (linksRes.data.links || []).find((l: any) => l.immich_album_id === albumId) + const linksRes = await apiClient.get(`/integrations/memories/trips/${tripId}/album-links`) + const newLink = (linksRes.data.links || []).find((l: any) => l.album_id === albumId && l.provider === selectedProvider) if (newLink) await syncAlbum(newLink.id) } catch { toast.error(t('memories.error.linkAlbum')) } } const unlinkAlbum = async (linkId: number) => { try { - await apiClient.delete(`/integrations/immich/trips/${tripId}/album-links/${linkId}`) + await apiClient.delete(`/integrations/memories/trips/${tripId}/album-links/${linkId}`) loadAlbumLinks() } catch { toast.error(t('memories.error.unlinkAlbum')) } } - const syncAlbum = async (linkId: number) => { + const syncAlbum = async (linkId: number, provider?: string) => { + const targetProvider = provider || selectedProvider + if (!targetProvider) return setSyncing(linkId) try { - await apiClient.post(`/integrations/immich/trips/${tripId}/album-links/${linkId}/sync`) + await apiClient.post(`/integrations/${targetProvider}/trips/${tripId}/album-links/${linkId}/sync`) await loadAlbumLinks() await loadPhotos() } catch { toast.error(t('memories.error.syncAlbum')) } @@ -138,7 +161,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const loadPhotos = async () => { try { - const photosRes = await apiClient.get(`/integrations/immich/trips/${tripId}/photos`) + const photosRes = await apiClient.get(`/integrations/memories/trips/${tripId}/photos`) setTripPhotos(photosRes.data.photos || []) } catch { setTripPhotos([]) @@ -148,9 +171,35 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const loadInitial = async () => { setLoading(true) try { - const statusRes = await apiClient.get('/integrations/immich/status') - setConnected(statusRes.data.connected) + const addonsRes = await addonsApi.enabled().catch(() => ({ addons: [] as any[] })) + const enabledAddons = addonsRes?.addons || [] + const photoProviders = enabledAddons.filter((a: any) => a.type === 'photo_provider' && a.enabled) + + // Test connection status for each enabled provider + const statusResults = await Promise.all( + photoProviders.map(async (provider: any) => { + const statusUrl = (provider.config as Record)?.status_get as string + if (!statusUrl) return { provider, connected: false } + try { + const res = await apiClient.get(statusUrl) + return { provider, connected: !!res.data?.connected } + } catch { + return { provider, connected: false } + } + }) + ) + + const connectedProviders = statusResults + .filter(r => r.connected) + .map(r => ({ id: r.provider.id, name: r.provider.name, icon: r.provider.icon, config: r.provider.config })) + + setAvailableProviders(connectedProviders) + setConnected(connectedProviders.length > 0) + if (connectedProviders.length > 0 && !selectedProvider) { + setSelectedProvider(connectedProviders[0].id) + } } catch { + setAvailableProviders([]) setConnected(false) } await loadPhotos() @@ -170,10 +219,26 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa await loadPickerPhotos(!!(startDate && endDate)) } + useEffect(() => { + if (showPicker) { + loadPickerPhotos(pickerDateFilter) + } + }, [selectedProvider]) + + useEffect(() => { + loadAlbumLinks() + }, [tripId]) + + useEffect(() => { + if (showAlbumPicker) { + loadAlbums(selectedProvider) + } + }, [showAlbumPicker, selectedProvider, tripId]) + const loadPickerPhotos = async (useDate: boolean) => { setPickerLoading(true) try { - const res = await apiClient.post('/integrations/immich/search', { + const res = await apiClient.post(`${pickerIntegrationBase}/search`, { from: useDate && startDate ? startDate : undefined, to: useDate && endDate ? endDate : undefined, }) @@ -203,7 +268,8 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const executeAddPhotos = async () => { setShowConfirmShare(false) try { - await apiClient.post(`/integrations/immich/trips/${tripId}/photos`, { + await apiClient.post(`/integrations/memories/trips/${tripId}/photos`, { + provider: selectedProvider, asset_ids: [...selectedIds], shared: true, }) @@ -214,28 +280,37 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa // ── Remove photo ────────────────────────────────────────────────────────── - const removePhoto = async (assetId: string) => { + const removePhoto = async (photo: TripPhoto) => { try { - await apiClient.delete(`/integrations/immich/trips/${tripId}/photos/${assetId}`) - setTripPhotos(prev => prev.filter(p => p.immich_asset_id !== assetId)) + await apiClient.delete(`/integrations/memories/trips/${tripId}/photos`, { + data: { + asset_id: photo.asset_id, + provider: photo.provider, + }, + }) + setTripPhotos(prev => prev.filter(p => !(p.provider === photo.provider && p.asset_id === photo.asset_id))) } catch { toast.error(t('memories.error.removePhoto')) } } // ── Toggle sharing ──────────────────────────────────────────────────────── - const toggleSharing = async (assetId: string, shared: boolean) => { + const toggleSharing = async (photo: TripPhoto, shared: boolean) => { try { - await apiClient.put(`/integrations/immich/trips/${tripId}/photos/${assetId}/sharing`, { shared }) + await apiClient.put(`/integrations/memories/trips/${tripId}/photos/sharing`, { + shared, + asset_id: photo.asset_id, + provider: photo.provider, + }) setTripPhotos(prev => prev.map(p => - p.immich_asset_id === assetId ? { ...p, shared: shared ? 1 : 0 } : p + p.provider === photo.provider && p.asset_id === photo.asset_id ? { ...p, shared: shared ? 1 : 0 } : p )) } catch { toast.error(t('memories.error.toggleSharing')) } } // ── Helpers ─────────────────────────────────────────────────────────────── - const thumbnailBaseUrl = (assetId: string, userId: number) => - `/api/integrations/immich/assets/${assetId}/thumbnail?userId=${userId}` + const thumbnailBaseUrl = (photo: TripPhoto) => + `/api/integrations/${photo.provider}/assets/${photo.asset_id}/thumbnail?userId=${photo.user_id}` const ownPhotos = tripPhotos.filter(p => p.user_id === currentUser?.id) const othersPhotos = tripPhotos.filter(p => p.user_id !== currentUser?.id && p.shared) @@ -286,10 +361,40 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa // ── Photo Picker Modal ──────────────────────────────────────────────────── + const ProviderTabs = () => { + if (availableProviders.length < 2) return null + return ( +
+ {availableProviders.map(provider => ( + + ))} +
+ ) + } + // ── Album Picker Modal ────────────────────────────────────────────────── if (showAlbumPicker) { - const linkedIds = new Set(albumLinks.map(l => l.immich_album_id)) + const linkedIds = new Set(albumLinks.map(l => l.album_id)) return (
@@ -297,6 +402,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa

{t('memories.selectAlbum')}

+ @@ -630,18 +741,18 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa {allVisible.map(photo => { const isOwn = photo.user_id === currentUser?.id return ( -
{ - setLightboxId(photo.immich_asset_id); setLightboxUserId(photo.user_id); setLightboxInfo(null) + setLightboxId(photo.asset_id); setLightboxUserId(photo.user_id); setLightboxInfo(null) setLightboxOriginalSrc('') - getAuthUrl(`/api/integrations/immich/assets/${photo.immich_asset_id}/original?userId=${photo.user_id}`, 'immich').then(setLightboxOriginalSrc) + getAuthUrl(`/api/integrations/${photo.provider}/assets/${photo.asset_id}/original?userId=${photo.user_id}`, photo.provider).then(setLightboxOriginalSrc).catch(() => {}) setLightboxInfoLoading(true) - apiClient.get(`/integrations/immich/assets/${photo.immich_asset_id}/info?userId=${photo.user_id}`) + apiClient.get(`/integrations/${photo.provider}/assets/${photo.asset_id}/info?userId=${photo.user_id}`) .then(r => setLightboxInfo(r.data)).catch(() => {}).finally(() => setLightboxInfoLoading(false)) }}> - {/* Other user's avatar */} @@ -672,7 +783,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa {isOwn && (
- - + + {connected && ( + + + {t('memories.connected')} + + )} +
+
+ + ) + } + // Map settings const [mapTileUrl, setMapTileUrl] = useState(settings.map_tile_url || '') const [defaultLat, setDefaultLat] = useState(settings.default_lat || 48.8566) @@ -673,45 +832,7 @@ export default function SettingsPage(): React.ReactElement { - {/* Immich — only when Memories addon is enabled */} - {memoriesEnabled && ( -
-
-
- - { setImmichUrl(e.target.value); setImmichTestPassed(false) }} - placeholder="https://immich.example.com" - className="w-full px-3 py-2.5 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-300" /> -
-
- - { setImmichApiKey(e.target.value); setImmichTestPassed(false) }} - placeholder={immichConnected ? '••••••••' : 'API Key'} - className="w-full px-3 py-2.5 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-300" /> -
-
- - - {immichConnected && ( - - - {t('memories.connected')} - - )} -
-
-
- )} + {activePhotoProviders.map(provider => renderPhotoProviderSection(provider as PhotoProviderAddon))} {/* MCP Configuration — only when MCP addon is enabled */} {mcpEnabled &&
diff --git a/client/src/pages/TripPlannerPage.tsx b/client/src/pages/TripPlannerPage.tsx index 47918bd..256714a 100644 --- a/client/src/pages/TripPlannerPage.tsx +++ b/client/src/pages/TripPlannerPage.tsx @@ -78,7 +78,9 @@ export default function TripPlannerPage(): React.ReactElement | null { addonsApi.enabled().then(data => { const map = {} data.addons.forEach(a => { map[a.id] = true }) - setEnabledAddons({ packing: !!map.packing, budget: !!map.budget, documents: !!map.documents, collab: !!map.collab, memories: !!map.memories }) + // Check if any photo provider is enabled (for memories tab to show) + const hasPhotoProviders = data.addons.some(a => a.type === 'photo_provider' && a.enabled) + setEnabledAddons({ packing: !!map.packing, budget: !!map.budget, documents: !!map.documents, collab: !!map.collab, memories: !!map.memories || hasPhotoProviders }) }).catch(() => {}) authApi.getAppConfig().then(config => { if (config.allowed_file_types) setAllowedFileTypes(config.allowed_file_types) diff --git a/client/src/store/addonStore.ts b/client/src/store/addonStore.ts index d0fce97..8ef6798 100644 --- a/client/src/store/addonStore.ts +++ b/client/src/store/addonStore.ts @@ -4,9 +4,22 @@ import { addonsApi } from '../api/client' interface Addon { id: string name: string + description?: string type: string icon: string enabled: boolean + config?: Record + fields?: Array<{ + key: string + label: string + input_type: string + placeholder?: string | null + required: boolean + secret: boolean + settings_key?: string | null + payload_key?: string | null + sort_order: number + }> } interface AddonState { @@ -30,6 +43,9 @@ export const useAddonStore = create((set, get) => ({ }, isEnabled: (id: string) => { + if (id === 'memories') { + return get().addons.some(a => a.type === 'photo_provider' && a.enabled) + } return get().addons.some(a => a.id === id && a.enabled) }, })) diff --git a/server/src/db/migrations.ts b/server/src/db/migrations.ts index c2f1271..8e01979 100644 --- a/server/src/db/migrations.ts +++ b/server/src/db/migrations.ts @@ -518,6 +518,120 @@ function runMigrations(db: Database.Database): void { CREATE INDEX IF NOT EXISTS idx_notifications_recipient_created ON notifications(recipient_id, created_at DESC); `); }, + () => { + // Normalize trip_photos to provider-based schema used by current routes + const tripPhotosExists = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'trip_photos'").get(); + if (!tripPhotosExists) { + db.exec(` + CREATE TABLE trip_photos ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + asset_id TEXT NOT NULL, + provider TEXT NOT NULL DEFAULT 'immich', + shared INTEGER NOT NULL DEFAULT 1, + added_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(trip_id, user_id, asset_id, provider) + ); + CREATE INDEX IF NOT EXISTS idx_trip_photos_trip ON trip_photos(trip_id); + `); + } else { + const columns = db.prepare("PRAGMA table_info('trip_photos')").all() as Array<{ name: string }>; + const names = new Set(columns.map(c => c.name)); + const assetSource = names.has('asset_id') ? 'asset_id' : (names.has('immich_asset_id') ? 'immich_asset_id' : null); + if (assetSource) { + const providerExpr = names.has('provider') + ? "CASE WHEN provider IS NULL OR provider = '' THEN 'immich' ELSE provider END" + : "'immich'"; + const sharedExpr = names.has('shared') ? 'COALESCE(shared, 1)' : '1'; + const addedAtExpr = names.has('added_at') ? 'COALESCE(added_at, CURRENT_TIMESTAMP)' : 'CURRENT_TIMESTAMP'; + + db.exec(` + CREATE TABLE trip_photos_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + asset_id TEXT NOT NULL, + provider TEXT NOT NULL DEFAULT 'immich', + shared INTEGER NOT NULL DEFAULT 1, + added_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(trip_id, user_id, asset_id, provider) + ); + `); + + db.exec(` + INSERT OR IGNORE INTO trip_photos_new (trip_id, user_id, asset_id, provider, shared, added_at) + SELECT trip_id, user_id, ${assetSource}, ${providerExpr}, ${sharedExpr}, ${addedAtExpr} + FROM trip_photos + WHERE ${assetSource} IS NOT NULL AND TRIM(${assetSource}) != '' + `); + + db.exec('DROP TABLE trip_photos'); + db.exec('ALTER TABLE trip_photos_new RENAME TO trip_photos'); + db.exec('CREATE INDEX IF NOT EXISTS idx_trip_photos_trip ON trip_photos(trip_id)'); + } + } + }, + () => { + // Normalize trip_album_links to provider + album_id schema used by current routes + const linksExists = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'trip_album_links'").get(); + if (!linksExists) { + db.exec(` + CREATE TABLE trip_album_links ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + provider TEXT NOT NULL, + album_id TEXT NOT NULL, + album_name TEXT NOT NULL DEFAULT '', + sync_enabled INTEGER NOT NULL DEFAULT 1, + last_synced_at DATETIME, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(trip_id, user_id, provider, album_id) + ); + CREATE INDEX IF NOT EXISTS idx_trip_album_links_trip ON trip_album_links(trip_id); + `); + } else { + const columns = db.prepare("PRAGMA table_info('trip_album_links')").all() as Array<{ name: string }>; + const names = new Set(columns.map(c => c.name)); + const albumIdSource = names.has('album_id') ? 'album_id' : (names.has('immich_album_id') ? 'immich_album_id' : null); + if (albumIdSource) { + const providerExpr = names.has('provider') + ? "CASE WHEN provider IS NULL OR provider = '' THEN 'immich' ELSE provider END" + : "'immich'"; + const albumNameExpr = names.has('album_name') ? "COALESCE(album_name, '')" : "''"; + const syncEnabledExpr = names.has('sync_enabled') ? 'COALESCE(sync_enabled, 1)' : '1'; + const lastSyncedExpr = names.has('last_synced_at') ? 'last_synced_at' : 'NULL'; + const createdAtExpr = names.has('created_at') ? 'COALESCE(created_at, CURRENT_TIMESTAMP)' : 'CURRENT_TIMESTAMP'; + + db.exec(` + CREATE TABLE trip_album_links_new ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, + user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE, + provider TEXT NOT NULL, + album_id TEXT NOT NULL, + album_name TEXT NOT NULL DEFAULT '', + sync_enabled INTEGER NOT NULL DEFAULT 1, + last_synced_at DATETIME, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE(trip_id, user_id, provider, album_id) + ); + `); + + db.exec(` + INSERT OR IGNORE INTO trip_album_links_new (trip_id, user_id, provider, album_id, album_name, sync_enabled, last_synced_at, created_at) + SELECT trip_id, user_id, ${providerExpr}, ${albumIdSource}, ${albumNameExpr}, ${syncEnabledExpr}, ${lastSyncedExpr}, ${createdAtExpr} + FROM trip_album_links + WHERE ${albumIdSource} IS NOT NULL AND TRIM(${albumIdSource}) != '' + `); + + db.exec('DROP TABLE trip_album_links'); + db.exec('ALTER TABLE trip_album_links_new RENAME TO trip_album_links'); + db.exec('CREATE INDEX IF NOT EXISTS idx_trip_album_links_trip ON trip_album_links(trip_id)'); + } + } + }, ]; if (currentVersion < migrations.length) { diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index 8506253..8fe5739 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -222,6 +222,31 @@ function createTables(db: Database.Database): void { sort_order INTEGER DEFAULT 0 ); + CREATE TABLE IF NOT EXISTS photo_providers ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + description TEXT, + icon TEXT DEFAULT 'Image', + enabled INTEGER DEFAULT 0, + config TEXT DEFAULT '{}', + sort_order INTEGER DEFAULT 0 + ); + + CREATE TABLE IF NOT EXISTS photo_provider_fields ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + provider_id TEXT NOT NULL REFERENCES photo_providers(id) ON DELETE CASCADE, + field_key TEXT NOT NULL, + label TEXT NOT NULL, + input_type TEXT NOT NULL DEFAULT 'text', + placeholder TEXT, + required INTEGER DEFAULT 0, + secret INTEGER DEFAULT 0, + settings_key TEXT, + payload_key TEXT, + sort_order INTEGER DEFAULT 0, + UNIQUE(provider_id, field_key) + ); + -- Vacay addon tables CREATE TABLE IF NOT EXISTS vacay_plans ( id INTEGER PRIMARY KEY AUTOINCREMENT, diff --git a/server/src/db/seeds.ts b/server/src/db/seeds.ts index 8e0d9c6..f875794 100644 --- a/server/src/db/seeds.ts +++ b/server/src/db/seeds.ts @@ -92,6 +92,34 @@ function seedAddons(db: Database.Database): void { ]; const insertAddon = db.prepare('INSERT OR IGNORE INTO addons (id, name, description, type, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)'); for (const a of defaultAddons) insertAddon.run(a.id, a.name, a.description, a.type, a.icon, a.enabled, a.sort_order); + + const providerRows = [ + { + id: 'immich', + name: 'Immich', + description: 'Immich photo provider', + icon: 'Image', + enabled: 0, + sort_order: 0, + config: JSON.stringify({ + settings_get: '/integrations/immich/settings', + settings_put: '/integrations/immich/settings', + status_get: '/integrations/immich/status', + test_post: '/integrations/immich/test', + }), + }, + ]; + const insertProvider = db.prepare('INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, config, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)'); + for (const p of providerRows) insertProvider.run(p.id, p.name, p.description, p.icon, p.enabled, p.config, p.sort_order); + + const providerFields = [ + { provider_id: 'immich', field_key: 'immich_url', label: 'Immich URL', input_type: 'url', placeholder: 'https://immich.example.com', required: 1, secret: 0, settings_key: 'immich_url', payload_key: 'immich_url', sort_order: 0 }, + { provider_id: 'immich', field_key: 'immich_api_key', label: 'API Key', input_type: 'password', placeholder: 'API Key', required: 1, secret: 1, settings_key: null, payload_key: 'immich_api_key', sort_order: 1 }, + ]; + const insertProviderField = db.prepare('INSERT OR IGNORE INTO photo_provider_fields (provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); + for (const f of providerFields) { + insertProviderField.run(f.provider_id, f.field_key, f.label, f.input_type, f.placeholder, f.required, f.secret, f.settings_key, f.payload_key, f.sort_order); + } console.log('Default addons seeded'); } catch (err: unknown) { console.error('Error seeding addons:', err instanceof Error ? err.message : err); diff --git a/server/src/index.ts b/server/src/index.ts index 5508542..533d92c 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -207,8 +207,71 @@ import { authenticate as addonAuth } from './middleware/auth'; import {db as addonDb} from './db/database'; import { Addon } from './types'; app.get('/api/addons', addonAuth, (req: Request, res: Response) => { - const addons = addonDb.prepare('SELECT id, name, type, icon, enabled FROM addons WHERE enabled = 1 ORDER BY sort_order').all() as Pick[]; - res.json({ addons: addons.map(a => ({ ...a, enabled: !!a.enabled })) }); + const addons = addonDb.prepare('SELECT id, name, type, icon, enabled, config, sort_order FROM addons WHERE enabled = 1 ORDER BY sort_order').all() as Array & { sort_order: number }>; + const photoProviders = addonDb.prepare(` + SELECT id, name, description, icon, enabled, config, sort_order + FROM photo_providers + WHERE enabled = 1 + ORDER BY sort_order + `).all() as Array<{ id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number }>; + const providerIds = photoProviders.map(p => p.id); + const providerFields = providerIds.length > 0 + ? addonDb.prepare(` + SELECT provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order + FROM photo_provider_fields + WHERE provider_id IN (${providerIds.map(() => '?').join(',')}) + ORDER BY sort_order, id + `).all(...providerIds) as Array<{ + provider_id: string; + field_key: string; + label: string; + input_type: string; + placeholder?: string | null; + required: number; + secret: number; + settings_key?: string | null; + payload_key?: string | null; + sort_order: number; + }> + : []; + const fieldsByProvider = new Map(); + for (const field of providerFields) { + const arr = fieldsByProvider.get(field.provider_id) || []; + arr.push(field); + fieldsByProvider.set(field.provider_id, arr); + } + + const combined = [ + ...addons, + ...photoProviders.map(p => ({ + id: p.id, + name: p.name, + type: 'photo_provider', + icon: p.icon, + enabled: p.enabled, + config: p.config, + fields: (fieldsByProvider.get(p.id) || []).map(f => ({ + key: f.field_key, + label: f.label, + input_type: f.input_type, + placeholder: f.placeholder || '', + required: !!f.required, + secret: !!f.secret, + settings_key: f.settings_key || null, + payload_key: f.payload_key || null, + sort_order: f.sort_order, + })), + sort_order: p.sort_order, + })), + ].sort((a, b) => a.sort_order - b.sort_order || a.id.localeCompare(b.id)); + + res.json({ + addons: combined.map(a => ({ + ...a, + enabled: !!a.enabled, + config: JSON.parse(a.config || '{}'), + })), + }); }); // Addon routes @@ -218,6 +281,8 @@ import atlasRoutes from './routes/atlas'; app.use('/api/addons/atlas', atlasRoutes); import immichRoutes from './routes/immich'; app.use('/api/integrations/immich', immichRoutes); +import memoriesRoutes from './routes/memories'; +app.use('/api/integrations/memories', memoriesRoutes); app.use('/api/maps', mapsRoutes); app.use('/api/weather', weatherRoutes); diff --git a/server/src/routes/admin.ts b/server/src/routes/admin.ts index 56a9136..ac5a4f3 100644 --- a/server/src/routes/admin.ts +++ b/server/src/routes/admin.ts @@ -300,12 +300,9 @@ router.post('/rotate-jwt-secret', (req: Request, res: Response) => { if (result.error) return res.status(result.status!).json({ error: result.error }); const authReq = req as AuthRequest; writeAudit({ - user_id: authReq.user?.id ?? null, - username: authReq.user?.username ?? 'unknown', + userId: authReq.user?.id ?? null, action: 'admin.rotate_jwt_secret', - target_type: 'system', - target_id: null, - details: null, + resource: 'system', ip: getClientIp(req), }); res.json({ success: true }); diff --git a/server/src/routes/immich.ts b/server/src/routes/immich.ts index 198b6e8..12adbee 100644 --- a/server/src/routes/immich.ts +++ b/server/src/routes/immich.ts @@ -30,7 +30,6 @@ import { const router = express.Router(); // ── Dual auth middleware (JWT or ephemeral token for src) ───────────── - function authFromQuery(req: Request, res: Response, next: NextFunction) { const queryToken = req.query.token as string | undefined; if (queryToken) { @@ -186,7 +185,6 @@ router.get('/trips/:tripId/album-links', authenticate, (req: Request, res: Respo if (!canAccessTrip(req.params.tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); res.json({ links: listAlbumLinks(req.params.tripId) }); }); - router.post('/trips/:tripId/album-links', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; diff --git a/server/src/routes/memories.ts b/server/src/routes/memories.ts new file mode 100644 index 0000000..d84925d --- /dev/null +++ b/server/src/routes/memories.ts @@ -0,0 +1,182 @@ +import express, { Request, Response } from 'express'; +import { db, canAccessTrip } from '../db/database'; +import { authenticate } from '../middleware/auth'; +import { broadcast } from '../websocket'; +import { AuthRequest } from '../types'; + +const router = express.Router(); + + +router.get('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + + if (!canAccessTrip(tripId, authReq.user.id)) { + return res.status(404).json({ error: 'Trip not found' }); + } + + const photos = db.prepare(` + SELECT tp.asset_id, tp.provider, tp.user_id, tp.shared, tp.added_at, + u.username, u.avatar + FROM trip_photos tp + JOIN users u ON tp.user_id = u.id + WHERE tp.trip_id = ? + AND (tp.user_id = ? OR tp.shared = 1) + ORDER BY tp.added_at ASC + `).all(tripId, authReq.user.id) as any[]; + + res.json({ photos }); +}); + +router.get('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + + if (!canAccessTrip(tripId, authReq.user.id)) { + return res.status(404).json({ error: 'Trip not found' }); + } + + const links = 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 = ? + ORDER BY tal.created_at ASC + `).all(tripId); + + res.json({ links }); +}); + +router.delete('/trips/:tripId/album-links/:linkId', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId, linkId } = req.params; + + if (!canAccessTrip(tripId, authReq.user.id)) { + return res.status(404).json({ error: 'Trip not found' }); + } + + db.prepare('DELETE FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') + .run(linkId, tripId, authReq.user.id); + + res.json({ success: true }); + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); +}); + +router.post('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + const provider = String(req.body?.provider || '').toLowerCase(); + const { shared = true } = req.body; + const assetIdsRaw = req.body?.asset_ids; + + if (!canAccessTrip(tripId, authReq.user.id)) { + return res.status(404).json({ error: 'Trip not found' }); + } + + if (!provider) { + return res.status(400).json({ error: 'provider is required' }); + } + + if (!Array.isArray(assetIdsRaw) || assetIdsRaw.length === 0) { + return res.status(400).json({ error: 'asset_ids required' }); + } + + const insert = db.prepare( + 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, ?, ?)' + ); + + let added = 0; + for (const raw of assetIdsRaw) { + const assetId = String(raw || '').trim(); + if (!assetId) continue; + const result = insert.run(tripId, authReq.user.id, assetId, provider, shared ? 1 : 0); + if (result.changes > 0) added++; + } + + res.json({ success: true, added }); + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); + + if (shared && added > 0) { + import('../services/notifications').then(({ notifyTripMembers }) => { + const tripInfo = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; + notifyTripMembers(Number(tripId), authReq.user.id, 'photos_shared', { + trip: tripInfo?.title || 'Untitled', + actor: authReq.user.username || authReq.user.email, + count: String(added), + }).catch(() => {}); + }); + } +}); + +router.delete('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + const provider = String(req.body?.provider || '').toLowerCase(); + const assetId = String(req.body?.asset_id || ''); + + if (!assetId) { + return res.status(400).json({ error: 'asset_id is required' }); + } + + if (!provider) { + return res.status(400).json({ error: 'provider is required' }); + } + + if (!canAccessTrip(tripId, authReq.user.id)) { + return res.status(404).json({ error: 'Trip not found' }); + } + + db.prepare(` + DELETE FROM trip_photos + WHERE trip_id = ? + AND user_id = ? + AND asset_id = ? + AND provider = ? + `).run(tripId, authReq.user.id, assetId, provider); + + res.json({ success: true }); + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); +}); + +router.put('/trips/:tripId/photos/sharing', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + const provider = String(req.body?.provider || '').toLowerCase(); + const assetId = String(req.body?.asset_id || ''); + const { shared } = req.body; + + if (!assetId) { + return res.status(400).json({ error: 'asset_id is required' }); + } + + if (!provider) { + return res.status(400).json({ error: 'provider is required' }); + } + + if (!canAccessTrip(tripId, authReq.user.id)) { + return res.status(404).json({ error: 'Trip not found' }); + } + + db.prepare(` + UPDATE trip_photos + SET shared = ? + WHERE trip_id = ? + AND user_id = ? + AND asset_id = ? + AND provider = ? + `).run(shared ? 1 : 0, tripId, authReq.user.id, assetId, provider); + + res.json({ success: true }); + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); +}); + +export default router; From 7a169d0596f30cee0a6ea017cf898e10eddc2817 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 02:58:22 +0200 Subject: [PATCH 010/117] feat(integrations): add synology photos support --- server/src/db/migrations.ts | 59 +++ server/src/db/schema.ts | 4 + server/src/db/seeds.ts | 17 + server/src/index.ts | 2 + server/src/routes/synology.ts | 610 +++++++++++++++++++++++++ server/src/services/authService.ts | 2 +- server/src/services/ephemeralTokens.ts | 1 + 7 files changed, 694 insertions(+), 1 deletion(-) create mode 100644 server/src/routes/synology.ts diff --git a/server/src/db/migrations.ts b/server/src/db/migrations.ts index 8e01979..d14d4a8 100644 --- a/server/src/db/migrations.ts +++ b/server/src/db/migrations.ts @@ -632,6 +632,65 @@ function runMigrations(db: Database.Database): void { } } }, + () => { + // Add Synology credential columns for existing databases + try { db.exec('ALTER TABLE users ADD COLUMN synology_url TEXT'); } catch (err: any) { if (!err.message?.includes('duplicate column name')) throw err; } + try { db.exec('ALTER TABLE users ADD COLUMN synology_username TEXT'); } catch (err: any) { if (!err.message?.includes('duplicate column name')) throw err; } + try { db.exec('ALTER TABLE users ADD COLUMN synology_password TEXT'); } catch (err: any) { if (!err.message?.includes('duplicate column name')) throw err; } + try { db.exec('ALTER TABLE users ADD COLUMN synology_sid TEXT'); } catch (err: any) { if (!err.message?.includes('duplicate column name')) throw err; } + }, + () => { + // Seed Synology Photos provider and fields in existing databases + try { + db.prepare(` + INSERT INTO photo_providers (id, name, description, icon, enabled, config, sort_order) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + name = excluded.name, + description = excluded.description, + icon = excluded.icon, + enabled = excluded.enabled, + config = excluded.config, + sort_order = excluded.sort_order + `).run( + 'synologyphotos', + 'Synology Photos', + 'Synology Photos integration with separate account settings', + 'Image', + 0, + JSON.stringify({ + settings_get: '/integrations/synologyphotos/settings', + settings_put: '/integrations/synologyphotos/settings', + status_get: '/integrations/synologyphotos/status', + test_get: '/integrations/synologyphotos/status', + }), + 1, + ); + } catch (err: any) { + if (!err.message?.includes('no such table')) throw err; + } + try { + const insertField = db.prepare(` + INSERT INTO photo_provider_fields + (provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(provider_id, field_key) DO UPDATE SET + label = excluded.label, + input_type = excluded.input_type, + placeholder = excluded.placeholder, + required = excluded.required, + secret = excluded.secret, + settings_key = excluded.settings_key, + payload_key = excluded.payload_key, + sort_order = excluded.sort_order + `); + insertField.run('synologyphotos', 'synology_url', 'Server URL', 'url', 'https://synology.example.com', 1, 0, 'synology_url', 'synology_url', 0); + insertField.run('synologyphotos', 'synology_username', 'Username', 'text', 'Username', 1, 0, 'synology_username', 'synology_username', 1); + insertField.run('synologyphotos', 'synology_password', 'Password', 'password', 'Password', 1, 1, null, 'synology_password', 2); + } catch (err: any) { + if (!err.message?.includes('no such table')) throw err; + } + }, ]; if (currentVersion < migrations.length) { diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index 8fe5739..9e243b6 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -18,6 +18,10 @@ function createTables(db: Database.Database): void { mfa_enabled INTEGER DEFAULT 0, mfa_secret TEXT, mfa_backup_codes TEXT, + synology_url TEXT, + synology_username TEXT, + synology_password TEXT, + synology_sid TEXT, must_change_password INTEGER DEFAULT 0, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP diff --git a/server/src/db/seeds.ts b/server/src/db/seeds.ts index f875794..8035d21 100644 --- a/server/src/db/seeds.ts +++ b/server/src/db/seeds.ts @@ -108,6 +108,20 @@ function seedAddons(db: Database.Database): void { test_post: '/integrations/immich/test', }), }, + { + id: 'synologyphotos', + name: 'Synology Photos', + description: 'Synology Photos integration with separate account settings', + icon: 'Image', + enabled: 0, + sort_order: 1, + config: JSON.stringify({ + settings_get: '/integrations/synologyphotos/settings', + settings_put: '/integrations/synologyphotos/settings', + status_get: '/integrations/synologyphotos/status', + test_get: '/integrations/synologyphotos/status', + }), + }, ]; const insertProvider = db.prepare('INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, config, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)'); for (const p of providerRows) insertProvider.run(p.id, p.name, p.description, p.icon, p.enabled, p.config, p.sort_order); @@ -115,6 +129,9 @@ function seedAddons(db: Database.Database): void { const providerFields = [ { provider_id: 'immich', field_key: 'immich_url', label: 'Immich URL', input_type: 'url', placeholder: 'https://immich.example.com', required: 1, secret: 0, settings_key: 'immich_url', payload_key: 'immich_url', sort_order: 0 }, { provider_id: 'immich', field_key: 'immich_api_key', label: 'API Key', input_type: 'password', placeholder: 'API Key', required: 1, secret: 1, settings_key: null, payload_key: 'immich_api_key', sort_order: 1 }, + { provider_id: 'synologyphotos', field_key: 'synology_url', label: 'Server URL', input_type: 'url', placeholder: 'https://synology.example.com', required: 1, secret: 0, settings_key: 'synology_url', payload_key: 'synology_url', sort_order: 0 }, + { provider_id: 'synologyphotos', field_key: 'synology_username', label: 'Username', input_type: 'text', placeholder: 'Username', required: 1, secret: 0, settings_key: 'synology_username', payload_key: 'synology_username', sort_order: 1 }, + { provider_id: 'synologyphotos', field_key: 'synology_password', label: 'Password', input_type: 'password', placeholder: 'Password', required: 1, secret: 1, settings_key: null, payload_key: 'synology_password', sort_order: 2 }, ]; const insertProviderField = db.prepare('INSERT OR IGNORE INTO photo_provider_fields (provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'); for (const f of providerFields) { diff --git a/server/src/index.ts b/server/src/index.ts index 533d92c..d1d682d 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -281,6 +281,8 @@ import atlasRoutes from './routes/atlas'; app.use('/api/addons/atlas', atlasRoutes); import immichRoutes from './routes/immich'; app.use('/api/integrations/immich', immichRoutes); +const synologyRoutes = require('./routes/synology').default; +app.use('/api/integrations/synologyphotos', synologyRoutes); import memoriesRoutes from './routes/memories'; app.use('/api/integrations/memories', memoriesRoutes); diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts new file mode 100644 index 0000000..9e98fcf --- /dev/null +++ b/server/src/routes/synology.ts @@ -0,0 +1,610 @@ +import express, { NextFunction, Request, Response } from 'express'; +import { Readable } from 'node:stream'; +import { pipeline } from 'node:stream/promises'; +import { db, canAccessTrip } from '../db/database'; +import { authenticate } from '../middleware/auth'; +import { broadcast } from '../websocket'; +import { AuthRequest } from '../types'; +import { maybe_encrypt_api_key, decrypt_api_key } from '../services/apiKeyCrypto'; +import { consumeEphemeralToken } from '../services/ephemeralTokens'; + +const router = express.Router(); + +function copyProxyHeaders(resp: Response, upstream: globalThis.Response, headerNames: string[]): void { + for (const headerName of headerNames) { + const value = upstream.headers.get(headerName); + if (value) { + resp.set(headerName, value); + } + } +} + +// Helper: Get Synology credentials from users table +function getSynologyCredentials(userId: number) { + try { + const user = db.prepare('SELECT synology_url, synology_username, synology_password FROM users WHERE id = ?').get(userId) as any; + if (!user?.synology_url || !user?.synology_username || !user?.synology_password) return null; + return { + synology_url: user.synology_url as string, + synology_username: user.synology_username as string, + synology_password: decrypt_api_key(user.synology_password) as string, + }; + } catch { + return null; + } +} + +// Helper: Get cached SID from settings or users table +function getCachedSynologySID(userId: number) { + try { + const row = db.prepare('SELECT synology_sid FROM users WHERE id = ?').get(userId) as any; + return row?.synology_sid || null; + } catch { + return null; + } +} + +// Helper: Cache SID in users table +function cacheSynologySID(userId: number, sid: string) { + try { + db.prepare('UPDATE users SET synology_sid = ? WHERE id = ?').run(sid, userId); + } catch (err) { + // Ignore if columns don't exist yet + } +} + +// Helper: Get authenticated session + +interface SynologySession { + success: boolean; + sid?: string; + error?: { code: number; message?: string }; +} + +async function getSynologySession(userId: number): Promise { + // Check for cached SID + const cachedSid = getCachedSynologySID(userId); + if (cachedSid) { + return { success: true, sid: cachedSid }; + } + + const creds = getSynologyCredentials(userId); + // Login with credentials + if (!creds) { + return { success: false, error: { code: 400, message: 'Invalid Synology credentials' } }; + } + const endpoint = prepareSynologyEndpoint(creds.synology_url); + + const body = new URLSearchParams({ + api: 'SYNO.API.Auth', + method: 'login', + version: '3', + account: creds.synology_username, + passwd: creds.synology_password, + }); + + const resp = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + }, + body, + signal: AbortSignal.timeout(30000), + }); + + if (!resp.ok) { + return { success: false, error: { code: resp.status, message: 'Failed to authenticate with Synology' } }; + } + + const data = await resp.json() as { success: boolean; data?: { sid?: string } }; + + if (data.success && data.data?.sid) { + const sid = data.data.sid; + cacheSynologySID(userId, sid); + return { success: true, sid }; + } + + return { success: false, error: { code: 500, message: 'Failed to get Synology session' } }; +} + +// Helper: Clear cached SID + +function clearSynologySID(userId: number): void { + try { + db.prepare('UPDATE users SET synology_sid = NULL WHERE id = ?').run(userId); + } catch { + // Ignore if columns don't exist yet + } +} + +interface ApiCallParams { + api: string; + method: string; + version?: number; + [key: string]: any; +} + +interface SynologyApiResponse { + success: boolean; + data?: T; + error?: { code: number, message?: string }; +} + +function prepareSynologyEndpoint(url: string): string { + url = url.replace(/\/$/, ''); + if (!/^https?:\/\//.test(url)) { + url = `https://${url}`; + } + return `${url}/photo/webapi/entry.cgi`; +} + +function splitPackedSynologyId(rawId: string): { id: string; cacheKey: string; assetId: string } { + const id = rawId.split('_')[0]; + return { id: id, cacheKey: rawId, assetId: rawId }; +} + +function transformSynologyPhoto(item: any): any { + const address = item.additional?.address || {}; + return { + id: item.additional?.thumbnail?.cache_key, + takenAt: item.time ? new Date(item.time * 1000).toISOString() : null, + city: address.city || null, + country: address.country || null, + }; +} + +async function callSynologyApi(userId: number, params: ApiCallParams): Promise> { + try { + const creds = getSynologyCredentials(userId); + if (!creds) { + return { success: false, error: { code: 400, message: 'Synology not configured' } }; + } + const endpoint = prepareSynologyEndpoint(creds.synology_url); + + + const body = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value === undefined || value === null) continue; + body.append(key, typeof value === 'object' ? JSON.stringify(value) : String(value)); + } + + const sid = await getSynologySession(userId); + if (!sid.success || !sid.sid) { + return { success: false, error: sid.error || { code: 500, message: 'Failed to get Synology session' } }; + } + body.append('_sid', sid.sid); + + const resp = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + }, + body, + signal: AbortSignal.timeout(30000), + }); + + + if (!resp.ok) { + const text = await resp.text(); + return { success: false, error: { code: resp.status, message: text } }; + } + + const result = await resp.json() as SynologyApiResponse; + if (!result.success && result.error?.code === 119) { + clearSynologySID(userId); + return callSynologyApi(userId, params); + } + return result; + } catch (err) { + return { success: false, error: { code: -1, message: err instanceof Error ? err.message : 'Unknown error' } }; + } +} + +// Settings +router.get('/settings', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const creds = getSynologyCredentials(authReq.user.id); + res.json({ + synology_url: creds?.synology_url || '', + synology_username: creds?.synology_username || '', + connected: !!(creds?.synology_url && creds?.synology_username), + }); +}); + +router.put('/settings', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { synology_url, synology_username, synology_password } = req.body; + + const url = String(synology_url || '').trim(); + const username = String(synology_username || '').trim(); + const password = String(synology_password || '').trim(); + + if (!url || !username) { + return res.status(400).json({ error: 'URL and username are required' }); + } + + const existing = db.prepare('SELECT synology_password FROM users WHERE id = ?').get(authReq.user.id) as { synology_password?: string | null } | undefined; + const existingEncryptedPassword = existing?.synology_password || null; + + // First-time setup requires password; later updates may keep existing password. + if (!password && !existingEncryptedPassword) { + return res.status(400).json({ error: 'Password is required' }); + } + + try { + db.prepare('UPDATE users SET synology_url = ?, synology_username = ?, synology_password = ? WHERE id = ?').run( + url, + username, + password ? maybe_encrypt_api_key(password) : existingEncryptedPassword, + authReq.user.id + ); + } catch (err) { + return res.status(400).json({ error: 'Failed to save settings' }); + } + + clearSynologySID(authReq.user.id); + res.json({ success: true }); +}); + +// Status +router.get('/status', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + + try { + const sid = await getSynologySession(authReq.user.id); + if (!sid.success || !sid.sid) { + return res.json({ connected: false, error: 'Authentication failed' }); + } + + const user = db.prepare('SELECT synology_username FROM users WHERE id = ?').get(authReq.user.id) as any; + res.json({ connected: true, user: { username: user.synology_username } }); + } catch (err: unknown) { + res.json({ connected: false, error: err instanceof Error ? err.message : 'Connection failed' }); + } +}); + +// Album linking parity with Immich +router.get('/albums', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + try { + const result = await callSynologyApi<{ list: any[] }>(authReq.user.id, { + api: 'SYNO.Foto.Browse.Album', + method: 'list', + version: 4, + offset: 0, + limit: 100, + }); + + if (!result.success || !result.data) { + return res.status(502).json({ error: result.error?.message || 'Failed to fetch albums' }); + } + + const albums = (result.data.list || []).map((a: any) => ({ + id: String(a.id), + albumName: a.name || '', + assetCount: a.item_count || 0, + })); + + res.json({ albums }); + } catch (err: unknown) { + res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology' }); + } +}); + +router.post('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + if (!canAccessTrip(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); + const { album_id, album_name } = req.body; + if (!album_id) return res.status(400).json({ error: 'album_id required' }); + + try { + db.prepare( + 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)' + ).run(tripId, authReq.user.id, 'synologyphotos', String(album_id), album_name || ''); + res.json({ success: true }); + } catch { + res.status(400).json({ error: 'Album already linked' }); + } +}); + +router.post('/trips/:tripId/album-links/:linkId/sync', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId, linkId } = req.params; + + const link = db.prepare("SELECT * FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ? AND provider = 'synologyphotos'") + .get(linkId, tripId, authReq.user.id) as any; + if (!link) return res.status(404).json({ error: 'Album link not found' }); + + try { + const allItems: any[] = []; + const pageSize = 1000; + let offset = 0; + + while (true) { + const result = await callSynologyApi<{ list: any[] }>(authReq.user.id, { + api: 'SYNO.Foto.Browse.Item', + method: 'list', + version: 1, + album_id: Number(link.album_id), + offset, + limit: pageSize, + additional: ['thumbnail'], + }); + + if (!result.success || !result.data) { + return res.status(502).json({ error: result.error?.message || 'Failed to fetch album' }); + } + + const items = result.data.list || []; + allItems.push(...items); + if (items.length < pageSize) break; + offset += pageSize; + } + + const insert = db.prepare( + "INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, 'synologyphotos', 1)" + ); + + let added = 0; + for (const item of allItems) { + const transformed = transformSynologyPhoto(item); + const assetId = String(transformed?.id || '').trim(); + if (!assetId) continue; + const r = insert.run(tripId, authReq.user.id, assetId); + if (r.changes > 0) added++; + } + + db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); + + res.json({ success: true, added, total: allItems.length }); + if (added > 0) { + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); + } + } catch (err: unknown) { + res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology' }); + } +}); + +// Search +router.post('/search', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + let { from, to, offset = 0, limit = 300 } = req.body; + + try { + const params: any = { + api: 'SYNO.Foto.Search.Search', + method: 'list_item', + version: 1, + offset, + limit, + keyword: '.', + additional: ['thumbnail', 'address'], + }; + + if (from || to) { + if (from) { + params.start_time = Math.floor(new Date(from).getTime() / 1000); + } + if (to) { + params.end_time = Math.floor(new Date(to).getTime() / 1000) + 86400; // Include entire end day + } + } + + + const result = await callSynologyApi<{ list: any[]; total: number }>(authReq.user.id, params); + + if (!result.success || !result.data) { + return res.status(502).json({ error: result.error?.message || 'Failed to fetch album photos' }); + } + + const allItems = (result.data.list || []); + const total = allItems.length; + + const assets = allItems.map((item: any) => transformSynologyPhoto(item)); + + res.json({ + assets, + total, + hasMore: total == limit, + }); + } catch (err: unknown) { + res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology' }); + } +}); + +// Proxy Synology Assets + +// Asset info endpoint (returns metadata, not image) +router.get('/assets/:photoId/info', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { photoId } = req.params; + const parsedId = splitPackedSynologyId(photoId); + const { userId } = req.query; + + const targetUserId = userId ? Number(userId) : authReq.user.id; + + try { + const result = await callSynologyApi(targetUserId, { + api: 'SYNO.Foto.Browse.Item', + method: 'get', + version: 2, + id: Number(parsedId.id), + additional: ['thumbnail', 'resolution', 'exif', 'gps', 'address', 'orientation', 'description'], + }); + if (!result.success || !result.data) { + return res.status(404).json({ error: 'Photo not found' }); + } + + + const exif = result.data.additional?.exif || {}; + const address = result.data.additional?.address || {}; + const gps = result.data.additional?.gps || {}; + res.json({ + id: result.data.id, + takenAt: result.data.time ? new Date(result.data.time * 1000).toISOString() : null, + width: result.data.additional?.resolution?.width || null, + height: result.data.additional?.resolution?.height || null, + camera: exif.model || null, + lens: exif.lens_model || null, + focalLength: exif.focal_length ? `${exif.focal_length}mm` : null, + aperture: exif.f_number ? `f/${exif.f_number}` : null, + shutter: exif.exposure_time || null, + iso: exif.iso_speed_ratings || null, + city: address.city || null, + state: address.state || null, + country: address.country || null, + lat: gps.latitude || null, + lng: gps.longitude || null, + orientation: result.data.additional?.orientation || null, + description: result.data.additional?.description || null, + fileSize: result.data.filesize || null, + fileName: result.data.filename || null, + }); + } catch (err: unknown) { + res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology'}); + } +}); + +// Middleware: Accept ephemeral token from query param for tags +function authFromQuery(req: Request, res: Response, next: NextFunction) { + const queryToken = req.query.token as string | undefined; + if (queryToken) { + const userId = consumeEphemeralToken(queryToken, 'synologyphotos'); + if (!userId) return res.status(401).send('Invalid or expired token'); + const user = db.prepare('SELECT id, username, email, role, mfa_enabled FROM users WHERE id = ?').get(userId) as any; + if (!user) return res.status(401).send('User not found'); + (req as AuthRequest).user = user; + return next(); + } + return (authenticate as any)(req, res, next); +} + +router.get('/assets/:photoId/thumbnail', authFromQuery, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { photoId } = req.params; + const parsedId = splitPackedSynologyId(photoId); + const { userId, cacheKey, size = 'sm' } = req.query; + + const targetUserId = userId ? Number(userId) : authReq.user.id; + + const creds = getSynologyCredentials(targetUserId); + if (!creds) { + return res.status(404).send('Not found'); + } + + try { + const sid = await getSynologySession(authReq.user.id); + if (!sid.success && !sid.sid) { + return res.status(401).send('Authentication failed'); + } + + let resolvedCacheKey = cacheKey ? String(cacheKey) : parsedId.cacheKey; + if (!resolvedCacheKey) { + const row = db.prepare(` + SELECT asset_id FROM trip_photos + WHERE user_id = ? AND (asset_id = ? OR asset_id = ? OR asset_id LIKE ? OR asset_id LIKE ?) + ORDER BY id DESC LIMIT 1 + `).get(targetUserId, parsedId.assetId, parsedId.id, `${parsedId.id}_%`, `${parsedId.id}::%`) as { asset_id?: string } | undefined; + const packed = row?.asset_id || ''; + if (packed) { + resolvedCacheKey = splitPackedSynologyId(packed).cacheKey; + } + } + if (!resolvedCacheKey) return res.status(404).send('Missing cache key for thumbnail'); + + const params = new URLSearchParams({ + api: 'SYNO.Foto.Thumbnail', + method: 'get', + version: '2', + mode: 'download', + id: String(parsedId.id), + type: 'unit', + size: String(size), + cache_key: resolvedCacheKey, + _sid: sid.sid, + }); + const url = prepareSynologyEndpoint(creds.synology_url) + '?' + params.toString(); + const resp = await fetch(url, { + signal: AbortSignal.timeout(30000), + }); + + if (!resp.ok) { + return res.status(resp.status).send('Failed'); + } + + res.status(resp.status); + copyProxyHeaders(res, resp, ['content-type', 'cache-control', 'content-length', 'content-disposition']); + res.set('Content-Type', resp.headers.get('content-type') || 'image/jpeg'); + res.set('Cache-Control', resp.headers.get('cache-control') || 'public, max-age=86400'); + + if (!resp.body) { + return res.end(); + } + + await pipeline(Readable.fromWeb(resp.body), res); + } catch (err: unknown) { + if (res.headersSent) { + return; + } + res.status(502).send('Proxy error: ' + (err instanceof Error ? err.message : String(err))); + } +}); + + +router.get('/assets/download', authFromQuery, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { userId, cacheKey, unitIds } = req.query; + + const targetUserId = userId ? Number(userId) : authReq.user.id; + + const creds = getSynologyCredentials(targetUserId); + if (!creds) { + return res.status(404).send('Not found'); + } + + try { + const sid = await getSynologySession(authReq.user.id); + if (!sid.success && !sid.sid) { + return res.status(401).send('Authentication failed'); + } + + const params = new URLSearchParams({ + api: 'SYNO.Foto.Download', + method: 'download', + version: '2', + cache_key: String(cacheKey), + unit_id: "[" + String(unitIds) + "]", + _sid: sid.sid, + }); + + const url = prepareSynologyEndpoint(creds.synology_url) + '?' + params.toString(); + const resp = await fetch(url, { + signal: AbortSignal.timeout(30000), + }); + + if (!resp.ok) { + const body = await resp.text(); + return res.status(resp.status).send('Failed: ' + body); + } + + res.status(resp.status); + copyProxyHeaders(res, resp, ['content-type', 'cache-control', 'content-length', 'content-disposition']); + res.set('Content-Type', resp.headers.get('content-type') || 'application/octet-stream'); + res.set('Cache-Control', resp.headers.get('cache-control') || 'public, max-age=86400'); + + if (!resp.body) { + return res.end(); + } + + await pipeline(Readable.fromWeb(resp.body), res); + } catch (err: unknown) { + if (res.headersSent) { + return; + } + res.status(502).send('Proxy error: ' + (err instanceof Error ? err.message : String(err))); + } +}); + + +export default router; diff --git a/server/src/services/authService.ts b/server/src/services/authService.ts index c069645..d743519 100644 --- a/server/src/services/authService.ts +++ b/server/src/services/authService.ts @@ -981,7 +981,7 @@ export function createWsToken(userId: number): { error?: string; status?: number } export function createResourceToken(userId: number, purpose?: string): { error?: string; status?: number; token?: string } { - if (purpose !== 'download' && purpose !== 'immich') { + if (purpose !== 'download' && purpose !== 'immich' && purpose !== 'synologyphotos') { return { error: 'Invalid purpose', status: 400 }; } const token = createEphemeralToken(userId, purpose); diff --git a/server/src/services/ephemeralTokens.ts b/server/src/services/ephemeralTokens.ts index 0d1c12b..f880951 100644 --- a/server/src/services/ephemeralTokens.ts +++ b/server/src/services/ephemeralTokens.ts @@ -4,6 +4,7 @@ const TTL: Record = { ws: 30_000, download: 60_000, immich: 60_000, + synologyphotos: 60_000, }; const MAX_STORE_SIZE = 10_000; From a7d3f9fc06ffe67f0b7fd8865835c91dde075671 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 03:08:15 +0200 Subject: [PATCH 011/117] returning test connectioon button to original intend --- server/src/db/migrations.ts | 2 +- server/src/db/seeds.ts | 2 +- server/src/routes/synology.ts | 44 +++++++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/server/src/db/migrations.ts b/server/src/db/migrations.ts index d14d4a8..20f160d 100644 --- a/server/src/db/migrations.ts +++ b/server/src/db/migrations.ts @@ -662,7 +662,7 @@ function runMigrations(db: Database.Database): void { settings_get: '/integrations/synologyphotos/settings', settings_put: '/integrations/synologyphotos/settings', status_get: '/integrations/synologyphotos/status', - test_get: '/integrations/synologyphotos/status', + test_post: '/integrations/synologyphotos/test', }), 1, ); diff --git a/server/src/db/seeds.ts b/server/src/db/seeds.ts index 8035d21..ef849d9 100644 --- a/server/src/db/seeds.ts +++ b/server/src/db/seeds.ts @@ -119,7 +119,7 @@ function seedAddons(db: Database.Database): void { settings_get: '/integrations/synologyphotos/settings', settings_put: '/integrations/synologyphotos/settings', status_get: '/integrations/synologyphotos/status', - test_get: '/integrations/synologyphotos/status', + test_post: '/integrations/synologyphotos/test', }), }, ]; diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index 9e98fcf..c1e868e 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -7,6 +7,7 @@ import { broadcast } from '../websocket'; import { AuthRequest } from '../types'; import { maybe_encrypt_api_key, decrypt_api_key } from '../services/apiKeyCrypto'; import { consumeEphemeralToken } from '../services/ephemeralTokens'; +import { checkSsrf } from '../utils/ssrfGuard'; const router = express.Router(); @@ -263,6 +264,49 @@ router.get('/status', authenticate, async (req: Request, res: Response) => { } }); +// Test connection with provided credentials only +router.post('/test', authenticate, async (req: Request, res: Response) => { + const { synology_url, synology_username, synology_password } = req.body as { synology_url?: string; synology_username?: string; synology_password?: string }; + + const url = String(synology_url || '').trim(); + const username = String(synology_username || '').trim(); + const password = String(synology_password || '').trim(); + + if (!url || !username || !password) { + return res.json({ connected: false, error: 'URL, username, and password are required' }); + } + + const ssrf = await checkSsrf(url); + if (!ssrf.allowed) return res.json({ connected: false, error: ssrf.error ?? 'Invalid Synology URL' }); + + try { + const endpoint = prepareSynologyEndpoint(url); + const body = new URLSearchParams({ + api: 'SYNO.API.Auth', + method: 'login', + version: '3', + account: username, + passwd: password, + }); + + const resp = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + }, + body, + signal: AbortSignal.timeout(30000), + }); + + if (!resp.ok) return res.json({ connected: false, error: `HTTP ${resp.status}` }); + const data = await resp.json() as { success: boolean; data?: { sid?: string } }; + if (!data.success || !data.data?.sid) return res.json({ connected: false, error: 'Authentication failed' }); + return res.json({ connected: true, user: { username } }); + } catch (err: unknown) { + return res.json({ connected: false, error: err instanceof Error ? err.message : 'Connection failed' }); + } +}); + // Album linking parity with Immich router.get('/albums', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; From d418d85d024eae6974e772348d39d63f80c9e43d Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 03:20:45 +0200 Subject: [PATCH 012/117] fixing selection of photos from multiple sources at once --- .../src/components/Memories/MemoriesPanel.tsx | 45 +++++++++++++------ server/src/routes/memories.ts | 32 ++++++++----- 2 files changed, 52 insertions(+), 25 deletions(-) diff --git a/client/src/components/Memories/MemoriesPanel.tsx b/client/src/components/Memories/MemoriesPanel.tsx index b288487..8787dd7 100644 --- a/client/src/components/Memories/MemoriesPanel.tsx +++ b/client/src/components/Memories/MemoriesPanel.tsx @@ -33,11 +33,12 @@ interface TripPhoto { city?: string | null } -interface ImmichAsset { +interface Asset { id: string takenAt: string city: string | null country: string | null + provider: string } interface MemoriesPanelProps { @@ -63,7 +64,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa // Photo picker const [showPicker, setShowPicker] = useState(false) - const [pickerPhotos, setPickerPhotos] = useState([]) + const [pickerPhotos, setPickerPhotos] = useState([]) const [pickerLoading, setPickerLoading] = useState(false) const [selectedIds, setSelectedIds] = useState>(new Set()) @@ -238,11 +239,16 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const loadPickerPhotos = async (useDate: boolean) => { setPickerLoading(true) try { - const res = await apiClient.post(`${pickerIntegrationBase}/search`, { + const provider = availableProviders.find(p => p.id === selectedProvider) + if (!provider) { + setPickerPhotos([]) + return + } + const res = await apiClient.post(`/integrations/${provider.id}/search`, { from: useDate && startDate ? startDate : undefined, to: useDate && endDate ? endDate : undefined, }) - setPickerPhotos(res.data.assets || []) + setPickerPhotos((res.data.assets || []).map((asset: Asset) => ({ ...asset, provider: provider.id }))) } catch { setPickerPhotos([]) toast.error(t('memories.error.loadPhotos')) @@ -268,9 +274,17 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const executeAddPhotos = async () => { setShowConfirmShare(false) try { + const groupedByProvider = new Map() + for (const key of selectedIds) { + const [provider, assetId] = key.split('::') + if (!provider || !assetId) continue + const list = groupedByProvider.get(provider) || [] + list.push(assetId) + groupedByProvider.set(provider, list) + } + await apiClient.post(`/integrations/memories/trips/${tripId}/photos`, { - provider: selectedProvider, - asset_ids: [...selectedIds], + selections: [...groupedByProvider.entries()].map(([provider, asset_ids]) => ({ provider, asset_ids })), shared: true, }) setShowPicker(false) @@ -312,6 +326,8 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const thumbnailBaseUrl = (photo: TripPhoto) => `/api/integrations/${photo.provider}/assets/${photo.asset_id}/thumbnail?userId=${photo.user_id}` + const makePickerKey = (provider: string, assetId: string): string => `${provider}::${assetId}` + const ownPhotos = tripPhotos.filter(p => p.user_id === currentUser?.id) const othersPhotos = tripPhotos.filter(p => p.user_id !== currentUser?.id && p.shared) const allVisibleRaw = [...ownPhotos, ...othersPhotos] @@ -461,8 +477,8 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa if (showPicker) { const alreadyAdded = new Set( tripPhotos - .filter(p => p.user_id === currentUser?.id && p.provider === selectedProvider) - .map(p => p.asset_id) + .filter(p => p.user_id === currentUser?.id) + .map(p => makePickerKey(p.provider, p.asset_id)) ) return ( @@ -537,7 +553,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa
) : (() => { // Group photos by month - const byMonth: Record = {} + const byMonth: Record = {} for (const asset of pickerPhotos) { const d = asset.takenAt ? new Date(asset.takenAt) : null const key = d ? `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}` : 'unknown' @@ -555,11 +571,12 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa
{byMonth[month].map(asset => { - const isSelected = selectedIds.has(asset.id) - const isAlready = alreadyAdded.has(asset.id) + const pickerKey = makePickerKey(asset.provider, asset.id) + const isSelected = selectedIds.has(pickerKey) + const isAlready = alreadyAdded.has(pickerKey) return ( -
!isAlready && togglePickerSelect(asset.id)} +
!isAlready && togglePickerSelect(pickerKey)} style={{ position: 'relative', aspectRatio: '1', borderRadius: 8, overflow: 'hidden', cursor: isAlready ? 'default' : 'pointer', @@ -567,7 +584,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa outline: isSelected ? '3px solid var(--text-primary)' : 'none', outlineOffset: -3, }}> - {isSelected && (
{ const authReq = req as AuthRequest; const { tripId } = req.params; - const provider = String(req.body?.provider || '').toLowerCase(); const { shared = true } = req.body; + const selectionsRaw = Array.isArray(req.body?.selections) ? req.body.selections : null; + const provider = String(req.body?.provider || '').toLowerCase(); const assetIdsRaw = req.body?.asset_ids; if (!canAccessTrip(tripId, authReq.user.id)) { return res.status(404).json({ error: 'Trip not found' }); } - if (!provider) { - return res.status(400).json({ error: 'provider is required' }); - } + const selections = selectionsRaw && selectionsRaw.length > 0 + ? selectionsRaw + .map((selection: any) => ({ + provider: String(selection?.provider || '').toLowerCase(), + asset_ids: Array.isArray(selection?.asset_ids) ? selection.asset_ids : [], + })) + .filter((selection: { provider: string; asset_ids: unknown[] }) => selection.provider && selection.asset_ids.length > 0) + : (provider && Array.isArray(assetIdsRaw) && assetIdsRaw.length > 0 + ? [{ provider, asset_ids: assetIdsRaw }] + : []); - if (!Array.isArray(assetIdsRaw) || assetIdsRaw.length === 0) { - return res.status(400).json({ error: 'asset_ids required' }); + if (selections.length === 0) { + return res.status(400).json({ error: 'selections required' }); } const insert = db.prepare( @@ -95,11 +103,13 @@ router.post('/trips/:tripId/photos', authenticate, (req: Request, res: Response) ); let added = 0; - for (const raw of assetIdsRaw) { - const assetId = String(raw || '').trim(); - if (!assetId) continue; - const result = insert.run(tripId, authReq.user.id, assetId, provider, shared ? 1 : 0); - if (result.changes > 0) added++; + for (const selection of selections) { + for (const raw of selection.asset_ids) { + const assetId = String(raw || '').trim(); + if (!assetId) continue; + const result = insert.run(tripId, authReq.user.id, assetId, selection.provider, shared ? 1 : 0); + if (result.changes > 0) added++; + } } res.json({ success: true, added }); From 1e27a62b537ba20a2201e15f76231f61af44686b Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 03:29:13 +0200 Subject: [PATCH 013/117] fixing path for asset in full res --- server/src/routes/synology.ts | 30 +++++++++--------------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index c1e868e..7312eaa 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -528,7 +528,7 @@ router.get('/assets/:photoId/thumbnail', authFromQuery, async (req: Request, res const authReq = req as AuthRequest; const { photoId } = req.params; const parsedId = splitPackedSynologyId(photoId); - const { userId, cacheKey, size = 'sm' } = req.query; + const { userId, size = 'sm' } = req.query; const targetUserId = userId ? Number(userId) : authReq.user.id; @@ -543,29 +543,15 @@ router.get('/assets/:photoId/thumbnail', authFromQuery, async (req: Request, res return res.status(401).send('Authentication failed'); } - let resolvedCacheKey = cacheKey ? String(cacheKey) : parsedId.cacheKey; - if (!resolvedCacheKey) { - const row = db.prepare(` - SELECT asset_id FROM trip_photos - WHERE user_id = ? AND (asset_id = ? OR asset_id = ? OR asset_id LIKE ? OR asset_id LIKE ?) - ORDER BY id DESC LIMIT 1 - `).get(targetUserId, parsedId.assetId, parsedId.id, `${parsedId.id}_%`, `${parsedId.id}::%`) as { asset_id?: string } | undefined; - const packed = row?.asset_id || ''; - if (packed) { - resolvedCacheKey = splitPackedSynologyId(packed).cacheKey; - } - } - if (!resolvedCacheKey) return res.status(404).send('Missing cache key for thumbnail'); - const params = new URLSearchParams({ api: 'SYNO.Foto.Thumbnail', method: 'get', version: '2', mode: 'download', - id: String(parsedId.id), + id: parsedId.id, type: 'unit', size: String(size), - cache_key: resolvedCacheKey, + cache_key: parsedId.cacheKey, _sid: sid.sid, }); const url = prepareSynologyEndpoint(creds.synology_url) + '?' + params.toString(); @@ -596,9 +582,11 @@ router.get('/assets/:photoId/thumbnail', authFromQuery, async (req: Request, res }); -router.get('/assets/download', authFromQuery, async (req: Request, res: Response) => { +router.get('/assets/:photoId/original', authFromQuery, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - const { userId, cacheKey, unitIds } = req.query; + const { photoId } = req.params; + const parsedId = splitPackedSynologyId(photoId || ''); + const { userId} = req.query; const targetUserId = userId ? Number(userId) : authReq.user.id; @@ -617,8 +605,8 @@ router.get('/assets/download', authFromQuery, async (req: Request, res: Response api: 'SYNO.Foto.Download', method: 'download', version: '2', - cache_key: String(cacheKey), - unit_id: "[" + String(unitIds) + "]", + cache_key: parsedId.cacheKey, + unit_id: `[${parsedId.id}]`, _sid: sid.sid, }); From be03fffcae98e48965688ba02318582235f8e4ec Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 03:47:44 +0200 Subject: [PATCH 014/117] fixing metada --- server/src/routes/synology.ts | 47 +++++++++++++++++++---------------- 1 file changed, 25 insertions(+), 22 deletions(-) diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index 7312eaa..71fed86 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -472,38 +472,41 @@ router.get('/assets/:photoId/info', authenticate, async (req: Request, res: Resp const result = await callSynologyApi(targetUserId, { api: 'SYNO.Foto.Browse.Item', method: 'get', - version: 2, - id: Number(parsedId.id), - additional: ['thumbnail', 'resolution', 'exif', 'gps', 'address', 'orientation', 'description'], + version: 5, + id: `[${parsedId.id}]`, + additional: ['resolution', 'exif', 'gps', 'address', 'orientation', 'description'], }); if (!result.success || !result.data) { return res.status(404).json({ error: 'Photo not found' }); } - - const exif = result.data.additional?.exif || {}; - const address = result.data.additional?.address || {}; - const gps = result.data.additional?.gps || {}; + const metadata = result.data.list[0]; + console.log(metadata); + const exif = metadata.additional?.exif || {}; + const address = metadata.additional?.address || {}; + const gps = metadata.additional?.gps || {}; res.json({ - id: result.data.id, - takenAt: result.data.time ? new Date(result.data.time * 1000).toISOString() : null, - width: result.data.additional?.resolution?.width || null, - height: result.data.additional?.resolution?.height || null, - camera: exif.model || null, - lens: exif.lens_model || null, - focalLength: exif.focal_length ? `${exif.focal_length}mm` : null, - aperture: exif.f_number ? `f/${exif.f_number}` : null, - shutter: exif.exposure_time || null, - iso: exif.iso_speed_ratings || null, + id: photoId, + takenAt: metadata.time ? new Date(metadata.time * 1000).toISOString() : null, city: address.city || null, - state: address.state || null, country: address.country || null, + state: address.state || null, + camera: exif.camera || null, + lens: exif.lens || null, + focalLength: exif.focal_length || null, + aperture: exif.aperture || null, + shutter: exif.exposure_time || null, + iso: exif.iso || null, lat: gps.latitude || null, lng: gps.longitude || null, - orientation: result.data.additional?.orientation || null, - description: result.data.additional?.description || null, - fileSize: result.data.filesize || null, - fileName: result.data.filename || null, + orientation: metadata.additional?.orientation || null, + description: metadata.additional?.description || null, + filename: metadata.filename || null, + filesize: metadata.filesize || null, + width: metadata.additional?.resolution?.width || null, + height: metadata.additional?.resolution?.height || null, + fileSize: metadata.filesize || null, + fileName: metadata.filename || null, }); } catch (err: unknown) { res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology'}); From b224f8b713efd18d4a6bac878d66708114c0b808 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 12:19:00 +0200 Subject: [PATCH 015/117] fixing errors in migration --- server/src/services/adminService.ts | 89 +++++++++++++++++++++++++--- server/src/services/immichService.ts | 33 +++++------ 2 files changed, 97 insertions(+), 25 deletions(-) diff --git a/server/src/services/adminService.ts b/server/src/services/adminService.ts index ae42c92..f7df1f4 100644 --- a/server/src/services/adminService.ts +++ b/server/src/services/adminService.ts @@ -465,17 +465,92 @@ export function deleteTemplateItem(itemId: string) { export function listAddons() { const addons = db.prepare('SELECT * FROM addons ORDER BY sort_order, id').all() as Addon[]; - return addons.map(a => ({ ...a, enabled: !!a.enabled, config: JSON.parse(a.config || '{}') })); + const providers = db.prepare(` + SELECT id, name, description, icon, enabled, config, sort_order + FROM photo_providers + ORDER BY sort_order, id + `).all() as Array<{ id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number }>; + const fields = db.prepare(` + SELECT provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order + FROM photo_provider_fields + ORDER BY sort_order, id + `).all() as Array<{ + provider_id: string; + field_key: string; + label: string; + input_type: string; + placeholder?: string | null; + required: number; + secret: number; + settings_key?: string | null; + payload_key?: string | null; + sort_order: number; + }>; + const fieldsByProvider = new Map(); + for (const field of fields) { + const arr = fieldsByProvider.get(field.provider_id) || []; + arr.push(field); + fieldsByProvider.set(field.provider_id, arr); + } + + return [ + ...addons.map(a => ({ ...a, enabled: !!a.enabled, config: JSON.parse(a.config || '{}') })), + ...providers.map(p => ({ + id: p.id, + name: p.name, + description: p.description, + type: 'photo_provider', + icon: p.icon, + enabled: !!p.enabled, + config: JSON.parse(p.config || '{}'), + fields: (fieldsByProvider.get(p.id) || []).map(f => ({ + key: f.field_key, + label: f.label, + input_type: f.input_type, + placeholder: f.placeholder || '', + required: !!f.required, + secret: !!f.secret, + settings_key: f.settings_key || null, + payload_key: f.payload_key || null, + sort_order: f.sort_order, + })), + sort_order: p.sort_order, + })), + ]; } export function updateAddon(id: string, data: { enabled?: boolean; config?: Record }) { - const addon = db.prepare('SELECT * FROM addons WHERE id = ?').get(id); - if (!addon) return { error: 'Addon not found', status: 404 }; - if (data.enabled !== undefined) db.prepare('UPDATE addons SET enabled = ? WHERE id = ?').run(data.enabled ? 1 : 0, id); - if (data.config !== undefined) db.prepare('UPDATE addons SET config = ? WHERE id = ?').run(JSON.stringify(data.config), id); - const updated = db.prepare('SELECT * FROM addons WHERE id = ?').get(id) as Addon; + const addon = db.prepare('SELECT * FROM addons WHERE id = ?').get(id) as Addon | undefined; + const provider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number } | undefined; + if (!addon && !provider) return { error: 'Addon not found', status: 404 }; + + if (addon) { + if (data.enabled !== undefined) db.prepare('UPDATE addons SET enabled = ? WHERE id = ?').run(data.enabled ? 1 : 0, id); + if (data.config !== undefined) db.prepare('UPDATE addons SET config = ? WHERE id = ?').run(JSON.stringify(data.config), id); + } else { + if (data.enabled !== undefined) db.prepare('UPDATE photo_providers SET enabled = ? WHERE id = ?').run(data.enabled ? 1 : 0, id); + if (data.config !== undefined) db.prepare('UPDATE photo_providers SET config = ? WHERE id = ?').run(JSON.stringify(data.config), id); + } + + const updatedAddon = db.prepare('SELECT * FROM addons WHERE id = ?').get(id) as Addon | undefined; + const updatedProvider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number } | undefined; + const updated = updatedAddon + ? { ...updatedAddon, enabled: !!updatedAddon.enabled, config: JSON.parse(updatedAddon.config || '{}') } + : updatedProvider + ? { + id: updatedProvider.id, + name: updatedProvider.name, + description: updatedProvider.description, + type: 'photo_provider', + icon: updatedProvider.icon, + enabled: !!updatedProvider.enabled, + config: JSON.parse(updatedProvider.config || '{}'), + sort_order: updatedProvider.sort_order, + } + : null; + return { - addon: { ...updated, enabled: !!updated.enabled, config: JSON.parse(updated.config || '{}') }, + addon: updated, auditDetails: { enabled: data.enabled !== undefined ? !!data.enabled : undefined, config_changed: data.config !== undefined }, }; } diff --git a/server/src/services/immichService.ts b/server/src/services/immichService.ts index 9dd3de5..4a3169f 100644 --- a/server/src/services/immichService.ts +++ b/server/src/services/immichService.ts @@ -175,11 +175,12 @@ export async function searchPhotos( export function listTripPhotos(tripId: string, userId: number) { return db.prepare(` - SELECT tp.immich_asset_id, tp.user_id, tp.shared, tp.added_at, + SELECT tp.asset_id AS immich_asset_id, tp.user_id, tp.shared, tp.added_at, u.username, u.avatar, u.immich_url FROM trip_photos tp JOIN users u ON tp.user_id = u.id WHERE tp.trip_id = ? + AND tp.provider = 'immich' AND (tp.user_id = ? OR tp.shared = 1) ORDER BY tp.added_at ASC `).all(tripId, userId); @@ -191,25 +192,23 @@ export function addTripPhotos( assetIds: string[], shared: boolean ): number { - const insert = db.prepare( - 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, immich_asset_id, shared) VALUES (?, ?, ?, ?)' - ); + const insert = db.prepare('INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, ?, ?)'); let added = 0; for (const assetId of assetIds) { - const result = insert.run(tripId, userId, assetId, shared ? 1 : 0); + const result = insert.run(tripId, userId, assetId, 'immich', shared ? 1 : 0); if (result.changes > 0) added++; } return added; } export function removeTripPhoto(tripId: string, userId: number, assetId: string) { - db.prepare('DELETE FROM trip_photos WHERE trip_id = ? AND user_id = ? AND immich_asset_id = ?') - .run(tripId, userId, assetId); + db.prepare('DELETE FROM trip_photos WHERE trip_id = ? AND user_id = ? AND asset_id = ? AND provider = ?') + .run(tripId, userId, assetId, 'immich'); } export function togglePhotoSharing(tripId: string, userId: number, assetId: string, shared: boolean) { - db.prepare('UPDATE trip_photos SET shared = ? WHERE trip_id = ? AND user_id = ? AND immich_asset_id = ?') - .run(shared ? 1 : 0, tripId, userId, assetId); + db.prepare('UPDATE trip_photos SET shared = ? WHERE trip_id = ? AND user_id = ? AND asset_id = ? AND provider = ?') + .run(shared ? 1 : 0, tripId, userId, assetId, 'immich'); } // ── Asset Info / Proxy ───────────────────────────────────────────────────── @@ -329,7 +328,7 @@ export function listAlbumLinks(tripId: string) { SELECT tal.*, u.username FROM trip_album_links tal JOIN users u ON tal.user_id = u.id - WHERE tal.trip_id = ? + WHERE tal.trip_id = ? AND tal.provider = 'immich' ORDER BY tal.created_at ASC `).all(tripId); } @@ -342,8 +341,8 @@ export function createAlbumLink( ): { success: boolean; error?: string } { try { db.prepare( - 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, immich_album_id, album_name) VALUES (?, ?, ?, ?)' - ).run(tripId, userId, albumId, albumName || ''); + 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)' + ).run(tripId, userId, 'immich', albumId, albumName || ''); return { success: true }; } catch { return { success: false, error: 'Album already linked' }; @@ -360,15 +359,15 @@ export async function syncAlbumAssets( linkId: string, userId: number ): Promise<{ success?: boolean; added?: number; total?: number; error?: string; status?: number }> { - const link = db.prepare('SELECT * FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') - .get(linkId, tripId, userId) as any; + const link = db.prepare('SELECT * FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ? AND provider = ?') + .get(linkId, tripId, userId, 'immich') as any; if (!link) return { error: 'Album link not found', status: 404 }; const creds = getImmichCredentials(userId); if (!creds) return { error: 'Immich not configured', status: 400 }; try { - const resp = await fetch(`${creds.immich_url}/api/albums/${link.immich_album_id}`, { + const resp = await fetch(`${creds.immich_url}/api/albums/${link.album_id}`, { headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, signal: AbortSignal.timeout(15000), }); @@ -376,9 +375,7 @@ export async function syncAlbumAssets( const albumData = await resp.json() as { assets?: any[] }; const assets = (albumData.assets || []).filter((a: any) => a.type === 'IMAGE'); - const insert = db.prepare( - 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, immich_asset_id, shared) VALUES (?, ?, ?, 1)' - ); + const insert = db.prepare("INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, 'immich', 1)"); let added = 0; for (const asset of assets) { const r = insert.run(tripId, userId, asset.id); From b4741c31a910891996d151cd47a4b97afe6e541b Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 16:25:45 +0200 Subject: [PATCH 016/117] moving business logic for synology to separet file --- server/src/routes/admin.ts | 5 +- server/src/routes/synology.ts | 720 +++++-------------------- server/src/services/synologyService.ts | 651 ++++++++++++++++++++++ 3 files changed, 783 insertions(+), 593 deletions(-) create mode 100644 server/src/services/synologyService.ts diff --git a/server/src/routes/admin.ts b/server/src/routes/admin.ts index 8558fe6..86896ab 100644 --- a/server/src/routes/admin.ts +++ b/server/src/routes/admin.ts @@ -1,6 +1,7 @@ import express, { Request, Response } from 'express'; import { authenticate, adminOnly } from '../middleware/auth'; -import { AuthRequest } from '../types'; +import { db } from '../db/database'; +import { AuthRequest, Addon } from '../types'; import { writeAudit, getClientIp, logInfo } from '../services/auditLog'; import * as svc from '../services/adminService'; @@ -355,7 +356,7 @@ router.put('/addons/:id', (req: Request, res: Response) => { action: 'admin.addon_update', resource: String(req.params.id), ip: getClientIp(req), - details: result.auditDetails, + details: { enabled: req.body.enabled, config: req.body.config }, }); res.json({ addon: updated }); }); diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index 71fed86..65f4dfb 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -1,645 +1,183 @@ -import express, { NextFunction, Request, Response } from 'express'; -import { Readable } from 'node:stream'; -import { pipeline } from 'node:stream/promises'; -import { db, canAccessTrip } from '../db/database'; +import express, { Request, Response } from 'express'; import { authenticate } from '../middleware/auth'; import { broadcast } from '../websocket'; import { AuthRequest } from '../types'; -import { maybe_encrypt_api_key, decrypt_api_key } from '../services/apiKeyCrypto'; -import { consumeEphemeralToken } from '../services/ephemeralTokens'; -import { checkSsrf } from '../utils/ssrfGuard'; +import { + getSynologySettings, + updateSynologySettings, + getSynologyStatus, + testSynologyConnection, + listSynologyAlbums, + linkSynologyAlbum, + syncSynologyAlbumLink, + searchSynologyPhotos, + getSynologyAssetInfo, + pipeSynologyProxy, + synologyAuthFromQuery, + getSynologyTargetUserId, + streamSynologyAsset, + handleSynologyError, + SynologyServiceError, +} from '../services/synologyService'; const router = express.Router(); -function copyProxyHeaders(resp: Response, upstream: globalThis.Response, headerNames: string[]): void { - for (const headerName of headerNames) { - const value = upstream.headers.get(headerName); - if (value) { - resp.set(headerName, value); - } - } +function parseStringBodyField(value: unknown): string { + return String(value ?? '').trim(); } -// Helper: Get Synology credentials from users table -function getSynologyCredentials(userId: number) { - try { - const user = db.prepare('SELECT synology_url, synology_username, synology_password FROM users WHERE id = ?').get(userId) as any; - if (!user?.synology_url || !user?.synology_username || !user?.synology_password) return null; - return { - synology_url: user.synology_url as string, - synology_username: user.synology_username as string, - synology_password: decrypt_api_key(user.synology_password) as string, - }; - } catch { - return null; - } +function parseNumberBodyField(value: unknown, fallback: number): number { + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : fallback; } -// Helper: Get cached SID from settings or users table -function getCachedSynologySID(userId: number) { - try { - const row = db.prepare('SELECT synology_sid FROM users WHERE id = ?').get(userId) as any; - return row?.synology_sid || null; - } catch { - return null; - } -} - -// Helper: Cache SID in users table -function cacheSynologySID(userId: number, sid: string) { - try { - db.prepare('UPDATE users SET synology_sid = ? WHERE id = ?').run(sid, userId); - } catch (err) { - // Ignore if columns don't exist yet - } -} - -// Helper: Get authenticated session - -interface SynologySession { - success: boolean; - sid?: string; - error?: { code: number; message?: string }; -} - -async function getSynologySession(userId: number): Promise { - // Check for cached SID - const cachedSid = getCachedSynologySID(userId); - if (cachedSid) { - return { success: true, sid: cachedSid }; - } - - const creds = getSynologyCredentials(userId); - // Login with credentials - if (!creds) { - return { success: false, error: { code: 400, message: 'Invalid Synology credentials' } }; - } - const endpoint = prepareSynologyEndpoint(creds.synology_url); - - const body = new URLSearchParams({ - api: 'SYNO.API.Auth', - method: 'login', - version: '3', - account: creds.synology_username, - passwd: creds.synology_password, - }); - - const resp = await fetch(endpoint, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', - }, - body, - signal: AbortSignal.timeout(30000), - }); - - if (!resp.ok) { - return { success: false, error: { code: resp.status, message: 'Failed to authenticate with Synology' } }; - } - - const data = await resp.json() as { success: boolean; data?: { sid?: string } }; - - if (data.success && data.data?.sid) { - const sid = data.data.sid; - cacheSynologySID(userId, sid); - return { success: true, sid }; - } - - return { success: false, error: { code: 500, message: 'Failed to get Synology session' } }; -} - -// Helper: Clear cached SID - -function clearSynologySID(userId: number): void { - try { - db.prepare('UPDATE users SET synology_sid = NULL WHERE id = ?').run(userId); - } catch { - // Ignore if columns don't exist yet - } -} - -interface ApiCallParams { - api: string; - method: string; - version?: number; - [key: string]: any; -} - -interface SynologyApiResponse { - success: boolean; - data?: T; - error?: { code: number, message?: string }; -} - -function prepareSynologyEndpoint(url: string): string { - url = url.replace(/\/$/, ''); - if (!/^https?:\/\//.test(url)) { - url = `https://${url}`; - } - return `${url}/photo/webapi/entry.cgi`; -} - -function splitPackedSynologyId(rawId: string): { id: string; cacheKey: string; assetId: string } { - const id = rawId.split('_')[0]; - return { id: id, cacheKey: rawId, assetId: rawId }; -} - -function transformSynologyPhoto(item: any): any { - const address = item.additional?.address || {}; - return { - id: item.additional?.thumbnail?.cache_key, - takenAt: item.time ? new Date(item.time * 1000).toISOString() : null, - city: address.city || null, - country: address.country || null, - }; -} - -async function callSynologyApi(userId: number, params: ApiCallParams): Promise> { - try { - const creds = getSynologyCredentials(userId); - if (!creds) { - return { success: false, error: { code: 400, message: 'Synology not configured' } }; - } - const endpoint = prepareSynologyEndpoint(creds.synology_url); - - - const body = new URLSearchParams(); - for (const [key, value] of Object.entries(params)) { - if (value === undefined || value === null) continue; - body.append(key, typeof value === 'object' ? JSON.stringify(value) : String(value)); - } - - const sid = await getSynologySession(userId); - if (!sid.success || !sid.sid) { - return { success: false, error: sid.error || { code: 500, message: 'Failed to get Synology session' } }; - } - body.append('_sid', sid.sid); - - const resp = await fetch(endpoint, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', - }, - body, - signal: AbortSignal.timeout(30000), - }); - - - if (!resp.ok) { - const text = await resp.text(); - return { success: false, error: { code: resp.status, message: text } }; - } - - const result = await resp.json() as SynologyApiResponse; - if (!result.success && result.error?.code === 119) { - clearSynologySID(userId); - return callSynologyApi(userId, params); - } - return result; - } catch (err) { - return { success: false, error: { code: -1, message: err instanceof Error ? err.message : 'Unknown error' } }; - } -} - -// Settings router.get('/settings', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const creds = getSynologyCredentials(authReq.user.id); - res.json({ - synology_url: creds?.synology_url || '', - synology_username: creds?.synology_username || '', - connected: !!(creds?.synology_url && creds?.synology_username), - }); + const authReq = req as AuthRequest; + res.json(getSynologySettings(authReq.user.id)); }); -router.put('/settings', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { synology_url, synology_username, synology_password } = req.body; +router.put('/settings', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const body = req.body as Record; + const synology_url = parseStringBodyField(body.synology_url); + const synology_username = parseStringBodyField(body.synology_username); + const synology_password = parseStringBodyField(body.synology_password); - const url = String(synology_url || '').trim(); - const username = String(synology_username || '').trim(); - const password = String(synology_password || '').trim(); + if (!synology_url || !synology_username) { + return handleSynologyError(res, new SynologyServiceError(400, 'URL and username are required'), 'Missing required fields'); + } - if (!url || !username) { - return res.status(400).json({ error: 'URL and username are required' }); - } - - const existing = db.prepare('SELECT synology_password FROM users WHERE id = ?').get(authReq.user.id) as { synology_password?: string | null } | undefined; - const existingEncryptedPassword = existing?.synology_password || null; - - // First-time setup requires password; later updates may keep existing password. - if (!password && !existingEncryptedPassword) { - return res.status(400).json({ error: 'Password is required' }); - } - - try { - db.prepare('UPDATE users SET synology_url = ?, synology_username = ?, synology_password = ? WHERE id = ?').run( - url, - username, - password ? maybe_encrypt_api_key(password) : existingEncryptedPassword, - authReq.user.id - ); - } catch (err) { - return res.status(400).json({ error: 'Failed to save settings' }); - } - - clearSynologySID(authReq.user.id); - res.json({ success: true }); + try { + await updateSynologySettings(authReq.user.id, synology_url, synology_username, synology_password); + res.json({ success: true }); + } catch (err: unknown) { + handleSynologyError(res, err, 'Failed to save settings'); + } }); -// Status router.get('/status', authenticate, async (req: Request, res: Response) => { - const authReq = req as AuthRequest; - - try { - const sid = await getSynologySession(authReq.user.id); - if (!sid.success || !sid.sid) { - return res.json({ connected: false, error: 'Authentication failed' }); - } - - const user = db.prepare('SELECT synology_username FROM users WHERE id = ?').get(authReq.user.id) as any; - res.json({ connected: true, user: { username: user.synology_username } }); - } catch (err: unknown) { - res.json({ connected: false, error: err instanceof Error ? err.message : 'Connection failed' }); - } + const authReq = req as AuthRequest; + res.json(await getSynologyStatus(authReq.user.id)); }); -// Test connection with provided credentials only router.post('/test', authenticate, async (req: Request, res: Response) => { - const { synology_url, synology_username, synology_password } = req.body as { synology_url?: string; synology_username?: string; synology_password?: string }; + const body = req.body as Record; + const synology_url = parseStringBodyField(body.synology_url); + const synology_username = parseStringBodyField(body.synology_username); + const synology_password = parseStringBodyField(body.synology_password); - const url = String(synology_url || '').trim(); - const username = String(synology_username || '').trim(); - const password = String(synology_password || '').trim(); - - if (!url || !username || !password) { - return res.json({ connected: false, error: 'URL, username, and password are required' }); - } - - const ssrf = await checkSsrf(url); - if (!ssrf.allowed) return res.json({ connected: false, error: ssrf.error ?? 'Invalid Synology URL' }); - - try { - const endpoint = prepareSynologyEndpoint(url); - const body = new URLSearchParams({ - api: 'SYNO.API.Auth', - method: 'login', - version: '3', - account: username, - passwd: password, - }); - - const resp = await fetch(endpoint, { - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', - }, - body, - signal: AbortSignal.timeout(30000), - }); - - if (!resp.ok) return res.json({ connected: false, error: `HTTP ${resp.status}` }); - const data = await resp.json() as { success: boolean; data?: { sid?: string } }; - if (!data.success || !data.data?.sid) return res.json({ connected: false, error: 'Authentication failed' }); - return res.json({ connected: true, user: { username } }); - } catch (err: unknown) { - return res.json({ connected: false, error: err instanceof Error ? err.message : 'Connection failed' }); - } -}); - -// Album linking parity with Immich -router.get('/albums', authenticate, async (req: Request, res: Response) => { - const authReq = req as AuthRequest; - try { - const result = await callSynologyApi<{ list: any[] }>(authReq.user.id, { - api: 'SYNO.Foto.Browse.Album', - method: 'list', - version: 4, - offset: 0, - limit: 100, - }); - - if (!result.success || !result.data) { - return res.status(502).json({ error: result.error?.message || 'Failed to fetch albums' }); + if (!synology_url || !synology_username || !synology_password) { + return handleSynologyError(res, new SynologyServiceError(400, 'URL, username and password are required'), 'Missing required fields'); } - const albums = (result.data.list || []).map((a: any) => ({ - id: String(a.id), - albumName: a.name || '', - assetCount: a.item_count || 0, - })); + res.json(await testSynologyConnection(synology_url, synology_username, synology_password)); +}); - res.json({ albums }); - } catch (err: unknown) { - res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology' }); - } +router.get('/albums', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + try { + res.json(await listSynologyAlbums(authReq.user.id)); + } catch (err: unknown) { + handleSynologyError(res, err, 'Could not reach Synology'); + } }); router.post('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { tripId } = req.params; - if (!canAccessTrip(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); - const { album_id, album_name } = req.body; - if (!album_id) return res.status(400).json({ error: 'album_id required' }); + const authReq = req as AuthRequest; + const { tripId } = req.params; + const body = req.body as Record; + const albumId = parseStringBodyField(body.album_id); + const albumName = parseStringBodyField(body.album_name); - try { - db.prepare( - 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)' - ).run(tripId, authReq.user.id, 'synologyphotos', String(album_id), album_name || ''); - res.json({ success: true }); - } catch { - res.status(400).json({ error: 'Album already linked' }); - } + if (!albumId) { + return handleSynologyError(res, new SynologyServiceError(400, 'Album ID is required'), 'Missing required fields'); + } + + try { + linkSynologyAlbum(authReq.user.id, tripId, albumId, albumName || undefined); + res.json({ success: true }); + } catch (err: unknown) { + handleSynologyError(res, err, 'Failed to link album'); + } }); router.post('/trips/:tripId/album-links/:linkId/sync', authenticate, async (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { tripId, linkId } = req.params; + const authReq = req as AuthRequest; + const { tripId, linkId } = req.params; - const link = db.prepare("SELECT * FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ? AND provider = 'synologyphotos'") - .get(linkId, tripId, authReq.user.id) as any; - if (!link) return res.status(404).json({ error: 'Album link not found' }); - - try { - const allItems: any[] = []; - const pageSize = 1000; - let offset = 0; - - while (true) { - const result = await callSynologyApi<{ list: any[] }>(authReq.user.id, { - api: 'SYNO.Foto.Browse.Item', - method: 'list', - version: 1, - album_id: Number(link.album_id), - offset, - limit: pageSize, - additional: ['thumbnail'], - }); - - if (!result.success || !result.data) { - return res.status(502).json({ error: result.error?.message || 'Failed to fetch album' }); - } - - const items = result.data.list || []; - allItems.push(...items); - if (items.length < pageSize) break; - offset += pageSize; + try { + const result = await syncSynologyAlbumLink(authReq.user.id, tripId, linkId); + res.json({ success: true, ...result }); + if (result.added > 0) { + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); + } + } catch (err: unknown) { + handleSynologyError(res, err, 'Could not reach Synology'); } - - const insert = db.prepare( - "INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, 'synologyphotos', 1)" - ); - - let added = 0; - for (const item of allItems) { - const transformed = transformSynologyPhoto(item); - const assetId = String(transformed?.id || '').trim(); - if (!assetId) continue; - const r = insert.run(tripId, authReq.user.id, assetId); - if (r.changes > 0) added++; - } - - db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); - - res.json({ success: true, added, total: allItems.length }); - if (added > 0) { - broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); - } - } catch (err: unknown) { - res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology' }); - } }); -// Search router.post('/search', authenticate, async (req: Request, res: Response) => { - const authReq = req as AuthRequest; - let { from, to, offset = 0, limit = 300 } = req.body; + const authReq = req as AuthRequest; + const body = req.body as Record; + const from = parseStringBodyField(body.from); + const to = parseStringBodyField(body.to); + const offset = parseNumberBodyField(body.offset, 0); + const limit = parseNumberBodyField(body.limit, 300); - try { - const params: any = { - api: 'SYNO.Foto.Search.Search', - method: 'list_item', - version: 1, - offset, - limit, - keyword: '.', - additional: ['thumbnail', 'address'], - }; - - if (from || to) { - if (from) { - params.start_time = Math.floor(new Date(from).getTime() / 1000); - } - if (to) { - params.end_time = Math.floor(new Date(to).getTime() / 1000) + 86400; // Include entire end day - } + try { + const result = await searchSynologyPhotos( + authReq.user.id, + from || undefined, + to || undefined, + offset, + limit, + ); + res.json(result); + } catch (err: unknown) { + handleSynologyError(res, err, 'Could not reach Synology'); } - - - const result = await callSynologyApi<{ list: any[]; total: number }>(authReq.user.id, params); - - if (!result.success || !result.data) { - return res.status(502).json({ error: result.error?.message || 'Failed to fetch album photos' }); - } - - const allItems = (result.data.list || []); - const total = allItems.length; - - const assets = allItems.map((item: any) => transformSynologyPhoto(item)); - - res.json({ - assets, - total, - hasMore: total == limit, - }); - } catch (err: unknown) { - res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology' }); - } }); -// Proxy Synology Assets - -// Asset info endpoint (returns metadata, not image) router.get('/assets/:photoId/info', authenticate, async (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { photoId } = req.params; - const parsedId = splitPackedSynologyId(photoId); - const { userId } = req.query; + const authReq = req as AuthRequest; + const { photoId } = req.params; - const targetUserId = userId ? Number(userId) : authReq.user.id; - - try { - const result = await callSynologyApi(targetUserId, { - api: 'SYNO.Foto.Browse.Item', - method: 'get', - version: 5, - id: `[${parsedId.id}]`, - additional: ['resolution', 'exif', 'gps', 'address', 'orientation', 'description'], - }); - if (!result.success || !result.data) { - return res.status(404).json({ error: 'Photo not found' }); + try { + res.json(await getSynologyAssetInfo(authReq.user.id, photoId, getSynologyTargetUserId(req))); + } catch (err: unknown) { + handleSynologyError(res, err, 'Could not reach Synology'); } - - const metadata = result.data.list[0]; - console.log(metadata); - const exif = metadata.additional?.exif || {}; - const address = metadata.additional?.address || {}; - const gps = metadata.additional?.gps || {}; - res.json({ - id: photoId, - takenAt: metadata.time ? new Date(metadata.time * 1000).toISOString() : null, - city: address.city || null, - country: address.country || null, - state: address.state || null, - camera: exif.camera || null, - lens: exif.lens || null, - focalLength: exif.focal_length || null, - aperture: exif.aperture || null, - shutter: exif.exposure_time || null, - iso: exif.iso || null, - lat: gps.latitude || null, - lng: gps.longitude || null, - orientation: metadata.additional?.orientation || null, - description: metadata.additional?.description || null, - filename: metadata.filename || null, - filesize: metadata.filesize || null, - width: metadata.additional?.resolution?.width || null, - height: metadata.additional?.resolution?.height || null, - fileSize: metadata.filesize || null, - fileName: metadata.filename || null, - }); - } catch (err: unknown) { - res.status(502).json({ error: err instanceof Error ? err.message : 'Could not reach Synology'}); - } }); -// Middleware: Accept ephemeral token from query param for tags -function authFromQuery(req: Request, res: Response, next: NextFunction) { - const queryToken = req.query.token as string | undefined; - if (queryToken) { - const userId = consumeEphemeralToken(queryToken, 'synologyphotos'); - if (!userId) return res.status(401).send('Invalid or expired token'); - const user = db.prepare('SELECT id, username, email, role, mfa_enabled FROM users WHERE id = ?').get(userId) as any; - if (!user) return res.status(401).send('User not found'); - (req as AuthRequest).user = user; - return next(); - } - return (authenticate as any)(req, res, next); -} +router.get('/assets/:photoId/thumbnail', synologyAuthFromQuery, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { photoId } = req.params; + const { size = 'sm' } = req.query; -router.get('/assets/:photoId/thumbnail', authFromQuery, async (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { photoId } = req.params; - const parsedId = splitPackedSynologyId(photoId); - const { userId, size = 'sm' } = req.query; - - const targetUserId = userId ? Number(userId) : authReq.user.id; - - const creds = getSynologyCredentials(targetUserId); - if (!creds) { - return res.status(404).send('Not found'); - } - - try { - const sid = await getSynologySession(authReq.user.id); - if (!sid.success && !sid.sid) { - return res.status(401).send('Authentication failed'); + try { + const proxy = await streamSynologyAsset(authReq.user.id, getSynologyTargetUserId(req), photoId, 'thumbnail', String(size)); + await pipeSynologyProxy(res, proxy); + } catch (err: unknown) { + if (res.headersSent) { + return; + } + handleSynologyError(res, err, 'Proxy error'); } - - const params = new URLSearchParams({ - api: 'SYNO.Foto.Thumbnail', - method: 'get', - version: '2', - mode: 'download', - id: parsedId.id, - type: 'unit', - size: String(size), - cache_key: parsedId.cacheKey, - _sid: sid.sid, - }); - const url = prepareSynologyEndpoint(creds.synology_url) + '?' + params.toString(); - const resp = await fetch(url, { - signal: AbortSignal.timeout(30000), - }); - - if (!resp.ok) { - return res.status(resp.status).send('Failed'); - } - - res.status(resp.status); - copyProxyHeaders(res, resp, ['content-type', 'cache-control', 'content-length', 'content-disposition']); - res.set('Content-Type', resp.headers.get('content-type') || 'image/jpeg'); - res.set('Cache-Control', resp.headers.get('cache-control') || 'public, max-age=86400'); - - if (!resp.body) { - return res.end(); - } - - await pipeline(Readable.fromWeb(resp.body), res); - } catch (err: unknown) { - if (res.headersSent) { - return; - } - res.status(502).send('Proxy error: ' + (err instanceof Error ? err.message : String(err))); - } }); +router.get('/assets/:photoId/original', synologyAuthFromQuery, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { photoId } = req.params; -router.get('/assets/:photoId/original', authFromQuery, async (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { photoId } = req.params; - const parsedId = splitPackedSynologyId(photoId || ''); - const { userId} = req.query; - - const targetUserId = userId ? Number(userId) : authReq.user.id; - - const creds = getSynologyCredentials(targetUserId); - if (!creds) { - return res.status(404).send('Not found'); - } - - try { - const sid = await getSynologySession(authReq.user.id); - if (!sid.success && !sid.sid) { - return res.status(401).send('Authentication failed'); + try { + const proxy = await streamSynologyAsset(authReq.user.id, getSynologyTargetUserId(req), photoId, 'original'); + await pipeSynologyProxy(res, proxy); + } catch (err: unknown) { + if (res.headersSent) { + return; + } + handleSynologyError(res, err, 'Proxy error'); } - - const params = new URLSearchParams({ - api: 'SYNO.Foto.Download', - method: 'download', - version: '2', - cache_key: parsedId.cacheKey, - unit_id: `[${parsedId.id}]`, - _sid: sid.sid, - }); - - const url = prepareSynologyEndpoint(creds.synology_url) + '?' + params.toString(); - const resp = await fetch(url, { - signal: AbortSignal.timeout(30000), - }); - - if (!resp.ok) { - const body = await resp.text(); - return res.status(resp.status).send('Failed: ' + body); - } - - res.status(resp.status); - copyProxyHeaders(res, resp, ['content-type', 'cache-control', 'content-length', 'content-disposition']); - res.set('Content-Type', resp.headers.get('content-type') || 'application/octet-stream'); - res.set('Cache-Control', resp.headers.get('cache-control') || 'public, max-age=86400'); - - if (!resp.body) { - return res.end(); - } - - await pipeline(Readable.fromWeb(resp.body), res); - } catch (err: unknown) { - if (res.headersSent) { - return; - } - res.status(502).send('Proxy error: ' + (err instanceof Error ? err.message : String(err))); - } }); - -export default router; +export default router; \ No newline at end of file diff --git a/server/src/services/synologyService.ts b/server/src/services/synologyService.ts new file mode 100644 index 0000000..1c25ef5 --- /dev/null +++ b/server/src/services/synologyService.ts @@ -0,0 +1,651 @@ +import { Readable } from 'node:stream'; +import { pipeline } from 'node:stream/promises'; +import { NextFunction, Request, Response as ExpressResponse } from 'express'; +import { db, canAccessTrip } from '../db/database'; +import { decrypt_api_key, maybe_encrypt_api_key } from './apiKeyCrypto'; +import { authenticate } from '../middleware/auth'; +import { AuthRequest } from '../types'; +import { consumeEphemeralToken } from './ephemeralTokens'; +import { checkSsrf } from '../utils/ssrfGuard'; +import { no } from 'zod/locales'; + +const SYNOLOGY_API_TIMEOUT_MS = 30000; +const SYNOLOGY_PROVIDER = 'synologyphotos'; +const SYNOLOGY_ENDPOINT_PATH = '/photo/webapi/entry.cgi'; +const SYNOLOGY_DEFAULT_THUMBNAIL_SIZE = 'sm'; + +interface SynologyCredentials { + synology_url: string; + synology_username: string; + synology_password: string; +} + +interface SynologySession { + success: boolean; + sid?: string; + error?: { code: number; message?: string }; +} + +interface ApiCallParams { + api: string; + method: string; + version?: number; + [key: string]: unknown; +} + +interface SynologyApiResponse { + success: boolean; + data?: T; + error?: { code: number; message?: string }; +} + +export class SynologyServiceError extends Error { + status: number; + + constructor(status: number, message: string) { + super(message); + this.status = status; + } +} + +export interface SynologySettings { + synology_url: string; + synology_username: string; + connected: boolean; +} + +export interface SynologyConnectionResult { + connected: boolean; + user?: { username: string }; + error?: string; +} + +export interface SynologyAlbumLinkInput { + album_id?: string | number; + album_name?: string; +} + +export interface SynologySearchInput { + from?: string; + to?: string; + offset?: number; + limit?: number; +} + +export interface SynologyProxyResult { + status: number; + headers: Record; + body: ReadableStream | null; +} + +interface SynologyPhotoInfo { + id: string; + takenAt: string | null; + city: string | null; + country: string | null; + state?: string | null; + camera?: string | null; + lens?: string | null; + focalLength?: string | number | null; + aperture?: string | number | null; + shutter?: string | number | null; + iso?: string | number | null; + lat?: number | null; + lng?: number | null; + orientation?: number | null; + description?: string | null; + filename?: string | null; + filesize?: number | null; + width?: number | null; + height?: number | null; + fileSize?: number | null; + fileName?: string | null; +} + +interface SynologyPhotoItem { + id?: string | number; + filename?: string; + filesize?: number; + time?: number; + item_count?: number; + name?: string; + additional?: { + thumbnail?: { cache_key?: string }; + address?: { city?: string; country?: string; state?: string }; + resolution?: { width?: number; height?: number }; + exif?: { + camera?: string; + lens?: string; + focal_length?: string | number; + aperture?: string | number; + exposure_time?: string | number; + iso?: string | number; + }; + gps?: { latitude?: number; longitude?: number }; + orientation?: number; + description?: string; + }; +} + +type SynologyUserRecord = { + synology_url?: string | null; + synology_username?: string | null; + synology_password?: string | null; + synology_sid?: string | null; +}; + +function readSynologyUser(userId: number, columns: string[]): SynologyUserRecord | null { + try { + + if (!columns) return null; + + const row = db.prepare(`SELECT synology_url, synology_username, synology_password, synology_sid FROM users WHERE id = ?`).get(userId) as SynologyUserRecord | undefined; + + if (!row) return null; + + const filtered: SynologyUserRecord = {}; + for (const column of columns) { + filtered[column] = row[column]; + } + + return filtered || null; + } catch { + return null; + } +} + +function getSynologyCredentials(userId: number): SynologyCredentials | null { + const user = readSynologyUser(userId, ['synology_url', 'synology_username', 'synology_password']); + if (!user?.synology_url || !user.synology_username || !user.synology_password) return null; + return { + synology_url: user.synology_url, + synology_username: user.synology_username, + synology_password: decrypt_api_key(user.synology_password) as string, + }; +} + + +function buildSynologyEndpoint(url: string): string { + const normalized = url.replace(/\/$/, '').match(/^https?:\/\//) ? url.replace(/\/$/, '') : `https://${url.replace(/\/$/, '')}`; + return `${normalized}${SYNOLOGY_ENDPOINT_PATH}`; +} + +function buildSynologyFormBody(params: ApiCallParams): URLSearchParams { + const body = new URLSearchParams(); + for (const [key, value] of Object.entries(params)) { + if (value === undefined || value === null) continue; + body.append(key, typeof value === 'object' ? JSON.stringify(value) : String(value)); + } + return body; +} + +async function fetchSynologyJson(url: string, body: URLSearchParams): Promise> { + const endpoint = buildSynologyEndpoint(url); + const resp = await fetch(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + }, + body, + signal: AbortSignal.timeout(SYNOLOGY_API_TIMEOUT_MS), + }); + + if (!resp.ok) { + const text = await resp.text(); + return { success: false, error: { code: resp.status, message: text } }; + } + + return resp.json() as Promise>; +} + +async function loginToSynology(url: string, username: string, password: string): Promise> { + const body = new URLSearchParams({ + api: 'SYNO.API.Auth', + method: 'login', + version: '3', + account: username, + passwd: password, + }); + + return fetchSynologyJson<{ sid?: string }>(url, body); +} + +async function requestSynologyApi(userId: number, params: ApiCallParams): Promise> { + const creds = getSynologyCredentials(userId); + if (!creds) { + return { success: false, error: { code: 400, message: 'Synology not configured' } }; + } + + const session = await getSynologySession(userId); + if (!session.success || !session.sid) { + return { success: false, error: session.error || { code: 400, message: 'Failed to get Synology session' } }; + } + + const body = buildSynologyFormBody({ ...params, _sid: session.sid }); + const result = await fetchSynologyJson(creds.synology_url, body); + if (!result.success && result.error?.code === 119) { + clearSynologySID(userId); + const retrySession = await getSynologySession(userId); + if (!retrySession.success || !retrySession.sid) { + return { success: false, error: retrySession.error || { code: 400, message: 'Failed to get Synology session' } }; + } + return fetchSynologyJson(creds.synology_url, buildSynologyFormBody({ ...params, _sid: retrySession.sid })); + } + return result; +} + +async function requestSynologyStream(url: string): Promise { + return fetch(url, { + signal: AbortSignal.timeout(SYNOLOGY_API_TIMEOUT_MS), + }); +} + +function normalizeSynologyPhotoInfo(item: SynologyPhotoItem): SynologyPhotoInfo { + const address = item.additional?.address || {}; + const exif = item.additional?.exif || {}; + const gps = item.additional?.gps || {}; + + return { + id: String(item.additional?.thumbnail?.cache_key || ''), + takenAt: item.time ? new Date(item.time * 1000).toISOString() : null, + city: address.city || null, + country: address.country || null, + state: address.state || null, + camera: exif.camera || null, + lens: exif.lens || null, + focalLength: exif.focal_length || null, + aperture: exif.aperture || null, + shutter: exif.exposure_time || null, + iso: exif.iso || null, + lat: gps.latitude || null, + lng: gps.longitude || null, + orientation: item.additional?.orientation || null, + description: item.additional?.description || null, + filename: item.filename || null, + filesize: item.filesize || null, + width: item.additional?.resolution?.width || null, + height: item.additional?.resolution?.height || null, + fileSize: item.filesize || null, + fileName: item.filename || null, + }; +} + +export function synologyAuthFromQuery(req: Request, res: ExpressResponse, next: NextFunction) { + const queryToken = req.query.token as string | undefined; + if (queryToken) { + const userId = consumeEphemeralToken(queryToken, SYNOLOGY_PROVIDER); + if (!userId) return res.status(401).send('Invalid or expired token'); + const user = db.prepare('SELECT id, username, email, role, mfa_enabled FROM users WHERE id = ?').get(userId) as any; + if (!user) return res.status(401).send('User not found'); + (req as AuthRequest).user = user; + return next(); + } + return (authenticate as any)(req, res, next); +} + +export function getSynologyTargetUserId(req: Request): number { + const { userId } = req.query; + return Number(userId); +} + +export function handleSynologyError(res: ExpressResponse, err: unknown, fallbackMessage: string): ExpressResponse { + if (err instanceof SynologyServiceError) { + return res.status(err.status).json({ error: err.message }); + } + return res.status(502).json({ error: err instanceof Error ? err.message : fallbackMessage }); +} + +function cacheSynologySID(userId: number, sid: string): void { + db.prepare('UPDATE users SET synology_sid = ? WHERE id = ?').run(sid, userId); +} + +function clearSynologySID(userId: number): void { + db.prepare('UPDATE users SET synology_sid = NULL WHERE id = ?').run(userId); +} + +function splitPackedSynologyId(rawId: string): { id: string; cacheKey: string; assetId: string } { + const id = rawId.split('_')[0]; + return { id, cacheKey: rawId, assetId: rawId }; +} + +function canStreamSynologyAsset(requestingUserId: number, targetUserId: number, assetId: string): boolean { + if (requestingUserId === targetUserId) { + return true; + } + + const sharedAsset = db.prepare(` + SELECT 1 + FROM trip_photos + WHERE user_id = ? + AND asset_id = ? + AND provider = 'synologyphotos' + AND shared = 1 + LIMIT 1 + `).get(targetUserId, assetId); + + return !!sharedAsset; +} + +async function getSynologySession(userId: number): Promise { + const cachedSid = readSynologyUser(userId, ['synology_sid'])?.synology_sid || null; + if (cachedSid) { + return { success: true, sid: cachedSid }; + } + + const creds = getSynologyCredentials(userId); + if (!creds) { + return { success: false, error: { code: 400, message: 'Invalid Synology credentials' } }; + } + + const resp = await loginToSynology(creds.synology_url, creds.synology_username, creds.synology_password); + + if (!resp.success || !resp.data?.sid) { + return { success: false, error: resp.error || { code: 400, message: 'Failed to authenticate with Synology' } }; + } + + cacheSynologySID(userId, resp.data.sid); + return { success: true, sid: resp.data.sid }; +} + +export async function getSynologySettings(userId: number): Promise { + const creds = getSynologyCredentials(userId); + const session = await getSynologySession(userId); + return { + synology_url: creds?.synology_url || '', + synology_username: creds?.synology_username || '', + connected: session.success, + }; +} + +export async function updateSynologySettings(userId: number, synologyUrl: string, synologyUsername: string, synologyPassword?: string): Promise { + + const ssrf = await checkSsrf(synologyUrl); + if (!ssrf.allowed) { + throw new SynologyServiceError(400, ssrf.error ?? 'Invalid Synology URL'); + } + + const existingEncryptedPassword = readSynologyUser(userId, ['synology_password'])?.synology_password || null; + + if (!synologyPassword && !existingEncryptedPassword) { + throw new SynologyServiceError(400, 'No stored password found. Please provide a password to save settings.'); + } + + try { + db.prepare('UPDATE users SET synology_url = ?, synology_username = ?, synology_password = ? WHERE id = ?').run( + synologyUrl, + synologyUsername, + synologyPassword ? maybe_encrypt_api_key(synologyPassword) : existingEncryptedPassword, + userId, + ); + } catch { + throw new SynologyServiceError(400, 'Failed to save settings'); + } + + clearSynologySID(userId); + await getSynologySession(userId); +} + +export async function getSynologyStatus(userId: number): Promise { + try { + const sid = await getSynologySession(userId); + if (!sid.success || !sid.sid) { + return { connected: false, error: 'Authentication failed' }; + } + + const user = db.prepare('SELECT synology_username FROM users WHERE id = ?').get(userId) as { synology_username?: string } | undefined; + return { connected: true, user: { username: user?.synology_username || '' } }; + } catch (err: unknown) { + return { connected: false, error: err instanceof Error ? err.message : 'Connection failed' }; + } +} + +export async function testSynologyConnection(synologyUrl: string, synologyUsername: string, synologyPassword: string): Promise { + + const ssrf = await checkSsrf(synologyUrl); + if (!ssrf.allowed) { + return { connected: false, error: ssrf.error ?? 'Invalid Synology URL' }; + } + try { + const login = await loginToSynology(synologyUrl, synologyUsername, synologyPassword); + if (!login.success || !login.data?.sid) { + return { connected: false, error: login.error?.message || 'Authentication failed' }; + } + return { connected: true, user: { username: synologyUsername } }; + } catch (err: unknown) { + return { connected: false, error: err instanceof Error ? err.message : 'Connection failed' }; + } +} + +export async function listSynologyAlbums(userId: number): Promise<{ albums: Array<{ id: string; albumName: string; assetCount: number }> }> { + const result = await requestSynologyApi<{ list: SynologyPhotoItem[] }>(userId, { + api: 'SYNO.Foto.Browse.Album', + method: 'list', + version: 4, + offset: 0, + limit: 100, + }); + + if (!result.success || !result.data) { + throw new SynologyServiceError(result.error?.code || 500, result.error?.message || 'Failed to fetch albums'); + } + + const albums = (result.data.list || []).map((album: SynologyPhotoItem) => ({ + id: String(album.id), + albumName: album.name || '', + assetCount: album.item_count || 0, + })); + + return { albums }; +} + +export function linkSynologyAlbum(userId: number, tripId: string, albumId: string | number | undefined, albumName?: string): void { + if (!canAccessTrip(tripId, userId)) { + throw new SynologyServiceError(404, 'Trip not found'); + } + + if (!albumId) { + throw new SynologyServiceError(400, 'album_id required'); + } + + const changes = db.prepare( + 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)' + ).run(tripId, userId, SYNOLOGY_PROVIDER, String(albumId), albumName || '').changes; + + if (changes === 0) { + throw new SynologyServiceError(400, 'Album already linked'); + } +} + +export async function syncSynologyAlbumLink(userId: number, tripId: string, linkId: string): Promise<{ added: number; total: number }> { + const link = db.prepare(`SELECT * FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ? AND provider = ?`) + .get(linkId, tripId, userId, SYNOLOGY_PROVIDER) as { album_id?: string | number } | undefined; + + if (!link) { + throw new SynologyServiceError(404, 'Album link not found'); + } + + const allItems: SynologyPhotoItem[] = []; + const pageSize = 1000; + let offset = 0; + + while (true) { + const result = await requestSynologyApi<{ list: SynologyPhotoItem[] }>(userId, { + api: 'SYNO.Foto.Browse.Item', + method: 'list', + version: 1, + album_id: Number(link.album_id), + offset, + limit: pageSize, + additional: ['thumbnail'], + }); + + if (!result.success || !result.data) { + throw new SynologyServiceError(502, result.error?.message || 'Failed to fetch album'); + } + + const items = result.data.list || []; + allItems.push(...items); + if (items.length < pageSize) break; + offset += pageSize; + } + + const insert = db.prepare( + "INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, 'synologyphotos', 1)" + ); + + let added = 0; + for (const item of allItems) { + const transformed = normalizeSynologyPhotoInfo(item); + const assetId = String(transformed?.id || '').trim(); + if (!assetId) continue; + const result = insert.run(tripId, userId, assetId); + if (result.changes > 0) added++; + } + + db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); + + return { added, total: allItems.length }; +} + +export async function searchSynologyPhotos(userId: number, from?: string, to?: string, offset = 0, limit = 300): Promise<{ assets: SynologyPhotoInfo[]; total: number; hasMore: boolean }> { + const params: ApiCallParams = { + api: 'SYNO.Foto.Search.Search', + method: 'list_item', + version: 1, + offset, + limit, + keyword: '.', + additional: ['thumbnail', 'address'], + }; + + if (from || to) { + if (from) { + params.start_time = Math.floor(new Date(from).getTime() / 1000); + } + if (to) { + params.end_time = Math.floor(new Date(to).getTime() / 1000) + 86400; //adding it as the next day 86400 seconds in day + } + } + + const result = await requestSynologyApi<{ list: SynologyPhotoItem[]; total: number }>(userId, params); + if (!result.success || !result.data) { + throw new SynologyServiceError(502, result.error?.message || 'Failed to fetch album photos'); + } + + const allItems = result.data.list || []; + const total = allItems.length; + const assets = allItems.map(item => normalizeSynologyPhotoInfo(item)); + + return { + assets, + total, + hasMore: total === limit, + }; +} + +export async function getSynologyAssetInfo(userId: number, photoId: string, targetUserId?: number): Promise { + if (!canStreamSynologyAsset(userId, targetUserId ?? userId, photoId)) { + throw new SynologyServiceError(403, 'Youd don\'t have access to this photo'); + } + const parsedId = splitPackedSynologyId(photoId); + const result = await requestSynologyApi<{ list: SynologyPhotoItem[] }>(targetUserId ?? userId, { + api: 'SYNO.Foto.Browse.Item', + method: 'get', + version: 5, + id: `[${parsedId.id}]`, + additional: ['resolution', 'exif', 'gps', 'address', 'orientation', 'description'], + }); + + if (!result.success || !result.data) { + throw new SynologyServiceError(404, 'Photo not found'); + } + + const metadata = result.data.list?.[0]; + if (!metadata) { + throw new SynologyServiceError(404, 'Photo not found'); + } + + const normalized = normalizeSynologyPhotoInfo(metadata); + normalized.id = photoId; + return normalized; +} + +export async function streamSynologyAsset( + userId: number, + targetUserId: number, + photoId: string, + kind: 'thumbnail' | 'original', + size?: string, +): Promise { + if (!canStreamSynologyAsset(userId, targetUserId, photoId)) { + throw new SynologyServiceError(403, 'Youd don\'t have access to this photo'); + } + + const parsedId = splitPackedSynologyId(photoId); + const synology_url = getSynologyCredentials(targetUserId).synology_url; + if (!synology_url) { + throw new SynologyServiceError(402, 'User not configured with Synology'); + } + + const sid = await getSynologySession(targetUserId); + if (!sid.success || !sid.sid) { + throw new SynologyServiceError(401, 'Authentication failed'); + } + + + + const params = kind === 'thumbnail' + ? new URLSearchParams({ + api: 'SYNO.Foto.Thumbnail', + method: 'get', + version: '2', + mode: 'download', + id: parsedId.id, + type: 'unit', + size: String(size || SYNOLOGY_DEFAULT_THUMBNAIL_SIZE), + cache_key: parsedId.cacheKey, + _sid: sid.sid, + }) + : new URLSearchParams({ + api: 'SYNO.Foto.Download', + method: 'download', + version: '2', + cache_key: parsedId.cacheKey, + unit_id: `[${parsedId.id}]`, + _sid: sid.sid, + }); + + const url = `${buildSynologyEndpoint(synology_url)}?${params.toString()}`; + const resp = await requestSynologyStream(url); + + if (!resp.ok) { + const body = kind === 'original' ? await resp.text() : 'Failed'; + throw new SynologyServiceError(resp.status, kind === 'original' ? `Failed: ${body}` : body); + } + + return { + status: resp.status, + headers: { + 'content-type': resp.headers.get('content-type') || (kind === 'thumbnail' ? 'image/jpeg' : 'application/octet-stream'), + 'cache-control': resp.headers.get('cache-control') || 'public, max-age=86400', + 'content-length': resp.headers.get('content-length'), + 'content-disposition': resp.headers.get('content-disposition'), + }, + body: resp.body, + }; +} + +export async function pipeSynologyProxy(response: ExpressResponse, proxy: SynologyProxyResult): Promise { + response.status(proxy.status); + if (proxy.headers['content-type']) response.set('Content-Type', proxy.headers['content-type'] as string); + if (proxy.headers['cache-control']) response.set('Cache-Control', proxy.headers['cache-control'] as string); + if (proxy.headers['content-length']) response.set('Content-Length', proxy.headers['content-length'] as string); + if (proxy.headers['content-disposition']) response.set('Content-Disposition', proxy.headers['content-disposition'] as string); + + if (!proxy.body) { + response.end(); + return; + } + + await pipeline(Readable.fromWeb(proxy.body), response); +} From 2ae9da315335f68bbb2be967b5ca0a0930aa8118 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 16:25:58 +0200 Subject: [PATCH 017/117] fix for auth tokens --- server/src/routes/auth.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.ts index 29aadd4..0216e17 100644 --- a/server/src/routes/auth.ts +++ b/server/src/routes/auth.ts @@ -319,9 +319,9 @@ router.post('/resource-token', authenticate, (req: Request, res: Response) => { if (purpose !== 'download' && purpose !== 'immich' && purpose !== 'synologyphotos') { return res.status(400).json({ error: 'Invalid purpose' }); } - const token = createEphemeralToken(authReq.user.id, purpose); + const token = createResourceToken(authReq.user.id, purpose); if (!token) return res.status(503).json({ error: 'Service unavailable' }); - res.json({ token }); + res.json(token); }); export default router; From 8c7f8d6ad1e8892c05bf313c7589049724f13025 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 16:37:21 +0200 Subject: [PATCH 018/117] fixing routes for immich --- server/src/routes/immich.ts | 123 ++++++------------------------------ 1 file changed, 20 insertions(+), 103 deletions(-) diff --git a/server/src/routes/immich.ts b/server/src/routes/immich.ts index 6c4363a..7021ec7 100644 --- a/server/src/routes/immich.ts +++ b/server/src/routes/immich.ts @@ -61,42 +61,13 @@ router.put('/settings', authenticate, async (req: Request, res: Response) => { router.get('/status', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - const creds = getImmichCredentials(authReq.user.id); - if (!creds) { - return res.json({ connected: false, error: 'Not configured' }); - } - try { - const resp = await fetch(`${creds.immich_url}/api/users/me`, { - headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, - signal: AbortSignal.timeout(10000), - }); - if (!resp.ok) return res.json({ connected: false, error: `HTTP ${resp.status}` }); - const data = await resp.json() as { name?: string; email?: string }; - res.json({ connected: true, user: { name: data.name, email: data.email } }); - } catch (err: unknown) { - res.json({ connected: false, error: err instanceof Error ? err.message : 'Connection failed' }); - } + res.json(await getConnectionStatus(authReq.user.id)); }); -// Test connection with provided credentials only router.post('/test', authenticate, async (req: Request, res: Response) => { - const { immich_url, immich_api_key } = req.body as { immich_url?: string; immich_api_key?: string }; - const url = String(immich_url || '').trim(); - const apiKey = String(immich_api_key || '').trim(); - if (!url || !apiKey) return res.json({ connected: false, error: 'URL and API key required' }); - const ssrf = await checkSsrf(url); - if (!ssrf.allowed) return res.json({ connected: false, error: ssrf.error ?? 'Invalid Immich URL' }); - try { - const resp = await fetch(`${url}/api/users/me`, { - headers: { 'x-api-key': apiKey, 'Accept': 'application/json' }, - signal: AbortSignal.timeout(10000), - }); - if (!resp.ok) return res.json({ connected: false, error: `HTTP ${resp.status}` }); - const data = await resp.json() as { name?: string; email?: string }; - res.json({ connected: true, user: { name: data.name, email: data.email } }); - } catch (err: unknown) { - res.json({ connected: false, error: err instanceof Error ? err.message : 'Connection failed' }); - } + const { immich_url, immich_api_key } = req.body; + if (!immich_url || !immich_api_key) return res.json({ connected: false, error: 'URL and API key required' }); + res.json(await testConnection(immich_url, immich_api_key)); }); // ── Browse Immich Library (for photo picker) ─────────────────────────────── @@ -118,13 +89,11 @@ router.post('/search', authenticate, async (req: Request, res: Response) => { // ── Asset Details ────────────────────────────────────────────────────────── -router.get('/assets/:assetId/info', authenticate, async (req: Request, res: Response) => { +router.get('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; - const { assetId } = req.params; - if (!isValidAssetId(assetId)) return res.status(400).json({ error: 'Invalid asset ID' }); - const result = await getAssetInfo(authReq.user.id, assetId); - if (result.error) return res.status(result.status!).json({ error: result.error }); - res.json(result.data); + const { tripId } = req.params; + if (!canAccessTrip(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); + res.json({ photos: listTripPhotos(tripId, authReq.user.id) }); }); // ── Proxy Immich Assets ──────────────────────────────────────────────────── @@ -155,82 +124,30 @@ router.get('/assets/:assetId/original', authFromQuery, async (req: Request, res: router.get('/albums', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - const creds = getImmichCredentials(authReq.user.id); - if (!creds) return res.status(400).json({ error: 'Immich not configured' }); - - try { - const resp = await fetch(`${creds.immich_url}/api/albums`, { - headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, - signal: AbortSignal.timeout(10000), - }); - if (!resp.ok) return res.status(resp.status).json({ error: 'Failed to fetch albums' }); - const albums = (await resp.json() as any[]).map((a: any) => ({ - id: a.id, - albumName: a.albumName, - assetCount: a.assetCount || 0, - startDate: a.startDate, - endDate: a.endDate, - albumThumbnailAssetId: a.albumThumbnailAssetId, - })); - res.json({ albums }); - } catch { - res.status(502).json({ error: 'Could not reach Immich' }); - } + const result = await listAlbums(authReq.user.id); + if (result.error) return res.status(result.status!).json({ error: result.error }); + res.json({ albums: result.albums }); }); + router.post('/trips/:tripId/album-links', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; if (!canAccessTrip(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); const { album_id, album_name } = req.body; if (!album_id) return res.status(400).json({ error: 'album_id required' }); - - try { - db.prepare( - 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)' - ).run(tripId, authReq.user.id, 'immich', album_id, album_name || ''); - res.json({ success: true }); - } catch (err: any) { - res.status(400).json({ error: 'Album already linked' }); - } + const result = createAlbumLink(tripId, authReq.user.id, album_id, album_name); + if (!result.success) return res.status(400).json({ error: result.error }); + res.json({ success: true }); }); router.post('/trips/:tripId/album-links/:linkId/sync', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId, linkId } = req.params; - - const link = db.prepare("SELECT * FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ? AND provider = 'immich'") - .get(linkId, tripId, authReq.user.id) as any; - if (!link) return res.status(404).json({ error: 'Album link not found' }); - - const creds = getImmichCredentials(authReq.user.id); - if (!creds) return res.status(400).json({ error: 'Immich not configured' }); - - try { - const resp = await fetch(`${creds.immich_url}/api/albums/${link.album_id}`, { - headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, - signal: AbortSignal.timeout(15000), - }); - if (!resp.ok) return res.status(resp.status).json({ error: 'Failed to fetch album' }); - const albumData = await resp.json() as { assets?: any[] }; - const assets = (albumData.assets || []).filter((a: any) => a.type === 'IMAGE'); - - const insert = db.prepare( - "INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, 'immich', 1)" - ); - let added = 0; - for (const asset of assets) { - const r = insert.run(tripId, authReq.user.id, asset.id); - if (r.changes > 0) added++; - } - - db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); - - res.json({ success: true, added, total: assets.length }); - if (added > 0) { - broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); - } - } catch { - res.status(502).json({ error: 'Could not reach Immich' }); + const result = await syncAlbumAssets(tripId, linkId, authReq.user.id); + if (result.error) return res.status(result.status!).json({ error: result.error }); + res.json({ success: true, added: result.added, total: result.total }); + if (result.added! > 0) { + broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); } }); From 0115987e5201a6e8dfe3e6a7c465a664cdc57751 Mon Sep 17 00:00:00 2001 From: Luca Date: Fri, 3 Apr 2026 15:47:06 +0200 Subject: [PATCH 019/117] feat: support multi-day spanning for reservations (flights, rental cars, events) - ReservationModal: add separate departure/arrival date+time fields with type-specific labels (Departure/Arrival for flights, Pickup/Return for cars, Start/End for generic types), timezone fields for flights - DayPlanSidebar: getTransportForDay now matches reservations across all days in their date range; shows phase badges (Departure/In Transit/ Arrival etc.) with appropriate time display per day - ReservationsPanel: show date range when end date differs from start - All 13 translation files updated with new keys --- .../src/components/Planner/DayPlanSidebar.tsx | 110 ++++++++++- .../components/Planner/ReservationModal.tsx | 176 ++++++++++++------ .../components/Planner/ReservationsPanel.tsx | 7 +- client/src/i18n/translations/ar.ts | 24 ++- client/src/i18n/translations/br.ts | 24 ++- client/src/i18n/translations/cs.ts | 24 ++- client/src/i18n/translations/de.ts | 24 ++- client/src/i18n/translations/en.ts | 21 +++ client/src/i18n/translations/es.ts | 24 ++- client/src/i18n/translations/fr.ts | 24 ++- client/src/i18n/translations/hu.ts | 24 ++- client/src/i18n/translations/it.ts | 24 ++- client/src/i18n/translations/nl.ts | 24 ++- client/src/i18n/translations/pl.ts | 21 +++ client/src/i18n/translations/ru.ts | 24 ++- client/src/i18n/translations/zh.ts | 24 ++- 16 files changed, 526 insertions(+), 73 deletions(-) diff --git a/client/src/components/Planner/DayPlanSidebar.tsx b/client/src/components/Planner/DayPlanSidebar.tsx index b9850f3..eabd9a6 100644 --- a/client/src/components/Planner/DayPlanSidebar.tsx +++ b/client/src/components/Planner/DayPlanSidebar.tsx @@ -211,13 +211,67 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ const TRANSPORT_TYPES = new Set(['flight', 'train', 'bus', 'car', 'cruise']) + // Determine if a reservation's end_time represents a different date (multi-day) + const getEndDate = (r: Reservation) => { + const endStr = r.reservation_end_time || '' + return endStr.includes('T') ? endStr.split('T')[0] : null + } + + // Get span phase: how a reservation relates to a specific day's date + const getSpanPhase = (r: Reservation, dayDate: string): 'single' | 'start' | 'middle' | 'end' => { + if (!r.reservation_time) return 'single' + const startDate = r.reservation_time.split('T')[0] + const endDate = getEndDate(r) || startDate + if (startDate === endDate) return 'single' + if (dayDate === startDate) return 'start' + if (dayDate === endDate) return 'end' + return 'middle' + } + + // Get the appropriate display time for a reservation on a specific day + const getDisplayTimeForDay = (r: Reservation, dayDate: string): string | null => { + const phase = getSpanPhase(r, dayDate) + if (phase === 'end') return r.reservation_end_time || null + if (phase === 'middle') return null + return r.reservation_time || null + } + + // Get phase label for multi-day badge + const getSpanLabel = (r: Reservation, phase: string): string | null => { + if (phase === 'single') return null + if (r.type === 'flight') return t(`reservations.span.${phase === 'start' ? 'departure' : phase === 'end' ? 'arrival' : 'inTransit'}`) + if (r.type === 'car') return t(`reservations.span.${phase === 'start' ? 'pickup' : phase === 'end' ? 'return' : 'active'}`) + return t(`reservations.span.${phase === 'start' ? 'start' : phase === 'end' ? 'end' : 'ongoing'}`) + } + const getTransportForDay = (dayId: number) => { const day = days.find(d => d.id === dayId) if (!day?.date) return [] return reservations.filter(r => { - if (!r.reservation_time || !TRANSPORT_TYPES.has(r.type)) return false - const resDate = r.reservation_time.split('T')[0] - return resDate === day.date + if (!r.reservation_time || r.type === 'hotel') return false + const startDate = r.reservation_time.split('T')[0] + const endDate = getEndDate(r) + + if (endDate && endDate !== startDate) { + // Multi-day: show on any day in range (car middle handled elsewhere) + return day.date >= startDate && day.date <= endDate + } else { + // Single-day: show all non-hotel reservations that match this day's date + return startDate === day.date + } + }) + } + + // Get car rentals that are in "active" (middle) phase for a day — shown in day header, not timeline + const getActiveRentalsForDay = (dayId: number) => { + const day = days.find(d => d.id === dayId) + if (!day?.date) return [] + return reservations.filter(r => { + if (r.type !== 'car' || !r.reservation_time) return false + const startDate = r.reservation_time.split('T')[0] + const endDate = getEndDate(r) + if (!endDate || endDate === startDate) return false + return day.date > startDate && day.date < endDate }) } @@ -279,6 +333,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ const da = getDayAssignments(dayId) const dn = (dayNotes[String(dayId)] || []).slice().sort((a, b) => a.sort_order - b.sort_order) const transport = getTransportForDay(dayId) + const dayDate = days.find(d => d.id === dayId)?.date || '' // Initialize positions for transports that don't have one yet if (transport.some(r => r.day_plan_position == null)) { @@ -295,9 +350,14 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ ].sort((a, b) => a.sortKey - b.sortKey) // Timed places + transports: compute sortKeys based on time, inserted among base items + // For multi-day transports, use the appropriate display time for this day const allTimed = [ ...timedPlaces.map(a => ({ type: 'place' as const, data: a, minutes: parseTimeToMinutes(a.place?.place_time)! })), - ...transport.map(r => ({ type: 'transport' as const, data: r, minutes: parseTimeToMinutes(r.reservation_time) ?? 0 })), + ...transport.map(r => ({ + type: 'transport' as const, + data: r, + minutes: parseTimeToMinutes(getDisplayTimeForDay(r, dayDate)) ?? 0, + })), ].sort((a, b) => a.minutes - b.minutes) if (allTimed.length === 0) return baseItems @@ -968,6 +1028,17 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ ) }) })()} + {/* Active rental car badges */} + {(() => { + const activeRentals = getActiveRentalsForDay(day.id) + if (activeRentals.length === 0) return null + return activeRentals.map(r => ( + { e.stopPropagation(); setTransportDetail(r) }} style={{ display: 'inline-flex', alignItems: 'center', gap: 3, padding: '2px 7px', borderRadius: 5, background: 'rgba(59,130,246,0.08)', border: '1px solid rgba(59,130,246,0.2)', flexShrink: 1, minWidth: 0, maxWidth: '40%', cursor: 'pointer' }}> + + {r.title} + + )) + })()}
)}
@@ -1291,6 +1362,11 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ // Transport booking (flight, train, bus, car, cruise) if (item.type === 'transport') { const res = item.data + const spanPhase = getSpanPhase(res, day.date) + + // Car "active" (middle) days are shown in the day header, skip here + if (res.type === 'car' && spanPhase === 'middle') return null + const TransportIcon = RES_ICONS[res.type] || Ticket const color = '#3b82f6' const meta = typeof res.metadata === 'string' ? JSON.parse(res.metadata || '{}') : (res.metadata || {}) @@ -1307,8 +1383,12 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ subtitle = [meta.train_number, meta.platform ? `Gl. ${meta.platform}` : '', meta.seat ? `Sitz ${meta.seat}` : ''].filter(Boolean).join(' · ') } + // Multi-day span phase + const spanLabel = getSpanLabel(res, spanPhase) + const displayTime = getDisplayTimeForDay(res, day.date) + return ( - + {showDropLine &&
}
setTransportDetail(res)} @@ -1340,6 +1420,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ background: isTransportHovered ? `${color}12` : `${color}08`, cursor: 'pointer', userSelect: 'none', transition: 'background 0.1s', + opacity: spanPhase === 'middle' ? 0.65 : 1, }} >
+ {spanLabel && ( + + {spanLabel} + + )} {res.title} - {res.reservation_time?.includes('T') && ( + {displayTime?.includes('T') && ( - {new Date(res.reservation_time).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', hour12: timeFormat === '12h' })} - {res.reservation_end_time?.includes('T') && ` – ${new Date(res.reservation_end_time).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', hour12: timeFormat === '12h' })}`} + {new Date(displayTime).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', hour12: timeFormat === '12h' })} + {spanPhase === 'single' && res.reservation_end_time && (() => { + const endStr = res.reservation_end_time.includes('T') ? res.reservation_end_time : (displayTime.split('T')[0] + 'T' + res.reservation_end_time) + return ` – ${new Date(endStr).toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', hour12: timeFormat === '12h' })}` + })()} + {meta.departure_timezone && spanPhase === 'start' && ` ${meta.departure_timezone}`} + {meta.arrival_timezone && spanPhase === 'end' && ` ${meta.arrival_timezone}`} )}
diff --git a/client/src/components/Planner/ReservationModal.tsx b/client/src/components/Planner/ReservationModal.tsx index dbc3ab3..1dd9f4d 100644 --- a/client/src/components/Planner/ReservationModal.tsx +++ b/client/src/components/Planner/ReservationModal.tsx @@ -73,9 +73,10 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p const [form, setForm] = useState({ title: '', type: 'other', status: 'pending', - reservation_time: '', reservation_end_time: '', location: '', confirmation_number: '', + reservation_time: '', reservation_end_time: '', end_date: '', location: '', confirmation_number: '', notes: '', assignment_id: '', accommodation_id: '', meta_airline: '', meta_flight_number: '', meta_departure_airport: '', meta_arrival_airport: '', + meta_departure_timezone: '', meta_arrival_timezone: '', meta_train_number: '', meta_platform: '', meta_seat: '', meta_check_in_time: '', meta_check_out_time: '', hotel_place_id: '', hotel_start_day: '', hotel_end_day: '', @@ -95,12 +96,21 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p useEffect(() => { if (reservation) { const meta = typeof reservation.metadata === 'string' ? JSON.parse(reservation.metadata || '{}') : (reservation.metadata || {}) + // Parse end_date from reservation_end_time if it's a full ISO datetime + const rawEnd = reservation.reservation_end_time || '' + let endDate = '' + let endTime = rawEnd + if (rawEnd.includes('T')) { + endDate = rawEnd.split('T')[0] + endTime = rawEnd.split('T')[1]?.slice(0, 5) || '' + } setForm({ title: reservation.title || '', type: reservation.type || 'other', status: reservation.status || 'pending', reservation_time: reservation.reservation_time ? reservation.reservation_time.slice(0, 16) : '', - reservation_end_time: reservation.reservation_end_time || '', + reservation_end_time: endTime, + end_date: endDate, location: reservation.location || '', confirmation_number: reservation.confirmation_number || '', notes: reservation.notes || '', @@ -110,6 +120,8 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p meta_flight_number: meta.flight_number || '', meta_departure_airport: meta.departure_airport || '', meta_arrival_airport: meta.arrival_airport || '', + meta_departure_timezone: meta.departure_timezone || '', + meta_arrival_timezone: meta.arrival_timezone || '', meta_train_number: meta.train_number || '', meta_platform: meta.platform || '', meta_seat: meta.seat || '', @@ -122,9 +134,10 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p } else { setForm({ title: '', type: 'other', status: 'pending', - reservation_time: '', reservation_end_time: '', location: '', confirmation_number: '', + reservation_time: '', reservation_end_time: '', end_date: '', location: '', confirmation_number: '', notes: '', assignment_id: '', accommodation_id: '', meta_airline: '', meta_flight_number: '', meta_departure_airport: '', meta_arrival_airport: '', + meta_departure_timezone: '', meta_arrival_timezone: '', meta_train_number: '', meta_platform: '', meta_seat: '', meta_check_in_time: '', meta_check_out_time: '', }) @@ -134,9 +147,21 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p const set = (field, value) => setForm(prev => ({ ...prev, [field]: value })) + // Validate that end datetime is after start datetime + const isEndBeforeStart = (() => { + if (!form.end_date || !form.reservation_time) return false + const startDate = form.reservation_time.split('T')[0] + const startTime = form.reservation_time.split('T')[1] || '00:00' + const endTime = form.reservation_end_time || '00:00' + const startFull = `${startDate}T${startTime}` + const endFull = `${form.end_date}T${endTime}` + return endFull <= startFull + })() + const handleSubmit = async (e) => { e.preventDefault() if (!form.title.trim()) return + if (isEndBeforeStart) { toast.error(t('reservations.validation.endBeforeStart')); return } setIsSaving(true) try { const metadata: Record = {} @@ -145,6 +170,8 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p if (form.meta_flight_number) metadata.flight_number = form.meta_flight_number if (form.meta_departure_airport) metadata.departure_airport = form.meta_departure_airport if (form.meta_arrival_airport) metadata.arrival_airport = form.meta_arrival_airport + if (form.meta_departure_timezone) metadata.departure_timezone = form.meta_departure_timezone + if (form.meta_arrival_timezone) metadata.arrival_timezone = form.meta_arrival_timezone } else if (form.type === 'hotel') { if (form.meta_check_in_time) metadata.check_in_time = form.meta_check_in_time if (form.meta_check_out_time) metadata.check_out_time = form.meta_check_out_time @@ -153,9 +180,14 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p if (form.meta_platform) metadata.platform = form.meta_platform if (form.meta_seat) metadata.seat = form.meta_seat } + // Combine end_date + end_time into reservation_end_time + let combinedEndTime = form.reservation_end_time + if (form.end_date) { + combinedEndTime = form.reservation_end_time ? `${form.end_date}T${form.reservation_end_time}` : form.end_date + } const saveData: Record = { title: form.title, type: form.type, status: form.status, - reservation_time: form.reservation_time, reservation_end_time: form.reservation_end_time, + reservation_time: form.reservation_time, reservation_end_time: combinedEndTime, location: form.location, confirmation_number: form.confirmation_number, notes: form.notes, assignment_id: form.assignment_id || null, @@ -257,10 +289,9 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p placeholder={t('reservations.titlePlaceholder')} style={inputStyle} />
- {/* Assignment Picker + Date (hidden for hotels) */} - {form.type !== 'hotel' && ( -
- {assignmentOptions.length > 0 && ( + {/* Assignment Picker (hidden for hotels) */} + {form.type !== 'hotel' && assignmentOptions.length > 0 && ( +
- )} -
- - { const [d] = (form.reservation_time || '').split('T'); return d || '' })()} - onChange={d => { - const [, t] = (form.reservation_time || '').split('T') - set('reservation_time', d ? (t ? `${d}T${t}` : d) : '') - }} - /> -
)} - {/* Start Time + End Time + Status */} -
- {form.type !== 'hotel' && ( - <> + {/* Start Date/Time + End Date/Time + Status (hidden for hotels) */} + {form.type !== 'hotel' && ( + <> +
+
+ + { const [d] = (form.reservation_time || '').split('T'); return d || '' })()} + onChange={d => { + const [, t] = (form.reservation_time || '').split('T') + set('reservation_time', d ? (t ? `${d}T${t}` : d) : '') + }} + /> +
+
+ + { const [, t] = (form.reservation_time || '').split('T'); return t || '' })()} + onChange={t => { + const [d] = (form.reservation_time || '').split('T') + const date = d || new Date().toISOString().split('T')[0] + set('reservation_time', t ? `${date}T${t}` : date) + }} + /> +
+ {form.type === 'flight' && (
- - { const [, t] = (form.reservation_time || '').split('T'); return t || '' })()} - onChange={t => { - const [d] = (form.reservation_time || '').split('T') - const date = d || new Date().toISOString().split('T')[0] - set('reservation_time', t ? `${date}T${t}` : date) - }} - /> + + set('meta_departure_timezone', e.target.value)} + placeholder="e.g. CET, UTC+1" style={inputStyle} />
-
- - set('reservation_end_time', v)} /> -
- - )} -
- - set('status', value)} - options={[ - { value: 'pending', label: t('reservations.pending') }, - { value: 'confirmed', label: t('reservations.confirmed') }, - ]} - size="sm" - /> + )}
-
+
+
+ + set('end_date', d || '')} + /> +
+
+ + set('reservation_end_time', v)} /> +
+ {form.type === 'flight' && ( +
+ + set('meta_arrival_timezone', e.target.value)} + placeholder="e.g. JST, UTC+9" style={inputStyle} /> +
+ )} +
+ {isEndBeforeStart && ( +
{t('reservations.validation.endBeforeStart')}
+ )} +
+
+ + set('status', value)} + options={[ + { value: 'pending', label: t('reservations.pending') }, + { value: 'confirmed', label: t('reservations.confirmed') }, + ]} + size="sm" + /> +
+
+ + )} {/* Location + Booking Code */}
@@ -422,8 +480,8 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p />
- {/* Check-in/out times */} -
+ {/* Check-in/out times + Status */} +
set('meta_check_in_time', v)} /> @@ -432,6 +490,18 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p set('meta_check_out_time', v)} />
+
+ + set('status', value)} + options={[ + { value: 'pending', label: t('reservations.pending') }, + { value: 'confirmed', label: t('reservations.confirmed') }, + ]} + size="sm" + /> +
)} @@ -561,7 +631,7 @@ export function ReservationModal({ isOpen, onClose, onSave, reservation, days, p -
diff --git a/client/src/components/Planner/ReservationsPanel.tsx b/client/src/components/Planner/ReservationsPanel.tsx index b6f9c55..f1a7e38 100644 --- a/client/src/components/Planner/ReservationsPanel.tsx +++ b/client/src/components/Planner/ReservationsPanel.tsx @@ -136,7 +136,12 @@ function ReservationCard({ r, tripId, onEdit, onDelete, files = [], onNavigateTo {r.reservation_time && (
{t('reservations.date')}
-
{fmtDate(r.reservation_time)}
+
+ {fmtDate(r.reservation_time)} + {r.reservation_end_time?.includes('T') && r.reservation_end_time.split('T')[0] !== r.reservation_time.split('T')[0] && ( + <> – {fmtDate(r.reservation_end_time)} + )} +
)} {r.reservation_time?.includes('T') && ( diff --git a/client/src/i18n/translations/ar.ts b/client/src/i18n/translations/ar.ts index 4ba26be..4d829ae 100644 --- a/client/src/i18n/translations/ar.ts +++ b/client/src/i18n/translations/ar.ts @@ -935,6 +935,27 @@ const ar: Record = { 'reservations.linkAssignment': 'ربط بخطة اليوم', 'reservations.pickAssignment': 'اختر عنصرًا من خطتك...', 'reservations.noAssignment': 'بلا ربط', + 'reservations.departureDate': 'المغادرة', + 'reservations.arrivalDate': 'الوصول', + 'reservations.departureTime': 'وقت المغادرة', + 'reservations.arrivalTime': 'وقت الوصول', + 'reservations.pickupDate': 'الاستلام', + 'reservations.returnDate': 'الإرجاع', + 'reservations.pickupTime': 'وقت الاستلام', + 'reservations.returnTime': 'وقت الإرجاع', + 'reservations.endDate': 'تاريخ الانتهاء', + 'reservations.meta.departureTimezone': 'TZ المغادرة', + 'reservations.meta.arrivalTimezone': 'TZ الوصول', + 'reservations.span.departure': 'المغادرة', + 'reservations.span.arrival': 'الوصول', + 'reservations.span.inTransit': 'في الطريق', + 'reservations.span.pickup': 'الاستلام', + 'reservations.span.return': 'الإرجاع', + 'reservations.span.active': 'نشط', + 'reservations.span.start': 'البداية', + 'reservations.span.end': 'النهاية', + 'reservations.span.ongoing': 'جارٍ', + 'reservations.validation.endBeforeStart': 'يجب أن يكون تاريخ/وقت الانتهاء بعد تاريخ/وقت البدء', // Budget 'budget.title': 'الميزانية', @@ -1545,4 +1566,5 @@ const ar: Record = { 'notifications.test.tripText': 'إشعار تجريبي للرحلة "{trip}".', } -export default ar \ No newline at end of file +export default ar + diff --git a/client/src/i18n/translations/br.ts b/client/src/i18n/translations/br.ts index c51907d..c6a59db 100644 --- a/client/src/i18n/translations/br.ts +++ b/client/src/i18n/translations/br.ts @@ -916,6 +916,27 @@ const br: Record = { 'reservations.linkAssignment': 'Vincular à atribuição do dia', 'reservations.pickAssignment': 'Selecione uma atribuição do seu plano...', 'reservations.noAssignment': 'Sem vínculo (avulsa)', + 'reservations.departureDate': 'Partida', + 'reservations.arrivalDate': 'Chegada', + 'reservations.departureTime': 'Hora partida', + 'reservations.arrivalTime': 'Hora chegada', + 'reservations.pickupDate': 'Retirada', + 'reservations.returnDate': 'Devolução', + 'reservations.pickupTime': 'Hora retirada', + 'reservations.returnTime': 'Hora devolução', + 'reservations.endDate': 'Data final', + 'reservations.meta.departureTimezone': 'TZ partida', + 'reservations.meta.arrivalTimezone': 'TZ chegada', + 'reservations.span.departure': 'Partida', + 'reservations.span.arrival': 'Chegada', + 'reservations.span.inTransit': 'Em trânsito', + 'reservations.span.pickup': 'Retirada', + 'reservations.span.return': 'Devolução', + 'reservations.span.active': 'Ativo', + 'reservations.span.start': 'Início', + 'reservations.span.end': 'Fim', + 'reservations.span.ongoing': 'Em andamento', + 'reservations.validation.endBeforeStart': 'A data/hora final deve ser posterior à data/hora inicial', // Budget 'budget.title': 'Orçamento', @@ -1540,4 +1561,5 @@ const br: Record = { 'notifications.test.tripText': 'Notificação de teste para a viagem "{trip}".', } -export default br \ No newline at end of file +export default br + diff --git a/client/src/i18n/translations/cs.ts b/client/src/i18n/translations/cs.ts index 1bf8e1d..ee9d921 100644 --- a/client/src/i18n/translations/cs.ts +++ b/client/src/i18n/translations/cs.ts @@ -933,6 +933,27 @@ const cs: Record = { 'reservations.linkAssignment': 'Propojit s přiřazením dne', 'reservations.pickAssignment': 'Vyberte přiřazení z vašeho plánu...', 'reservations.noAssignment': 'Bez propojení (samostatné)', + 'reservations.departureDate': 'Odlet', + 'reservations.arrivalDate': 'Přílet', + 'reservations.departureTime': 'Čas odletu', + 'reservations.arrivalTime': 'Čas příletu', + 'reservations.pickupDate': 'Vyzvednutí', + 'reservations.returnDate': 'Vrácení', + 'reservations.pickupTime': 'Čas vyzvednutí', + 'reservations.returnTime': 'Čas vrácení', + 'reservations.endDate': 'Datum konce', + 'reservations.meta.departureTimezone': 'TZ odletu', + 'reservations.meta.arrivalTimezone': 'TZ příletu', + 'reservations.span.departure': 'Odlet', + 'reservations.span.arrival': 'Přílet', + 'reservations.span.inTransit': 'Na cestě', + 'reservations.span.pickup': 'Vyzvednutí', + 'reservations.span.return': 'Vrácení', + 'reservations.span.active': 'Aktivní', + 'reservations.span.start': 'Začátek', + 'reservations.span.end': 'Konec', + 'reservations.span.ongoing': 'Probíhá', + 'reservations.validation.endBeforeStart': 'Datum/čas konce musí být po datu/čase začátku', // Rozpočet (Budget) 'budget.title': 'Rozpočet', @@ -1545,4 +1566,5 @@ const cs: Record = { 'notifications.test.tripText': 'Testovací oznámení pro výlet "{trip}".', } -export default cs \ No newline at end of file +export default cs + diff --git a/client/src/i18n/translations/de.ts b/client/src/i18n/translations/de.ts index 7ebb8c0..54304e6 100644 --- a/client/src/i18n/translations/de.ts +++ b/client/src/i18n/translations/de.ts @@ -932,6 +932,27 @@ const de: Record = { 'reservations.linkAssignment': 'Mit Tagesplanung verknüpfen', 'reservations.pickAssignment': 'Zuordnung aus dem Plan wählen...', 'reservations.noAssignment': 'Keine Verknüpfung', + 'reservations.departureDate': 'Abflug', + 'reservations.arrivalDate': 'Ankunft', + 'reservations.departureTime': 'Abflugzeit', + 'reservations.arrivalTime': 'Ankunftszeit', + 'reservations.pickupDate': 'Abholung', + 'reservations.returnDate': 'Rückgabe', + 'reservations.pickupTime': 'Abholzeit', + 'reservations.returnTime': 'Rückgabezeit', + 'reservations.endDate': 'Enddatum', + 'reservations.meta.departureTimezone': 'Abfl. TZ', + 'reservations.meta.arrivalTimezone': 'Ank. TZ', + 'reservations.span.departure': 'Abflug', + 'reservations.span.arrival': 'Ankunft', + 'reservations.span.inTransit': 'Unterwegs', + 'reservations.span.pickup': 'Abholung', + 'reservations.span.return': 'Rückgabe', + 'reservations.span.active': 'Aktiv', + 'reservations.span.start': 'Start', + 'reservations.span.end': 'Ende', + 'reservations.span.ongoing': 'Laufend', + 'reservations.validation.endBeforeStart': 'Enddatum/-zeit muss nach dem Startdatum/-zeit liegen', // Budget 'budget.title': 'Budget', @@ -1542,4 +1563,5 @@ const de: Record = { 'notifications.test.tripText': 'Testbenachrichtigung für Reise "{trip}".', } -export default de \ No newline at end of file +export default de + diff --git a/client/src/i18n/translations/en.ts b/client/src/i18n/translations/en.ts index 9f1c3f6..b7a80f2 100644 --- a/client/src/i18n/translations/en.ts +++ b/client/src/i18n/translations/en.ts @@ -929,6 +929,27 @@ const en: Record = { 'reservations.linkAssignment': 'Link to day assignment', 'reservations.pickAssignment': 'Select an assignment from your plan...', 'reservations.noAssignment': 'No link (standalone)', + 'reservations.departureDate': 'Departure', + 'reservations.arrivalDate': 'Arrival', + 'reservations.departureTime': 'Dep. time', + 'reservations.arrivalTime': 'Arr. time', + 'reservations.pickupDate': 'Pickup', + 'reservations.returnDate': 'Return', + 'reservations.pickupTime': 'Pickup time', + 'reservations.returnTime': 'Return time', + 'reservations.endDate': 'End date', + 'reservations.meta.departureTimezone': 'Dep. TZ', + 'reservations.meta.arrivalTimezone': 'Arr. TZ', + 'reservations.span.departure': 'Departure', + 'reservations.span.arrival': 'Arrival', + 'reservations.span.inTransit': 'In transit', + 'reservations.span.pickup': 'Pickup', + 'reservations.span.return': 'Return', + 'reservations.span.active': 'Active', + 'reservations.span.start': 'Start', + 'reservations.span.end': 'End', + 'reservations.span.ongoing': 'Ongoing', + 'reservations.validation.endBeforeStart': 'End date/time must be after start date/time', // Budget 'budget.title': 'Budget', diff --git a/client/src/i18n/translations/es.ts b/client/src/i18n/translations/es.ts index bafee34..65f57a6 100644 --- a/client/src/i18n/translations/es.ts +++ b/client/src/i18n/translations/es.ts @@ -892,6 +892,27 @@ const es: Record = { 'reservations.linkAssignment': 'Vincular a una asignación del día', 'reservations.pickAssignment': 'Selecciona una asignación de tu plan...', 'reservations.noAssignment': 'Sin vínculo (independiente)', + 'reservations.departureDate': 'Salida', + 'reservations.arrivalDate': 'Llegada', + 'reservations.departureTime': 'Hora salida', + 'reservations.arrivalTime': 'Hora llegada', + 'reservations.pickupDate': 'Recogida', + 'reservations.returnDate': 'Devolución', + 'reservations.pickupTime': 'Hora recogida', + 'reservations.returnTime': 'Hora devolución', + 'reservations.endDate': 'Fecha fin', + 'reservations.meta.departureTimezone': 'TZ salida', + 'reservations.meta.arrivalTimezone': 'TZ llegada', + 'reservations.span.departure': 'Salida', + 'reservations.span.arrival': 'Llegada', + 'reservations.span.inTransit': 'En tránsito', + 'reservations.span.pickup': 'Recogida', + 'reservations.span.return': 'Devolución', + 'reservations.span.active': 'Activo', + 'reservations.span.start': 'Inicio', + 'reservations.span.end': 'Fin', + 'reservations.span.ongoing': 'En curso', + 'reservations.validation.endBeforeStart': 'La fecha/hora de fin debe ser posterior a la de inicio', // Budget 'budget.title': 'Presupuesto', @@ -1547,4 +1568,5 @@ const es: Record = { 'notifications.test.tripText': 'Notificación de prueba para el viaje "{trip}".', } -export default es \ No newline at end of file +export default es + diff --git a/client/src/i18n/translations/fr.ts b/client/src/i18n/translations/fr.ts index 4727ff7..ca5886e 100644 --- a/client/src/i18n/translations/fr.ts +++ b/client/src/i18n/translations/fr.ts @@ -931,6 +931,27 @@ const fr: Record = { 'reservations.linkAssignment': 'Lier à l\'affectation du jour', 'reservations.pickAssignment': 'Sélectionnez une affectation de votre plan…', 'reservations.noAssignment': 'Aucun lien (autonome)', + 'reservations.departureDate': 'Départ', + 'reservations.arrivalDate': 'Arrivée', + 'reservations.departureTime': 'Heure dép.', + 'reservations.arrivalTime': 'Heure arr.', + 'reservations.pickupDate': 'Prise en charge', + 'reservations.returnDate': 'Restitution', + 'reservations.pickupTime': 'Heure prise en charge', + 'reservations.returnTime': 'Heure restitution', + 'reservations.endDate': 'Date de fin', + 'reservations.meta.departureTimezone': 'TZ dép.', + 'reservations.meta.arrivalTimezone': 'TZ arr.', + 'reservations.span.departure': 'Départ', + 'reservations.span.arrival': 'Arrivée', + 'reservations.span.inTransit': 'En transit', + 'reservations.span.pickup': 'Prise en charge', + 'reservations.span.return': 'Restitution', + 'reservations.span.active': 'Actif', + 'reservations.span.start': 'Début', + 'reservations.span.end': 'Fin', + 'reservations.span.ongoing': 'En cours', + 'reservations.validation.endBeforeStart': 'La date/heure de fin doit être postérieure à la date/heure de début', // Budget 'budget.title': 'Budget', @@ -1541,4 +1562,5 @@ const fr: Record = { 'notifications.test.tripText': 'Notification de test pour le voyage "{trip}".', } -export default fr \ No newline at end of file +export default fr + diff --git a/client/src/i18n/translations/hu.ts b/client/src/i18n/translations/hu.ts index 91211d8..06e5c14 100644 --- a/client/src/i18n/translations/hu.ts +++ b/client/src/i18n/translations/hu.ts @@ -932,6 +932,27 @@ const hu: Record = { 'reservations.linkAssignment': 'Összekapcsolás napi tervvel', 'reservations.pickAssignment': 'Válassz hozzárendelést a tervedből...', 'reservations.noAssignment': 'Nincs összekapcsolás (önálló)', + 'reservations.departureDate': 'Indulás', + 'reservations.arrivalDate': 'Érkezés', + 'reservations.departureTime': 'Indulási idő', + 'reservations.arrivalTime': 'Érkezési idő', + 'reservations.pickupDate': 'Felvétel', + 'reservations.returnDate': 'Visszaadás', + 'reservations.pickupTime': 'Felvétel ideje', + 'reservations.returnTime': 'Visszaadás ideje', + 'reservations.endDate': 'Befejezés dátuma', + 'reservations.meta.departureTimezone': 'TZ indulás', + 'reservations.meta.arrivalTimezone': 'TZ érkezés', + 'reservations.span.departure': 'Indulás', + 'reservations.span.arrival': 'Érkezés', + 'reservations.span.inTransit': 'Úton', + 'reservations.span.pickup': 'Felvétel', + 'reservations.span.return': 'Visszaadás', + 'reservations.span.active': 'Aktív', + 'reservations.span.start': 'Kezdés', + 'reservations.span.end': 'Vége', + 'reservations.span.ongoing': 'Folyamatban', + 'reservations.validation.endBeforeStart': 'A befejezés dátuma/időpontja a kezdés utáni kell legyen', // Költségvetés 'budget.title': 'Költségvetés', @@ -1542,4 +1563,5 @@ const hu: Record = { 'notifications.test.tripText': 'Teszt értesítés a(z) "{trip}" utazáshoz.', } -export default hu \ No newline at end of file +export default hu + diff --git a/client/src/i18n/translations/it.ts b/client/src/i18n/translations/it.ts index bebaf16..73496a6 100644 --- a/client/src/i18n/translations/it.ts +++ b/client/src/i18n/translations/it.ts @@ -932,6 +932,27 @@ const it: Record = { 'reservations.linkAssignment': 'Collega all\'assegnazione del giorno', 'reservations.pickAssignment': 'Seleziona un\'assegnazione dal tuo programma...', 'reservations.noAssignment': 'Nessun collegamento (autonomo)', + 'reservations.departureDate': 'Partenza', + 'reservations.arrivalDate': 'Arrivo', + 'reservations.departureTime': 'Ora part.', + 'reservations.arrivalTime': 'Ora arr.', + 'reservations.pickupDate': 'Ritiro', + 'reservations.returnDate': 'Riconsegna', + 'reservations.pickupTime': 'Ora ritiro', + 'reservations.returnTime': 'Ora riconsegna', + 'reservations.endDate': 'Data fine', + 'reservations.meta.departureTimezone': 'TZ part.', + 'reservations.meta.arrivalTimezone': 'TZ arr.', + 'reservations.span.departure': 'Partenza', + 'reservations.span.arrival': 'Arrivo', + 'reservations.span.inTransit': 'In transito', + 'reservations.span.pickup': 'Ritiro', + 'reservations.span.return': 'Riconsegna', + 'reservations.span.active': 'Attivo', + 'reservations.span.start': 'Inizio', + 'reservations.span.end': 'Fine', + 'reservations.span.ongoing': 'In corso', + 'reservations.validation.endBeforeStart': 'La data/ora di fine deve essere successiva alla data/ora di inizio', // Budget 'budget.title': 'Budget', @@ -1542,4 +1563,5 @@ const it: Record = { 'notifications.test.tripText': 'Notifica di test per il viaggio "{trip}".', } -export default it \ No newline at end of file +export default it + diff --git a/client/src/i18n/translations/nl.ts b/client/src/i18n/translations/nl.ts index 814be9b..ad164a8 100644 --- a/client/src/i18n/translations/nl.ts +++ b/client/src/i18n/translations/nl.ts @@ -931,6 +931,27 @@ const nl: Record = { 'reservations.linkAssignment': 'Koppelen aan dagtoewijzing', 'reservations.pickAssignment': 'Selecteer een toewijzing uit je plan...', 'reservations.noAssignment': 'Geen koppeling (zelfstandig)', + 'reservations.departureDate': 'Vertrek', + 'reservations.arrivalDate': 'Aankomst', + 'reservations.departureTime': 'Vertrektijd', + 'reservations.arrivalTime': 'Aankomsttijd', + 'reservations.pickupDate': 'Ophalen', + 'reservations.returnDate': 'Inleveren', + 'reservations.pickupTime': 'Ophaaltijd', + 'reservations.returnTime': 'Inlevertijd', + 'reservations.endDate': 'Einddatum', + 'reservations.meta.departureTimezone': 'TZ vertrek', + 'reservations.meta.arrivalTimezone': 'TZ aankomst', + 'reservations.span.departure': 'Vertrek', + 'reservations.span.arrival': 'Aankomst', + 'reservations.span.inTransit': 'Onderweg', + 'reservations.span.pickup': 'Ophalen', + 'reservations.span.return': 'Inleveren', + 'reservations.span.active': 'Actief', + 'reservations.span.start': 'Start', + 'reservations.span.end': 'Einde', + 'reservations.span.ongoing': 'Lopend', + 'reservations.validation.endBeforeStart': 'Einddatum/-tijd moet na de startdatum/-tijd liggen', // Budget 'budget.title': 'Budget', @@ -1541,4 +1562,5 @@ const nl: Record = { 'notifications.test.tripText': 'Testmelding voor reis "{trip}".', } -export default nl \ No newline at end of file +export default nl + diff --git a/client/src/i18n/translations/pl.ts b/client/src/i18n/translations/pl.ts index 36d9e9f..fb1da71 100644 --- a/client/src/i18n/translations/pl.ts +++ b/client/src/i18n/translations/pl.ts @@ -887,6 +887,27 @@ const pl: Record = { 'reservations.linkAssignment': 'Przypisz do miejsca', 'reservations.pickAssignment': 'Wybierz miejsce z planu...', 'reservations.noAssignment': 'Brak przypisania (samodzielna)', + 'reservations.departureDate': 'Wylot', + 'reservations.arrivalDate': 'Przylot', + 'reservations.departureTime': 'Godz. wylotu', + 'reservations.arrivalTime': 'Godz. przylotu', + 'reservations.pickupDate': 'Odbiór', + 'reservations.returnDate': 'Zwrot', + 'reservations.pickupTime': 'Godz. odbioru', + 'reservations.returnTime': 'Godz. zwrotu', + 'reservations.endDate': 'Data końca', + 'reservations.meta.departureTimezone': 'TZ wylotu', + 'reservations.meta.arrivalTimezone': 'TZ przylotu', + 'reservations.span.departure': 'Wylot', + 'reservations.span.arrival': 'Przylot', + 'reservations.span.inTransit': 'W tranzycie', + 'reservations.span.pickup': 'Odbiór', + 'reservations.span.return': 'Zwrot', + 'reservations.span.active': 'Aktywny', + 'reservations.span.start': 'Start', + 'reservations.span.end': 'Koniec', + 'reservations.span.ongoing': 'W trakcie', + 'reservations.validation.endBeforeStart': 'Data/godzina zakończenia musi być późniejsza niż data/godzina rozpoczęcia', // Budget 'budget.title': 'Budżet', diff --git a/client/src/i18n/translations/ru.ts b/client/src/i18n/translations/ru.ts index 997e25b..994067b 100644 --- a/client/src/i18n/translations/ru.ts +++ b/client/src/i18n/translations/ru.ts @@ -931,6 +931,27 @@ const ru: Record = { 'reservations.linkAssignment': 'Привязать к назначению дня', 'reservations.pickAssignment': 'Выберите назначение из вашего плана...', 'reservations.noAssignment': 'Без привязки (самостоятельное)', + 'reservations.departureDate': 'Вылет', + 'reservations.arrivalDate': 'Прилёт', + 'reservations.departureTime': 'Время вылета', + 'reservations.arrivalTime': 'Время прилёта', + 'reservations.pickupDate': 'Получение', + 'reservations.returnDate': 'Возврат', + 'reservations.pickupTime': 'Время получения', + 'reservations.returnTime': 'Время возврата', + 'reservations.endDate': 'Дата окончания', + 'reservations.meta.departureTimezone': 'TZ вылета', + 'reservations.meta.arrivalTimezone': 'TZ прилёта', + 'reservations.span.departure': 'Вылет', + 'reservations.span.arrival': 'Прилёт', + 'reservations.span.inTransit': 'В пути', + 'reservations.span.pickup': 'Получение', + 'reservations.span.return': 'Возврат', + 'reservations.span.active': 'Активно', + 'reservations.span.start': 'Начало', + 'reservations.span.end': 'Конец', + 'reservations.span.ongoing': 'Продолжается', + 'reservations.validation.endBeforeStart': 'Дата/время окончания должны быть позже даты/времени начала', // Budget 'budget.title': 'Бюджет', @@ -1541,4 +1562,5 @@ const ru: Record = { 'notifications.test.tripText': 'Тестовое уведомление для поездки "{trip}".', } -export default ru \ No newline at end of file +export default ru + diff --git a/client/src/i18n/translations/zh.ts b/client/src/i18n/translations/zh.ts index 5fd14e4..21fd9ea 100644 --- a/client/src/i18n/translations/zh.ts +++ b/client/src/i18n/translations/zh.ts @@ -931,6 +931,27 @@ const zh: Record = { 'reservations.linkAssignment': '关联日程分配', 'reservations.pickAssignment': '从计划中选择一个分配...', 'reservations.noAssignment': '无关联(独立)', + 'reservations.departureDate': '出发', + 'reservations.arrivalDate': '到达', + 'reservations.departureTime': '出发时间', + 'reservations.arrivalTime': '到达时间', + 'reservations.pickupDate': '取车', + 'reservations.returnDate': '还车', + 'reservations.pickupTime': '取车时间', + 'reservations.returnTime': '还车时间', + 'reservations.endDate': '结束日期', + 'reservations.meta.departureTimezone': '出发时区', + 'reservations.meta.arrivalTimezone': '到达时区', + 'reservations.span.departure': '出发', + 'reservations.span.arrival': '到达', + 'reservations.span.inTransit': '途中', + 'reservations.span.pickup': '取车', + 'reservations.span.return': '还车', + 'reservations.span.active': '使用中', + 'reservations.span.start': '开始', + 'reservations.span.end': '结束', + 'reservations.span.ongoing': '进行中', + 'reservations.validation.endBeforeStart': '结束日期/时间必须晚于开始日期/时间', // Budget 'budget.title': '预算', @@ -1541,4 +1562,5 @@ const zh: Record = { 'notifications.test.tripText': '行程"{trip}"的测试通知。', } -export default zh \ No newline at end of file +export default zh + From 21f87d9b91ed5f7c40f6b12188e2236e941a4cf6 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 16:56:41 +0200 Subject: [PATCH 020/117] fixes after merge --- server/src/app.ts | 59 ++++++++++++++++++++++++++++++++++- server/src/routes/synology.ts | 8 +++-- 2 files changed, 64 insertions(+), 3 deletions(-) diff --git a/server/src/app.ts b/server/src/app.ts index c1c5ebc..13b7668 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -34,6 +34,8 @@ import oidcRoutes from './routes/oidc'; import vacayRoutes from './routes/vacay'; import atlasRoutes from './routes/atlas'; import immichRoutes from './routes/immich'; +import synologyRoutes from './routes/synology'; +import memoriesRoutes from './routes/memories'; import notificationRoutes from './routes/notifications'; import shareRoutes from './routes/share'; import { mcpHandler } from './mcp'; @@ -193,13 +195,68 @@ export function createApp(): express.Application { // Addons list endpoint app.get('/api/addons', authenticate, (_req: Request, res: Response) => { const addons = db.prepare('SELECT id, name, type, icon, enabled FROM addons WHERE enabled = 1 ORDER BY sort_order').all() as Pick[]; - res.json({ addons: addons.map(a => ({ ...a, enabled: !!a.enabled })) }); + const providers = db.prepare(` + SELECT id, name, icon, enabled, config, sort_order + FROM photo_providers + WHERE enabled = 1 + ORDER BY sort_order, id + `).all() as Array<{ id: string; name: string; icon: string; enabled: number; config: string; sort_order: number }>; + const fields = db.prepare(` + SELECT provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order + FROM photo_provider_fields + ORDER BY sort_order, id + `).all() as Array<{ + provider_id: string; + field_key: string; + label: string; + input_type: string; + placeholder?: string | null; + required: number; + secret: number; + settings_key?: string | null; + payload_key?: string | null; + sort_order: number; + }>; + + const fieldsByProvider = new Map(); + for (const field of fields) { + const arr = fieldsByProvider.get(field.provider_id) || []; + arr.push(field); + fieldsByProvider.set(field.provider_id, arr); + } + + res.json({ + addons: [ + ...addons.map(a => ({ ...a, enabled: !!a.enabled })), + ...providers.map(p => ({ + id: p.id, + name: p.name, + type: 'photo_provider', + icon: p.icon, + enabled: !!p.enabled, + config: JSON.parse(p.config || '{}'), + fields: (fieldsByProvider.get(p.id) || []).map(f => ({ + key: f.field_key, + label: f.label, + input_type: f.input_type, + placeholder: f.placeholder || '', + required: !!f.required, + secret: !!f.secret, + settings_key: f.settings_key || null, + payload_key: f.payload_key || null, + sort_order: f.sort_order, + })), + })), + ], + }); }); // Addon routes app.use('/api/addons/vacay', vacayRoutes); app.use('/api/addons/atlas', atlasRoutes); + app.use('/api/integrations/memories', memoriesRoutes); app.use('/api/integrations/immich', immichRoutes); + app.use('/api/integrations/synologyphotos', synologyRoutes); app.use('/api/maps', mapsRoutes); app.use('/api/weather', weatherRoutes); app.use('/api/settings', settingsRoutes); diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index 65f4dfb..9b26acc 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -31,9 +31,13 @@ function parseNumberBodyField(value: unknown, fallback: number): number { return Number.isFinite(parsed) ? parsed : fallback; } -router.get('/settings', authenticate, (req: Request, res: Response) => { +router.get('/settings', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - res.json(getSynologySettings(authReq.user.id)); + try { + res.json(await getSynologySettings(authReq.user.id)); + } catch (err: unknown) { + handleSynologyError(res, err, 'Failed to load settings'); + } }); router.put('/settings', authenticate, async (req: Request, res: Response) => { From fa25ff29bb6ce3447388b618c0a111c17a1e64df Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 17:02:53 +0200 Subject: [PATCH 021/117] moving memories bl --- server/src/routes/memories.ts | 185 ++++++----------------- server/src/services/memoriesService.ts | 199 +++++++++++++++++++++++++ 2 files changed, 242 insertions(+), 142 deletions(-) create mode 100644 server/src/services/memoriesService.ts diff --git a/server/src/routes/memories.ts b/server/src/routes/memories.ts index 6b510f3..6bd6e6f 100644 --- a/server/src/routes/memories.ts +++ b/server/src/routes/memories.ts @@ -1,8 +1,16 @@ import express, { Request, Response } from 'express'; -import { db, canAccessTrip } from '../db/database'; import { authenticate } from '../middleware/auth'; import { broadcast } from '../websocket'; import { AuthRequest } from '../types'; +import { + listTripPhotos, + listTripAlbumLinks, + removeAlbumLink, + addTripPhotos, + removeTripPhoto, + setTripPhotoSharing, + notifySharedTripPhotos, +} from '../services/memoriesService'; const router = express.Router(); @@ -10,63 +18,24 @@ const router = express.Router(); router.get('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; - - if (!canAccessTrip(tripId, authReq.user.id)) { - return res.status(404).json({ error: 'Trip not found' }); - } - - const photos = db.prepare(` - SELECT tp.asset_id, tp.provider, tp.user_id, tp.shared, tp.added_at, - u.username, u.avatar - FROM trip_photos tp - JOIN users u ON tp.user_id = u.id - WHERE tp.trip_id = ? - AND (tp.user_id = ? OR tp.shared = 1) - ORDER BY tp.added_at ASC - `).all(tripId, authReq.user.id) as any[]; - - res.json({ photos }); + const result = listTripPhotos(tripId, authReq.user.id); + if ('error' in result) return res.status(result.status).json({ error: result.error }); + res.json({ photos: result.photos }); }); router.get('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; - - if (!canAccessTrip(tripId, authReq.user.id)) { - return res.status(404).json({ error: 'Trip not found' }); - } - - const links = 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 = ? - ORDER BY tal.created_at ASC - `).all(tripId); - - res.json({ links }); + const result = listTripAlbumLinks(tripId, authReq.user.id); + if ('error' in result) return res.status(result.status).json({ error: result.error }); + res.json({ links: result.links }); }); router.delete('/trips/:tripId/album-links/:linkId', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId, linkId } = req.params; - - if (!canAccessTrip(tripId, authReq.user.id)) { - return res.status(404).json({ error: 'Trip not found' }); - } - - db.prepare('DELETE FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') - .run(linkId, tripId, authReq.user.id); - + const result = removeAlbumLink(tripId, linkId, authReq.user.id); + if ('error' in result) return res.status(result.status).json({ error: result.error }); res.json({ success: true }); broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); }); @@ -74,85 +43,34 @@ router.delete('/trips/:tripId/album-links/:linkId', authenticate, (req: Request, router.post('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; - const { shared = true } = req.body; - const selectionsRaw = Array.isArray(req.body?.selections) ? req.body.selections : null; - const provider = String(req.body?.provider || '').toLowerCase(); - const assetIdsRaw = req.body?.asset_ids; - - if (!canAccessTrip(tripId, authReq.user.id)) { - return res.status(404).json({ error: 'Trip not found' }); - } - - const selections = selectionsRaw && selectionsRaw.length > 0 - ? selectionsRaw - .map((selection: any) => ({ - provider: String(selection?.provider || '').toLowerCase(), - asset_ids: Array.isArray(selection?.asset_ids) ? selection.asset_ids : [], - })) - .filter((selection: { provider: string; asset_ids: unknown[] }) => selection.provider && selection.asset_ids.length > 0) - : (provider && Array.isArray(assetIdsRaw) && assetIdsRaw.length > 0 - ? [{ provider, asset_ids: assetIdsRaw }] - : []); - - if (selections.length === 0) { - return res.status(400).json({ error: 'selections required' }); - } - - const insert = db.prepare( - 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, ?, ?)' + const result = addTripPhotos( + tripId, + authReq.user.id, + req.body?.shared, + req.body?.selections, + req.body?.provider, + req.body?.asset_ids, ); + if ('error' in result) return res.status(result.status).json({ error: result.error }); - let added = 0; - for (const selection of selections) { - for (const raw of selection.asset_ids) { - const assetId = String(raw || '').trim(); - if (!assetId) continue; - const result = insert.run(tripId, authReq.user.id, assetId, selection.provider, shared ? 1 : 0); - if (result.changes > 0) added++; - } - } - - res.json({ success: true, added }); + res.json({ success: true, added: result.added }); broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); - if (shared && added > 0) { - import('../services/notifications').then(({ notifyTripMembers }) => { - const tripInfo = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; - notifyTripMembers(Number(tripId), authReq.user.id, 'photos_shared', { - trip: tripInfo?.title || 'Untitled', - actor: authReq.user.username || authReq.user.email, - count: String(added), - }).catch(() => {}); - }); + if (result.shared && result.added > 0) { + void notifySharedTripPhotos( + tripId, + authReq.user.id, + authReq.user.username || authReq.user.email, + result.added, + ).catch(() => {}); } }); router.delete('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; - const provider = String(req.body?.provider || '').toLowerCase(); - const assetId = String(req.body?.asset_id || ''); - - if (!assetId) { - return res.status(400).json({ error: 'asset_id is required' }); - } - - if (!provider) { - return res.status(400).json({ error: 'provider is required' }); - } - - if (!canAccessTrip(tripId, authReq.user.id)) { - return res.status(404).json({ error: 'Trip not found' }); - } - - db.prepare(` - DELETE FROM trip_photos - WHERE trip_id = ? - AND user_id = ? - AND asset_id = ? - AND provider = ? - `).run(tripId, authReq.user.id, assetId, provider); - + const result = removeTripPhoto(tripId, authReq.user.id, req.body?.provider, req.body?.asset_id); + if ('error' in result) return res.status(result.status).json({ error: result.error }); res.json({ success: true }); broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); }); @@ -160,31 +78,14 @@ router.delete('/trips/:tripId/photos', authenticate, (req: Request, res: Respons router.put('/trips/:tripId/photos/sharing', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; - const provider = String(req.body?.provider || '').toLowerCase(); - const assetId = String(req.body?.asset_id || ''); - const { shared } = req.body; - - if (!assetId) { - return res.status(400).json({ error: 'asset_id is required' }); - } - - if (!provider) { - return res.status(400).json({ error: 'provider is required' }); - } - - if (!canAccessTrip(tripId, authReq.user.id)) { - return res.status(404).json({ error: 'Trip not found' }); - } - - db.prepare(` - UPDATE trip_photos - SET shared = ? - WHERE trip_id = ? - AND user_id = ? - AND asset_id = ? - AND provider = ? - `).run(shared ? 1 : 0, tripId, authReq.user.id, assetId, provider); - + const result = setTripPhotoSharing( + tripId, + authReq.user.id, + req.body?.provider, + req.body?.asset_id, + req.body?.shared, + ); + if ('error' in result) return res.status(result.status).json({ error: result.error }); res.json({ success: true }); broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); }); diff --git a/server/src/services/memoriesService.ts b/server/src/services/memoriesService.ts new file mode 100644 index 0000000..eb8acc3 --- /dev/null +++ b/server/src/services/memoriesService.ts @@ -0,0 +1,199 @@ +import { db, canAccessTrip } from '../db/database'; +import { notifyTripMembers } from './notifications'; + +type ServiceError = { error: string; status: number }; + +function accessDeniedIfMissing(tripId: string, userId: number): ServiceError | null { + if (!canAccessTrip(tripId, userId)) { + return { error: 'Trip not found', status: 404 }; + } + return null; +} + +type Selection = { + provider: string; + asset_ids: unknown[]; +}; + +function normalizeSelections(selectionsRaw: unknown, providerRaw: unknown, assetIdsRaw: unknown): Selection[] { + const selectionsFromBody = Array.isArray(selectionsRaw) ? selectionsRaw : null; + const provider = String(providerRaw || '').toLowerCase(); + + if (selectionsFromBody && selectionsFromBody.length > 0) { + return selectionsFromBody + .map((selection: any) => ({ + provider: String(selection?.provider || '').toLowerCase(), + asset_ids: Array.isArray(selection?.asset_ids) ? selection.asset_ids : [], + })) + .filter((selection: Selection) => selection.provider && selection.asset_ids.length > 0); + } + + if (provider && Array.isArray(assetIdsRaw) && assetIdsRaw.length > 0) { + return [{ provider, asset_ids: assetIdsRaw }]; + } + + return []; +} + +export function listTripPhotos(tripId: string, userId: number): { photos: any[] } | ServiceError { + const denied = accessDeniedIfMissing(tripId, userId); + if (denied) return denied; + + const photos = db.prepare(` + SELECT tp.asset_id, tp.provider, tp.user_id, tp.shared, tp.added_at, + u.username, u.avatar + FROM trip_photos tp + JOIN users u ON tp.user_id = u.id + WHERE tp.trip_id = ? + AND (tp.user_id = ? OR tp.shared = 1) + ORDER BY tp.added_at ASC + `).all(tripId, userId) as any[]; + + return { photos }; +} + +export function listTripAlbumLinks(tripId: string, userId: number): { links: any[] } | ServiceError { + const denied = accessDeniedIfMissing(tripId, userId); + if (denied) return denied; + + const links = 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 = ? + ORDER BY tal.created_at ASC + `).all(tripId); + + return { links }; +} + +export function removeAlbumLink(tripId: string, linkId: string, userId: number): { success: true } | ServiceError { + const denied = accessDeniedIfMissing(tripId, userId); + if (denied) return denied; + + db.prepare('DELETE FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') + .run(linkId, tripId, userId); + + return { success: true }; +} + +export function addTripPhotos( + tripId: string, + userId: number, + sharedRaw: unknown, + selectionsRaw: unknown, + providerRaw: unknown, + assetIdsRaw: unknown, +): { success: true; added: number; shared: boolean } | ServiceError { + const denied = accessDeniedIfMissing(tripId, userId); + if (denied) return denied; + + const shared = sharedRaw === undefined ? true : !!sharedRaw; + const selections = normalizeSelections(selectionsRaw, providerRaw, assetIdsRaw); + if (selections.length === 0) { + return { error: 'selections required', status: 400 }; + } + + const insert = db.prepare( + 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, ?, ?)' + ); + + let added = 0; + for (const selection of selections) { + for (const raw of selection.asset_ids) { + const assetId = String(raw || '').trim(); + if (!assetId) continue; + const result = insert.run(tripId, userId, assetId, selection.provider, shared ? 1 : 0); + if (result.changes > 0) added++; + } + } + + return { success: true, added, shared }; +} + +export function removeTripPhoto( + tripId: string, + userId: number, + providerRaw: unknown, + assetIdRaw: unknown, +): { success: true } | ServiceError { + const assetId = String(assetIdRaw || ''); + const provider = String(providerRaw || '').toLowerCase(); + + if (!assetId) { + return { error: 'asset_id is required', status: 400 }; + } + if (!provider) { + return { error: 'provider is required', status: 400 }; + } + + const denied = accessDeniedIfMissing(tripId, userId); + if (denied) return denied; + + db.prepare(` + DELETE FROM trip_photos + WHERE trip_id = ? + AND user_id = ? + AND asset_id = ? + AND provider = ? + `).run(tripId, userId, assetId, provider); + + return { success: true }; +} + +export function setTripPhotoSharing( + tripId: string, + userId: number, + providerRaw: unknown, + assetIdRaw: unknown, + sharedRaw: unknown, +): { success: true } | ServiceError { + const assetId = String(assetIdRaw || ''); + const provider = String(providerRaw || '').toLowerCase(); + + if (!assetId) { + return { error: 'asset_id is required', status: 400 }; + } + if (!provider) { + return { error: 'provider is required', status: 400 }; + } + + const denied = accessDeniedIfMissing(tripId, userId); + if (denied) return denied; + + db.prepare(` + UPDATE trip_photos + SET shared = ? + WHERE trip_id = ? + AND user_id = ? + AND asset_id = ? + AND provider = ? + `).run(sharedRaw ? 1 : 0, tripId, userId, assetId, provider); + + return { success: true }; +} + +export async function notifySharedTripPhotos( + tripId: string, + actorUserId: number, + actorName: string, + added: number, +): Promise { + if (added <= 0) return; + + const tripInfo = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; + await notifyTripMembers(Number(tripId), actorUserId, 'photos_shared', { + trip: tripInfo?.title || 'Untitled', + actor: actorName, + count: String(added), + }); +} From de4bdb4a99349b9c7d8a9b6b9282c0568a75e318 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 17:10:18 +0200 Subject: [PATCH 022/117] fixing routes for asset details --- server/src/routes/immich.ts | 18 ++++----- server/src/services/immichService.ts | 55 +--------------------------- 2 files changed, 8 insertions(+), 65 deletions(-) diff --git a/server/src/routes/immich.ts b/server/src/routes/immich.ts index 7021ec7..31391f4 100644 --- a/server/src/routes/immich.ts +++ b/server/src/routes/immich.ts @@ -12,19 +12,13 @@ import { getConnectionStatus, browseTimeline, searchPhotos, - listTripPhotos, - addTripPhotos, - removeTripPhoto, - togglePhotoSharing, - getAssetInfo, proxyThumbnail, proxyOriginal, isValidAssetId, listAlbums, - listAlbumLinks, createAlbumLink, - deleteAlbumLink, syncAlbumAssets, + getAssetInfo, } from '../services/immichService'; const router = express.Router(); @@ -89,11 +83,13 @@ router.post('/search', authenticate, async (req: Request, res: Response) => { // ── Asset Details ────────────────────────────────────────────────────────── -router.get('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { +router.get('/assets/:assetId/info', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - const { tripId } = req.params; - if (!canAccessTrip(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); - res.json({ photos: listTripPhotos(tripId, authReq.user.id) }); + const { assetId } = req.params; + if (!isValidAssetId(assetId)) return res.status(400).json({ error: 'Invalid asset ID' }); + const result = await getAssetInfo(authReq.user.id, assetId); + if (result.error) return res.status(result.status!).json({ error: result.error }); + res.json(result.data); }); // ── Proxy Immich Assets ──────────────────────────────────────────────────── diff --git a/server/src/services/immichService.ts b/server/src/services/immichService.ts index 4a3169f..eb563cd 100644 --- a/server/src/services/immichService.ts +++ b/server/src/services/immichService.ts @@ -1,4 +1,4 @@ -import { db, canAccessTrip } from '../db/database'; +import { db } from '../db/database'; import { maybe_encrypt_api_key, decrypt_api_key } from './apiKeyCrypto'; import { checkSsrf } from '../utils/ssrfGuard'; import { writeAudit } from './auditLog'; @@ -171,45 +171,6 @@ export async function searchPhotos( } } -// ── Trip Photos ──────────────────────────────────────────────────────────── - -export function listTripPhotos(tripId: string, userId: number) { - return db.prepare(` - SELECT tp.asset_id AS immich_asset_id, tp.user_id, tp.shared, tp.added_at, - u.username, u.avatar, u.immich_url - FROM trip_photos tp - JOIN users u ON tp.user_id = u.id - WHERE tp.trip_id = ? - AND tp.provider = 'immich' - AND (tp.user_id = ? OR tp.shared = 1) - ORDER BY tp.added_at ASC - `).all(tripId, userId); -} - -export function addTripPhotos( - tripId: string, - userId: number, - assetIds: string[], - shared: boolean -): number { - const insert = db.prepare('INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, ?, ?)'); - let added = 0; - for (const assetId of assetIds) { - const result = insert.run(tripId, userId, assetId, 'immich', shared ? 1 : 0); - if (result.changes > 0) added++; - } - return added; -} - -export function removeTripPhoto(tripId: string, userId: number, assetId: string) { - db.prepare('DELETE FROM trip_photos WHERE trip_id = ? AND user_id = ? AND asset_id = ? AND provider = ?') - .run(tripId, userId, assetId, 'immich'); -} - -export function togglePhotoSharing(tripId: string, userId: number, assetId: string, shared: boolean) { - db.prepare('UPDATE trip_photos SET shared = ? WHERE trip_id = ? AND user_id = ? AND asset_id = ? AND provider = ?') - .run(shared ? 1 : 0, tripId, userId, assetId, 'immich'); -} // ── Asset Info / Proxy ───────────────────────────────────────────────────── @@ -323,15 +284,6 @@ export async function listAlbums( } } -export function listAlbumLinks(tripId: string) { - return db.prepare(` - SELECT tal.*, u.username - FROM trip_album_links tal - JOIN users u ON tal.user_id = u.id - WHERE tal.trip_id = ? AND tal.provider = 'immich' - ORDER BY tal.created_at ASC - `).all(tripId); -} export function createAlbumLink( tripId: string, @@ -349,11 +301,6 @@ export function createAlbumLink( } } -export function deleteAlbumLink(linkId: string, tripId: string, userId: number) { - db.prepare('DELETE FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') - .run(linkId, tripId, userId); -} - export async function syncAlbumAssets( tripId: string, linkId: string, From 90af1332e85dde6fc28d5a6274ade26c4f40bf02 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 17:25:25 +0200 Subject: [PATCH 023/117] moving linking album to common interface --- .../src/components/Memories/MemoriesPanel.tsx | 12 +++++-- server/src/routes/immich.ts | 12 ------- server/src/routes/memories.ts | 9 ++++++ server/src/routes/synology.ts | 19 ------------ server/src/services/immichService.ts | 16 ---------- server/src/services/memoriesService.ts | 31 +++++++++++++++++++ server/src/services/synologyService.ts | 17 ---------- 7 files changed, 50 insertions(+), 66 deletions(-) diff --git a/client/src/components/Memories/MemoriesPanel.tsx b/client/src/components/Memories/MemoriesPanel.tsx index 8787dd7..4614f6d 100644 --- a/client/src/components/Memories/MemoriesPanel.tsx +++ b/client/src/components/Memories/MemoriesPanel.tsx @@ -81,7 +81,6 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const [albumsLoading, setAlbumsLoading] = useState(false) const [albumLinks, setAlbumLinks] = useState<{ id: number; provider: string; album_id: string; album_name: string; user_id: number; username: string; sync_enabled: number; last_synced_at: string | null }[]>([]) const [syncing, setSyncing] = useState(null) - const pickerIntegrationBase = selectedProvider ? `/integrations/${selectedProvider}` : '' const loadAlbumLinks = async () => { try { @@ -110,8 +109,17 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa } const linkAlbum = async (albumId: string, albumName: string) => { + if (!selectedProvider) { + toast.error(t('memories.error.linkAlbum')) + return + } + try { - await apiClient.post(`${pickerIntegrationBase}/trips/${tripId}/album-links`, { album_id: albumId, album_name: albumName }) + await apiClient.post(`/integrations/memories/trips/${tripId}/album-links`, { + album_id: albumId, + album_name: albumName, + provider: selectedProvider, + }) setShowAlbumPicker(false) await loadAlbumLinks() // Auto-sync after linking diff --git a/server/src/routes/immich.ts b/server/src/routes/immich.ts index 31391f4..4225367 100644 --- a/server/src/routes/immich.ts +++ b/server/src/routes/immich.ts @@ -16,7 +16,6 @@ import { proxyOriginal, isValidAssetId, listAlbums, - createAlbumLink, syncAlbumAssets, getAssetInfo, } from '../services/immichService'; @@ -125,17 +124,6 @@ router.get('/albums', authenticate, async (req: Request, res: Response) => { res.json({ albums: result.albums }); }); -router.post('/trips/:tripId/album-links', authenticate, async (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { tripId } = req.params; - if (!canAccessTrip(tripId, authReq.user.id)) return res.status(404).json({ error: 'Trip not found' }); - const { album_id, album_name } = req.body; - if (!album_id) return res.status(400).json({ error: 'album_id required' }); - const result = createAlbumLink(tripId, authReq.user.id, album_id, album_name); - if (!result.success) return res.status(400).json({ error: result.error }); - res.json({ success: true }); -}); - router.post('/trips/:tripId/album-links/:linkId/sync', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId, linkId } = req.params; diff --git a/server/src/routes/memories.ts b/server/src/routes/memories.ts index 6bd6e6f..5a6f1cf 100644 --- a/server/src/routes/memories.ts +++ b/server/src/routes/memories.ts @@ -5,6 +5,7 @@ import { AuthRequest } from '../types'; import { listTripPhotos, listTripAlbumLinks, + createTripAlbumLink, removeAlbumLink, addTripPhotos, removeTripPhoto, @@ -90,4 +91,12 @@ router.put('/trips/:tripId/photos/sharing', authenticate, (req: Request, res: Re broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); }); +router.post('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + const result = createTripAlbumLink(tripId, authReq.user.id, req.body?.provider, req.body?.album_id, req.body?.album_name); + if ('error' in result) return res.status(result.status).json({ error: result.error }); + res.json({ success: true }); +}); + export default router; diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index 9b26acc..f5f7203 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -86,25 +86,6 @@ router.get('/albums', authenticate, async (req: Request, res: Response) => { } }); -router.post('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { tripId } = req.params; - const body = req.body as Record; - const albumId = parseStringBodyField(body.album_id); - const albumName = parseStringBodyField(body.album_name); - - if (!albumId) { - return handleSynologyError(res, new SynologyServiceError(400, 'Album ID is required'), 'Missing required fields'); - } - - try { - linkSynologyAlbum(authReq.user.id, tripId, albumId, albumName || undefined); - res.json({ success: true }); - } catch (err: unknown) { - handleSynologyError(res, err, 'Failed to link album'); - } -}); - router.post('/trips/:tripId/album-links/:linkId/sync', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId, linkId } = req.params; diff --git a/server/src/services/immichService.ts b/server/src/services/immichService.ts index eb563cd..9d8e9c3 100644 --- a/server/src/services/immichService.ts +++ b/server/src/services/immichService.ts @@ -285,22 +285,6 @@ export async function listAlbums( } -export function createAlbumLink( - tripId: string, - userId: number, - albumId: string, - albumName: string -): { success: boolean; error?: string } { - try { - db.prepare( - 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)' - ).run(tripId, userId, 'immich', albumId, albumName || ''); - return { success: true }; - } catch { - return { success: false, error: 'Album already linked' }; - } -} - export async function syncAlbumAssets( tripId: string, linkId: string, diff --git a/server/src/services/memoriesService.ts b/server/src/services/memoriesService.ts index eb8acc3..5fdfbce 100644 --- a/server/src/services/memoriesService.ts +++ b/server/src/services/memoriesService.ts @@ -76,6 +76,37 @@ export function listTripAlbumLinks(tripId: string, userId: number): { links: any return { links }; } +export function createTripAlbumLink( + tripId: string, + userId: number, + providerRaw: unknown, + albumIdRaw: unknown, + albumNameRaw: unknown, +): { success: true } | ServiceError { + const denied = accessDeniedIfMissing(tripId, userId); + if (denied) return denied; + + const provider = String(providerRaw || '').toLowerCase(); + const albumId = String(albumIdRaw || '').trim(); + const albumName = String(albumNameRaw || '').trim(); + + if (!provider) { + return { error: 'provider is required', status: 400 }; + } + if (!albumId) { + return { error: 'album_id required', status: 400 }; + } + + try { + db.prepare( + 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)' + ).run(tripId, userId, provider, albumId, albumName); + return { success: true }; + } catch { + return { error: 'Album already linked', status: 400 }; + } +} + export function removeAlbumLink(tripId: string, linkId: string, userId: number): { success: true } | ServiceError { const denied = accessDeniedIfMissing(tripId, userId); if (denied) return denied; diff --git a/server/src/services/synologyService.ts b/server/src/services/synologyService.ts index 1c25ef5..7b3182e 100644 --- a/server/src/services/synologyService.ts +++ b/server/src/services/synologyService.ts @@ -438,23 +438,6 @@ export async function listSynologyAlbums(userId: number): Promise<{ albums: Arra return { albums }; } -export function linkSynologyAlbum(userId: number, tripId: string, albumId: string | number | undefined, albumName?: string): void { - if (!canAccessTrip(tripId, userId)) { - throw new SynologyServiceError(404, 'Trip not found'); - } - - if (!albumId) { - throw new SynologyServiceError(400, 'album_id required'); - } - - const changes = db.prepare( - 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)' - ).run(tripId, userId, SYNOLOGY_PROVIDER, String(albumId), albumName || '').changes; - - if (changes === 0) { - throw new SynologyServiceError(400, 'Album already linked'); - } -} export async function syncSynologyAlbumLink(userId: number, tripId: string, linkId: string): Promise<{ added: number; total: number }> { const link = db.prepare(`SELECT * FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ? AND provider = ?`) From a9c392e26e3dd7bc0b7a1e75e20138789ae9b3c7 Mon Sep 17 00:00:00 2001 From: micro92 Date: Fri, 3 Apr 2026 11:26:28 -0400 Subject: [PATCH 024/117] Replace Emoji By Lucide Icon --- client/src/components/PDF/TripPDF.tsx | 68 +++++++++++++++++++-------- 1 file changed, 49 insertions(+), 19 deletions(-) diff --git a/client/src/components/PDF/TripPDF.tsx b/client/src/components/PDF/TripPDF.tsx index 57412d2..64b5df7 100644 --- a/client/src/components/PDF/TripPDF.tsx +++ b/client/src/components/PDF/TripPDF.tsx @@ -1,22 +1,33 @@ // Trip PDF via browser print window import { createElement } from 'react' import { getCategoryIcon } from '../shared/categoryIcons' -import { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark } from 'lucide-react' +import { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark, Hotel, LogIn, LogOut, KeyRound, BedDouble, LucideIcon } from 'lucide-react' import { accommodationsApi, mapsApi } from '../../api/client' import type { Trip, Day, Place, Category, AssignmentsMap, DayNotesMap } from '../../types' +function renderLucideIcon(icon:LucideIcon, props = {}) { + if (!_renderToStaticMarkup) return '' + return _renderToStaticMarkup( + createElement(icon, props) + ); +} + const NOTE_ICON_MAP = { FileText, Info, Clock, MapPin, Navigation, Train, Plane, Bus, Car, Ship, Coffee, Ticket, Star, Heart, Camera, Flag, Lightbulb, AlertTriangle, ShoppingBag, Bookmark } function noteIconSvg(iconId) { - if (!_renderToStaticMarkup) return '' const Icon = NOTE_ICON_MAP[iconId] || FileText - return _renderToStaticMarkup(createElement(Icon, { size: 14, strokeWidth: 1.8, color: '#94a3b8' })) + return renderLucideIcon(Icon, { size: 14, strokeWidth: 1.8, color: '#94a3b8' }) } const TRANSPORT_ICON_MAP = { flight: Plane, train: Train, bus: Bus, car: Car, cruise: Ship } function transportIconSvg(type) { - if (!_renderToStaticMarkup) return '' const Icon = TRANSPORT_ICON_MAP[type] || Ticket - return _renderToStaticMarkup(createElement(Icon, { size: 14, strokeWidth: 1.8, color: '#3b82f6' })) + return renderLucideIcon(Icon, { size: 14, strokeWidth: 1.8, color: '#3b82f6' }) +} + +const ACCOMMODATION_ICON_MAP = { accommodation: Hotel, checkin: LogIn, checkout: LogOut, location: MapPin, note: FileText, confirmation: KeyRound } +function accommodationIconSvg(type) { + const Icon = ACCOMMODATION_ICON_MAP[type] || BedDouble + return renderLucideIcon(Icon, { size: 14, strokeWidth: 1.8, color: '#03398f', className: 'accommodation-icon' }) } // ── SVG inline icons (for chips) ───────────────────────────────────────────── @@ -231,17 +242,25 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor days.some(d => d.id >= a.start_day_id && d.id <= a.end_day_id && d.id === day?.id) ).sort((a, b) => a.start_day_id - b.start_day_id); - const accomodationDetails = accomodationsForDay.map(item => { + //Const icons for accomodation actions and details + const ICON_ACC_CHECKIN = accommodationIconSvg('checkin'); + const ICON_ACC_CHECKOUT = accommodationIconSvg('checkout'); + const ICON_ACC_LOCATION = accommodationIconSvg('location'); + const ICON_ACC_NOTE = accommodationIconSvg('note'); + const ICON_ACC_CONFIRMATION = accommodationIconSvg('confirmation'); + const ICON_ACC_ACCOMMODATION = accommodationIconSvg('accommodation'); + const accomodationDetails = accomodationsForDay.map(item => { + const isCheckIn = day.id === item.start_day_id; const isCheckOut = day.id === item.end_day_id; - const accomoAction = isCheckIn ? '🛎️ '+tr('reservations.meta.checkIn') - : isCheckOut ? '🧳 '+tr('reservations.meta.checkOut') - : '🏨 '+tr('reservations.meta.linkAccommodation') + const accomoAction = isCheckIn ? tr('reservations.meta.checkIn') + : isCheckOut ? tr('reservations.meta.checkOut') + : tr('reservations.meta.linkAccommodation') - const accomoEmoji = isCheckIn ? '🛎️' - : isCheckOut ? '🧳' - : '' + const accomoEmoji = isCheckIn ? ICON_ACC_CHECKIN + : isCheckOut ? ICON_ACC_CHECKOUT + : ICON_ACC_ACCOMMODATION const accomoTime = isCheckIn ? item.check_in || 'N/A' : isCheckOut ? item.check_out || 'N/A' @@ -249,13 +268,13 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor return `
-
${escHtml(accomoAction)}
- ${accomoTime ? `
${accomoEmoji} ${accomoTime}
` : ''} +
${accomoEmoji} ${escHtml(accomoAction)}
+ ${accomoTime ? `
${accomoEmoji} ${accomoTime}
` : ''} -
🏨 ${escHtml(item.place_name)}
- ${item.place_address ? `
📌 ${escHtml(item.place_address)}
` : ''} - ${item.notes ? `
📝 ${escHtml(item.notes)}
` : ''} - ${isCheckIn && item.confirmation ? `
🔑 ${escHtml(item.confirmation)}
` : ''} +
${ICON_ACC_ACCOMMODATION} ${escHtml(item.place_name)}
+ ${item.place_address ? `
${ICON_ACC_LOCATION} ${escHtml(item.place_address)}
` : ''} + ${item.notes ? `
${ICON_ACC_NOTE} ${escHtml(item.notes)}
` : ''} + ${isCheckIn && item.confirmation ? `
${ICON_ACC_CONFIRMATION} ${escHtml(item.confirmation)}
` : ''}
` }).join(''); @@ -373,13 +392,24 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor flex-direction: column; } - .day-accomodation-action { + .day-accomodation-title { font-size: 18px; font-weight: 600; text-align: center; margin-bottom: 4px; + align-self: center; } + .accomodation-center-icon { + display: flex; + align-items: center; + } + + .accommodation-icon { + margin-right: 4px; + } + + /* ── Place card ────────────────────────────────── */ .place-card { display: flex; align-items: stretch; From f4f768a1b33d4c6b33593451ce353c1fcb541750 Mon Sep 17 00:00:00 2001 From: micro92 Date: Fri, 3 Apr 2026 11:27:17 -0400 Subject: [PATCH 025/117] =?UTF-8?q?fix=20accomodation=20-=C2=AD=C2=AD>=20a?= =?UTF-8?q?ccommodation=20typo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- client/src/components/PDF/TripPDF.tsx | 48 +++++++++++++-------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/client/src/components/PDF/TripPDF.tsx b/client/src/components/PDF/TripPDF.tsx index 64b5df7..edb7649 100644 --- a/client/src/components/PDF/TripPDF.tsx +++ b/client/src/components/PDF/TripPDF.tsx @@ -126,8 +126,8 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor const sorted = [...(days || [])].sort((a, b) => a.day_number - b.day_number) const range = longDateRange(sorted, loc) const coverImg = safeImg(trip?.cover_image) - //retrieve accomodations for the trip to display on the day sections and prefetch their photos if needed - const accomodations = await accommodationsApi.list(trip.id); + //retrieve accommodations for the trip to display on the day sections and prefetch their photos if needed + const accommodations = await accommodationsApi.list(trip.id); // Pre-fetch place photos from Google const photoMap = await fetchPlacePhotos(assignments) @@ -238,11 +238,11 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor
` }).join('') - const accomodationsForDay = accomodations.accommodations?.filter(a => + const accommodationsForDay = accommodations.accommodations?.filter(a => days.some(d => d.id >= a.start_day_id && d.id <= a.end_day_id && d.id === day?.id) ).sort((a, b) => a.start_day_id - b.start_day_id); - //Const icons for accomodation actions and details + //Const icons for accommodation actions and details const ICON_ACC_CHECKIN = accommodationIconSvg('checkin'); const ICON_ACC_CHECKOUT = accommodationIconSvg('checkout'); const ICON_ACC_LOCATION = accommodationIconSvg('location'); @@ -250,8 +250,8 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor const ICON_ACC_CONFIRMATION = accommodationIconSvg('confirmation'); const ICON_ACC_ACCOMMODATION = accommodationIconSvg('accommodation'); - const accomodationDetails = accomodationsForDay.map(item => { - + const accommodationDetails = accommodationsForDay.map(item => { + const isCheckIn = day.id === item.start_day_id; const isCheckOut = day.id === item.end_day_id; const accomoAction = isCheckIn ? tr('reservations.meta.checkIn') @@ -267,21 +267,21 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor : '' return ` -
-
${accomoEmoji} ${escHtml(accomoAction)}
- ${accomoTime ? `
${accomoEmoji} ${accomoTime}
` : ''} +
+
${accomoEmoji} ${escHtml(accomoAction)}
+ ${accomoTime ? `
${accomoEmoji} ${accomoTime}
` : ''} -
${ICON_ACC_ACCOMMODATION} ${escHtml(item.place_name)}
- ${item.place_address ? `
${ICON_ACC_LOCATION} ${escHtml(item.place_address)}
` : ''} - ${item.notes ? `
${ICON_ACC_NOTE} ${escHtml(item.notes)}
` : ''} - ${isCheckIn && item.confirmation ? `
${ICON_ACC_CONFIRMATION} ${escHtml(item.confirmation)}
` : ''} +
${ICON_ACC_ACCOMMODATION} ${escHtml(item.place_name)}
+ ${item.place_address ? `
${ICON_ACC_LOCATION} ${escHtml(item.place_address)}
` : ''} + ${item.notes ? `
${ICON_ACC_NOTE} ${escHtml(item.notes)}
` : ''} + ${isCheckIn && item.confirmation ? `
${ICON_ACC_CONFIRMATION} ${escHtml(item.confirmation)}
` : ''}
` }).join(''); - const accomodationsHtml = accomodationDetails ? - `
-
${accomodationDetails}
+ const accommodationsHtml = accommodationDetails ? + `
+
${accommodationDetails}
` : ''; return ` @@ -292,7 +292,7 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor ${day.date ? `${shortDate(day.date, loc)}` : ''} ${cost ? `${cost}` : ''}
-
${accomodationsHtml}${itemsHtml}
+
${accommodationsHtml}${itemsHtml}
` }).join('') @@ -376,12 +376,12 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor .day-cost { font-size: 9px; font-weight: 600; color: rgba(255,255,255,0.65); } .day-body { padding: 12px 28px 6px; } - /* Accomodation info */ - .day-accomodations-overview { font-size: 12px; } - .day-accomodations { display: flex; flex-direction: row; justify-content: space-between; } - .day-accomodations.single { justify-content: center; } + /* accommodation info */ + .day-accommodations-overview { font-size: 12px; } + .day-accommodations { display: flex; flex-direction: row; justify-content: space-between; } + .day-accommodations.single { justify-content: center; } - .day-accomodation { + .day-accommodation { width: 50%; margin:10px; padding:10px; @@ -392,7 +392,7 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor flex-direction: column; } - .day-accomodation-title { + .day-accommodation-title { font-size: 18px; font-weight: 600; text-align: center; @@ -400,7 +400,7 @@ export async function downloadTripPDF({ trip, days, places, assignments, categor align-self: center; } - .accomodation-center-icon { + .accommodation-center-icon { display: flex; align-items: center; } From 07546c47902278c0a3d012ee5640f264d8d362e5 Mon Sep 17 00:00:00 2001 From: Marek Maslowski <99432678+tiquis0290@users.noreply.github.com> Date: Fri, 3 Apr 2026 17:29:50 +0200 Subject: [PATCH 026/117] Refactor resource token creation logic Simplified token creation by directly using req.body.purpose. --- server/src/routes/auth.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/server/src/routes/auth.ts b/server/src/routes/auth.ts index 3947cf7..dd977df 100644 --- a/server/src/routes/auth.ts +++ b/server/src/routes/auth.ts @@ -317,11 +317,7 @@ router.post('/ws-token', authenticate, (req: Request, res: Response) => { // Short-lived single-use token for direct resource URLs router.post('/resource-token', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; - const { purpose } = req.body as { purpose?: string }; - if (purpose !== 'download' && purpose !== 'immich' && purpose !== 'synologyphotos') { - return res.status(400).json({ error: 'Invalid purpose' }); - } - const token = createResourceToken(authReq.user.id, purpose); + const token = createResourceToken(authReq.user.id, req.body.purpose); if (!token) return res.status(503).json({ error: 'Service unavailable' }); res.json(token); }); From 61a5e42403a2cd9f9914902214a0c618240e381d Mon Sep 17 00:00:00 2001 From: Marek Maslowski <99432678+tiquis0290@users.noreply.github.com> Date: Fri, 3 Apr 2026 17:31:30 +0200 Subject: [PATCH 027/117] Fix export statement formatting in synology.ts --- server/src/routes/synology.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index f5f7203..51ad572 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -165,4 +165,4 @@ router.get('/assets/:photoId/original', synologyAuthFromQuery, async (req: Reque } }); -export default router; \ No newline at end of file +export default router; From 69deaf99699107b3a07f51c061a203e0bd63becc Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 17:41:40 +0200 Subject: [PATCH 028/117] removing uneccessary login in admin.ts --- server/src/routes/admin.ts | 92 +++----------------------------------- 1 file changed, 6 insertions(+), 86 deletions(-) diff --git a/server/src/routes/admin.ts b/server/src/routes/admin.ts index 86896ab..530a967 100644 --- a/server/src/routes/admin.ts +++ b/server/src/routes/admin.ts @@ -1,7 +1,6 @@ import express, { Request, Response } from 'express'; import { authenticate, adminOnly } from '../middleware/auth'; -import { db } from '../db/database'; -import { AuthRequest, Addon } from '../types'; +import { AuthRequest } from '../types'; import { writeAudit, getClientIp, logInfo } from '../services/auditLog'; import * as svc from '../services/adminService'; @@ -265,100 +264,21 @@ router.delete('/packing-templates/:templateId/items/:itemId', (req: Request, res // ── Addons ───────────────────────────────────────────────────────────────── router.get('/addons', (_req: Request, res: Response) => { - const addons = db.prepare('SELECT * FROM addons ORDER BY sort_order, id').all() as Addon[]; - const providers = db.prepare(` - SELECT id, name, description, icon, enabled, config, sort_order - FROM photo_providers - ORDER BY sort_order, id - `).all() as Array<{ id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number }>; - const fields = db.prepare(` - SELECT provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order - FROM photo_provider_fields - ORDER BY sort_order, id - `).all() as Array<{ - provider_id: string; - field_key: string; - label: string; - input_type: string; - placeholder?: string | null; - required: number; - secret: number; - settings_key?: string | null; - payload_key?: string | null; - sort_order: number; - }>; - const fieldsByProvider = new Map(); - for (const field of fields) { - const arr = fieldsByProvider.get(field.provider_id) || []; - arr.push(field); - fieldsByProvider.set(field.provider_id, arr); - } - - res.json({ - addons: [ - ...addons.map(a => ({ ...a, enabled: !!a.enabled, config: JSON.parse(a.config || '{}') })), - ...providers.map(p => ({ - id: p.id, - name: p.name, - description: p.description, - type: 'photo_provider', - icon: p.icon, - enabled: !!p.enabled, - config: JSON.parse(p.config || '{}'), - fields: (fieldsByProvider.get(p.id) || []).map(f => ({ - key: f.field_key, - label: f.label, - input_type: f.input_type, - placeholder: f.placeholder || '', - required: !!f.required, - secret: !!f.secret, - settings_key: f.settings_key || null, - payload_key: f.payload_key || null, - sort_order: f.sort_order, - })), - sort_order: p.sort_order, - })), - ], - }); + res.json({ addons: svc.listAddons() }); }); router.put('/addons/:id', (req: Request, res: Response) => { - const addon = db.prepare('SELECT * FROM addons WHERE id = ?').get(req.params.id) as Addon | undefined; - const provider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(req.params.id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number } | undefined; - if (!addon && !provider) return res.status(404).json({ error: 'Addon not found' }); - const { enabled, config } = req.body; - if (addon) { - if (enabled !== undefined) db.prepare('UPDATE addons SET enabled = ? WHERE id = ?').run(enabled ? 1 : 0, req.params.id); - if (config !== undefined) db.prepare('UPDATE addons SET config = ? WHERE id = ?').run(JSON.stringify(config), req.params.id); - } else { - if (enabled !== undefined) db.prepare('UPDATE photo_providers SET enabled = ? WHERE id = ?').run(enabled ? 1 : 0, req.params.id); - if (config !== undefined) db.prepare('UPDATE photo_providers SET config = ? WHERE id = ?').run(JSON.stringify(config), req.params.id); - } - const updatedAddon = db.prepare('SELECT * FROM addons WHERE id = ?').get(req.params.id) as Addon | undefined; - const updatedProvider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(req.params.id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number } | undefined; - const updated = updatedAddon - ? { ...updatedAddon, enabled: !!updatedAddon.enabled, config: JSON.parse(updatedAddon.config || '{}') } - : updatedProvider - ? { - id: updatedProvider.id, - name: updatedProvider.name, - description: updatedProvider.description, - type: 'photo_provider', - icon: updatedProvider.icon, - enabled: !!updatedProvider.enabled, - config: JSON.parse(updatedProvider.config || '{}'), - sort_order: updatedProvider.sort_order, - } - : null; + const result = svc.updateAddon(req.params.id, req.body || {}); + if ('error' in result) return res.status(result.status!).json({ error: result.error }); const authReq = req as AuthRequest; writeAudit({ userId: authReq.user.id, action: 'admin.addon_update', resource: String(req.params.id), ip: getClientIp(req), - details: { enabled: req.body.enabled, config: req.body.config }, + details: result.auditDetails, }); - res.json({ addon: updated }); + res.json({ addon: result.addon }); }); // ── MCP Tokens ───────────────────────────────────────────────────────────── From 66740887e7c4d2bf574de5f17e0bf8905a47d8a0 Mon Sep 17 00:00:00 2001 From: Marek Maslowski <99432678+tiquis0290@users.noreply.github.com> Date: Fri, 3 Apr 2026 17:46:00 +0200 Subject: [PATCH 029/117] returning admin file to orginal look --- server/src/routes/admin.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/server/src/routes/admin.ts b/server/src/routes/admin.ts index 530a967..56a9136 100644 --- a/server/src/routes/admin.ts +++ b/server/src/routes/admin.ts @@ -268,7 +268,7 @@ router.get('/addons', (_req: Request, res: Response) => { }); router.put('/addons/:id', (req: Request, res: Response) => { - const result = svc.updateAddon(req.params.id, req.body || {}); + const result = svc.updateAddon(req.params.id, req.body); if ('error' in result) return res.status(result.status!).json({ error: result.error }); const authReq = req as AuthRequest; writeAudit({ @@ -300,9 +300,12 @@ router.post('/rotate-jwt-secret', (req: Request, res: Response) => { if (result.error) return res.status(result.status!).json({ error: result.error }); const authReq = req as AuthRequest; writeAudit({ - userId: authReq.user?.id ?? null, + user_id: authReq.user?.id ?? null, + username: authReq.user?.username ?? 'unknown', action: 'admin.rotate_jwt_secret', - resource: 'system', + target_type: 'system', + target_id: null, + details: null, ip: getClientIp(req), }); res.json({ success: true }); From 7d51eadf90309aa689d90f0d7f2a12dfd9eff693 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 16:08:46 +0000 Subject: [PATCH 030/117] removing old function import --- server/src/routes/synology.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index 51ad572..7dd44d8 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -8,7 +8,6 @@ import { getSynologyStatus, testSynologyConnection, listSynologyAlbums, - linkSynologyAlbum, syncSynologyAlbumLink, searchSynologyPhotos, getSynologyAssetInfo, From b6686a462fa0f77e31e0498d605b41470f377d0d Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Fri, 3 Apr 2026 22:30:49 +0200 Subject: [PATCH 031/117] removing use of single sue auth tokens for assets --- server/src/routes/synology.ts | 5 ++--- server/src/services/synologyService.ts | 13 ------------- 2 files changed, 2 insertions(+), 16 deletions(-) diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index 7dd44d8..c01e49e 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -12,7 +12,6 @@ import { searchSynologyPhotos, getSynologyAssetInfo, pipeSynologyProxy, - synologyAuthFromQuery, getSynologyTargetUserId, streamSynologyAsset, handleSynologyError, @@ -133,7 +132,7 @@ router.get('/assets/:photoId/info', authenticate, async (req: Request, res: Resp } }); -router.get('/assets/:photoId/thumbnail', synologyAuthFromQuery, async (req: Request, res: Response) => { +router.get('/assets/:photoId/thumbnail', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { photoId } = req.params; const { size = 'sm' } = req.query; @@ -149,7 +148,7 @@ router.get('/assets/:photoId/thumbnail', synologyAuthFromQuery, async (req: Requ } }); -router.get('/assets/:photoId/original', synologyAuthFromQuery, async (req: Request, res: Response) => { +router.get('/assets/:photoId/original', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { photoId } = req.params; diff --git a/server/src/services/synologyService.ts b/server/src/services/synologyService.ts index 7b3182e..646c592 100644 --- a/server/src/services/synologyService.ts +++ b/server/src/services/synologyService.ts @@ -270,19 +270,6 @@ function normalizeSynologyPhotoInfo(item: SynologyPhotoItem): SynologyPhotoInfo }; } -export function synologyAuthFromQuery(req: Request, res: ExpressResponse, next: NextFunction) { - const queryToken = req.query.token as string | undefined; - if (queryToken) { - const userId = consumeEphemeralToken(queryToken, SYNOLOGY_PROVIDER); - if (!userId) return res.status(401).send('Invalid or expired token'); - const user = db.prepare('SELECT id, username, email, role, mfa_enabled FROM users WHERE id = ?').get(userId) as any; - if (!user) return res.status(401).send('User not found'); - (req as AuthRequest).user = user; - return next(); - } - return (authenticate as any)(req, res, next); -} - export function getSynologyTargetUserId(req: Request): number { const { userId } = req.query; return Number(userId); From 6400c2d27d2554d2165b2c2de4acc21a5d146fc8 Mon Sep 17 00:00:00 2001 From: jubnl Date: Sat, 4 Apr 2026 00:09:28 +0200 Subject: [PATCH 032/117] fix(mcp): wire check_in/check_out times through hotel accommodation tools Adds optional check_in and check_out fields to create_reservation and link_hotel_accommodation so MCP clients can set accommodation times, matching the existing REST API behaviour. Closes #363 --- server/src/mcp/tools.ts | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/server/src/mcp/tools.ts b/server/src/mcp/tools.ts index fd3180c..e147907 100644 --- a/server/src/mcp/tools.ts +++ b/server/src/mcp/tools.ts @@ -509,10 +509,12 @@ export function registerTools(server: McpServer, userId: number): void { place_id: z.number().int().positive().optional().describe('Hotel place to link (hotel type only)'), start_day_id: z.number().int().positive().optional().describe('Check-in day (hotel type only; requires place_id and end_day_id)'), end_day_id: z.number().int().positive().optional().describe('Check-out day (hotel type only; requires place_id and start_day_id)'), + check_in: z.string().max(10).optional().describe('Check-in time (e.g. "15:00", hotel type only)'), + check_out: z.string().max(10).optional().describe('Check-out time (e.g. "11:00", hotel type only)'), assignment_id: z.number().int().positive().optional().describe('Link to a day assignment (restaurant, train, car, cruise, event, tour, activity, other)'), }, }, - async ({ tripId, title, type, reservation_time, location, confirmation_number, notes, day_id, place_id, start_day_id, end_day_id, assignment_id }) => { + async ({ tripId, title, type, reservation_time, location, confirmation_number, notes, day_id, place_id, start_day_id, end_day_id, check_in, check_out, assignment_id }) => { if (isDemoUser(userId)) return demoDenied(); if (!canAccessTrip(tripId, userId)) return noAccess(); @@ -542,8 +544,8 @@ export function registerTools(server: McpServer, userId: number): void { let accommodationId: number | null = null; if (type === 'hotel' && place_id && start_day_id && end_day_id) { const accResult = db.prepare( - 'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, confirmation) VALUES (?, ?, ?, ?, ?)' - ).run(tripId, place_id, start_day_id, end_day_id, confirmation_number || null); + 'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_out, confirmation) VALUES (?, ?, ?, ?, ?, ?, ?)' + ).run(tripId, place_id, start_day_id, end_day_id, check_in || null, check_out || null, confirmation_number || null); accommodationId = accResult.lastInsertRowid as number; } const result = db.prepare(` @@ -599,9 +601,11 @@ export function registerTools(server: McpServer, userId: number): void { place_id: z.number().int().positive().describe('The hotel place to link'), start_day_id: z.number().int().positive().describe('Check-in day ID'), end_day_id: z.number().int().positive().describe('Check-out day ID'), + check_in: z.string().max(10).optional().describe('Check-in time (e.g. "15:00")'), + check_out: z.string().max(10).optional().describe('Check-out time (e.g. "11:00")'), }, }, - async ({ tripId, reservationId, place_id, start_day_id, end_day_id }) => { + async ({ tripId, reservationId, place_id, start_day_id, end_day_id, check_in, check_out }) => { if (isDemoUser(userId)) return demoDenied(); if (!canAccessTrip(tripId, userId)) return noAccess(); const reservation = db.prepare('SELECT * FROM reservations WHERE id = ? AND trip_id = ?').get(reservationId, tripId) as Record | undefined; @@ -619,12 +623,12 @@ export function registerTools(server: McpServer, userId: number): void { const isNewAccommodation = !accommodationId; db.transaction(() => { if (accommodationId) { - db.prepare('UPDATE day_accommodations SET place_id = ?, start_day_id = ?, end_day_id = ? WHERE id = ?') - .run(place_id, start_day_id, end_day_id, accommodationId); + db.prepare('UPDATE day_accommodations SET place_id = ?, start_day_id = ?, end_day_id = ?, check_in = COALESCE(?, check_in), check_out = COALESCE(?, check_out) WHERE id = ?') + .run(place_id, start_day_id, end_day_id, check_in || null, check_out || null, accommodationId); } else { const accResult = db.prepare( - 'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, confirmation) VALUES (?, ?, ?, ?, ?)' - ).run(tripId, place_id, start_day_id, end_day_id, reservation.confirmation_number || null); + 'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_out, confirmation) VALUES (?, ?, ?, ?, ?, ?, ?)' + ).run(tripId, place_id, start_day_id, end_day_id, check_in || null, check_out || null, reservation.confirmation_number || null); accommodationId = accResult.lastInsertRowid as number; } db.prepare('UPDATE reservations SET place_id = ?, accommodation_id = ? WHERE id = ?') From ae0d48ac83e1e15bfb117904cd0fecd73232145a Mon Sep 17 00:00:00 2001 From: jubnl Date: Sat, 4 Apr 2026 00:14:11 +0200 Subject: [PATCH 033/117] fix(immich): check all trips when verifying shared photo access canAccessUserPhoto was using .get() which only returned the first matching trip, causing access to be incorrectly denied when a photo was shared across multiple trips and the requester was a member of a non-first trip. --- server/src/services/immichService.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/server/src/services/immichService.ts b/server/src/services/immichService.ts index aceb8c0..0429086 100644 --- a/server/src/services/immichService.ts +++ b/server/src/services/immichService.ts @@ -236,12 +236,12 @@ export function togglePhotoSharing(tripId: string, userId: number, assetId: stri * the same trip that contains the photo. */ export function canAccessUserPhoto(requestingUserId: number, ownerUserId: number, assetId: string): boolean { - const row = db.prepare(` + const rows = db.prepare(` SELECT tp.trip_id FROM trip_photos tp WHERE tp.immich_asset_id = ? AND tp.user_id = ? AND tp.shared = 1 - `).get(assetId, ownerUserId) as { trip_id: number } | undefined; - if (!row) return false; - return !!canAccessTrip(String(row.trip_id), requestingUserId); + `).all(assetId, ownerUserId) as { trip_id: number }[]; + if (rows.length === 0) return false; + return rows.some(row => !!canAccessTrip(String(row.trip_id), requestingUserId)); } export async function getAssetInfo( From a307d8d1c98044b6e52e680989087196403dad6c Mon Sep 17 00:00:00 2001 From: jubnl Date: Sat, 4 Apr 2026 00:17:34 +0200 Subject: [PATCH 034/117] test(trips): update TRIP-002 to expect default 7-day window Now that trips always default to a start+7 day window when no dates are provided, the test expectation of null dates and zero dated days is no longer valid. --- server/tests/integration/trips.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/server/tests/integration/trips.test.ts b/server/tests/integration/trips.test.ts index 6c619d7..b862b23 100644 --- a/server/tests/integration/trips.test.ts +++ b/server/tests/integration/trips.test.ts @@ -89,7 +89,7 @@ describe('Create trip', () => { expect(days[4].date).toBe('2026-06-05'); }); - it('TRIP-002 — POST /api/trips without dates returns 201 and no date-specific days', async () => { + it('TRIP-002 — POST /api/trips without dates returns 201 and defaults to a 7-day window', async () => { const { user } = createUser(testDb); const res = await request(app) @@ -99,12 +99,12 @@ describe('Create trip', () => { expect(res.status).toBe(201); expect(res.body.trip).toBeDefined(); - expect(res.body.trip.start_date).toBeNull(); - expect(res.body.trip.end_date).toBeNull(); + expect(res.body.trip.start_date).not.toBeNull(); + expect(res.body.trip.end_date).not.toBeNull(); - // Days with explicit dates should not be present + // Should have 8 days (start + 7 day window) const daysWithDate = testDb.prepare('SELECT * FROM days WHERE trip_id = ? AND date IS NOT NULL').all(res.body.trip.id) as any[]; - expect(daysWithDate).toHaveLength(0); + expect(daysWithDate).toHaveLength(8); }); it('TRIP-001 — POST /api/trips requires a title, returns 400 without one', async () => { From 846db9d076ec0d72eb79c30d7db6d93b69918a1b Mon Sep 17 00:00:00 2001 From: jubnl Date: Sat, 4 Apr 2026 00:18:13 +0200 Subject: [PATCH 035/117] test(trips): assert exact start/end dates in TRIP-002 Replace not-null checks with exact date assertions mirroring the route's defaulting logic (tomorrow + 7-day window). --- server/tests/integration/trips.test.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/server/tests/integration/trips.test.ts b/server/tests/integration/trips.test.ts index b862b23..16d224d 100644 --- a/server/tests/integration/trips.test.ts +++ b/server/tests/integration/trips.test.ts @@ -92,6 +92,12 @@ describe('Create trip', () => { it('TRIP-002 — POST /api/trips without dates returns 201 and defaults to a 7-day window', async () => { const { user } = createUser(testDb); + const addDays = (d: Date, n: number) => { const r = new Date(d); r.setDate(r.getDate() + n); return r; }; + const toDateStr = (d: Date) => d.toISOString().slice(0, 10); + const tomorrow = addDays(new Date(), 1); + const expectedStart = toDateStr(tomorrow); + const expectedEnd = toDateStr(addDays(tomorrow, 7)); + const res = await request(app) .post('/api/trips') .set('Cookie', authCookie(user.id)) @@ -99,10 +105,10 @@ describe('Create trip', () => { expect(res.status).toBe(201); expect(res.body.trip).toBeDefined(); - expect(res.body.trip.start_date).not.toBeNull(); - expect(res.body.trip.end_date).not.toBeNull(); + expect(res.body.trip.start_date).toBe(expectedStart); + expect(res.body.trip.end_date).toBe(expectedEnd); - // Should have 8 days (start + 7 day window) + // Should have 8 days (start through end inclusive) const daysWithDate = testDb.prepare('SELECT * FROM days WHERE trip_id = ? AND date IS NOT NULL').all(res.body.trip.id) as any[]; expect(daysWithDate).toHaveLength(8); }); From 2197e0e1fd2eeafd20d12b90a72b7f37741d6fa4 Mon Sep 17 00:00:00 2001 From: jubnl Date: Sat, 4 Apr 2026 00:19:23 +0200 Subject: [PATCH 036/117] ci(test): remove push trigger, keep only pull_request --- .github/workflows/test.yml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fb16112..70eea81 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -4,11 +4,6 @@ permissions: contents: read on: - push: - branches: [main, dev] - paths: - - 'server/**' - - '.github/workflows/test.yml' pull_request: branches: [main, dev] paths: From 2469739bcaa5fb431745370f5671d52ff364ef72 Mon Sep 17 00:00:00 2001 From: jubnl Date: Sat, 4 Apr 2026 00:21:01 +0200 Subject: [PATCH 037/117] fix(admin): update stale NOMAD references to TREK - GitHubPanel: point release fetcher to mauriceboe/TREK - AdminPage: fix Docker update instructions (image, container name, volume paths) - es.ts: replace all remaining NOMAD occurrences with TREK --- client/src/components/Admin/GitHubPanel.tsx | 2 +- client/src/i18n/translations/es.ts | 18 +++++++++--------- client/src/pages/AdminPage.tsx | 12 ++++++------ 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/client/src/components/Admin/GitHubPanel.tsx b/client/src/components/Admin/GitHubPanel.tsx index 96a3b28..64b469a 100644 --- a/client/src/components/Admin/GitHubPanel.tsx +++ b/client/src/components/Admin/GitHubPanel.tsx @@ -3,7 +3,7 @@ import { Tag, Calendar, ExternalLink, ChevronDown, ChevronUp, Loader2, Heart, Co import { getLocaleForLanguage, useTranslation } from '../../i18n' import apiClient from '../../api/client' -const REPO = 'mauriceboe/NOMAD' +const REPO = 'mauriceboe/TREK' const PER_PAGE = 10 export default function GitHubPanel() { diff --git a/client/src/i18n/translations/es.ts b/client/src/i18n/translations/es.ts index b1142fd..4de28e2 100644 --- a/client/src/i18n/translations/es.ts +++ b/client/src/i18n/translations/es.ts @@ -327,7 +327,7 @@ const es: Record = { 'login.signingIn': 'Iniciando sesión…', 'login.signIn': 'Entrar', 'login.createAdmin': 'Crear cuenta de administrador', - 'login.createAdminHint': 'Configura la primera cuenta administradora de NOMAD.', + 'login.createAdminHint': 'Configura la primera cuenta administradora de TREK.', 'login.setNewPassword': 'Establecer nueva contraseña', 'login.setNewPasswordHint': 'Debe cambiar su contraseña antes de continuar.', 'login.createAccount': 'Crear cuenta', @@ -483,7 +483,7 @@ const es: Record = { // Addons 'admin.tabs.addons': 'Complementos', 'admin.addons.title': 'Complementos', - 'admin.addons.subtitle': 'Activa o desactiva funciones para personalizar tu experiencia en NOMAD.', + 'admin.addons.subtitle': 'Activa o desactiva funciones para personalizar tu experiencia en TREK.', 'admin.addons.subtitleBefore': 'Activa o desactiva funciones para personalizar tu experiencia en ', 'admin.addons.subtitleAfter': '.', 'admin.addons.enabled': 'Activo', @@ -499,7 +499,7 @@ const es: Record = { 'admin.addons.noAddons': 'No hay complementos disponibles', 'admin.weather.title': 'Datos meteorológicos', 'admin.weather.badge': 'Desde el 24 de marzo de 2026', - 'admin.weather.description': 'NOMAD utiliza Open-Meteo como fuente de datos meteorológicos. Open-Meteo es un servicio meteorológico gratuito y de código abierto: no requiere clave API.', + 'admin.weather.description': 'TREK utiliza Open-Meteo como fuente de datos meteorológicos. Open-Meteo es un servicio meteorológico gratuito y de código abierto: no requiere clave API.', 'admin.weather.forecast': 'Pronóstico de 16 días', 'admin.weather.forecastDesc': 'Antes eran 5 días (OpenWeatherMap)', 'admin.weather.climate': 'Datos climáticos históricos', @@ -551,11 +551,11 @@ const es: Record = { 'admin.github.error': 'No se pudieron cargar las versiones', 'admin.github.by': 'por', 'admin.update.available': 'Actualización disponible', - 'admin.update.text': 'NOMAD {version} está disponible. Estás usando {current}.', + 'admin.update.text': 'TREK {version} está disponible. Estás usando {current}.', 'admin.update.button': 'Ver en GitHub', 'admin.update.install': 'Instalar actualización', 'admin.update.confirmTitle': '¿Instalar actualización?', - 'admin.update.confirmText': 'NOMAD se actualizará de {current} a {version}. Después, el servidor se reiniciará automáticamente.', + 'admin.update.confirmText': 'TREK se actualizará de {current} a {version}. Después, el servidor se reiniciará automáticamente.', 'admin.update.dataInfo': 'Todos tus datos (viajes, usuarios, claves API, subidas, Vacay, Atlas, presupuestos) se conservarán.', 'admin.update.warning': 'La app estará brevemente no disponible durante el reinicio.', 'admin.update.confirm': 'Actualizar ahora', @@ -565,7 +565,7 @@ const es: Record = { 'admin.update.backupHint': 'Recomendamos crear una copia de seguridad antes de actualizar.', 'admin.update.backupLink': 'Ir a Copia de seguridad', 'admin.update.howTo': 'Cómo actualizar', - 'admin.update.dockerText': 'Tu instancia de NOMAD se ejecuta en Docker. Para actualizar a {version}, ejecuta los siguientes comandos en tu servidor:', + 'admin.update.dockerText': 'Tu instancia de TREK se ejecuta en Docker. Para actualizar a {version}, ejecuta los siguientes comandos en tu servidor:', 'admin.update.reloadHint': 'Recarga la página en unos segundos.', // Vacay addon @@ -620,9 +620,9 @@ const es: Record = { 'vacay.carryOver': 'Arrastrar saldo', 'vacay.carryOverHint': 'Trasladar automáticamente los días restantes al año siguiente', 'vacay.sharing': 'Compartir', - 'vacay.sharingHint': 'Comparte tu calendario de vacaciones con otros usuarios de NOMAD', + 'vacay.sharingHint': 'Comparte tu calendario de vacaciones con otros usuarios de TREK', 'vacay.owner': 'Propietario', - 'vacay.shareEmailPlaceholder': 'Correo electrónico del usuario de NOMAD', + 'vacay.shareEmailPlaceholder': 'Correo electrónico del usuario de TREK', 'vacay.shareSuccess': 'Plan compartido correctamente', 'vacay.shareError': 'No se pudo compartir el plan', 'vacay.dissolve': 'Deshacer fusión', @@ -634,7 +634,7 @@ const es: Record = { 'vacay.noData': 'Sin datos', 'vacay.changeColor': 'Cambiar color', 'vacay.inviteUser': 'Invitar usuario', - 'vacay.inviteHint': 'Invita a otro usuario de NOMAD a compartir un calendario combinado de vacaciones.', + 'vacay.inviteHint': 'Invita a otro usuario de TREK a compartir un calendario combinado de vacaciones.', 'vacay.selectUser': 'Seleccionar usuario', 'vacay.sendInvite': 'Enviar invitación', 'vacay.inviteSent': 'Invitación enviada', diff --git a/client/src/pages/AdminPage.tsx b/client/src/pages/AdminPage.tsx index 45ef2b0..471338c 100644 --- a/client/src/pages/AdminPage.tsx +++ b/client/src/pages/AdminPage.tsx @@ -1358,14 +1358,14 @@ export default function AdminPage(): React.ReactElement {
-{`docker pull mauriceboe/nomad:latest -docker stop nomad && docker rm nomad -docker run -d --name nomad \\ +{`docker pull mauriceboe/trek:latest +docker stop trek && docker rm trek +docker run -d --name trek \\ -p 3000:3000 \\ - -v /opt/nomad/data:/app/data \\ - -v /opt/nomad/uploads:/app/uploads \\ + -v /opt/trek/data:/app/data \\ + -v /opt/trek/uploads:/app/uploads \\ --restart unless-stopped \\ - mauriceboe/nomad:latest`} + mauriceboe/trek:latest`}
Date: Sat, 4 Apr 2026 00:52:01 +0200 Subject: [PATCH 038/117] changing handling of rights for accesing assets --- .../src/components/Memories/MemoriesPanel.tsx | 8 ++-- server/src/routes/immich.ts | 42 ++++++++----------- server/src/routes/synology.ts | 32 +++++++++----- server/src/services/immichService.ts | 13 ------ server/src/services/memoriesService.ts | 28 +++++++++++++ server/src/services/synologyService.ts | 39 ++--------------- 6 files changed, 75 insertions(+), 87 deletions(-) diff --git a/client/src/components/Memories/MemoriesPanel.tsx b/client/src/components/Memories/MemoriesPanel.tsx index ad9be29..963f547 100644 --- a/client/src/components/Memories/MemoriesPanel.tsx +++ b/client/src/components/Memories/MemoriesPanel.tsx @@ -338,7 +338,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa // ── Helpers ─────────────────────────────────────────────────────────────── const thumbnailBaseUrl = (photo: TripPhoto) => - `/api/integrations/${photo.provider}/assets/${photo.asset_id}/thumbnail?userId=${photo.user_id}` + `/api/integrations/${photo.provider}/assets/${tripId}/${photo.asset_id}/${photo.user_id}/thumbnail` const makePickerKey = (provider: string, assetId: string): string => `${provider}::${assetId}` @@ -775,12 +775,12 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa
{ - setLightboxId(photo.immich_asset_id); setLightboxUserId(photo.user_id); setLightboxInfo(null) + setLightboxId(photo.asset_id); setLightboxUserId(photo.user_id); setLightboxInfo(null) if (lightboxOriginalSrc) URL.revokeObjectURL(lightboxOriginalSrc) setLightboxOriginalSrc('') - fetchImageAsBlob(`/api/integrations/immich/assets/${photo.immich_asset_id}/original?userId=${photo.user_id}`).then(setLightboxOriginalSrc) + fetchImageAsBlob(`/api/integrations/${photo.provider}/assets/${tripId}/${photo.asset_id}/${photo.user_id}/original`).then(setLightboxOriginalSrc) setLightboxInfoLoading(true) - apiClient.get(`/integrations/${photo.provider}/assets/${photo.asset_id}/info?userId=${photo.user_id}`) + apiClient.get(`/integrations/${photo.provider}/assets/${tripId}/${photo.asset_id}/${photo.user_id}/info`) .then(r => setLightboxInfo(r.data)).catch(() => {}).finally(() => setLightboxInfoLoading(false)) }}> diff --git a/server/src/routes/immich.ts b/server/src/routes/immich.ts index 4a166a1..012d7ef 100644 --- a/server/src/routes/immich.ts +++ b/server/src/routes/immich.ts @@ -15,11 +15,11 @@ import { proxyThumbnail, proxyOriginal, isValidAssetId, - canAccessUserPhoto, listAlbums, syncAlbumAssets, getAssetInfo, } from '../services/immichService'; +import { canAccessUserPhoto } from '../services/memoriesService'; const router = express.Router(); @@ -83,48 +83,42 @@ router.post('/search', authenticate, async (req: Request, res: Response) => { // ── Asset Details ────────────────────────────────────────────────────────── -router.get('/assets/:assetId/info', authenticate, async (req: Request, res: Response) => { +router.get('/assets/:tripId/:assetId/:ownerId/info', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - const { assetId } = req.params; - if (!isValidAssetId(assetId)) return res.status(400).json({ error: 'Invalid asset ID' }); - const queryUserId = req.query.userId ? Number(req.query.userId) : undefined; - const ownerUserId = queryUserId && queryUserId !== authReq.user.id ? queryUserId : undefined; - if (ownerUserId && !canAccessUserPhoto(authReq.user.id, ownerUserId, assetId)) { + const { tripId, assetId, ownerId } = req.params; + + if (!canAccessUserPhoto(authReq.user.id, Number(ownerId), tripId, assetId, 'immich')) { return res.status(403).json({ error: 'Forbidden' }); } - const result = await getAssetInfo(authReq.user.id, assetId, ownerUserId); + const result = await getAssetInfo(authReq.user.id, assetId, Number(ownerId)); if (result.error) return res.status(result.status!).json({ error: result.error }); res.json(result.data); }); // ── Proxy Immich Assets ──────────────────────────────────────────────────── -router.get('/assets/:assetId/thumbnail', authFromQuery, async (req: Request, res: Response) => { +router.get('/assets/:tripId/:assetId/:ownerId/thumbnail', authFromQuery, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - const { assetId } = req.params; - if (!isValidAssetId(assetId)) return res.status(400).send('Invalid asset ID'); - const queryUserId = req.query.userId ? Number(req.query.userId) : undefined; - const ownerUserId = queryUserId && queryUserId !== authReq.user.id ? queryUserId : undefined; - if (ownerUserId && !canAccessUserPhoto(authReq.user.id, ownerUserId, assetId)) { - return res.status(403).send('Forbidden'); + const { tripId, assetId, ownerId } = req.params; + + if (!canAccessUserPhoto(authReq.user.id, Number(ownerId), tripId, assetId, 'immich')) { + return res.status(403).json({ error: 'Forbidden' }); } - const result = await proxyThumbnail(authReq.user.id, assetId, ownerUserId); + const result = await proxyThumbnail(authReq.user.id, assetId, Number(ownerId)); if (result.error) return res.status(result.status!).send(result.error); res.set('Content-Type', result.contentType!); res.set('Cache-Control', 'public, max-age=86400'); res.send(result.buffer); }); -router.get('/assets/:assetId/original', authFromQuery, async (req: Request, res: Response) => { +router.get('/assets/:tripId/:assetId/:ownerId/original', authFromQuery, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - const { assetId } = req.params; - if (!isValidAssetId(assetId)) return res.status(400).send('Invalid asset ID'); - const queryUserId = req.query.userId ? Number(req.query.userId) : undefined; - const ownerUserId = queryUserId && queryUserId !== authReq.user.id ? queryUserId : undefined; - if (ownerUserId && !canAccessUserPhoto(authReq.user.id, ownerUserId, assetId)) { - return res.status(403).send('Forbidden'); + const { tripId, assetId, ownerId } = req.params; + + if (!canAccessUserPhoto(authReq.user.id, Number(ownerId), tripId, assetId, 'immich')) { + return res.status(403).json({ error: 'Forbidden' }); } - const result = await proxyOriginal(authReq.user.id, assetId, ownerUserId); + const result = await proxyOriginal(authReq.user.id, assetId, Number(ownerId)); if (result.error) return res.status(result.status!).send(result.error); res.set('Content-Type', result.contentType!); res.set('Cache-Control', 'public, max-age=86400'); diff --git a/server/src/routes/synology.ts b/server/src/routes/synology.ts index c01e49e..838a3de 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/synology.ts @@ -12,11 +12,11 @@ import { searchSynologyPhotos, getSynologyAssetInfo, pipeSynologyProxy, - getSynologyTargetUserId, streamSynologyAsset, handleSynologyError, SynologyServiceError, } from '../services/synologyService'; +import { canAccessUserPhoto } from '../services/memoriesService'; const router = express.Router(); @@ -121,24 +121,32 @@ router.post('/search', authenticate, async (req: Request, res: Response) => { } }); -router.get('/assets/:photoId/info', authenticate, async (req: Request, res: Response) => { +router.get('/assets/:tripId/:photoId/:ownerId/info', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - const { photoId } = req.params; + const { tripId, photoId, ownerId } = req.params; + + if (!canAccessUserPhoto(authReq.user.id, Number(ownerId), tripId, photoId, 'synologyphotos')) { + return handleSynologyError(res, new SynologyServiceError(403, 'You don\'t have access to this photo'), 'Access denied'); + } try { - res.json(await getSynologyAssetInfo(authReq.user.id, photoId, getSynologyTargetUserId(req))); + res.json(await getSynologyAssetInfo(authReq.user.id, photoId, Number(ownerId))); } catch (err: unknown) { handleSynologyError(res, err, 'Could not reach Synology'); } }); -router.get('/assets/:photoId/thumbnail', authenticate, async (req: Request, res: Response) => { +router.get('/assets/:tripId/:photoId/:ownerId/thumbnail', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - const { photoId } = req.params; + const { tripId, photoId, ownerId } = req.params; const { size = 'sm' } = req.query; + if (!canAccessUserPhoto(authReq.user.id, Number(ownerId), tripId, photoId, 'synologyphotos')) { + return handleSynologyError(res, new SynologyServiceError(403, 'You don\'t have access to this photo'), 'Access denied'); + } + try { - const proxy = await streamSynologyAsset(authReq.user.id, getSynologyTargetUserId(req), photoId, 'thumbnail', String(size)); + const proxy = await streamSynologyAsset(authReq.user.id, Number(ownerId), photoId, 'thumbnail', String(size)); await pipeSynologyProxy(res, proxy); } catch (err: unknown) { if (res.headersSent) { @@ -148,12 +156,16 @@ router.get('/assets/:photoId/thumbnail', authenticate, async (req: Request, res: } }); -router.get('/assets/:photoId/original', authenticate, async (req: Request, res: Response) => { +router.get('/assets/:tripId/:photoId/:ownerId/original', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; - const { photoId } = req.params; + const { tripId, photoId, ownerId } = req.params; + + if (!canAccessUserPhoto(authReq.user.id, Number(ownerId), tripId, photoId, 'synologyphotos')) { + return handleSynologyError(res, new SynologyServiceError(403, 'You don\'t have access to this photo'), 'Access denied'); + } try { - const proxy = await streamSynologyAsset(authReq.user.id, getSynologyTargetUserId(req), photoId, 'original'); + const proxy = await streamSynologyAsset(authReq.user.id, Number(ownerId), photoId, 'original'); await pipeSynologyProxy(res, proxy); } catch (err: unknown) { if (res.headersSent) { diff --git a/server/src/services/immichService.ts b/server/src/services/immichService.ts index 5515d9e..baef3bb 100644 --- a/server/src/services/immichService.ts +++ b/server/src/services/immichService.ts @@ -190,19 +190,6 @@ export async function searchPhotos( // ── Asset Info / Proxy ───────────────────────────────────────────────────── -/** - * Verify that requestingUserId can access a shared photo belonging to ownerUserId. - * The asset must be shared (shared=1) and the requesting user must be a member of - * the same trip that contains the photo. - */ -export function canAccessUserPhoto(requestingUserId: number, ownerUserId: number, assetId: string): boolean { - const row = db.prepare(` - SELECT tp.trip_id FROM trip_photos tp - WHERE tp.immich_asset_id = ? AND tp.user_id = ? AND tp.shared = 1 - `).get(assetId, ownerUserId) as { trip_id: number } | undefined; - if (!row) return false; - return !!canAccessTrip(String(row.trip_id), requestingUserId); -} export async function getAssetInfo( userId: number, diff --git a/server/src/services/memoriesService.ts b/server/src/services/memoriesService.ts index 5fdfbce..3886c8d 100644 --- a/server/src/services/memoriesService.ts +++ b/server/src/services/memoriesService.ts @@ -3,6 +3,34 @@ import { notifyTripMembers } from './notifications'; type ServiceError = { error: string; status: number }; + +/** + * Verify that requestingUserId can access a shared photo belonging to ownerUserId. + * The asset must be shared (shared=1) and the requesting user must be a member of + * the same trip that contains the photo. + */ +export function canAccessUserPhoto(requestingUserId: number, ownerUserId: number, tripId: string, assetId: string, provider: string): boolean { + if (requestingUserId === ownerUserId) { + return true; + } + const sharedAsset = db.prepare(` + SELECT 1 + FROM trip_photos + WHERE user_id = ? + AND asset_id = ? + AND provider = ? + AND trip_id = ? + AND shared = 1 + LIMIT 1 + `).get(ownerUserId, assetId, provider, tripId); + + if (!sharedAsset) { + return false; + } + return !!canAccessTrip(String(tripId), requestingUserId); +} + + function accessDeniedIfMissing(tripId: string, userId: number): ServiceError | null { if (!canAccessTrip(tripId, userId)) { return { error: 'Trip not found', status: 404 }; diff --git a/server/src/services/synologyService.ts b/server/src/services/synologyService.ts index 646c592..0cb3308 100644 --- a/server/src/services/synologyService.ts +++ b/server/src/services/synologyService.ts @@ -1,13 +1,9 @@ import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; -import { NextFunction, Request, Response as ExpressResponse } from 'express'; -import { db, canAccessTrip } from '../db/database'; +import { Request, Response as ExpressResponse } from 'express'; +import { db } from '../db/database'; import { decrypt_api_key, maybe_encrypt_api_key } from './apiKeyCrypto'; -import { authenticate } from '../middleware/auth'; -import { AuthRequest } from '../types'; -import { consumeEphemeralToken } from './ephemeralTokens'; import { checkSsrf } from '../utils/ssrfGuard'; -import { no } from 'zod/locales'; const SYNOLOGY_API_TIMEOUT_MS = 30000; const SYNOLOGY_PROVIDER = 'synologyphotos'; @@ -270,11 +266,6 @@ function normalizeSynologyPhotoInfo(item: SynologyPhotoItem): SynologyPhotoInfo }; } -export function getSynologyTargetUserId(req: Request): number { - const { userId } = req.query; - return Number(userId); -} - export function handleSynologyError(res: ExpressResponse, err: unknown, fallbackMessage: string): ExpressResponse { if (err instanceof SynologyServiceError) { return res.status(err.status).json({ error: err.message }); @@ -295,23 +286,6 @@ function splitPackedSynologyId(rawId: string): { id: string; cacheKey: string; a return { id, cacheKey: rawId, assetId: rawId }; } -function canStreamSynologyAsset(requestingUserId: number, targetUserId: number, assetId: string): boolean { - if (requestingUserId === targetUserId) { - return true; - } - - const sharedAsset = db.prepare(` - SELECT 1 - FROM trip_photos - WHERE user_id = ? - AND asset_id = ? - AND provider = 'synologyphotos' - AND shared = 1 - LIMIT 1 - `).get(targetUserId, assetId); - - return !!sharedAsset; -} async function getSynologySession(userId: number): Promise { const cachedSid = readSynologyUser(userId, ['synology_sid'])?.synology_sid || null; @@ -514,9 +488,6 @@ export async function searchSynologyPhotos(userId: number, from?: string, to?: s } export async function getSynologyAssetInfo(userId: number, photoId: string, targetUserId?: number): Promise { - if (!canStreamSynologyAsset(userId, targetUserId ?? userId, photoId)) { - throw new SynologyServiceError(403, 'Youd don\'t have access to this photo'); - } const parsedId = splitPackedSynologyId(photoId); const result = await requestSynologyApi<{ list: SynologyPhotoItem[] }>(targetUserId ?? userId, { api: 'SYNO.Foto.Browse.Item', @@ -546,11 +517,7 @@ export async function streamSynologyAsset( photoId: string, kind: 'thumbnail' | 'original', size?: string, -): Promise { - if (!canStreamSynologyAsset(userId, targetUserId, photoId)) { - throw new SynologyServiceError(403, 'Youd don\'t have access to this photo'); - } - +): Promise { const parsedId = splitPackedSynologyId(photoId); const synology_url = getSynologyCredentials(targetUserId).synology_url; if (!synology_url) { From 1305a0750278fa6e1ab4070412c43b7d337fe833 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Sat, 4 Apr 2026 11:34:48 +0200 Subject: [PATCH 039/117] after changing routes i forgot to chang them in picker --- client/src/components/Memories/MemoriesPanel.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/components/Memories/MemoriesPanel.tsx b/client/src/components/Memories/MemoriesPanel.tsx index 963f547..d8d167d 100644 --- a/client/src/components/Memories/MemoriesPanel.tsx +++ b/client/src/components/Memories/MemoriesPanel.tsx @@ -598,7 +598,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa outline: isSelected ? '3px solid var(--text-primary)' : 'none', outlineOffset: -3, }}> - {isSelected && (
Date: Sat, 4 Apr 2026 12:22:22 +0200 Subject: [PATCH 040/117] adding helper functions for syncing albums --- server/src/routes/memories.ts | 10 +++-- server/src/services/immichService.ts | 25 +++++++------ server/src/services/memoriesService.ts | 52 +++++++++++++++++--------- server/src/services/synologyService.ts | 33 +++++++--------- 4 files changed, 68 insertions(+), 52 deletions(-) diff --git a/server/src/routes/memories.ts b/server/src/routes/memories.ts index 5a6f1cf..1b1fac3 100644 --- a/server/src/routes/memories.ts +++ b/server/src/routes/memories.ts @@ -11,6 +11,7 @@ import { removeTripPhoto, setTripPhotoSharing, notifySharedTripPhotos, + normalizeSelections, } from '../services/memoriesService'; const router = express.Router(); @@ -44,13 +45,14 @@ router.delete('/trips/:tripId/album-links/:linkId', authenticate, (req: Request, router.post('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; + + const selections = normalizeSelections(req.body?.selections, req.body?.provider, req.body?.asset_ids); + const shared = req.body?.shared === undefined ? true : !!req.body?.shared; const result = addTripPhotos( tripId, authReq.user.id, - req.body?.shared, - req.body?.selections, - req.body?.provider, - req.body?.asset_ids, + shared, + selections, ); if ('error' in result) return res.status(result.status).json({ error: result.error }); diff --git a/server/src/services/immichService.ts b/server/src/services/immichService.ts index baef3bb..4550b2a 100644 --- a/server/src/services/immichService.ts +++ b/server/src/services/immichService.ts @@ -2,6 +2,7 @@ import { db } from '../db/database'; import { maybe_encrypt_api_key, decrypt_api_key } from './apiKeyCrypto'; import { checkSsrf } from '../utils/ssrfGuard'; import { writeAudit } from './auditLog'; +import { addTripPhotos, getAlbumIdFromLink, Selection, updateSyncTimeForAlbumLink } from './memoriesService'; // ── Credentials ──────────────────────────────────────────────────────────── @@ -313,15 +314,14 @@ export async function syncAlbumAssets( linkId: string, userId: number ): Promise<{ success?: boolean; added?: number; total?: number; error?: string; status?: number }> { - const link = db.prepare('SELECT * FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ? AND provider = ?') - .get(linkId, tripId, userId, 'immich') as any; - if (!link) return { error: 'Album link not found', status: 404 }; + const albumId = getAlbumIdFromLink(tripId, linkId, userId); + if (!albumId) return { error: 'Album link not found', status: 404 }; const creds = getImmichCredentials(userId); if (!creds) return { error: 'Immich not configured', status: 400 }; try { - const resp = await fetch(`${creds.immich_url}/api/albums/${link.album_id}`, { + const resp = await fetch(`${creds.immich_url}/api/albums/${albumId}`, { headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, signal: AbortSignal.timeout(15000), }); @@ -329,16 +329,17 @@ export async function syncAlbumAssets( const albumData = await resp.json() as { assets?: any[] }; const assets = (albumData.assets || []).filter((a: any) => a.type === 'IMAGE'); - const insert = db.prepare("INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, 'immich', 1)"); - let added = 0; - for (const asset of assets) { - const r = insert.run(tripId, userId, asset.id); - if (r.changes > 0) added++; - } + const selection: Selection = { + provider: 'immich', + asset_ids: assets.map((a: any) => a.id), + }; - db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); + const addResult = addTripPhotos(tripId, userId, true, [selection]); + if ('error' in addResult) return { error: addResult.error, status: addResult.status }; - return { success: true, added, total: assets.length }; + updateSyncTimeForAlbumLink(linkId); + + return { success: true, added: addResult.added, total: assets.length }; } catch { return { error: 'Could not reach Immich', status: 502 }; } diff --git a/server/src/services/memoriesService.ts b/server/src/services/memoriesService.ts index 3886c8d..0470559 100644 --- a/server/src/services/memoriesService.ts +++ b/server/src/services/memoriesService.ts @@ -38,12 +38,14 @@ function accessDeniedIfMissing(tripId: string, userId: number): ServiceError | n return null; } -type Selection = { +export type Selection = { provider: string; - asset_ids: unknown[]; + asset_ids: string[]; }; -function normalizeSelections(selectionsRaw: unknown, providerRaw: unknown, assetIdsRaw: unknown): Selection[] { + +//fallback for old clients that don't send selections as an array of provider/asset_id groups +export function normalizeSelections(selectionsRaw: unknown, providerRaw: unknown, assetIdsRaw: unknown): Selection[] { const selectionsFromBody = Array.isArray(selectionsRaw) ? selectionsRaw : null; const provider = String(providerRaw || '').toLowerCase(); @@ -145,40 +147,54 @@ export function removeAlbumLink(tripId: string, linkId: string, userId: number): return { success: true }; } +function addTripPhoto(tripId: string, userId: number, provider: string, assetId: string, shared: boolean): boolean { + const result = db.prepare( + 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, ?, ?)' + ).run(tripId, userId, assetId, provider, shared ? 1 : 0); + return result.changes > 0; +} + export function addTripPhotos( tripId: string, userId: number, - sharedRaw: unknown, - selectionsRaw: unknown, - providerRaw: unknown, - assetIdsRaw: unknown, + shared: boolean, + selections: Selection[], ): { success: true; added: number; shared: boolean } | ServiceError { const denied = accessDeniedIfMissing(tripId, userId); if (denied) return denied; - const shared = sharedRaw === undefined ? true : !!sharedRaw; - const selections = normalizeSelections(selectionsRaw, providerRaw, assetIdsRaw); if (selections.length === 0) { - return { error: 'selections required', status: 400 }; + return { error: 'No photos selected', status: 400 }; } - const insert = db.prepare( - 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, ?, ?)' - ); - let added = 0; for (const selection of selections) { for (const raw of selection.asset_ids) { const assetId = String(raw || '').trim(); if (!assetId) continue; - const result = insert.run(tripId, userId, assetId, selection.provider, shared ? 1 : 0); - if (result.changes > 0) added++; + if (addTripPhoto(tripId, userId, selection.provider, assetId, shared)) { + added++; + } } } - return { success: true, added, shared }; } +export function getAlbumIdFromLink(tripId: string, linkId: string, userId: number): string { + const denied = accessDeniedIfMissing(tripId, userId); + if (denied) return null; + + const { album_id } = db.prepare('SELECT album_id FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?').get(linkId, tripId, userId) as { album_id: string } | null; + + return album_id; +} + +export function updateSyncTimeForAlbumLink(linkId: string): void { + db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); +} + + + export function removeTripPhoto( tripId: string, userId: number, @@ -256,3 +272,5 @@ export async function notifySharedTripPhotos( count: String(added), }); } + + diff --git a/server/src/services/synologyService.ts b/server/src/services/synologyService.ts index 0cb3308..7a01c1c 100644 --- a/server/src/services/synologyService.ts +++ b/server/src/services/synologyService.ts @@ -1,9 +1,11 @@ import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; -import { Request, Response as ExpressResponse } from 'express'; +import { Response as ExpressResponse } from 'express'; import { db } from '../db/database'; import { decrypt_api_key, maybe_encrypt_api_key } from './apiKeyCrypto'; import { checkSsrf } from '../utils/ssrfGuard'; +import { addTripPhotos, getAlbumIdFromLink, Selection, updateSyncTimeForAlbumLink } from './memoriesService'; +import { error } from 'node:console'; const SYNOLOGY_API_TIMEOUT_MS = 30000; const SYNOLOGY_PROVIDER = 'synologyphotos'; @@ -401,10 +403,8 @@ export async function listSynologyAlbums(userId: number): Promise<{ albums: Arra export async function syncSynologyAlbumLink(userId: number, tripId: string, linkId: string): Promise<{ added: number; total: number }> { - const link = db.prepare(`SELECT * FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ? AND provider = ?`) - .get(linkId, tripId, userId, SYNOLOGY_PROVIDER) as { album_id?: string | number } | undefined; - - if (!link) { + const albumId = getAlbumIdFromLink(tripId, linkId, userId); + if (!albumId) { throw new SynologyServiceError(404, 'Album link not found'); } @@ -417,7 +417,7 @@ export async function syncSynologyAlbumLink(userId: number, tripId: string, link api: 'SYNO.Foto.Browse.Item', method: 'list', version: 1, - album_id: Number(link.album_id), + album_id: Number(albumId), offset, limit: pageSize, additional: ['thumbnail'], @@ -433,22 +433,17 @@ export async function syncSynologyAlbumLink(userId: number, tripId: string, link offset += pageSize; } - const insert = db.prepare( - "INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, 'synologyphotos', 1)" - ); + const selection: Selection = { + provider: SYNOLOGY_PROVIDER, + asset_ids: allItems.map(item => String(item.additional?.thumbnail?.cache_key || '')).filter(id => id), + }; - let added = 0; - for (const item of allItems) { - const transformed = normalizeSynologyPhotoInfo(item); - const assetId = String(transformed?.id || '').trim(); - if (!assetId) continue; - const result = insert.run(tripId, userId, assetId); - if (result.changes > 0) added++; - } + const addResult = addTripPhotos(tripId, userId, true, [selection]); + if ('error' in addResult) throw new SynologyServiceError(addResult.status, addResult.error); - db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); + updateSyncTimeForAlbumLink(linkId); - return { added, total: allItems.length }; + return { added: addResult.added, total: allItems.length }; } export async function searchSynologyPhotos(userId: number, from?: string, to?: string, offset = 0, limit = 300): Promise<{ assets: SynologyPhotoInfo[]; total: number; hasMore: boolean }> { From 50d2a211e5248c3e24523a5da418ab370c010099 Mon Sep 17 00:00:00 2001 From: mauriceboe Date: Sat, 4 Apr 2026 12:53:12 +0200 Subject: [PATCH 041/117] fix(oidc): revert default scope to 'openid email profile' Removes 'groups' from the default OIDC_SCOPE fallback, which caused invalid_scope errors with providers that don't support it (e.g. Google). Fixes #391 --- server/src/routes/oidc.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/routes/oidc.ts b/server/src/routes/oidc.ts index 338c4bd..dc01827 100644 --- a/server/src/routes/oidc.ts +++ b/server/src/routes/oidc.ts @@ -43,7 +43,7 @@ router.get('/login', async (req: Request, res: Response) => { response_type: 'code', client_id: config.clientId, redirect_uri: redirectUri, - scope: process.env.OIDC_SCOPE || 'openid email profile groups', + scope: process.env.OIDC_SCOPE || 'openid email profile', state, }); From 504713d920eb5f8b78fab3a4230409b23786e23f Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Sat, 4 Apr 2026 13:36:12 +0200 Subject: [PATCH 042/117] change in hadnling return values from unified service --- server/src/routes/memories.ts | 96 +++--- server/src/services/immichService.ts | 13 +- server/src/services/memoriesService.ts | 450 +++++++++++++------------ server/src/services/synologyService.ts | 15 +- 4 files changed, 300 insertions(+), 274 deletions(-) diff --git a/server/src/routes/memories.ts b/server/src/routes/memories.ts index 1b1fac3..e60b9e1 100644 --- a/server/src/routes/memories.ts +++ b/server/src/routes/memories.ts @@ -1,6 +1,5 @@ import express, { Request, Response } from 'express'; import { authenticate } from '../middleware/auth'; -import { broadcast } from '../websocket'; import { AuthRequest } from '../types'; import { listTripPhotos, @@ -10,94 +9,85 @@ import { addTripPhotos, removeTripPhoto, setTripPhotoSharing, - notifySharedTripPhotos, - normalizeSelections, } from '../services/memoriesService'; const router = express.Router(); +//------------------------------------------------ +// routes for managing photos linked to trip router.get('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; const result = listTripPhotos(tripId, authReq.user.id); - if ('error' in result) return res.status(result.status).json({ error: result.error }); - res.json({ photos: result.photos }); + if ('error' in result) return res.status(result.error.status).json({ error: result.error.message }); + res.json({ photos: result.data }); }); -router.get('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { tripId } = req.params; - const result = listTripAlbumLinks(tripId, authReq.user.id); - if ('error' in result) return res.status(result.status).json({ error: result.error }); - res.json({ links: result.links }); -}); - -router.delete('/trips/:tripId/album-links/:linkId', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { tripId, linkId } = req.params; - const result = removeAlbumLink(tripId, linkId, authReq.user.id); - if ('error' in result) return res.status(result.status).json({ error: result.error }); - res.json({ success: true }); - broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); -}); - -router.post('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { +router.post('/trips/:tripId/photos', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; + const sid = req.headers['x-socket-id'] as string; - const selections = normalizeSelections(req.body?.selections, req.body?.provider, req.body?.asset_ids); const shared = req.body?.shared === undefined ? true : !!req.body?.shared; - const result = addTripPhotos( + const result = await addTripPhotos( tripId, authReq.user.id, shared, - selections, + req.body?.selections || [], + sid, ); - if ('error' in result) return res.status(result.status).json({ error: result.error }); + if ('error' in result) return res.status(result.error.status).json({ error: result.error.message }); - res.json({ success: true, added: result.added }); - broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); - - if (result.shared && result.added > 0) { - void notifySharedTripPhotos( - tripId, - authReq.user.id, - authReq.user.username || authReq.user.email, - result.added, - ).catch(() => {}); - } + res.json({ success: true, added: result.data.added }); }); -router.delete('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { +router.put('/trips/:tripId/photos/sharing', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; - const result = removeTripPhoto(tripId, authReq.user.id, req.body?.provider, req.body?.asset_id); - if ('error' in result) return res.status(result.status).json({ error: result.error }); - res.json({ success: true }); - broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); -}); - -router.put('/trips/:tripId/photos/sharing', authenticate, (req: Request, res: Response) => { - const authReq = req as AuthRequest; - const { tripId } = req.params; - const result = setTripPhotoSharing( + const result = await setTripPhotoSharing( tripId, authReq.user.id, req.body?.provider, req.body?.asset_id, req.body?.shared, ); - if ('error' in result) return res.status(result.status).json({ error: result.error }); + if ('error' in result) return res.status(result.error.status).json({ error: result.error.message }); res.json({ success: true }); - broadcast(tripId, 'memories:updated', { userId: authReq.user.id }, req.headers['x-socket-id'] as string); }); -router.post('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { +router.delete('/trips/:tripId/photos', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + const result = await removeTripPhoto(tripId, authReq.user.id, req.body?.provider, req.body?.asset_id); + if ('error' in result) return res.status(result.error.status).json({ error: result.error.message }); + res.json({ success: true }); +}); + +//------------------------------ +// routes for managing album links + +router.get('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId } = req.params; + const result = listTripAlbumLinks(tripId, authReq.user.id); + if ('error' in result) return res.status(result.error.status).json({ error: result.error.message }); + res.json({ links: result.data }); +}); + +router.post('/trips/:tripId/album-links', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; const result = createTripAlbumLink(tripId, authReq.user.id, req.body?.provider, req.body?.album_id, req.body?.album_name); - if ('error' in result) return res.status(result.status).json({ error: result.error }); + if ('error' in result) return res.status(result.error.status).json({ error: result.error.message }); + res.json({ success: true }); +}); + +router.delete('/trips/:tripId/album-links/:linkId', authenticate, async (req: Request, res: Response) => { + const authReq = req as AuthRequest; + const { tripId, linkId } = req.params; + const result = removeAlbumLink(tripId, linkId, authReq.user.id); + if ('error' in result) return res.status(result.error.status).json({ error: result.error.message }); res.json({ success: true }); }); diff --git a/server/src/services/immichService.ts b/server/src/services/immichService.ts index 4550b2a..d4a353b 100644 --- a/server/src/services/immichService.ts +++ b/server/src/services/immichService.ts @@ -3,6 +3,7 @@ import { maybe_encrypt_api_key, decrypt_api_key } from './apiKeyCrypto'; import { checkSsrf } from '../utils/ssrfGuard'; import { writeAudit } from './auditLog'; import { addTripPhotos, getAlbumIdFromLink, Selection, updateSyncTimeForAlbumLink } from './memoriesService'; +import { error } from 'node:console'; // ── Credentials ──────────────────────────────────────────────────────────── @@ -314,14 +315,14 @@ export async function syncAlbumAssets( linkId: string, userId: number ): Promise<{ success?: boolean; added?: number; total?: number; error?: string; status?: number }> { - const albumId = getAlbumIdFromLink(tripId, linkId, userId); - if (!albumId) return { error: 'Album link not found', status: 404 }; + const response = getAlbumIdFromLink(tripId, linkId, userId); + if (!response.success) return { error: 'Album link not found', status: 404 }; const creds = getImmichCredentials(userId); if (!creds) return { error: 'Immich not configured', status: 400 }; try { - const resp = await fetch(`${creds.immich_url}/api/albums/${albumId}`, { + const resp = await fetch(`${creds.immich_url}/api/albums/${response.data}`, { headers: { 'x-api-key': creds.immich_api_key, 'Accept': 'application/json' }, signal: AbortSignal.timeout(15000), }); @@ -334,12 +335,12 @@ export async function syncAlbumAssets( asset_ids: assets.map((a: any) => a.id), }; - const addResult = addTripPhotos(tripId, userId, true, [selection]); - if ('error' in addResult) return { error: addResult.error, status: addResult.status }; + const result = await addTripPhotos(tripId, userId, true, [selection]); + if ('error' in result) return { error: result.error.message, status: result.error.status }; updateSyncTimeForAlbumLink(linkId); - return { success: true, added: addResult.added, total: assets.length }; + return { success: true, added: result.data.added, total: assets.length }; } catch { return { error: 'Could not reach Immich', status: 502 }; } diff --git a/server/src/services/memoriesService.ts b/server/src/services/memoriesService.ts index 0470559..03ac465 100644 --- a/server/src/services/memoriesService.ts +++ b/server/src/services/memoriesService.ts @@ -1,14 +1,29 @@ import { db, canAccessTrip } from '../db/database'; import { notifyTripMembers } from './notifications'; - -type ServiceError = { error: string; status: number }; +import { broadcast } from '../websocket'; -/** - * Verify that requestingUserId can access a shared photo belonging to ownerUserId. - * The asset must be shared (shared=1) and the requesting user must be a member of - * the same trip that contains the photo. - */ +type ServiceError = { success: false; error: { message: string; status: number } }; +type ServiceResult = { success: true; data: T } | ServiceError; + +function fail(error: string, status: number): ServiceError { + return { success: false, error: { message: error, status }}; +} + +function success(data: T): ServiceResult { + return { success: true, data: data }; +} + +function mapDbError(error: unknown, fallbackMessage: string): ServiceError { + if (error instanceof Error && /unique|constraint/i.test(error.message)) { + return fail('Resource already exists', 409); + } + return fail(fallbackMessage, 500); +} + +//----------------------------------------------- +//access check helper + export function canAccessUserPhoto(requestingUserId: number, ownerUserId: number, tripId: string, assetId: string, provider: string): boolean { if (requestingUserId === ownerUserId) { return true; @@ -27,15 +42,70 @@ export function canAccessUserPhoto(requestingUserId: number, ownerUserId: number if (!sharedAsset) { return false; } - return !!canAccessTrip(String(tripId), requestingUserId); + return !!canAccessTrip(tripId, requestingUserId); } - -function accessDeniedIfMissing(tripId: string, userId: number): ServiceError | null { - if (!canAccessTrip(tripId, userId)) { - return { error: 'Trip not found', status: 404 }; +export function listTripPhotos(tripId: string, userId: number): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); } - return null; + + try { + const photos = db.prepare(` + SELECT tp.asset_id, tp.provider, tp.user_id, tp.shared, tp.added_at, + u.username, u.avatar + FROM trip_photos tp + JOIN users u ON tp.user_id = u.id + WHERE tp.trip_id = ? + AND (tp.user_id = ? OR tp.shared = 1) + ORDER BY tp.added_at ASC + `).all(tripId, userId) as any[]; + + return success(photos); + } catch (error) { + return mapDbError(error, 'Failed to list trip photos'); + } +} + +export function listTripAlbumLinks(tripId: string, userId: number): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } + + try { + const links = 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 = ? + ORDER BY tal.created_at ASC + `).all(tripId); + + return success(links); + } catch (error) { + return mapDbError(error, 'Failed to list trip album links'); + } +} + +//----------------------------------------------- +// managing photos in trip + +function _addTripPhoto(tripId: string, userId: number, provider: string, assetId: string, shared: boolean): boolean { + const result = db.prepare( + 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, ?, ?)' + ).run(tripId, userId, assetId, provider, shared ? 1 : 0); + return result.changes > 0; } export type Selection = { @@ -43,234 +113,198 @@ export type Selection = { asset_ids: string[]; }; - -//fallback for old clients that don't send selections as an array of provider/asset_id groups -export function normalizeSelections(selectionsRaw: unknown, providerRaw: unknown, assetIdsRaw: unknown): Selection[] { - const selectionsFromBody = Array.isArray(selectionsRaw) ? selectionsRaw : null; - const provider = String(providerRaw || '').toLowerCase(); - - if (selectionsFromBody && selectionsFromBody.length > 0) { - return selectionsFromBody - .map((selection: any) => ({ - provider: String(selection?.provider || '').toLowerCase(), - asset_ids: Array.isArray(selection?.asset_ids) ? selection.asset_ids : [], - })) - .filter((selection: Selection) => selection.provider && selection.asset_ids.length > 0); - } - - if (provider && Array.isArray(assetIdsRaw) && assetIdsRaw.length > 0) { - return [{ provider, asset_ids: assetIdsRaw }]; - } - - return []; -} - -export function listTripPhotos(tripId: string, userId: number): { photos: any[] } | ServiceError { - const denied = accessDeniedIfMissing(tripId, userId); - if (denied) return denied; - - const photos = db.prepare(` - SELECT tp.asset_id, tp.provider, tp.user_id, tp.shared, tp.added_at, - u.username, u.avatar - FROM trip_photos tp - JOIN users u ON tp.user_id = u.id - WHERE tp.trip_id = ? - AND (tp.user_id = ? OR tp.shared = 1) - ORDER BY tp.added_at ASC - `).all(tripId, userId) as any[]; - - return { photos }; -} - -export function listTripAlbumLinks(tripId: string, userId: number): { links: any[] } | ServiceError { - const denied = accessDeniedIfMissing(tripId, userId); - if (denied) return denied; - - const links = 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 = ? - ORDER BY tal.created_at ASC - `).all(tripId); - - return { links }; -} - -export function createTripAlbumLink( +export async function addTripPhotos( tripId: string, userId: number, - providerRaw: unknown, - albumIdRaw: unknown, - albumNameRaw: unknown, -): { success: true } | ServiceError { - const denied = accessDeniedIfMissing(tripId, userId); - if (denied) return denied; + shared: boolean, + selections: Selection[], + sid?: string, +): Promise> { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } + + if (selections.length === 0) { + return fail('No photos selected', 400); + } + + try { + let added = 0; + for (const selection of selections) { + for (const raw of selection.asset_ids) { + const assetId = String(raw || '').trim(); + if (!assetId) continue; + if (_addTripPhoto(tripId, userId, selection.provider, assetId, shared)) { + added++; + } + } + } + + await _notifySharedTripPhotos(tripId, userId, added); + broadcast(tripId, 'memories:updated', { userId }, sid); + return success({ added, shared }); + } catch (error) { + return mapDbError(error, 'Failed to add trip photos'); + } +} + + +export async function setTripPhotoSharing( + tripId: string, + userId: number, + provider: string, + assetId: string, + shared: boolean, + sid?: string, +): Promise> { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } + + try { + db.prepare(` + UPDATE trip_photos + SET shared = ? + WHERE trip_id = ? + AND user_id = ? + AND asset_id = ? + AND provider = ? + `).run(shared ? 1 : 0, tripId, userId, assetId, provider); + + await _notifySharedTripPhotos(tripId, userId, 1); + broadcast(tripId, 'memories:updated', { userId }, sid); + return success(true); + } catch (error) { + return mapDbError(error, 'Failed to update photo sharing'); + } +} + + +export function removeTripPhoto( + tripId: string, + userId: number, + provider: string, + assetId: string, + sid?: string, +): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } + + try { + db.prepare(` + DELETE FROM trip_photos + WHERE trip_id = ? + AND user_id = ? + AND asset_id = ? + AND provider = ? + `).run(tripId, userId, assetId, provider); + + broadcast(tripId, 'memories:updated', { userId }, sid); + + return success(true); + } catch (error) { + return mapDbError(error, 'Failed to remove trip photo'); + } +} + +// ---------------------------------------------- +// managing album links in trip + +export function createTripAlbumLink(tripId: string, userId: number, providerRaw: unknown, albumIdRaw: unknown, albumNameRaw: unknown): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } const provider = String(providerRaw || '').toLowerCase(); const albumId = String(albumIdRaw || '').trim(); const albumName = String(albumNameRaw || '').trim(); if (!provider) { - return { error: 'provider is required', status: 400 }; + return fail('provider is required', 400); } if (!albumId) { - return { error: 'album_id required', status: 400 }; + return fail('album_id required', 400); } try { - db.prepare( + const result = db.prepare( 'INSERT OR IGNORE INTO trip_album_links (trip_id, user_id, provider, album_id, album_name) VALUES (?, ?, ?, ?, ?)' ).run(tripId, userId, provider, albumId, albumName); - return { success: true }; - } catch { - return { error: 'Album already linked', status: 400 }; - } -} -export function removeAlbumLink(tripId: string, linkId: string, userId: number): { success: true } | ServiceError { - const denied = accessDeniedIfMissing(tripId, userId); - if (denied) return denied; - - db.prepare('DELETE FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') - .run(linkId, tripId, userId); - - return { success: true }; -} - -function addTripPhoto(tripId: string, userId: number, provider: string, assetId: string, shared: boolean): boolean { - const result = db.prepare( - 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, asset_id, provider, shared) VALUES (?, ?, ?, ?, ?)' - ).run(tripId, userId, assetId, provider, shared ? 1 : 0); - return result.changes > 0; -} - -export function addTripPhotos( - tripId: string, - userId: number, - shared: boolean, - selections: Selection[], -): { success: true; added: number; shared: boolean } | ServiceError { - const denied = accessDeniedIfMissing(tripId, userId); - if (denied) return denied; - - if (selections.length === 0) { - return { error: 'No photos selected', status: 400 }; - } - - let added = 0; - for (const selection of selections) { - for (const raw of selection.asset_ids) { - const assetId = String(raw || '').trim(); - if (!assetId) continue; - if (addTripPhoto(tripId, userId, selection.provider, assetId, shared)) { - added++; - } + if (result.changes === 0) { + return fail('Album already linked', 409); } + + return success(true); + } catch (error) { + return mapDbError(error, 'Failed to link album'); } - return { success: true, added, shared }; } -export function getAlbumIdFromLink(tripId: string, linkId: string, userId: number): string { - const denied = accessDeniedIfMissing(tripId, userId); - if (denied) return null; +export function removeAlbumLink(tripId: string, linkId: string, userId: number): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) { + return fail('Trip not found or access denied', 404); + } - const { album_id } = db.prepare('SELECT album_id FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?').get(linkId, tripId, userId) as { album_id: string } | null; + try { + db.prepare('DELETE FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') + .run(linkId, tripId, userId); - return album_id; + return success(true); + } catch (error) { + return mapDbError(error, 'Failed to remove album link'); + } +} + +//helpers for album link syncing + +export function getAlbumIdFromLink(tripId: string, linkId: string, userId: number): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) return fail('Trip not found or access denied', 404); + + try { + const row = db.prepare('SELECT album_id FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') + .get(linkId, tripId, userId) as { album_id: string } | null; + + return row ? success(row.album_id) : fail('Album link not found', 404); + } catch { + return fail('Failed to retrieve album link', 500); + } } export function updateSyncTimeForAlbumLink(linkId: string): void { db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); } +//----------------------------------------------- +// notifications helper - -export function removeTripPhoto( - tripId: string, - userId: number, - providerRaw: unknown, - assetIdRaw: unknown, -): { success: true } | ServiceError { - const assetId = String(assetIdRaw || ''); - const provider = String(providerRaw || '').toLowerCase(); - - if (!assetId) { - return { error: 'asset_id is required', status: 400 }; - } - if (!provider) { - return { error: 'provider is required', status: 400 }; - } - - const denied = accessDeniedIfMissing(tripId, userId); - if (denied) return denied; - - db.prepare(` - DELETE FROM trip_photos - WHERE trip_id = ? - AND user_id = ? - AND asset_id = ? - AND provider = ? - `).run(tripId, userId, assetId, provider); - - return { success: true }; -} - -export function setTripPhotoSharing( - tripId: string, - userId: number, - providerRaw: unknown, - assetIdRaw: unknown, - sharedRaw: unknown, -): { success: true } | ServiceError { - const assetId = String(assetIdRaw || ''); - const provider = String(providerRaw || '').toLowerCase(); - - if (!assetId) { - return { error: 'asset_id is required', status: 400 }; - } - if (!provider) { - return { error: 'provider is required', status: 400 }; - } - - const denied = accessDeniedIfMissing(tripId, userId); - if (denied) return denied; - - db.prepare(` - UPDATE trip_photos - SET shared = ? - WHERE trip_id = ? - AND user_id = ? - AND asset_id = ? - AND provider = ? - `).run(sharedRaw ? 1 : 0, tripId, userId, assetId, provider); - - return { success: true }; -} - -export async function notifySharedTripPhotos( +async function _notifySharedTripPhotos( tripId: string, actorUserId: number, - actorName: string, added: number, -): Promise { - if (added <= 0) return; +): Promise> { + if (added <= 0) return fail('No photos shared, skipping notifications', 200); - const tripInfo = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; - await notifyTripMembers(Number(tripId), actorUserId, 'photos_shared', { - trip: tripInfo?.title || 'Untitled', - actor: actorName, - count: String(added), - }); + try { + const actorRow = db.prepare('SELECT username FROM users WHERE id = ?').get(actorUserId) as { username: string | null }; + + const tripInfo = db.prepare('SELECT title FROM trips WHERE id = ?').get(tripId) as { title: string } | undefined; + await notifyTripMembers(Number(tripId), actorUserId, 'photos_shared', { + trip: tripInfo?.title || 'Untitled', + actor: actorRow?.username || 'Unknown', + count: String(added), + }); + return success(undefined); + } catch { + return fail('Failed to send notifications', 500); + } } diff --git a/server/src/services/synologyService.ts b/server/src/services/synologyService.ts index 7a01c1c..4f66fbd 100644 --- a/server/src/services/synologyService.ts +++ b/server/src/services/synologyService.ts @@ -6,6 +6,7 @@ import { decrypt_api_key, maybe_encrypt_api_key } from './apiKeyCrypto'; import { checkSsrf } from '../utils/ssrfGuard'; import { addTripPhotos, getAlbumIdFromLink, Selection, updateSyncTimeForAlbumLink } from './memoriesService'; import { error } from 'node:console'; +import { th } from 'zod/locales'; const SYNOLOGY_API_TIMEOUT_MS = 30000; const SYNOLOGY_PROVIDER = 'synologyphotos'; @@ -403,8 +404,8 @@ export async function listSynologyAlbums(userId: number): Promise<{ albums: Arra export async function syncSynologyAlbumLink(userId: number, tripId: string, linkId: string): Promise<{ added: number; total: number }> { - const albumId = getAlbumIdFromLink(tripId, linkId, userId); - if (!albumId) { + const response = getAlbumIdFromLink(tripId, linkId, userId); + if (!response.success) { throw new SynologyServiceError(404, 'Album link not found'); } @@ -417,7 +418,7 @@ export async function syncSynologyAlbumLink(userId: number, tripId: string, link api: 'SYNO.Foto.Browse.Item', method: 'list', version: 1, - album_id: Number(albumId), + album_id: Number(response.data), offset, limit: pageSize, additional: ['thumbnail'], @@ -438,12 +439,12 @@ export async function syncSynologyAlbumLink(userId: number, tripId: string, link asset_ids: allItems.map(item => String(item.additional?.thumbnail?.cache_key || '')).filter(id => id), }; - const addResult = addTripPhotos(tripId, userId, true, [selection]); - if ('error' in addResult) throw new SynologyServiceError(addResult.status, addResult.error); - updateSyncTimeForAlbumLink(linkId); - return { added: addResult.added, total: allItems.length }; + const result = await addTripPhotos(tripId, userId, true, [selection]); + if ('error' in result) throw new SynologyServiceError(result.error.status, result.error.message); + + return { added: result.data.added, total: allItems.length }; } export async function searchSynologyPhotos(userId: number, from?: string, to?: string, offset = 0, limit = 300): Promise<{ assets: SynologyPhotoInfo[]; total: number; hasMore: boolean }> { From bca82b3f8c3de1b00b7789adbe11d7f7c6764820 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Sat, 4 Apr 2026 14:01:51 +0200 Subject: [PATCH 043/117] changing routes and hierarchy of files for memories --- .../src/components/Memories/MemoriesPanel.tsx | 30 +++---- server/src/app.ts | 6 +- server/src/routes/{ => memories}/immich.ts | 17 ++-- server/src/routes/{ => memories}/synology.ts | 10 +-- .../{memories.ts => memories/unified.ts} | 28 ++++--- .../src/services/memories/helpersService.ts | 79 ++++++++++++++++++ .../services/{ => memories}/immichService.ts | 12 +-- .../{ => memories}/synologyService.ts | 11 ++- .../unifiedService.ts} | 81 +++---------------- 9 files changed, 147 insertions(+), 127 deletions(-) rename server/src/routes/{ => memories}/immich.ts (93%) rename server/src/routes/{ => memories}/synology.ts (96%) rename server/src/routes/{memories.ts => memories/unified.ts} (74%) create mode 100644 server/src/services/memories/helpersService.ts rename server/src/services/{ => memories}/immichService.ts (97%) rename server/src/services/{ => memories}/synologyService.ts (98%) rename server/src/services/{memoriesService.ts => memories/unifiedService.ts} (75%) diff --git a/client/src/components/Memories/MemoriesPanel.tsx b/client/src/components/Memories/MemoriesPanel.tsx index d8d167d..da9873e 100644 --- a/client/src/components/Memories/MemoriesPanel.tsx +++ b/client/src/components/Memories/MemoriesPanel.tsx @@ -89,7 +89,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const loadAlbumLinks = async () => { try { - const res = await apiClient.get(`/integrations/memories/trips/${tripId}/album-links`) + const res = await apiClient.get(`/integrations/memories/unified/trips/${tripId}/album-links`) setAlbumLinks(res.data.links || []) } catch { setAlbumLinks([]) } } @@ -98,7 +98,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa if (!provider) return setAlbumsLoading(true) try { - const res = await apiClient.get(`/integrations/${provider}/albums`) + const res = await apiClient.get(`/integrations/memories/${provider}/albums`) setAlbums(res.data.albums || []) } catch { setAlbums([]) @@ -120,7 +120,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa } try { - await apiClient.post(`/integrations/memories/trips/${tripId}/album-links`, { + await apiClient.post(`/integrations/memories/unified/trips/${tripId}/album-links`, { album_id: albumId, album_name: albumName, provider: selectedProvider, @@ -128,7 +128,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa setShowAlbumPicker(false) await loadAlbumLinks() // Auto-sync after linking - const linksRes = await apiClient.get(`/integrations/memories/trips/${tripId}/album-links`) + const linksRes = await apiClient.get(`/integrations/memories/unified/trips/${tripId}/album-links`) const newLink = (linksRes.data.links || []).find((l: any) => l.album_id === albumId && l.provider === selectedProvider) if (newLink) await syncAlbum(newLink.id) } catch { toast.error(t('memories.error.linkAlbum')) } @@ -136,7 +136,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const unlinkAlbum = async (linkId: number) => { try { - await apiClient.delete(`/integrations/memories/trips/${tripId}/album-links/${linkId}`) + await apiClient.delete(`/integrations/memories/unified/trips/${tripId}/album-links/${linkId}`) loadAlbumLinks() } catch { toast.error(t('memories.error.unlinkAlbum')) } } @@ -146,7 +146,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa if (!targetProvider) return setSyncing(linkId) try { - await apiClient.post(`/integrations/${targetProvider}/trips/${tripId}/album-links/${linkId}/sync`) + await apiClient.post(`/integrations/memories/${targetProvider}/trips/${tripId}/album-links/${linkId}/sync`) await loadAlbumLinks() await loadPhotos() } catch { toast.error(t('memories.error.syncAlbum')) } @@ -175,7 +175,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const loadPhotos = async () => { try { - const photosRes = await apiClient.get(`/integrations/memories/trips/${tripId}/photos`) + const photosRes = await apiClient.get(`/integrations/memories/unified/trips/${tripId}/photos`) setTripPhotos(photosRes.data.photos || []) } catch { setTripPhotos([]) @@ -257,7 +257,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa setPickerPhotos([]) return } - const res = await apiClient.post(`/integrations/${provider.id}/search`, { + const res = await apiClient.post(`/integrations/memories/${provider.id}/search`, { from: useDate && startDate ? startDate : undefined, to: useDate && endDate ? endDate : undefined, }) @@ -296,7 +296,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa groupedByProvider.set(provider, list) } - await apiClient.post(`/integrations/memories/trips/${tripId}/photos`, { + await apiClient.post(`/integrations/memories/unified/trips/${tripId}/photos`, { selections: [...groupedByProvider.entries()].map(([provider, asset_ids]) => ({ provider, asset_ids })), shared: true, }) @@ -310,7 +310,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const removePhoto = async (photo: TripPhoto) => { try { - await apiClient.delete(`/integrations/memories/trips/${tripId}/photos`, { + await apiClient.delete(`/integrations/memories/unified/trips/${tripId}/photos`, { data: { asset_id: photo.asset_id, provider: photo.provider, @@ -324,7 +324,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const toggleSharing = async (photo: TripPhoto, shared: boolean) => { try { - await apiClient.put(`/integrations/memories/trips/${tripId}/photos/sharing`, { + await apiClient.put(`/integrations/memories/unified/trips/${tripId}/photos/sharing`, { shared, asset_id: photo.asset_id, provider: photo.provider, @@ -338,7 +338,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa // ── Helpers ─────────────────────────────────────────────────────────────── const thumbnailBaseUrl = (photo: TripPhoto) => - `/api/integrations/${photo.provider}/assets/${tripId}/${photo.asset_id}/${photo.user_id}/thumbnail` + `/api/integrations/memories/${photo.provider}/assets/${tripId}/${photo.asset_id}/${photo.user_id}/thumbnail` const makePickerKey = (provider: string, assetId: string): string => `${provider}::${assetId}` @@ -598,7 +598,7 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa outline: isSelected ? '3px solid var(--text-primary)' : 'none', outlineOffset: -3, }}> - {isSelected && (
setLightboxInfo(r.data)).catch(() => {}).finally(() => setLightboxInfoLoading(false)) }}> diff --git a/server/src/app.ts b/server/src/app.ts index 13b7668..60ddcb8 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -33,9 +33,7 @@ import backupRoutes from './routes/backup'; import oidcRoutes from './routes/oidc'; import vacayRoutes from './routes/vacay'; import atlasRoutes from './routes/atlas'; -import immichRoutes from './routes/immich'; -import synologyRoutes from './routes/synology'; -import memoriesRoutes from './routes/memories'; +import memoriesRoutes from './routes/memories/unified'; import notificationRoutes from './routes/notifications'; import shareRoutes from './routes/share'; import { mcpHandler } from './mcp'; @@ -255,8 +253,6 @@ export function createApp(): express.Application { app.use('/api/addons/vacay', vacayRoutes); app.use('/api/addons/atlas', atlasRoutes); app.use('/api/integrations/memories', memoriesRoutes); - app.use('/api/integrations/immich', immichRoutes); - app.use('/api/integrations/synologyphotos', synologyRoutes); app.use('/api/maps', mapsRoutes); app.use('/api/weather', weatherRoutes); app.use('/api/settings', settingsRoutes); diff --git a/server/src/routes/immich.ts b/server/src/routes/memories/immich.ts similarity index 93% rename from server/src/routes/immich.ts rename to server/src/routes/memories/immich.ts index 012d7ef..af9b4d0 100644 --- a/server/src/routes/immich.ts +++ b/server/src/routes/memories/immich.ts @@ -1,10 +1,10 @@ import express, { Request, Response, NextFunction } from 'express'; -import { db, canAccessTrip } from '../db/database'; -import { authenticate } from '../middleware/auth'; -import { broadcast } from '../websocket'; -import { AuthRequest } from '../types'; -import { consumeEphemeralToken } from '../services/ephemeralTokens'; -import { getClientIp } from '../services/auditLog'; +import { db, canAccessTrip } from '../../db/database'; +import { authenticate } from '../../middleware/auth'; +import { broadcast } from '../../websocket'; +import { AuthRequest } from '../../types'; +import { consumeEphemeralToken } from '../../services/ephemeralTokens'; +import { getClientIp } from '../../services/auditLog'; import { getConnectionSettings, saveImmichSettings, @@ -14,12 +14,11 @@ import { searchPhotos, proxyThumbnail, proxyOriginal, - isValidAssetId, listAlbums, syncAlbumAssets, getAssetInfo, -} from '../services/immichService'; -import { canAccessUserPhoto } from '../services/memoriesService'; +} from '../../services/memories/immichService'; +import { canAccessUserPhoto } from '../../services/memories/helpersService'; const router = express.Router(); diff --git a/server/src/routes/synology.ts b/server/src/routes/memories/synology.ts similarity index 96% rename from server/src/routes/synology.ts rename to server/src/routes/memories/synology.ts index 838a3de..cd3512d 100644 --- a/server/src/routes/synology.ts +++ b/server/src/routes/memories/synology.ts @@ -1,7 +1,7 @@ import express, { Request, Response } from 'express'; -import { authenticate } from '../middleware/auth'; -import { broadcast } from '../websocket'; -import { AuthRequest } from '../types'; +import { authenticate } from '../../middleware/auth'; +import { broadcast } from '../../websocket'; +import { AuthRequest } from '../../types'; import { getSynologySettings, updateSynologySettings, @@ -15,8 +15,8 @@ import { streamSynologyAsset, handleSynologyError, SynologyServiceError, -} from '../services/synologyService'; -import { canAccessUserPhoto } from '../services/memoriesService'; +} from '../../services/memories/synologyService'; +import { canAccessUserPhoto } from '../../services/memories/helpersService'; const router = express.Router(); diff --git a/server/src/routes/memories.ts b/server/src/routes/memories/unified.ts similarity index 74% rename from server/src/routes/memories.ts rename to server/src/routes/memories/unified.ts index e60b9e1..3e4561d 100644 --- a/server/src/routes/memories.ts +++ b/server/src/routes/memories/unified.ts @@ -1,6 +1,6 @@ import express, { Request, Response } from 'express'; -import { authenticate } from '../middleware/auth'; -import { AuthRequest } from '../types'; +import { authenticate } from '../../middleware/auth'; +import { AuthRequest } from '../../types'; import { listTripPhotos, listTripAlbumLinks, @@ -9,14 +9,19 @@ import { addTripPhotos, removeTripPhoto, setTripPhotoSharing, -} from '../services/memoriesService'; +} from '../../services/memories/unifiedService'; +import immichRouter from './immich'; +import synologyRouter from './synology'; const router = express.Router(); +router.use('/immich', immichRouter); +router.use('/synologyphotos', synologyRouter); + //------------------------------------------------ // routes for managing photos linked to trip -router.get('/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { +router.get('/unified/trips/:tripId/photos', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; const result = listTripPhotos(tripId, authReq.user.id); @@ -24,7 +29,7 @@ router.get('/trips/:tripId/photos', authenticate, (req: Request, res: Response) res.json({ photos: result.data }); }); -router.post('/trips/:tripId/photos', authenticate, async (req: Request, res: Response) => { +router.post('/unified/trips/:tripId/photos', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; const sid = req.headers['x-socket-id'] as string; @@ -42,7 +47,7 @@ router.post('/trips/:tripId/photos', authenticate, async (req: Request, res: Res res.json({ success: true, added: result.data.added }); }); -router.put('/trips/:tripId/photos/sharing', authenticate, async (req: Request, res: Response) => { +router.put('/unified/trips/:tripId/photos/sharing', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; const result = await setTripPhotoSharing( @@ -56,7 +61,7 @@ router.put('/trips/:tripId/photos/sharing', authenticate, async (req: Request, r res.json({ success: true }); }); -router.delete('/trips/:tripId/photos', authenticate, async (req: Request, res: Response) => { +router.delete('/unified/trips/:tripId/photos', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; const result = await removeTripPhoto(tripId, authReq.user.id, req.body?.provider, req.body?.asset_id); @@ -67,7 +72,7 @@ router.delete('/trips/:tripId/photos', authenticate, async (req: Request, res: R //------------------------------ // routes for managing album links -router.get('/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { +router.get('/unified/trips/:tripId/album-links', authenticate, (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; const result = listTripAlbumLinks(tripId, authReq.user.id); @@ -75,7 +80,7 @@ router.get('/trips/:tripId/album-links', authenticate, (req: Request, res: Respo res.json({ links: result.data }); }); -router.post('/trips/:tripId/album-links', authenticate, async (req: Request, res: Response) => { +router.post('/unified/trips/:tripId/album-links', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId } = req.params; const result = createTripAlbumLink(tripId, authReq.user.id, req.body?.provider, req.body?.album_id, req.body?.album_name); @@ -83,7 +88,7 @@ router.post('/trips/:tripId/album-links', authenticate, async (req: Request, res res.json({ success: true }); }); -router.delete('/trips/:tripId/album-links/:linkId', authenticate, async (req: Request, res: Response) => { +router.delete('/unified/trips/:tripId/album-links/:linkId', authenticate, async (req: Request, res: Response) => { const authReq = req as AuthRequest; const { tripId, linkId } = req.params; const result = removeAlbumLink(tripId, linkId, authReq.user.id); @@ -91,4 +96,7 @@ router.delete('/trips/:tripId/album-links/:linkId', authenticate, async (req: Re res.json({ success: true }); }); + + + export default router; diff --git a/server/src/services/memories/helpersService.ts b/server/src/services/memories/helpersService.ts new file mode 100644 index 0000000..51c899a --- /dev/null +++ b/server/src/services/memories/helpersService.ts @@ -0,0 +1,79 @@ +import { canAccessTrip, db } from "../../db/database"; + +// helpers for handling return types + +type ServiceError = { success: false; error: { message: string; status: number } }; +export type ServiceResult = { success: true; data: T } | ServiceError; + + +export function fail(error: string, status: number): ServiceError { + return { success: false, error: { message: error, status } }; +} + + +export function success(data: T): ServiceResult { + return { success: true, data: data }; +} + + +export function mapDbError(error: unknown, fallbackMessage: string): ServiceError { + if (error instanceof Error && /unique|constraint/i.test(error.message)) { + return fail('Resource already exists', 409); + } + return fail(fallbackMessage, 500); +} + + +// ---------------------------------------------- +// types used across memories services +export type Selection = { + provider: string; + asset_ids: string[]; +}; + + +//----------------------------------------------- +//access check helper + +export function canAccessUserPhoto(requestingUserId: number, ownerUserId: number, tripId: string, assetId: string, provider: string): boolean { + if (requestingUserId === ownerUserId) { + return true; + } + const sharedAsset = db.prepare(` + SELECT 1 + FROM trip_photos + WHERE user_id = ? + AND asset_id = ? + AND provider = ? + AND trip_id = ? + AND shared = 1 + LIMIT 1 + `).get(ownerUserId, assetId, provider, tripId); + + if (!sharedAsset) { + return false; + } + return !!canAccessTrip(tripId, requestingUserId); +} + + +// ---------------------------------------------- +//helpers for album link syncing + +export function getAlbumIdFromLink(tripId: string, linkId: string, userId: number): ServiceResult { + const access = canAccessTrip(tripId, userId); + if (!access) return fail('Trip not found or access denied', 404); + + try { + const row = db.prepare('SELECT album_id FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') + .get(linkId, tripId, userId) as { album_id: string } | null; + + return row ? success(row.album_id) : fail('Album link not found', 404); + } catch { + return fail('Failed to retrieve album link', 500); + } +} + +export function updateSyncTimeForAlbumLink(linkId: string): void { + db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); +} diff --git a/server/src/services/immichService.ts b/server/src/services/memories/immichService.ts similarity index 97% rename from server/src/services/immichService.ts rename to server/src/services/memories/immichService.ts index d4a353b..47a9895 100644 --- a/server/src/services/immichService.ts +++ b/server/src/services/memories/immichService.ts @@ -1,9 +1,9 @@ -import { db } from '../db/database'; -import { maybe_encrypt_api_key, decrypt_api_key } from './apiKeyCrypto'; -import { checkSsrf } from '../utils/ssrfGuard'; -import { writeAudit } from './auditLog'; -import { addTripPhotos, getAlbumIdFromLink, Selection, updateSyncTimeForAlbumLink } from './memoriesService'; -import { error } from 'node:console'; +import { db } from '../../db/database'; +import { maybe_encrypt_api_key, decrypt_api_key } from '../apiKeyCrypto'; +import { checkSsrf } from '../../utils/ssrfGuard'; +import { writeAudit } from '../auditLog'; +import { addTripPhotos} from './unifiedService'; +import { getAlbumIdFromLink, updateSyncTimeForAlbumLink, Selection } from './helpersService'; // ── Credentials ──────────────────────────────────────────────────────────── diff --git a/server/src/services/synologyService.ts b/server/src/services/memories/synologyService.ts similarity index 98% rename from server/src/services/synologyService.ts rename to server/src/services/memories/synologyService.ts index 4f66fbd..c9c8b57 100644 --- a/server/src/services/synologyService.ts +++ b/server/src/services/memories/synologyService.ts @@ -1,12 +1,11 @@ import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import { Response as ExpressResponse } from 'express'; -import { db } from '../db/database'; -import { decrypt_api_key, maybe_encrypt_api_key } from './apiKeyCrypto'; -import { checkSsrf } from '../utils/ssrfGuard'; -import { addTripPhotos, getAlbumIdFromLink, Selection, updateSyncTimeForAlbumLink } from './memoriesService'; -import { error } from 'node:console'; -import { th } from 'zod/locales'; +import { db } from '../../db/database'; +import { decrypt_api_key, maybe_encrypt_api_key } from '../apiKeyCrypto'; +import { checkSsrf } from '../../utils/ssrfGuard'; +import { addTripPhotos} from './unifiedService'; +import { getAlbumIdFromLink, updateSyncTimeForAlbumLink, Selection } from './helpersService'; const SYNOLOGY_API_TIMEOUT_MS = 30000; const SYNOLOGY_PROVIDER = 'synologyphotos'; diff --git a/server/src/services/memoriesService.ts b/server/src/services/memories/unifiedService.ts similarity index 75% rename from server/src/services/memoriesService.ts rename to server/src/services/memories/unifiedService.ts index 03ac465..35d47eb 100644 --- a/server/src/services/memoriesService.ts +++ b/server/src/services/memories/unifiedService.ts @@ -1,49 +1,15 @@ -import { db, canAccessTrip } from '../db/database'; -import { notifyTripMembers } from './notifications'; -import { broadcast } from '../websocket'; +import { db, canAccessTrip } from '../../db/database'; +import { notifyTripMembers } from '../notifications'; +import { broadcast } from '../../websocket'; +import { + ServiceResult, + fail, + success, + mapDbError, + Selection, +} from './helpersService'; -type ServiceError = { success: false; error: { message: string; status: number } }; -type ServiceResult = { success: true; data: T } | ServiceError; - -function fail(error: string, status: number): ServiceError { - return { success: false, error: { message: error, status }}; -} - -function success(data: T): ServiceResult { - return { success: true, data: data }; -} - -function mapDbError(error: unknown, fallbackMessage: string): ServiceError { - if (error instanceof Error && /unique|constraint/i.test(error.message)) { - return fail('Resource already exists', 409); - } - return fail(fallbackMessage, 500); -} - -//----------------------------------------------- -//access check helper - -export function canAccessUserPhoto(requestingUserId: number, ownerUserId: number, tripId: string, assetId: string, provider: string): boolean { - if (requestingUserId === ownerUserId) { - return true; - } - const sharedAsset = db.prepare(` - SELECT 1 - FROM trip_photos - WHERE user_id = ? - AND asset_id = ? - AND provider = ? - AND trip_id = ? - AND shared = 1 - LIMIT 1 - `).get(ownerUserId, assetId, provider, tripId); - - if (!sharedAsset) { - return false; - } - return !!canAccessTrip(tripId, requestingUserId); -} export function listTripPhotos(tripId: string, userId: number): ServiceResult { const access = canAccessTrip(tripId, userId); @@ -108,11 +74,6 @@ function _addTripPhoto(tripId: string, userId: number, provider: string, assetId return result.changes > 0; } -export type Selection = { - provider: string; - asset_ids: string[]; -}; - export async function addTripPhotos( tripId: string, userId: number, @@ -181,7 +142,6 @@ export async function setTripPhotoSharing( } } - export function removeTripPhoto( tripId: string, userId: number, @@ -262,25 +222,6 @@ export function removeAlbumLink(tripId: string, linkId: string, userId: number): } } -//helpers for album link syncing - -export function getAlbumIdFromLink(tripId: string, linkId: string, userId: number): ServiceResult { - const access = canAccessTrip(tripId, userId); - if (!access) return fail('Trip not found or access denied', 404); - - try { - const row = db.prepare('SELECT album_id FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') - .get(linkId, tripId, userId) as { album_id: string } | null; - - return row ? success(row.album_id) : fail('Album link not found', 404); - } catch { - return fail('Failed to retrieve album link', 500); - } -} - -export function updateSyncTimeForAlbumLink(linkId: string): void { - db.prepare('UPDATE trip_album_links SET last_synced_at = CURRENT_TIMESTAMP WHERE id = ?').run(linkId); -} //----------------------------------------------- // notifications helper @@ -306,5 +247,3 @@ async function _notifySharedTripPhotos( return fail('Failed to send notifications', 500); } } - - From 877e1a09ccc6ceb5369809415fe7f71ceb7ef453 Mon Sep 17 00:00:00 2001 From: Marek Maslowski Date: Sat, 4 Apr 2026 14:20:52 +0200 Subject: [PATCH 044/117] removing the need of suplementing provider links in config --- server/src/app.ts | 7 ++++--- server/src/db/migrations.ts | 19 ++++++++++--------- server/src/db/schema.ts | 1 - server/src/db/seeds.ts | 16 ++-------------- server/src/services/adminService.ts | 14 +++++++------- .../src/services/memories/helpersService.ts | 19 +++++++++++++++++++ 6 files changed, 42 insertions(+), 34 deletions(-) diff --git a/server/src/app.ts b/server/src/app.ts index 60ddcb8..c46cfe7 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -38,6 +38,7 @@ import notificationRoutes from './routes/notifications'; import shareRoutes from './routes/share'; import { mcpHandler } from './mcp'; import { Addon } from './types'; +import { getPhotoProviderConfig } from './services/memories/helpersService'; export function createApp(): express.Application { const app = express(); @@ -194,11 +195,11 @@ export function createApp(): express.Application { app.get('/api/addons', authenticate, (_req: Request, res: Response) => { const addons = db.prepare('SELECT id, name, type, icon, enabled FROM addons WHERE enabled = 1 ORDER BY sort_order').all() as Pick[]; const providers = db.prepare(` - SELECT id, name, icon, enabled, config, sort_order + SELECT id, name, icon, enabled, sort_order FROM photo_providers WHERE enabled = 1 ORDER BY sort_order, id - `).all() as Array<{ id: string; name: string; icon: string; enabled: number; config: string; sort_order: number }>; + `).all() as Array<{ id: string; name: string; icon: string; enabled: number; sort_order: number }>; const fields = db.prepare(` SELECT provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order FROM photo_provider_fields @@ -232,7 +233,7 @@ export function createApp(): express.Application { type: 'photo_provider', icon: p.icon, enabled: !!p.enabled, - config: JSON.parse(p.config || '{}'), + config: getPhotoProviderConfig(p.id), fields: (fieldsByProvider.get(p.id) || []).map(f => ({ key: f.field_key, label: f.label, diff --git a/server/src/db/migrations.ts b/server/src/db/migrations.ts index 20f160d..aee415e 100644 --- a/server/src/db/migrations.ts +++ b/server/src/db/migrations.ts @@ -643,14 +643,13 @@ function runMigrations(db: Database.Database): void { // Seed Synology Photos provider and fields in existing databases try { db.prepare(` - INSERT INTO photo_providers (id, name, description, icon, enabled, config, sort_order) - VALUES (?, ?, ?, ?, ?, ?, ?) + INSERT INTO photo_providers (id, name, description, icon, enabled, sort_order) + VALUES (?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET name = excluded.name, description = excluded.description, icon = excluded.icon, enabled = excluded.enabled, - config = excluded.config, sort_order = excluded.sort_order `).run( 'synologyphotos', @@ -658,12 +657,6 @@ function runMigrations(db: Database.Database): void { 'Synology Photos integration with separate account settings', 'Image', 0, - JSON.stringify({ - settings_get: '/integrations/synologyphotos/settings', - settings_put: '/integrations/synologyphotos/settings', - status_get: '/integrations/synologyphotos/status', - test_post: '/integrations/synologyphotos/test', - }), 1, ); } catch (err: any) { @@ -691,6 +684,14 @@ function runMigrations(db: Database.Database): void { if (!err.message?.includes('no such table')) throw err; } }, + () => { + // Remove the stored config column from photo_providers now that it is generated from provider id. + const columns = db.prepare("PRAGMA table_info('photo_providers')").all() as Array<{ name: string }>; + const names = new Set(columns.map(c => c.name)); + if (!names.has('config')) return; + + db.exec('ALTER TABLE photo_providers DROP COLUMN config'); + }, ]; if (currentVersion < migrations.length) { diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index 9e243b6..e053df6 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -232,7 +232,6 @@ function createTables(db: Database.Database): void { description TEXT, icon TEXT DEFAULT 'Image', enabled INTEGER DEFAULT 0, - config TEXT DEFAULT '{}', sort_order INTEGER DEFAULT 0 ); diff --git a/server/src/db/seeds.ts b/server/src/db/seeds.ts index ef849d9..2e233f6 100644 --- a/server/src/db/seeds.ts +++ b/server/src/db/seeds.ts @@ -101,12 +101,6 @@ function seedAddons(db: Database.Database): void { icon: 'Image', enabled: 0, sort_order: 0, - config: JSON.stringify({ - settings_get: '/integrations/immich/settings', - settings_put: '/integrations/immich/settings', - status_get: '/integrations/immich/status', - test_post: '/integrations/immich/test', - }), }, { id: 'synologyphotos', @@ -115,16 +109,10 @@ function seedAddons(db: Database.Database): void { icon: 'Image', enabled: 0, sort_order: 1, - config: JSON.stringify({ - settings_get: '/integrations/synologyphotos/settings', - settings_put: '/integrations/synologyphotos/settings', - status_get: '/integrations/synologyphotos/status', - test_post: '/integrations/synologyphotos/test', - }), }, ]; - const insertProvider = db.prepare('INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, config, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)'); - for (const p of providerRows) insertProvider.run(p.id, p.name, p.description, p.icon, p.enabled, p.config, p.sort_order); + const insertProvider = db.prepare('INSERT OR IGNORE INTO photo_providers (id, name, description, icon, enabled, sort_order) VALUES (?, ?, ?, ?, ?, ?)'); + for (const p of providerRows) insertProvider.run(p.id, p.name, p.description, p.icon, p.enabled, p.sort_order); const providerFields = [ { provider_id: 'immich', field_key: 'immich_url', label: 'Immich URL', input_type: 'url', placeholder: 'https://immich.example.com', required: 1, secret: 0, settings_key: 'immich_url', payload_key: 'immich_url', sort_order: 0 }, diff --git a/server/src/services/adminService.ts b/server/src/services/adminService.ts index f7df1f4..167eaeb 100644 --- a/server/src/services/adminService.ts +++ b/server/src/services/adminService.ts @@ -9,6 +9,7 @@ import { maybe_encrypt_api_key, decrypt_api_key } from './apiKeyCrypto'; import { getAllPermissions, savePermissions as savePerms, PERMISSION_ACTIONS } from './permissions'; import { revokeUserSessions } from '../mcp'; import { validatePassword } from './passwordPolicy'; +import { getPhotoProviderConfig } from './memories/helpersService'; // ── Helpers ──────────────────────────────────────────────────────────────── @@ -466,10 +467,10 @@ export function deleteTemplateItem(itemId: string) { export function listAddons() { const addons = db.prepare('SELECT * FROM addons ORDER BY sort_order, id').all() as Addon[]; const providers = db.prepare(` - SELECT id, name, description, icon, enabled, config, sort_order + SELECT id, name, description, icon, enabled, sort_order FROM photo_providers ORDER BY sort_order, id - `).all() as Array<{ id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number }>; + `).all() as Array<{ id: string; name: string; description?: string | null; icon: string; enabled: number; sort_order: number }>; const fields = db.prepare(` SELECT provider_id, field_key, label, input_type, placeholder, required, secret, settings_key, payload_key, sort_order FROM photo_provider_fields @@ -502,7 +503,7 @@ export function listAddons() { type: 'photo_provider', icon: p.icon, enabled: !!p.enabled, - config: JSON.parse(p.config || '{}'), + config: getPhotoProviderConfig(p.id), fields: (fieldsByProvider.get(p.id) || []).map(f => ({ key: f.field_key, label: f.label, @@ -521,7 +522,7 @@ export function listAddons() { export function updateAddon(id: string, data: { enabled?: boolean; config?: Record }) { const addon = db.prepare('SELECT * FROM addons WHERE id = ?').get(id) as Addon | undefined; - const provider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number } | undefined; + const provider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; sort_order: number } | undefined; if (!addon && !provider) return { error: 'Addon not found', status: 404 }; if (addon) { @@ -529,11 +530,10 @@ export function updateAddon(id: string, data: { enabled?: boolean; config?: Reco if (data.config !== undefined) db.prepare('UPDATE addons SET config = ? WHERE id = ?').run(JSON.stringify(data.config), id); } else { if (data.enabled !== undefined) db.prepare('UPDATE photo_providers SET enabled = ? WHERE id = ?').run(data.enabled ? 1 : 0, id); - if (data.config !== undefined) db.prepare('UPDATE photo_providers SET config = ? WHERE id = ?').run(JSON.stringify(data.config), id); } const updatedAddon = db.prepare('SELECT * FROM addons WHERE id = ?').get(id) as Addon | undefined; - const updatedProvider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; config: string; sort_order: number } | undefined; + const updatedProvider = db.prepare('SELECT * FROM photo_providers WHERE id = ?').get(id) as { id: string; name: string; description?: string | null; icon: string; enabled: number; sort_order: number } | undefined; const updated = updatedAddon ? { ...updatedAddon, enabled: !!updatedAddon.enabled, config: JSON.parse(updatedAddon.config || '{}') } : updatedProvider @@ -544,7 +544,7 @@ export function updateAddon(id: string, data: { enabled?: boolean; config?: Reco type: 'photo_provider', icon: updatedProvider.icon, enabled: !!updatedProvider.enabled, - config: JSON.parse(updatedProvider.config || '{}'), + config: getPhotoProviderConfig(updatedProvider.id), sort_order: updatedProvider.sort_order, } : null; diff --git a/server/src/services/memories/helpersService.ts b/server/src/services/memories/helpersService.ts index 51c899a..465842f 100644 --- a/server/src/services/memories/helpersService.ts +++ b/server/src/services/memories/helpersService.ts @@ -32,6 +32,25 @@ export type Selection = { }; +//for loading routes to settings page, and validating which services user has connected +type PhotoProviderConfig = { + settings_get: string; + settings_put: string; + status_get: string; + test_post: string; +}; + + +export function getPhotoProviderConfig(providerId: string): PhotoProviderConfig { + const prefix = `/integrations/memories/${providerId}`; + return { + settings_get: `${prefix}/settings`, + settings_put: `${prefix}/settings`, + status_get: `${prefix}/status`, + test_post: `${prefix}/test`, + }; +} + //----------------------------------------------- //access check helper From 3f612c4d265b50cf981910ae89a3166b50876d7c Mon Sep 17 00:00:00 2001 From: mauriceboe Date: Sat, 4 Apr 2026 14:49:16 +0200 Subject: [PATCH 045/117] fix(dayplan): improve drag-and-drop for items around transport bookings - Allow dropping places above or below transport cards (top/bottom half detection) - Fix visual re-render after transport position changes (useMemo invalidation) - Fix drop indicator showing on all days for multi-day transports (scope key to day) - Keep all places in order_index order so untimed places can be positioned between timed items --- .../src/components/Planner/DayPlanSidebar.tsx | 72 ++++++++++--------- 1 file changed, 39 insertions(+), 33 deletions(-) diff --git a/client/src/components/Planner/DayPlanSidebar.tsx b/client/src/components/Planner/DayPlanSidebar.tsx index c062584..58e8a75 100644 --- a/client/src/components/Planner/DayPlanSidebar.tsx +++ b/client/src/components/Planner/DayPlanSidebar.tsx @@ -136,6 +136,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ const [dragOverDayId, setDragOverDayId] = useState(null) const [hoveredId, setHoveredId] = useState(null) const [transportDetail, setTransportDetail] = useState(null) + const [transportPosVersion, setTransportPosVersion] = useState(0) const [timeConfirm, setTimeConfirm] = useState<{ dayId: number; fromId: number; time: string; // For drag & drop reorder @@ -340,46 +341,38 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ initTransportPositions(dayId) } - // Build base list: untimed places + notes sorted by order_index/sort_order - const timedPlaces = da.filter(a => parseTimeToMinutes(a.place?.place_time) !== null) - const freePlaces = da.filter(a => parseTimeToMinutes(a.place?.place_time) === null) - + // Build base list: ALL places (timed and untimed) + notes sorted by order_index/sort_order + // Places keep their order_index ordering — only transports are inserted based on time. const baseItems = [ - ...freePlaces.map(a => ({ type: 'place' as const, sortKey: a.order_index, data: a })), + ...da.map(a => ({ type: 'place' as const, sortKey: a.order_index, data: a })), ...dn.map(n => ({ type: 'note' as const, sortKey: n.sort_order, data: n })), ].sort((a, b) => a.sortKey - b.sortKey) - // Timed places + transports: compute sortKeys based on time, inserted among base items - // For multi-day transports, use the appropriate display time for this day - const allTimed = [ - ...timedPlaces.map(a => ({ type: 'place' as const, data: a, minutes: parseTimeToMinutes(a.place?.place_time)! })), - ...transport.map(r => ({ - type: 'transport' as const, - data: r, - minutes: parseTimeToMinutes(getDisplayTimeForDay(r, dayDate)) ?? 0, - })), - ].sort((a, b) => a.minutes - b.minutes) + // Only transports are inserted among base items based on time/position + const timedTransports = transport.map(r => ({ + type: 'transport' as const, + data: r, + minutes: parseTimeToMinutes(getDisplayTimeForDay(r, dayDate)) ?? 0, + })).sort((a, b) => a.minutes - b.minutes) - if (allTimed.length === 0) return baseItems + if (timedTransports.length === 0) return baseItems if (baseItems.length === 0) { - return allTimed.map((item, i) => ({ ...item, sortKey: i })) + return timedTransports.map((item, i) => ({ ...item, sortKey: i })) } - // Insert timed items among base items using time-to-position mapping. - // Each timed item finds the last base place whose order_index corresponds - // to a reasonable position, then gets a fractional sortKey after it. + // Insert transports among base items using persisted position or time-to-position mapping. const result = [...baseItems] - for (let ti = 0; ti < allTimed.length; ti++) { - const timed = allTimed[ti] + for (let ti = 0; ti < timedTransports.length; ti++) { + const timed = timedTransports[ti] const minutes = timed.minutes - // For transports, use persisted position if available - if (timed.type === 'transport' && timed.data.day_plan_position != null) { + // Use persisted position if available + if (timed.data.day_plan_position != null) { result.push({ type: timed.type, sortKey: timed.data.day_plan_position, data: timed.data }) continue } - // Find insertion position: after the last base item with time <= this item's time + // Find insertion position: after the last base item with time <= this transport's time let insertAfterKey = -Infinity for (const item of result) { if (item.type === 'place') { @@ -410,7 +403,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ return map // getMergedItems is redefined each render but captures assignments/dayNotes/reservations/days via closure // eslint-disable-next-line react-hooks/exhaustive-deps - }, [days, assignments, dayNotes, reservations]) + }, [days, assignments, dayNotes, reservations, transportPosVersion]) const openAddNote = (dayId, e) => { e?.stopPropagation() @@ -509,6 +502,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ const res = reservations.find(r => r.id === tu.id) if (res) res.day_plan_position = tu.day_plan_position } + setTransportPosVersion(v => v + 1) await reservationsApi.updatePositions(tripId, transportUpdates) } if (prevAssignmentIds.length) { @@ -1081,18 +1075,20 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ const { placeId, assignmentId, noteId, fromDayId } = getDragData(e) // Drop on transport card (detected via dropTargetRef for sync accuracy) if (dropTargetRef.current?.startsWith('transport-')) { - const transportId = Number(dropTargetRef.current.replace('transport-', '')) + const isAfter = dropTargetRef.current.startsWith('transport-after-') + const parts = dropTargetRef.current.replace('transport-after-', '').replace('transport-', '').split('-') + const transportId = Number(parts[0]) if (placeId) { onAssignToDay?.(parseInt(placeId), day.id) } else if (assignmentId && fromDayId !== day.id) { tripActions.moveAssignment(tripId, Number(assignmentId), fromDayId, day.id).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error')) } else if (assignmentId) { - handleMergedDrop(day.id, 'place', Number(assignmentId), 'transport', transportId) + handleMergedDrop(day.id, 'place', Number(assignmentId), 'transport', transportId, isAfter) } else if (noteId && fromDayId !== day.id) { tripActions.moveDayNote(tripId, fromDayId, day.id, Number(noteId)).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error')) } else if (noteId) { - handleMergedDrop(day.id, 'note', Number(noteId), 'transport', transportId) + handleMergedDrop(day.id, 'note', Number(noteId), 'transport', transportId, isAfter) } setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; window.__dragData = null return @@ -1133,8 +1129,9 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({
) : ( merged.map((item, idx) => { - const itemKey = item.type === 'transport' ? `transport-${item.data.id}` : (item.type === 'place' ? `place-${item.data.id}` : `note-${item.data.id}`) + const itemKey = item.type === 'transport' ? `transport-${item.data.id}-${day.id}` : (item.type === 'place' ? `place-${item.data.id}` : `note-${item.data.id}`) const showDropLine = (!!draggingId || !!dropTargetKey) && dropTargetKey === itemKey + const showDropLineAfter = item.type === 'transport' && (!!draggingId || !!dropTargetKey) && dropTargetKey === `transport-after-${item.data.id}-${day.id}` if (item.type === 'place') { const assignment = item.data @@ -1392,20 +1389,28 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ {showDropLine &&
}
setTransportDetail(res)} - onDragOver={e => { e.preventDefault(); e.stopPropagation(); setDropTargetKey(`transport-${res.id}`) }} + onDragOver={e => { + e.preventDefault(); e.stopPropagation() + const rect = e.currentTarget.getBoundingClientRect() + const inBottom = e.clientY > rect.top + rect.height / 2 + const key = inBottom ? `transport-after-${res.id}-${day.id}` : `transport-${res.id}-${day.id}` + if (dropTargetRef.current !== key) setDropTargetKey(key) + }} onDrop={e => { e.preventDefault(); e.stopPropagation() + const rect = e.currentTarget.getBoundingClientRect() + const insertAfter = e.clientY > rect.top + rect.height / 2 const { placeId, assignmentId: fromAssignmentId, noteId, fromDayId } = getDragData(e) if (placeId) { onAssignToDay?.(parseInt(placeId), day.id) } else if (fromAssignmentId && fromDayId !== day.id) { tripActions.moveAssignment(tripId, Number(fromAssignmentId), fromDayId, day.id).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error')) } else if (fromAssignmentId) { - handleMergedDrop(day.id, 'place', Number(fromAssignmentId), 'transport', res.id) + handleMergedDrop(day.id, 'place', Number(fromAssignmentId), 'transport', res.id, insertAfter) } else if (noteId && fromDayId !== day.id) { tripActions.moveDayNote(tripId, fromDayId, day.id, Number(noteId)).catch((err: unknown) => toast.error(err instanceof Error ? err.message : 'Unknown error')) } else if (noteId) { - handleMergedDrop(day.id, 'note', Number(noteId), 'transport', res.id) + handleMergedDrop(day.id, 'note', Number(noteId), 'transport', res.id, insertAfter) } setDraggingId(null); setDropTargetKey(null); dragDataRef.current = null; window.__dragData = null }} @@ -1462,6 +1467,7 @@ const DayPlanSidebar = React.memo(function DayPlanSidebar({ )}
+ {showDropLineAfter &&
} ) } From c4c3ea1e6db201460d99583aeb9730d7732e4eac Mon Sep 17 00:00:00 2001 From: jubnl Date: Sat, 4 Apr 2026 16:36:44 +0200 Subject: [PATCH 046/117] fix(immich): remove album photos on unlink When unlinking an Immich album, photos synced from that album are now deleted. A new `album_link_id` FK column on `trip_photos` tracks the source album link at sync time; `deleteAlbumLink` deletes matching photos before removing the link. Individually-added photos are unaffected. The client now refreshes the photo grid after unlinking. Adds integration tests IMMICH-020 through IMMICH-024. Closes #398 --- .../src/components/Memories/MemoriesPanel.tsx | 3 +- server/src/db/migrations.ts | 5 + server/src/services/immichService.ts | 6 +- server/tests/helpers/test-db.ts | 2 + server/tests/integration/immich.test.ts | 95 +++++++++++++++++++ 5 files changed, 108 insertions(+), 3 deletions(-) diff --git a/client/src/components/Memories/MemoriesPanel.tsx b/client/src/components/Memories/MemoriesPanel.tsx index 13a8bab..9193aa5 100644 --- a/client/src/components/Memories/MemoriesPanel.tsx +++ b/client/src/components/Memories/MemoriesPanel.tsx @@ -107,7 +107,8 @@ export default function MemoriesPanel({ tripId, startDate, endDate }: MemoriesPa const unlinkAlbum = async (linkId: number) => { try { await apiClient.delete(`/integrations/immich/trips/${tripId}/album-links/${linkId}`) - loadAlbumLinks() + await loadAlbumLinks() + await loadPhotos() } catch { toast.error(t('memories.error.unlinkAlbum')) } } diff --git a/server/src/db/migrations.ts b/server/src/db/migrations.ts index c2f1271..f468803 100644 --- a/server/src/db/migrations.ts +++ b/server/src/db/migrations.ts @@ -518,6 +518,11 @@ function runMigrations(db: Database.Database): void { CREATE INDEX IF NOT EXISTS idx_notifications_recipient_created ON notifications(recipient_id, created_at DESC); `); }, + () => { + // Track which album link each photo was synced from + try { db.exec("ALTER TABLE trip_photos ADD COLUMN album_link_id INTEGER REFERENCES trip_album_links(id) ON DELETE SET NULL DEFAULT NULL"); } catch (err: any) { if (!err.message?.includes('duplicate column name')) throw err; } + db.exec('CREATE INDEX IF NOT EXISTS idx_trip_photos_album_link ON trip_photos(album_link_id)'); + }, ]; if (currentVersion < migrations.length) { diff --git a/server/src/services/immichService.ts b/server/src/services/immichService.ts index 0429086..99fec67 100644 --- a/server/src/services/immichService.ts +++ b/server/src/services/immichService.ts @@ -387,6 +387,8 @@ export function createAlbumLink( } export function deleteAlbumLink(linkId: string, tripId: string, userId: number) { + db.prepare('DELETE FROM trip_photos WHERE album_link_id = ? AND trip_id = ? AND user_id = ?') + .run(linkId, tripId, userId); db.prepare('DELETE FROM trip_album_links WHERE id = ? AND trip_id = ? AND user_id = ?') .run(linkId, tripId, userId); } @@ -413,11 +415,11 @@ export async function syncAlbumAssets( const assets = (albumData.assets || []).filter((a: any) => a.type === 'IMAGE'); const insert = db.prepare( - 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, immich_asset_id, shared) VALUES (?, ?, ?, 1)' + 'INSERT OR IGNORE INTO trip_photos (trip_id, user_id, immich_asset_id, shared, album_link_id) VALUES (?, ?, ?, 1, ?)' ); let added = 0; for (const asset of assets) { - const r = insert.run(tripId, userId, asset.id); + const r = insert.run(tripId, userId, asset.id, linkId); if (r.changes > 0) added++; } diff --git a/server/tests/helpers/test-db.ts b/server/tests/helpers/test-db.ts index f038fce..bae53a8 100644 --- a/server/tests/helpers/test-db.ts +++ b/server/tests/helpers/test-db.ts @@ -36,6 +36,8 @@ const RESET_TABLES = [ 'packing_items', 'budget_item_members', 'budget_items', + 'trip_photos', + 'trip_album_links', 'trip_files', 'share_tokens', 'photos', diff --git a/server/tests/integration/immich.test.ts b/server/tests/integration/immich.test.ts index 12f8644..21e88d2 100644 --- a/server/tests/integration/immich.test.ts +++ b/server/tests/integration/immich.test.ts @@ -145,3 +145,98 @@ describe('Immich authentication', () => { expect(res.status).toBe(401); }); }); + +describe('Immich album links', () => { + it('IMMICH-020 — POST album-links creates a link', async () => { + const { user } = createUser(testDb); + const trip = testDb.prepare('INSERT INTO trips (user_id, title) VALUES (?, ?) RETURNING *').get(user.id, 'Test Trip') as any; + + const res = await request(app) + .post(`/api/integrations/immich/trips/${trip.id}/album-links`) + .set('Cookie', authCookie(user.id)) + .send({ album_id: 'album-uuid-123', album_name: 'Vacation 2024' }); + + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + + const link = testDb.prepare('SELECT * FROM trip_album_links WHERE trip_id = ? AND user_id = ?').get(trip.id, user.id) as any; + expect(link).toBeDefined(); + expect(link.immich_album_id).toBe('album-uuid-123'); + expect(link.album_name).toBe('Vacation 2024'); + }); + + it('IMMICH-021 — GET album-links returns linked albums', async () => { + const { user } = createUser(testDb); + const trip = testDb.prepare('INSERT INTO trips (user_id, title) VALUES (?, ?) RETURNING *').get(user.id, 'Test Trip') as any; + testDb.prepare('INSERT INTO trip_album_links (trip_id, user_id, immich_album_id, album_name) VALUES (?, ?, ?, ?)').run(trip.id, user.id, 'album-abc', 'My Album'); + + const res = await request(app) + .get(`/api/integrations/immich/trips/${trip.id}/album-links`) + .set('Cookie', authCookie(user.id)); + + expect(res.status).toBe(200); + expect(res.body.links).toBeDefined(); + expect(res.body.links.length).toBe(1); + expect(res.body.links[0].immich_album_id).toBe('album-abc'); + }); + + it('IMMICH-022 — DELETE album-links removes associated photos but not individually-added ones', async () => { + const { user } = createUser(testDb); + const trip = testDb.prepare('INSERT INTO trips (user_id, title) VALUES (?, ?) RETURNING *').get(user.id, 'Test Trip') as any; + + // Create album link + const linkResult = testDb.prepare('INSERT INTO trip_album_links (trip_id, user_id, immich_album_id, album_name) VALUES (?, ?, ?, ?) RETURNING *') + .get(trip.id, user.id, 'album-xyz', 'Album XYZ') as any; + + // Insert photos synced from the album + testDb.prepare('INSERT INTO trip_photos (trip_id, user_id, immich_asset_id, shared, album_link_id) VALUES (?, ?, ?, 1, ?)').run(trip.id, user.id, 'asset-001', linkResult.id); + testDb.prepare('INSERT INTO trip_photos (trip_id, user_id, immich_asset_id, shared, album_link_id) VALUES (?, ?, ?, 1, ?)').run(trip.id, user.id, 'asset-002', linkResult.id); + + // Insert an individually-added photo (no album_link_id) + testDb.prepare('INSERT INTO trip_photos (trip_id, user_id, immich_asset_id, shared) VALUES (?, ?, ?, 1)').run(trip.id, user.id, 'asset-manual'); + + const res = await request(app) + .delete(`/api/integrations/immich/trips/${trip.id}/album-links/${linkResult.id}`) + .set('Cookie', authCookie(user.id)); + + expect(res.status).toBe(200); + expect(res.body.success).toBe(true); + + // Album-linked photos should be gone + const remainingPhotos = testDb.prepare('SELECT * FROM trip_photos WHERE trip_id = ?').all(trip.id) as any[]; + expect(remainingPhotos.length).toBe(1); + expect(remainingPhotos[0].immich_asset_id).toBe('asset-manual'); + + // Album link itself should be gone + const link = testDb.prepare('SELECT * FROM trip_album_links WHERE id = ?').get(linkResult.id); + expect(link).toBeUndefined(); + }); + + it('IMMICH-023 — DELETE album-link by non-owner is a no-op', async () => { + const { user: owner } = createUser(testDb); + const { user: other } = createUser(testDb); + const trip = testDb.prepare('INSERT INTO trips (user_id, title) VALUES (?, ?) RETURNING *').get(owner.id, 'Test Trip') as any; + + const linkResult = testDb.prepare('INSERT INTO trip_album_links (trip_id, user_id, immich_album_id, album_name) VALUES (?, ?, ?, ?) RETURNING *') + .get(trip.id, owner.id, 'album-secret', 'Secret Album') as any; + testDb.prepare('INSERT INTO trip_photos (trip_id, user_id, immich_asset_id, shared, album_link_id) VALUES (?, ?, ?, 1, ?)').run(trip.id, owner.id, 'asset-owned', linkResult.id); + + // Other user tries to delete owner's album link + const res = await request(app) + .delete(`/api/integrations/immich/trips/${trip.id}/album-links/${linkResult.id}`) + .set('Cookie', authCookie(other.id)); + + expect(res.status).toBe(200); // endpoint returns 200 even when no row matched + + // Link and photos should still exist + const link = testDb.prepare('SELECT * FROM trip_album_links WHERE id = ?').get(linkResult.id); + expect(link).toBeDefined(); + const photo = testDb.prepare('SELECT * FROM trip_photos WHERE immich_asset_id = ?').get('asset-owned'); + expect(photo).toBeDefined(); + }); + + it('IMMICH-024 — DELETE album-link without auth returns 401', async () => { + const res = await request(app).delete('/api/integrations/immich/trips/1/album-links/1'); + expect(res.status).toBe(401); + }); +}); From 0b36427c09678e656d8761cc92d369f40136a90f Mon Sep 17 00:00:00 2001 From: mauriceboe Date: Sat, 4 Apr 2026 16:58:24 +0200 Subject: [PATCH 047/117] feat(todo): add To-Do list feature with 3-column layout - New todo_items DB table with priority, due date, description, user assignment - Full CRUD API with WebSocket real-time sync - 3-column UI: sidebar filters (All, My Tasks, Overdue, Done, by Priority), task list with inline badges, and detail/create pane - Apple-inspired design with custom dropdowns, date picker, priority system (P1-P3) - Mobile responsive: icon-only sidebar, bottom-sheet modals for detail/create - Lists tab with sub-tabs (Packing List + To-Do), persisted selection - Addon renamed from "Packing List" to "Lists" - i18n keys for all 13 languages - UI polish: notification colors use system theme, mobile navbar cleanup, settings page responsive buttons --- client/src/api/client.ts | 10 + .../Layout/InAppNotificationBell.tsx | 6 +- client/src/components/Layout/Navbar.tsx | 11 +- .../Notifications/InAppNotificationItem.tsx | 8 +- client/src/components/Todo/TodoListPanel.tsx | 778 ++++++++++++++++++ client/src/i18n/translations/ar.ts | 40 +- client/src/i18n/translations/br.ts | 40 +- client/src/i18n/translations/cs.ts | 40 +- client/src/i18n/translations/de.ts | 40 +- client/src/i18n/translations/en.ts | 40 +- client/src/i18n/translations/es.ts | 40 +- client/src/i18n/translations/fr.ts | 40 +- client/src/i18n/translations/hu.ts | 40 +- client/src/i18n/translations/it.ts | 40 +- client/src/i18n/translations/nl.ts | 40 +- client/src/i18n/translations/pl.ts | 40 +- client/src/i18n/translations/ru.ts | 40 +- client/src/i18n/translations/zh.ts | 40 +- client/src/pages/InAppNotificationsPage.tsx | 16 +- client/src/pages/SettingsPage.tsx | 12 +- client/src/pages/TripPlannerPage.tsx | 45 +- client/src/store/slices/remoteEventHandler.ts | 15 +- client/src/store/slices/todoSlice.ts | 67 ++ client/src/store/tripStore.ts | 14 +- client/src/types.ts | 13 + server/package-lock.json | 39 - server/src/app.ts | 2 + server/src/db/migrations.ts | 27 + server/src/db/seeds.ts | 2 +- server/src/routes/todo.ts | 127 +++ server/src/services/todoService.ts | 122 +++ 31 files changed, 1732 insertions(+), 102 deletions(-) create mode 100644 client/src/components/Todo/TodoListPanel.tsx create mode 100644 client/src/store/slices/todoSlice.ts create mode 100644 server/src/routes/todo.ts create mode 100644 server/src/services/todoService.ts diff --git a/client/src/api/client.ts b/client/src/api/client.ts index 81a28b6..179021c 100644 --- a/client/src/api/client.ts +++ b/client/src/api/client.ts @@ -136,6 +136,16 @@ export const packingApi = { deleteBag: (tripId: number | string, bagId: number) => apiClient.delete(`/trips/${tripId}/packing/bags/${bagId}`).then(r => r.data), } +export const todoApi = { + list: (tripId: number | string) => apiClient.get(`/trips/${tripId}/todo`).then(r => r.data), + create: (tripId: number | string, data: Record) => apiClient.post(`/trips/${tripId}/todo`, data).then(r => r.data), + update: (tripId: number | string, id: number, data: Record) => apiClient.put(`/trips/${tripId}/todo/${id}`, data).then(r => r.data), + delete: (tripId: number | string, id: number) => apiClient.delete(`/trips/${tripId}/todo/${id}`).then(r => r.data), + reorder: (tripId: number | string, orderedIds: number[]) => apiClient.put(`/trips/${tripId}/todo/reorder`, { orderedIds }).then(r => r.data), + getCategoryAssignees: (tripId: number | string) => apiClient.get(`/trips/${tripId}/todo/category-assignees`).then(r => r.data), + setCategoryAssignees: (tripId: number | string, categoryName: string, userIds: number[]) => apiClient.put(`/trips/${tripId}/todo/category-assignees/${encodeURIComponent(categoryName)}`, { user_ids: userIds }).then(r => r.data), +} + export const tagsApi = { list: () => apiClient.get('/tags').then(r => r.data), create: (data: Record) => apiClient.post('/tags', data).then(r => r.data), diff --git a/client/src/components/Layout/InAppNotificationBell.tsx b/client/src/components/Layout/InAppNotificationBell.tsx index fcf14cb..0b22038 100644 --- a/client/src/components/Layout/InAppNotificationBell.tsx +++ b/client/src/components/Layout/InAppNotificationBell.tsx @@ -96,7 +96,7 @@ export default function InAppNotificationBell(): React.ReactElement { {t('notifications.title')} {unreadCount > 0 && ( + style={{ background: 'var(--text-primary)', color: 'var(--bg-primary)' }}> {unreadCount} )} @@ -133,7 +133,7 @@ export default function InAppNotificationBell(): React.ReactElement {
{isLoading && notifications.length === 0 ? (
-
+
) : notifications.length === 0 ? (
@@ -154,7 +154,7 @@ export default function InAppNotificationBell(): React.ReactElement { className="w-full py-2.5 text-xs font-medium transition-colors flex-shrink-0" style={{ borderTop: '1px solid var(--border-secondary)', - color: '#6366f1', + color: 'var(--text-primary)', background: 'transparent', }} onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-hover)'} diff --git a/client/src/components/Layout/Navbar.tsx b/client/src/components/Layout/Navbar.tsx index 1d92876..e4e1dc9 100644 --- a/client/src/components/Layout/Navbar.tsx +++ b/client/src/components/Layout/Navbar.tsx @@ -133,7 +133,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onShare }: {tripTitle && ( <> / - + {tripTitle} @@ -155,17 +155,18 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onShare }: )} - {/* Dark mode toggle (light ↔ dark, overrides auto) */} + {/* Dark mode toggle (light ↔ dark, overrides auto) — hidden on mobile */} - {/* Notification bell */} - {user && } + {/* Notification bell — only in trip view on mobile, everywhere on desktop */} + {user && tripId && } + {user && !tripId && } {/* User menu */} {user && ( diff --git a/client/src/components/Notifications/InAppNotificationItem.tsx b/client/src/components/Notifications/InAppNotificationItem.tsx index a791fe7..f0ef4fa 100644 --- a/client/src/components/Notifications/InAppNotificationItem.tsx +++ b/client/src/components/Notifications/InAppNotificationItem.tsx @@ -59,10 +59,6 @@ export default function InAppNotificationItem({ notification, onClose }: Notific borderBottom: '1px solid var(--border-secondary)', }} > - {/* Unread dot */} - {!notification.is_read && ( -
- )}
{/* Sender avatar */} @@ -102,7 +98,7 @@ export default function InAppNotificationItem({ notification, onClose }: Notific title={t('notifications.markRead')} className="p-1 rounded transition-colors" style={{ color: 'var(--text-faint)' }} - onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-hover)'; e.currentTarget.style.color = '#6366f1' }} + onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-hover)'; e.currentTarget.style.color = 'var(--text-primary)' }} onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--text-faint)' }} > @@ -134,7 +130,7 @@ export default function InAppNotificationItem({ notification, onClose }: Notific className="flex items-center gap-1 px-2.5 py-1 rounded-lg text-xs font-medium transition-colors" style={{ background: notification.response === 'positive' - ? '#6366f1' + ? 'var(--text-primary)' : notification.response === 'negative' ? (dark ? '#27272a' : '#f1f5f9') : (dark ? '#27272a' : '#f1f5f9'), diff --git a/client/src/components/Todo/TodoListPanel.tsx b/client/src/components/Todo/TodoListPanel.tsx new file mode 100644 index 0000000..10c2d39 --- /dev/null +++ b/client/src/components/Todo/TodoListPanel.tsx @@ -0,0 +1,778 @@ +import { useState, useMemo, useEffect } from 'react' +import { useTripStore } from '../../store/tripStore' +import { useCanDo } from '../../store/permissionsStore' +import { useToast } from '../shared/Toast' +import { useTranslation } from '../../i18n' +import { tripsApi } from '../../api/client' +import apiClient from '../../api/client' +import CustomSelect from '../shared/CustomSelect' +import { CustomDatePicker } from '../shared/CustomDateTimePicker' +import { formatDate as fmtDate } from '../../utils/formatters' +import { + CheckSquare, Square, Plus, ChevronRight, Flag, + X, Check, Calendar, User, FolderPlus, AlertCircle, ListChecks, Inbox, CheckCheck, Trash2, +} from 'lucide-react' +import type { TodoItem } from '../../types' + +const KAT_COLORS = [ + '#3b82f6', '#a855f7', '#ec4899', '#22c55e', '#f97316', + '#06b6d4', '#ef4444', '#eab308', '#8b5cf6', '#14b8a6', +] + +const PRIO_CONFIG: Record = { + 1: { label: 'P1', color: '#ef4444' }, + 2: { label: 'P2', color: '#f59e0b' }, + 3: { label: 'P3', color: '#3b82f6' }, +} + +function katColor(kat: string, allCategories: string[]) { + const idx = allCategories.indexOf(kat) + if (idx >= 0) return KAT_COLORS[idx % KAT_COLORS.length] + let h = 0 + for (let i = 0; i < kat.length; i++) h = ((h << 5) - h + kat.charCodeAt(i)) | 0 + return KAT_COLORS[Math.abs(h) % KAT_COLORS.length] +} + +type FilterType = 'all' | 'my' | 'overdue' | 'done' | string + +interface Member { id: number; username: string; avatar: string | null } + +export default function TodoListPanel({ tripId, items }: { tripId: number; items: TodoItem[] }) { + const { addTodoItem, updateTodoItem, deleteTodoItem, toggleTodoItem } = useTripStore() + const canEdit = useCanDo('packing_edit') + const toast = useToast() + const { t, locale } = useTranslation() + const formatDate = (d: string) => fmtDate(d, locale) || d + + const [isMobile, setIsMobile] = useState(() => window.innerWidth < 768) + useEffect(() => { + const mq = window.matchMedia('(max-width: 767px)') + const handler = (e: MediaQueryListEvent) => setIsMobile(e.matches) + mq.addEventListener('change', handler) + return () => mq.removeEventListener('change', handler) + }, []) + + const [filter, setFilter] = useState('all') + const [selectedId, setSelectedId] = useState(null) + const [isAddingNew, setIsAddingNew] = useState(false) + const [sortByPrio, setSortByPrio] = useState(false) + const [addingCategory, setAddingCategory] = useState(false) + const [newCategoryName, setNewCategoryName] = useState('') + const [members, setMembers] = useState([]) + const [currentUserId, setCurrentUserId] = useState(null) + + useEffect(() => { + apiClient.get(`/trips/${tripId}/members`).then(r => { + const owner = r.data?.owner + const mems = r.data?.members || [] + const all = owner ? [owner, ...mems] : mems + setMembers(all) + setCurrentUserId(r.data?.current_user_id || null) + }).catch(() => {}) + }, [tripId]) + + const categories = useMemo(() => { + const cats = new Set() + items.forEach(i => { if (i.category) cats.add(i.category) }) + return Array.from(cats).sort() + }, [items]) + + const today = new Date().toISOString().split('T')[0] + + const filtered = useMemo(() => { + let result: TodoItem[] + if (filter === 'all') result = items.filter(i => !i.checked) + else if (filter === 'done') result = items.filter(i => !!i.checked) + else if (filter === 'my') result = items.filter(i => !i.checked && i.assigned_user_id === currentUserId) + else if (filter === 'overdue') result = items.filter(i => !i.checked && i.due_date && i.due_date < today) + else result = items.filter(i => i.category === filter) + if (sortByPrio) result = [...result].sort((a, b) => { + const ap = a.priority || 99 + const bp = b.priority || 99 + return ap - bp + }) + return result + }, [items, filter, currentUserId, today, sortByPrio]) + + const selectedItem = items.find(i => i.id === selectedId) || null + const totalCount = items.length + const doneCount = items.filter(i => !!i.checked).length + const overdueCount = items.filter(i => !i.checked && i.due_date && i.due_date < today).length + const myCount = currentUserId ? items.filter(i => !i.checked && i.assigned_user_id === currentUserId).length : 0 + + const addCategory = () => { + const name = newCategoryName.trim() + if (!name || categories.includes(name)) { setAddingCategory(false); setNewCategoryName(''); return } + addTodoItem(tripId, { name: t('todo.newItem'), category: name } as any) + .then(() => { setAddingCategory(false); setNewCategoryName(''); setFilter(name) }) + .catch(err => toast.error(err instanceof Error ? err.message : 'Error')) + } + + // Get category count (non-done items) + const catCount = (cat: string) => items.filter(i => i.category === cat && !i.checked).length + + // Sidebar filter item + const SidebarItem = ({ id, icon: Icon, label, count, color }: { id: string; icon: any; label: string; count: number; color?: string }) => ( + + ) + + // Filter title + const filterTitle = (() => { + if (filter === 'all') return t('todo.filter.all') + if (filter === 'done') return t('todo.filter.done') + if (filter === 'my') return t('todo.filter.my') + if (filter === 'overdue') return t('todo.filter.overdue') + return filter + })() + + return ( +
+ + {/* ── Left Sidebar ── */} +
+ {/* Progress Card */} + {!isMobile &&
+
+ + {totalCount > 0 ? Math.round((doneCount / totalCount) * 100) : 0}% + +
+
+
0 ? `${Math.round((doneCount / totalCount) * 100)}%` : '0%', background: '#22c55e', borderRadius: 2, transition: 'width 0.3s' }} /> +
+
+ {doneCount} / {totalCount} {t('todo.completed')} +
+
} + + {/* Smart filters */} + {!isMobile &&
+ {t('todo.sidebar.tasks')} +
} + !i.checked).length} /> + + + + + {/* Sort by priority */} + + + {/* Categories */} + {!isMobile &&
+ {t('todo.sidebar.categories')} +
} + {isMobile &&
} + {categories.map(cat => ( + + ))} + + {canEdit && ( + addingCategory && !isMobile ? ( +
+ setNewCategoryName(e.target.value)} + onKeyDown={e => { if (e.key === 'Enter') addCategory(); if (e.key === 'Escape') { setAddingCategory(false); setNewCategoryName('') } }} + placeholder={t('todo.newCategory')} + style={{ flex: 1, fontSize: 12, padding: '4px 6px', border: '1px solid var(--border-primary)', borderRadius: 5, background: 'var(--bg-hover)', color: 'var(--text-primary)', fontFamily: 'inherit', minWidth: 0 }} /> + +
+ ) : ( + + ) + )} +
+ + {/* ── Middle: Task List ── */} +
+ {/* Header */} +
+
+

+ {filterTitle} +

+ + {filtered.length} + +
+
+ + {/* Add task */} + {canEdit && ( +
+ +
+ )} + + {/* Task list */} +
+ {filtered.length === 0 ? null : ( + filtered.map(item => { + const done = !!item.checked + const assignedUser = members.find(m => m.id === item.assigned_user_id) + const isOverdue = item.due_date && !done && item.due_date < today + const isSelected = selectedId === item.id + const catColor = item.category ? katColor(item.category, categories) : null + + return ( +
{ setSelectedId(isSelected ? null : item.id); setIsAddingNew(false) }} + style={{ + display: 'flex', alignItems: 'center', gap: 10, padding: '10px 20px', + borderBottom: '1px solid var(--border-faint)', cursor: 'pointer', + background: isSelected ? 'var(--bg-hover)' : 'transparent', + transition: 'background 0.1s', + }} + onMouseEnter={e => { if (!isSelected) e.currentTarget.style.background = 'rgba(0,0,0,0.02)' }} + onMouseLeave={e => { if (!isSelected) e.currentTarget.style.background = 'transparent' }}> + + {/* Checkbox */} + + + {/* Content */} +
+
+ {item.name} +
+ {/* Description preview */} + {item.description && ( +
+ {item.description} +
+ )} + {/* Inline badges */} + {(item.priority || item.due_date || catColor || assignedUser) && ( +
+ {item.priority > 0 && PRIO_CONFIG[item.priority] && ( + + {PRIO_CONFIG[item.priority].label} + + )} + {item.due_date && ( + + {formatDate(item.due_date)} + + )} + {catColor && ( + + + {item.category} + + )} + {assignedUser && ( + + {assignedUser.avatar ? ( + + ) : ( + + {assignedUser.username.charAt(0).toUpperCase()} + + )} + {assignedUser.username} + + )} +
+ )} +
+ + {/* Chevron */} + +
+ ) + }) + )} +
+
+ + {/* ── Right: Detail Pane ── */} + {selectedItem && !isAddingNew && !isMobile && ( + setSelectedId(null)} + /> + )} + {selectedItem && !isAddingNew && isMobile && ( +
{ if (e.target === e.currentTarget) setSelectedId(null) }} + style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(0,0,0,0.4)', display: 'flex', justifyContent: 'center', alignItems: 'flex-end' }}> +
{ if (el) { const child = el.firstElementChild as HTMLElement; if (child) { child.style.width = '100%'; child.style.borderLeft = 'none'; child.style.borderRadius = '16px 16px 0 0' } } }}> + setSelectedId(null)} + /> +
+
+ )} + {isAddingNew && !selectedItem && !isMobile && ( + { setIsAddingNew(false); setSelectedId(id) }} + onClose={() => setIsAddingNew(false)} + /> + )} + {isAddingNew && !selectedItem && isMobile && ( +
{ if (e.target === e.currentTarget) setIsAddingNew(false) }} + style={{ position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(0,0,0,0.4)', display: 'flex', justifyContent: 'center', alignItems: 'flex-end' }}> +
{ if (el) { const child = el.firstElementChild as HTMLElement; if (child) { child.style.width = '100%'; child.style.borderLeft = 'none'; child.style.borderRadius = '16px 16px 0 0' } } }}> + { setIsAddingNew(false); setSelectedId(id) }} + onClose={() => setIsAddingNew(false)} + /> +
+
+ )} +
+ ) +} + +// ── Detail Pane (right side) ────────────────────────────────────────────── + +function DetailPane({ item, tripId, categories, members, onClose }: { + item: TodoItem; tripId: number; categories: string[]; members: Member[]; + onClose: () => void; +}) { + const { updateTodoItem, deleteTodoItem } = useTripStore() + const canEdit = useCanDo('packing_edit') + const toast = useToast() + const { t } = useTranslation() + + const [name, setName] = useState(item.name) + const [desc, setDesc] = useState(item.description || '') + const [dueDate, setDueDate] = useState(item.due_date || '') + const [category, setCategory] = useState(item.category || '') + const [assignedUserId, setAssignedUserId] = useState(item.assigned_user_id) + const [priority, setPriority] = useState(item.priority || 0) + const [saving, setSaving] = useState(false) + + // Sync when selected item changes + useEffect(() => { + setName(item.name) + setDesc(item.description || '') + setDueDate(item.due_date || '') + setCategory(item.category || '') + setAssignedUserId(item.assigned_user_id) + setPriority(item.priority || 0) + }, [item.id, item.name, item.description, item.due_date, item.category, item.assigned_user_id, item.priority]) + + const hasChanges = name !== item.name || desc !== (item.description || '') || + dueDate !== (item.due_date || '') || category !== (item.category || '') || + assignedUserId !== item.assigned_user_id || priority !== (item.priority || 0) + + const save = async () => { + if (!name.trim() || !hasChanges) return + setSaving(true) + try { + await updateTodoItem(tripId, item.id, { + name: name.trim(), description: desc || null, + due_date: dueDate || null, category: category || null, + assigned_user_id: assignedUserId, priority, + } as any) + } catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Error') } + setSaving(false) + } + + const handleDelete = async () => { + try { + await deleteTodoItem(tripId, item.id) + onClose() + } catch (err: unknown) { toast.error(err instanceof Error ? err.message : 'Error') } + } + + const labelStyle: React.CSSProperties = { fontSize: 12, fontWeight: 500, color: 'var(--text-secondary)', marginBottom: 4, display: 'block' } + const inputStyle: React.CSSProperties = { + width: '100%', fontSize: 13, padding: '8px 10px', border: '1px solid var(--border-primary)', + borderRadius: 8, background: 'var(--bg-primary)', color: 'var(--text-primary)', fontFamily: 'inherit', + } + + return ( +
+ {/* Header */} +
+ {t('todo.detail.title')} + +
+ + {/* Form */} +
+ {/* Name */} +
+ setName(e.target.value)} disabled={!canEdit} + style={{ ...inputStyle, fontSize: 15, fontWeight: 600, border: 'none', padding: '4px 0', background: 'transparent' }} + placeholder={t('todo.namePlaceholder')} /> +
+ + {/* Description */} +
+ +