From 01499e7c4ee33ef65e8fbd21c7cbe45e6187e3b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Gil=20P=C3=A9rez?= Date: Mon, 20 Apr 2026 22:36:10 +0200 Subject: [PATCH 1/6] feat(potential-albums): add Trips view that groups consecutive away days MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #267 (proposal accepted in spirit; happy to iterate on review). Today the Potential Albums page groups orphan assets by single day, which is great for one-off events but tedious for trips: a 7-day Lisbon holiday shows up as 7 separate rows that the user has to merge by hand. This adds a sibling view that detects multi-day stretches of photos taken away from the user's "home" location and surfaces each as one row, with a sensible suggested name like `20180401 - Lisboa`. What's in this PR: Backend - `src/helpers/trips.helper.ts` — pure TS clustering helper (haversine distance, home detection by mode-city + GPS centroid, linear-scan trip extraction with configurable gap tolerance and min-trip-days). Easy to unit-test. - `src/pages/api/albums/potential-trips.ts` — per-day aggregation in PG (count + lat/lon centroid + MODE() city/country) → call helper → return `{ home, trips[] }`. - `src/pages/api/albums/potential-trip-assets.ts` — orphan assets in a date range, with the same shape the existing single-day endpoint returns. Date format validated to keep the literal-interpolated SQL safe. Frontend - `src/components/albums/potential-albums/PotentialTrips.tsx` — list rows, click a trip to load its assets in the existing right panel. - `src/components/albums/AlbumSelectorDialog.tsx` — accepts a new `defaultName` prop and pre-fills the "Create New" tab from `config.suggestedAlbumName`. User can still edit. - `src/pages/albums/potential-albums.tsx` — Days/Trips Tabs at the top of the left panel. Trips tab passes `{startDate, endDate, suggestedAlbumName}` into the shared selection context; the existing `PotentialAlbumsAssets` component now fetches a date range when `endDate` is set. - `src/contexts/PhotoSelectionContext.tsx` — adds `endDate` and `suggestedAlbumName` to the shared config. Defaults match the issue: - home radius 50 km - min trip days 2 - gap tolerance 2 (transit days, days with no photos) - name format `YYYYMMDD - {city}` (or `YYYYMMDD - Trip` if no city resolved) Libraries with no GPS at all fall through to the existing Days view — no regression. Open for the maintainer: - Whether to also expose the three thresholds in Settings (left out here to keep the PR small; trivial follow-up). - Whether the trips endpoint should cache its result per-user (some libraries are large). --- src/components/albums/AlbumSelectorDialog.tsx | 18 +- .../PotentialAlbumsAssets.tsx | 16 +- .../potential-albums/PotentialTrips.tsx | 128 +++++++++++ src/config/routes.ts | 2 + src/contexts/PhotoSelectionContext.tsx | 3 + src/handlers/api/album.handler.ts | 32 ++- src/helpers/trips.helper.ts | 199 ++++++++++++++++++ src/pages/albums/potential-albums.tsx | 37 +++- src/pages/api/albums/potential-trip-assets.ts | 71 +++++++ src/pages/api/albums/potential-trips.ts | 80 +++++++ 10 files changed, 574 insertions(+), 12 deletions(-) create mode 100644 src/components/albums/potential-albums/PotentialTrips.tsx create mode 100644 src/helpers/trips.helper.ts create mode 100644 src/pages/api/albums/potential-trip-assets.ts create mode 100644 src/pages/api/albums/potential-trips.ts diff --git a/src/components/albums/AlbumSelectorDialog.tsx b/src/components/albums/AlbumSelectorDialog.tsx index 2f8b7b3..27309d6 100644 --- a/src/components/albums/AlbumSelectorDialog.tsx +++ b/src/components/albums/AlbumSelectorDialog.tsx @@ -20,18 +20,30 @@ interface IProps { onSelected: (album: IAlbum) => Promise; onCreated?: (album: IAlbum) => Promise; onSubmit?: (data: IAlbumCreate) => Promise; + /** + * Pre-filled album name suggestion for the "Create New" tab. Useful when + * the caller already has a sensible default (e.g. the trip suggested name + * "20180401 - Lisboa"). The user can still edit it. + */ + defaultName?: string; } -export default function AlbumSelectorDialog({ onSelected, onCreated, onSubmit }: IProps) { +export default function AlbumSelectorDialog({ onSelected, onCreated, onSubmit, defaultName }: IProps) { const [open, setOpen] = useState(false); const [albums, setAlbums] = useState([]); const [loading, setLoading] = useState(false); const [errorMessage, setErrorMessage] = useState(null); const [search, setSearch] = useState(""); - const { selectedIds, assets } = usePhotoSelectionContext(); + const { selectedIds, assets, config } = usePhotoSelectionContext(); const [formData, setFormData] = useState({ - albumName: "", + albumName: defaultName ?? config.suggestedAlbumName ?? "", }); + // Sync the pre-fill if it changes after mount (e.g., user picks another trip) + useEffect(() => { + const next = defaultName ?? config.suggestedAlbumName ?? ""; + setFormData((prev) => (prev.albumName ? prev : { albumName: next })); + }, [defaultName, config.suggestedAlbumName]); + const fetchData = () => { setLoading(true); return listAlbums() diff --git a/src/components/albums/potential-albums/PotentialAlbumsAssets.tsx b/src/components/albums/potential-albums/PotentialAlbumsAssets.tsx index d0c8159..82e93c4 100644 --- a/src/components/albums/potential-albums/PotentialAlbumsAssets.tsx +++ b/src/components/albums/potential-albums/PotentialAlbumsAssets.tsx @@ -1,5 +1,8 @@ import { usePhotoSelectionContext } from "@/contexts/PhotoSelectionContext"; -import { listPotentialAlbumsAssets } from "@/handlers/api/album.handler"; +import { + listPotentialAlbumsAssets, + listPotentialTripAssets, +} from "@/handlers/api/album.handler"; import type { IAsset } from "@/types/asset"; import React, { useEffect, useMemo, useState } from "react"; import { CalendarArrowUp, Hourglass } from "lucide-react"; @@ -14,7 +17,7 @@ export default function PotentialAlbumsAssets() { updateContext, config } = usePhotoSelectionContext(); - const { startDate } = config; + const { startDate, endDate } = config; const [loading, setLoading] = useState(false); const [errorMessage, setErrorMessage] = useState(null); @@ -26,7 +29,11 @@ export default function PotentialAlbumsAssets() { assets: [], selectedIds: [], }); - return listPotentialAlbumsAssets({ startDate }) + // If endDate is set we're in trip-range mode, else single-day mode. + const fetcher = endDate + ? listPotentialTripAssets(startDate, endDate) + : listPotentialAlbumsAssets({ startDate }); + return fetcher .then((fetchedAssets) => updateContext({ assets: fetchedAssets })) .catch(setErrorMessage) .finally(() => setLoading(false)); @@ -62,7 +69,8 @@ export default function PotentialAlbumsAssets() { useEffect(() => { if (startDate) fetchAssets(); - }, [startDate]); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [startDate, endDate]); if (loading) return ( diff --git a/src/components/albums/potential-albums/PotentialTrips.tsx b/src/components/albums/potential-albums/PotentialTrips.tsx new file mode 100644 index 0000000..9f56cc8 --- /dev/null +++ b/src/components/albums/potential-albums/PotentialTrips.tsx @@ -0,0 +1,128 @@ +import { + IPotentialTrip, + IPotentialTripsResponse, + listPotentialTrips, +} from "@/handlers/api/album.handler"; +import React, { useEffect, useState } from "react"; +import { usePhotoSelectionContext } from "@/contexts/PhotoSelectionContext"; +import { useRouter } from "next/router"; +import { Loader, MapPin, Plane } from "lucide-react"; +import { format, parseISO } from "date-fns"; + +interface IProps { + onSelectTrip: (trip: IPotentialTrip) => void; +} + +export default function PotentialTrips({ onSelectTrip }: IProps) { + const router = useRouter(); + const { config } = usePhotoSelectionContext(); + const { startDate: activeStart, endDate: activeEnd } = router.query as { + startDate?: string; + endDate?: string; + }; + + const [data, setData] = useState(null); + const [loading, setLoading] = useState(false); + const [errorMessage, setErrorMessage] = useState(null); + + useEffect(() => { + setLoading(true); + listPotentialTrips() + .then(setData) + .catch((e: any) => setErrorMessage(e?.message ?? "Failed to load trips")) + .finally(() => setLoading(false)); + }, []); + + const handleSelect = (trip: IPotentialTrip) => { + onSelectTrip(trip); + router.push({ + pathname: router.pathname, + query: { startDate: trip.startDate, endDate: trip.endDate }, + }); + }; + + if (loading) { + return ( +
+ Computing trips… +
+ ); + } + + if (errorMessage) { + return

{errorMessage}

; + } + + if (!data || data.trips.length === 0) { + return ( +
+

No trips detected.

+

+ A trip is ≥{" "} + + {data?.home?.city ? "2" : "—"} + {" "} + consecutive days of photos taken away from your home location + {data?.home?.city ? ( + <> + {" "} + (currently {data.home.city}) + + ) : null} + . If your library has no GPS data, this view will stay empty — use + the Days tab instead. +

+
+ ); + } + + return ( +
+ {data.trips.map((t) => { + const isActive = activeStart === t.startDate && activeEnd === t.endDate; + return ( + + ); + })} + {data.home.city ? ( +
+ Home: {data.home.city} + {data.home.lat != null && data.home.lon != null ? ( + <> + {" "} + ({data.home.lat.toFixed(2)}, {data.home.lon.toFixed(2)}) + + ) : null} +
+ ) : null} +
+ ); +} diff --git a/src/config/routes.ts b/src/config/routes.ts index 5ecd930..008cc52 100644 --- a/src/config/routes.ts +++ b/src/config/routes.ts @@ -19,6 +19,8 @@ export const EXIF_DISTRIBUTION_PATH = (column: string) => BASE_API_ENDPOINT + "/ // Albums export const LIST_POTENTIAL_ALBUMS_DATES_PATH = BASE_API_ENDPOINT + "/albums/potential-albums-dates"; export const LIST_POTENTIAL_ALBUMS_ASSETS_PATH = BASE_API_ENDPOINT + "/albums/potential-albums-assets"; +export const LIST_POTENTIAL_TRIPS_PATH = BASE_API_ENDPOINT + "/albums/potential-trips"; +export const LIST_POTENTIAL_TRIP_ASSETS_PATH = BASE_API_ENDPOINT + "/albums/potential-trip-assets"; export const LIST_ALBUMS_PATH = BASE_API_ENDPOINT + "/albums/list"; export const ALBUM_INFO_PATH = (id: string) => BASE_API_ENDPOINT + "/albums/" + id + "/info"; diff --git a/src/contexts/PhotoSelectionContext.tsx b/src/contexts/PhotoSelectionContext.tsx index b70bef8..fcfba23 100644 --- a/src/contexts/PhotoSelectionContext.tsx +++ b/src/contexts/PhotoSelectionContext.tsx @@ -6,6 +6,9 @@ import { createContext, useContext } from "react"; export interface IPhotoSelectionConfig { // Common config potentially used by multiple features startDate?: string; + endDate?: string; + /** Pre-filled name suggestion for a new album (e.g. "20180401 - Lisboa"). */ + suggestedAlbumName?: string; // MissingLocation specific config albumId?: string; diff --git a/src/handlers/api/album.handler.ts b/src/handlers/api/album.handler.ts index 2179afb..5d59b06 100644 --- a/src/handlers/api/album.handler.ts +++ b/src/handlers/api/album.handler.ts @@ -1,4 +1,4 @@ -import { ADD_ASSETS_ALBUMS_PATH, ALBUM_ASSETS_PATH, ALBUM_INFO_PATH, ALBUM_PEOPLE_PATH, CREATE_ALBUM_PATH, DELETE_ALBUMS_PATH, LIST_ALBUMS_PATH, LIST_POTENTIAL_ALBUMS_ASSETS_PATH, LIST_POTENTIAL_ALBUMS_DATES_PATH, MERGE_ALBUMS_PATH, SHARE_ALBUMS_PATH } from "@/config/routes"; +import { ADD_ASSETS_ALBUMS_PATH, ALBUM_ASSETS_PATH, ALBUM_INFO_PATH, ALBUM_PEOPLE_PATH, CREATE_ALBUM_PATH, DELETE_ALBUMS_PATH, LIST_ALBUMS_PATH, LIST_POTENTIAL_ALBUMS_ASSETS_PATH, LIST_POTENTIAL_ALBUMS_DATES_PATH, LIST_POTENTIAL_TRIPS_PATH, LIST_POTENTIAL_TRIP_ASSETS_PATH, MERGE_ALBUMS_PATH, SHARE_ALBUMS_PATH } from "@/config/routes"; import { cleanUpAsset } from "@/helpers/asset.helper"; import API from "@/lib/api"; import { IAlbumCreate } from "@/types/album"; @@ -24,6 +24,36 @@ export const listPotentialAlbumsAssets = async (filters: IPotentialAlbumsDatesFi return API.get(LIST_POTENTIAL_ALBUMS_ASSETS_PATH, filters).then((assets) => assets.map(cleanUpAsset)); } +export interface IPotentialTripsFilters { + homeRadiusKm?: number; + minTripDays?: number; + gapTolerance?: number; +} + +export interface IPotentialTrip { + startDate: string; + endDate: string; + cityName: string | null; + countryName: string | null; + assetCount: number; + dayCount: number; + awayDays: number; + suggestedName: string; +} + +export interface IPotentialTripsResponse { + home: { city: string | null; lat: number | null; lon: number | null }; + trips: IPotentialTrip[]; +} + +export const listPotentialTrips = async (filters?: IPotentialTripsFilters): Promise => { + return API.get(LIST_POTENTIAL_TRIPS_PATH, filters); +} + +export const listPotentialTripAssets = async (startDate: string, endDate: string): Promise => { + return API.get(LIST_POTENTIAL_TRIP_ASSETS_PATH, { startDate, endDate }).then((assets) => assets.map(cleanUpAsset)); +} + export const listAlbums = async (filters?: { sortBy?: string, sortOrder?: string }) => { return API.get(LIST_ALBUMS_PATH, filters); } diff --git a/src/helpers/trips.helper.ts b/src/helpers/trips.helper.ts new file mode 100644 index 0000000..00c2f87 --- /dev/null +++ b/src/helpers/trips.helper.ts @@ -0,0 +1,199 @@ +/** + * Trip clustering for the Potential Albums "Trips" view. + * + * Given per-day signals (asset count, mode city/country, GPS centroid), + * identify multi-day stretches where the user was "away" from home, + * tolerating small gaps (transit days, days with no photos). + * + * Pure functions — no DB, no network. Easy to unit-test. + */ + +export interface DaySignal { + /** YYYY-MM-DD */ + date: string; + assetCount: number; + /** most common city for that day's assets, null if unknown */ + cityMode: string | null; + /** most common country for that day's assets, null if unknown */ + countryMode: string | null; + /** mean lat/lon of that day's assets, null if no asset had GPS */ + centroidLat: number | null; + centroidLon: number | null; +} + +export interface Trip { + /** YYYY-MM-DD of the first away day */ + startDate: string; + /** YYYY-MM-DD of the last away day */ + endDate: string; + /** dominant city across the trip's away days (null if none known) */ + cityName: string | null; + countryName: string | null; + assetCount: number; + dayCount: number; + /** days classified as away (rest are tolerated gaps) */ + awayDays: number; + /** suggested album name: "YYYYMMDD - City" or "YYYYMMDD - Trip" */ + suggestedName: string; +} + +export interface Home { + city: string | null; + lat: number | null; + lon: number | null; +} + +export interface ClusterOptions { + home: Home; + /** radius in km from `home` to treat a day as "at home" (default 50) */ + homeRadiusKm: number; + /** minimum count of away days for a stretch to qualify as a trip (default 2) */ + minTripDays: number; + /** maximum consecutive non-away days tolerated inside a trip (default 2) */ + gapTolerance: number; +} + +export const DEFAULT_CLUSTER_OPTIONS: Omit = { + homeRadiusKm: 50, + minTripDays: 2, + gapTolerance: 2, +}; + +export function haversineKm(lat1: number, lon1: number, lat2: number, lon2: number): number { + const R = 6371; // Earth radius (km) + const toRad = (deg: number) => (deg * Math.PI) / 180; + const dLat = toRad(lat2 - lat1); + const dLon = toRad(lon2 - lon1); + const a = + Math.sin(dLat / 2) ** 2 + + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLon / 2) ** 2; + return 2 * R * Math.asin(Math.sqrt(a)); +} + +/** + * Pick the library's home as the most asset-rich city, and compute a centroid + * from the GPS of that city's days. + */ +export function computeHome(days: DaySignal[]): Home { + if (days.length === 0) return { city: null, lat: null, lon: null }; + + const cityCounts = new Map(); + for (const d of days) { + if (d.cityMode) cityCounts.set(d.cityMode, (cityCounts.get(d.cityMode) ?? 0) + d.assetCount); + } + const homeCity = [...cityCounts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null; + + const homeDays = days.filter( + (d) => d.cityMode === homeCity && d.centroidLat != null && d.centroidLon != null + ); + const totalWeight = homeDays.reduce((s, d) => s + d.assetCount, 0); + if (totalWeight === 0) return { city: homeCity, lat: null, lon: null }; + + const lat = + homeDays.reduce((s, d) => s + (d.centroidLat as number) * d.assetCount, 0) / totalWeight; + const lon = + homeDays.reduce((s, d) => s + (d.centroidLon as number) * d.assetCount, 0) / totalWeight; + + return { city: homeCity, lat, lon }; +} + +export function isAwayDay(day: DaySignal, opts: ClusterOptions): boolean { + const { home, homeRadiusKm } = opts; + // Prefer geo distance when both sides have it + if ( + day.centroidLat != null && + day.centroidLon != null && + home.lat != null && + home.lon != null + ) { + return haversineKm(day.centroidLat, day.centroidLon, home.lat, home.lon) > homeRadiusKm; + } + // Fall back to string city comparison + if (day.cityMode && home.city) { + return day.cityMode !== home.city; + } + // No signal — treat as home to avoid false trips + return false; +} + +function suggestName(startDate: string, cityName: string | null): string { + const compact = startDate.replace(/-/g, ""); + return `${compact} - ${cityName ?? "Trip"}`; +} + +function modeBy(items: T[], weight: (t: T) => number, key: (t: T) => K | null): K | null { + const counts = new Map(); + for (const it of items) { + const k = key(it); + if (k == null) continue; + counts.set(k, (counts.get(k) ?? 0) + weight(it)); + } + return [...counts.entries()].sort((a, b) => b[1] - a[1])[0]?.[0] ?? null; +} + +/** + * Cluster consecutive "away" days into trips. + * + * Algorithm: + * Linear scan. When we hit an away day, keep extending the window: + * - another away day → extend `endIdx` + * - a run of non-away days ≤ gapTolerance → tolerated, keep scanning + * - a run > gapTolerance → close the trip at `endIdx` + * Emit the trip only if it has ≥ minTripDays away days. + */ +export function clusterTrips(days: DaySignal[], opts: ClusterOptions): Trip[] { + const sorted = [...days].sort((a, b) => a.date.localeCompare(b.date)); + const away = sorted.map((d) => isAwayDay(d, opts)); + const trips: Trip[] = []; + + let i = 0; + while (i < sorted.length) { + if (!away[i]) { + i += 1; + continue; + } + let endIdx = i; + let k = i + 1; + while (k < sorted.length) { + if (away[k]) { + endIdx = k; + k += 1; + continue; + } + // Count consecutive non-away days + const gapStart = k; + while (k < sorted.length && !away[k]) k += 1; + const gapLen = k - gapStart; + if (gapLen > opts.gapTolerance) break; // close trip at endIdx + // else tolerated; `k` now points at next away day (or end) + } + + const slice = sorted.slice(i, endIdx + 1); + const awayCount = slice.filter((_, idx) => away[i + idx]).length; + if (awayCount >= opts.minTripDays) { + const awayOnly = slice.filter((_, idx) => away[i + idx]); + const cityName = modeBy( + awayOnly, + (d) => d.assetCount, + (d) => d.cityMode + ); + const countryName = modeBy( + awayOnly, + (d) => d.assetCount, + (d) => d.countryMode + ); + trips.push({ + startDate: sorted[i].date, + endDate: sorted[endIdx].date, + cityName, + countryName, + assetCount: slice.reduce((s, d) => s + d.assetCount, 0), + dayCount: endIdx - i + 1, + awayDays: awayCount, + suggestedName: suggestName(sorted[i].date, cityName), + }); + } + i = endIdx + 1; + } + return trips; +} diff --git a/src/pages/albums/potential-albums.tsx b/src/pages/albums/potential-albums.tsx index e9cccf6..4b69a72 100644 --- a/src/pages/albums/potential-albums.tsx +++ b/src/pages/albums/potential-albums.tsx @@ -1,6 +1,7 @@ import AlbumSelectorDialog from "@/components/albums/AlbumSelectorDialog"; import PotentialAlbumsAssets from "@/components/albums/potential-albums/PotentialAlbumsAssets"; import PotentialAlbumsDates from "@/components/albums/potential-albums/PotentialAlbumsDates"; +import PotentialTrips from "@/components/albums/potential-albums/PotentialTrips"; import AssetOffsetDialog from "@/components/assets/assets-options/AssetOffsetDialog"; import PageLayout from "@/components/layouts/PageLayout"; import FloatingBar from "@/components/shared/FloatingBar"; @@ -9,10 +10,11 @@ import { AlertDialog } from "@/components/ui/alert-dialog"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; +import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; import { useToast } from "@/components/ui/use-toast"; import { useCurrentUser } from "@/contexts/CurrentUserContext"; import PhotoSelectionContext, { IPhotoSelectionContext } from "@/contexts/PhotoSelectionContext"; -import { addAssetToAlbum, createAlbum } from "@/handlers/api/album.handler"; +import { addAssetToAlbum, createAlbum, IPotentialTrip } from "@/handlers/api/album.handler"; import { deleteAssets } from "@/handlers/api/asset.handler"; import { IAlbum, IAlbumCreate } from "@/types/album"; import { useRouter } from "next/router"; @@ -23,13 +25,14 @@ export default function PotentialAlbums() { const { id } = useCurrentUser(); const { query } = useRouter(); - const { startDate } = query as { startDate: string }; + const { startDate, endDate } = query as { startDate?: string; endDate?: string }; const [contextState, setContextState] = React.useState({ selectedIds: [], assets: [], config: { startDate: startDate || undefined, + endDate: endDate || undefined, minAssets: 1, }, updateContext: (newConfig: Partial) => { @@ -140,7 +143,29 @@ export default function PotentialAlbums() { }} >
- + + + Days + Trips + + + + + + + updateContext({ + config: { + ...contextState.config, + startDate: trip.startDate, + endDate: trip.endDate, + suggestedAlbumName: trip.suggestedName, + }, + }) + } + /> + +
{selectedAssets.length > 0 && @@ -175,7 +200,11 @@ export default function PotentialAlbums() { Select all )} - +
diff --git a/src/pages/api/albums/potential-trip-assets.ts b/src/pages/api/albums/potential-trip-assets.ts new file mode 100644 index 0000000..8c8fae3 --- /dev/null +++ b/src/pages/api/albums/potential-trip-assets.ts @@ -0,0 +1,71 @@ +// Fetch orphan assets that fall within a date range (for the Potential Trips view). +import { db } from "@/config/db"; +import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; +import { isFlipped } from "@/helpers/asset.helper"; +import { sql } from "drizzle-orm"; +import type { NextApiRequest, NextApiResponse } from "next"; + +const SELECT_ORPHAN_RANGE = (startDate: string, endDate: string, ownerId: string) => + sql.raw(` + SELECT + a."id", + a."ownerId", + a."deviceId", + a."type", + a."originalPath", + a."isFavorite", + a."duration", + a."originalFileName", + a."thumbhash", + a."deletedAt", + e."exifImageWidth", + e."exifImageHeight", + e."dateTimeOriginal", + e."orientation" + FROM + asset a + LEFT JOIN + album_asset aaa + ON a.id = aaa."assetId" + LEFT JOIN + asset_exif e + ON a.id = e."assetId" + WHERE + aaa."albumId" IS NULL + AND a."ownerId" = '${ownerId}' + AND e."dateTimeOriginal"::date BETWEEN '${startDate}' AND '${endDate}' + AND a."visibility" = 'timeline' + ORDER BY + e."dateTimeOriginal" ASC +`); + +export default async function handler(req: NextApiRequest, res: NextApiResponse) { + try { + const currentUser = await getCurrentUser(req); + if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); + + const { startDate, endDate } = req.query as { startDate?: string; endDate?: string }; + if (!startDate || !endDate) { + return res.status(400).json({ error: "startDate and endDate are required (YYYY-MM-DD)" }); + } + // Basic format sanity (the strings are interpolated into the SQL literal, so + // reject anything that isn't YYYY-MM-DD to keep this endpoint from becoming + // an injection vector — same shape check the single-date endpoint should have.) + const DATE_RE = /^\d{4}-\d{2}-\d{2}$/; + if (!DATE_RE.test(startDate) || !DATE_RE.test(endDate)) { + return res.status(400).json({ error: "Invalid date format, expected YYYY-MM-DD" }); + } + + const { rows } = await db.execute(SELECT_ORPHAN_RANGE(startDate, endDate, currentUser.id)); + + const cleaned = rows.map((row: any) => ({ + ...row, + exifImageWidth: isFlipped(row.orientation || 0) ? row.exifImageHeight : row.exifImageWidth, + exifImageHeight: isFlipped(row.orientation || 0) ? row.exifImageWidth : row.exifImageHeight, + })); + return res.status(200).json(cleaned); + } catch (error: any) { + console.error(error); + return res.status(500).json({ error: error?.message }); + } +} diff --git a/src/pages/api/albums/potential-trips.ts b/src/pages/api/albums/potential-trips.ts new file mode 100644 index 0000000..ce59041 --- /dev/null +++ b/src/pages/api/albums/potential-trips.ts @@ -0,0 +1,80 @@ +// Potential trips — multi-day stretches of photos away from home. +// Companion to /api/albums/potential-albums-dates (which groups by single day). +import { db } from "@/config/db"; +import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; +import { + DaySignal, + DEFAULT_CLUSTER_OPTIONS, + clusterTrips, + computeHome, +} from "@/helpers/trips.helper"; +import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; +import { assets } from "@/schema/assets.schema"; +import { exif } from "@/schema/exif.schema"; +import { and, avg, count, eq, isNotNull, isNull, sql } from "drizzle-orm"; +import type { NextApiRequest, NextApiResponse } from "next"; + +export default async function handler(req: NextApiRequest, res: NextApiResponse) { + try { + const { + homeRadiusKm = DEFAULT_CLUSTER_OPTIONS.homeRadiusKm, + minTripDays = DEFAULT_CLUSTER_OPTIONS.minTripDays, + gapTolerance = DEFAULT_CLUSTER_OPTIONS.gapTolerance, + } = req.query as Record; + + const currentUser = await getCurrentUser(req); + if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); + + // Per-day aggregation: count, centroid, dominant city/country via PG MODE(). + const rows = (await db + .select({ + date: sql`TO_CHAR(DATE(${exif.dateTimeOriginal}), 'YYYY-MM-DD')`, + assetCount: count(assets.id), + centroidLat: avg(exif.latitude), + centroidLon: avg(exif.longitude), + cityMode: sql`MODE() WITHIN GROUP (ORDER BY ${exif.city})`, + countryMode: sql`MODE() WITHIN GROUP (ORDER BY ${exif.country})`, + }) + .from(assets) + .leftJoin(albumsAssetsAssets, eq(assets.id, albumsAssetsAssets.assetId)) + .leftJoin(exif, eq(assets.id, exif.assetId)) + .where( + and( + eq(assets.ownerId, currentUser.id), + eq(assets.visibility, "timeline"), + isNull(albumsAssetsAssets.albumId), + isNotNull(exif.dateTimeOriginal) + ) + ) + .groupBy(sql`DATE(${exif.dateTimeOriginal})`)) as Array<{ + date: string; + assetCount: number | string; + centroidLat: string | null; + centroidLon: string | null; + cityMode: string | null; + countryMode: string | null; + }>; + + const days: DaySignal[] = rows.map((r) => ({ + date: r.date, + assetCount: Number(r.assetCount), + cityMode: r.cityMode, + countryMode: r.countryMode, + centroidLat: r.centroidLat == null ? null : Number(r.centroidLat), + centroidLon: r.centroidLon == null ? null : Number(r.centroidLon), + })); + + const home = computeHome(days); + const trips = clusterTrips(days, { + home, + homeRadiusKm: Number(homeRadiusKm), + minTripDays: Number(minTripDays), + gapTolerance: Number(gapTolerance), + }); + + return res.status(200).json({ home, trips }); + } catch (error: any) { + console.error(error); + return res.status(500).json({ error: error?.message }); + } +} From 4439367f4f8ffa5ee72415dd1838e2c04d0414b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Gil=20P=C3=A9rez?= Date: Mon, 20 Apr 2026 22:49:02 +0200 Subject: [PATCH 2/6] feat(potential-trips): filter trip assets by trip city The trip-assets endpoint was returning every orphan asset in the date range, so screenshots, photos taken at the airport coming back, or anything else timestamped during the trip days mixed in. The right panel ended up showing photos from multiple cities for one trip selection. Pass the trip's dominant city through the context to the asset fetcher and add an optional 'city' filter on /api/albums/potential-trip-assets: WHERE e.city = :city OR e.city IS NULL NULL is included so we don't lose photos taken during the trip whose EXIF lacks a city tag (no GPS, screenshots edited later, older devices, etc.). When no city is provided (single-day Days view, or a trip whose city couldn't be resolved) the previous date-only behaviour is preserved. --- .../PotentialAlbumsAssets.tsx | 6 ++-- src/contexts/PhotoSelectionContext.tsx | 2 ++ src/handlers/api/album.handler.ts | 10 ++++-- src/pages/albums/potential-albums.tsx | 1 + src/pages/api/albums/potential-trip-assets.ts | 34 ++++++++++++++++--- 5 files changed, 43 insertions(+), 10 deletions(-) diff --git a/src/components/albums/potential-albums/PotentialAlbumsAssets.tsx b/src/components/albums/potential-albums/PotentialAlbumsAssets.tsx index 82e93c4..c261847 100644 --- a/src/components/albums/potential-albums/PotentialAlbumsAssets.tsx +++ b/src/components/albums/potential-albums/PotentialAlbumsAssets.tsx @@ -17,7 +17,7 @@ export default function PotentialAlbumsAssets() { updateContext, config } = usePhotoSelectionContext(); - const { startDate, endDate } = config; + const { startDate, endDate, tripCity } = config; const [loading, setLoading] = useState(false); const [errorMessage, setErrorMessage] = useState(null); @@ -31,7 +31,7 @@ export default function PotentialAlbumsAssets() { }); // If endDate is set we're in trip-range mode, else single-day mode. const fetcher = endDate - ? listPotentialTripAssets(startDate, endDate) + ? listPotentialTripAssets(startDate, endDate, tripCity) : listPotentialAlbumsAssets({ startDate }); return fetcher .then((fetchedAssets) => updateContext({ assets: fetchedAssets })) @@ -70,7 +70,7 @@ export default function PotentialAlbumsAssets() { useEffect(() => { if (startDate) fetchAssets(); // eslint-disable-next-line react-hooks/exhaustive-deps - }, [startDate, endDate]); + }, [startDate, endDate, tripCity]); if (loading) return ( diff --git a/src/contexts/PhotoSelectionContext.tsx b/src/contexts/PhotoSelectionContext.tsx index fcfba23..e9f6acf 100644 --- a/src/contexts/PhotoSelectionContext.tsx +++ b/src/contexts/PhotoSelectionContext.tsx @@ -7,6 +7,8 @@ export interface IPhotoSelectionConfig { // Common config potentially used by multiple features startDate?: string; endDate?: string; + /** Trip's dominant city, used to filter the asset list to that location. */ + tripCity?: string | null; /** Pre-filled name suggestion for a new album (e.g. "20180401 - Lisboa"). */ suggestedAlbumName?: string; diff --git a/src/handlers/api/album.handler.ts b/src/handlers/api/album.handler.ts index 5d59b06..32d26ec 100644 --- a/src/handlers/api/album.handler.ts +++ b/src/handlers/api/album.handler.ts @@ -50,8 +50,14 @@ export const listPotentialTrips = async (filters?: IPotentialTripsFilters): Prom return API.get(LIST_POTENTIAL_TRIPS_PATH, filters); } -export const listPotentialTripAssets = async (startDate: string, endDate: string): Promise => { - return API.get(LIST_POTENTIAL_TRIP_ASSETS_PATH, { startDate, endDate }).then((assets) => assets.map(cleanUpAsset)); +export const listPotentialTripAssets = async ( + startDate: string, + endDate: string, + city?: string | null, +): Promise => { + const params: Record = { startDate, endDate }; + if (city) params.city = city; + return API.get(LIST_POTENTIAL_TRIP_ASSETS_PATH, params).then((assets) => assets.map(cleanUpAsset)); } export const listAlbums = async (filters?: { sortBy?: string, sortOrder?: string }) => { diff --git a/src/pages/albums/potential-albums.tsx b/src/pages/albums/potential-albums.tsx index 4b69a72..f03c48f 100644 --- a/src/pages/albums/potential-albums.tsx +++ b/src/pages/albums/potential-albums.tsx @@ -159,6 +159,7 @@ export default function PotentialAlbums() { ...contextState.config, startDate: trip.startDate, endDate: trip.endDate, + tripCity: trip.cityName, suggestedAlbumName: trip.suggestedName, }, }) diff --git a/src/pages/api/albums/potential-trip-assets.ts b/src/pages/api/albums/potential-trip-assets.ts index 8c8fae3..ec6bd9e 100644 --- a/src/pages/api/albums/potential-trip-assets.ts +++ b/src/pages/api/albums/potential-trip-assets.ts @@ -5,8 +5,22 @@ import { isFlipped } from "@/helpers/asset.helper"; import { sql } from "drizzle-orm"; import type { NextApiRequest, NextApiResponse } from "next"; -const SELECT_ORPHAN_RANGE = (startDate: string, endDate: string, ownerId: string) => - sql.raw(` +// Optional `city` narrows the result to assets whose EXIF city matches the +// trip's dominant city. Assets with NULL city are included alongside the +// match: they may be photos taken during the trip but without GPS metadata +// (screenshots, edited copies, older devices, etc.) and excluding them would +// lose real trip content. If `city` is not provided the date range alone +// determines membership. +const SELECT_ORPHAN_RANGE = ( + startDate: string, + endDate: string, + ownerId: string, + city: string | null +) => { + const cityClause = city + ? `AND (e."city" = '${city.replace(/'/g, "''")}' OR e."city" IS NULL)` + : ""; + return sql.raw(` SELECT a."id", a."ownerId", @@ -21,7 +35,9 @@ const SELECT_ORPHAN_RANGE = (startDate: string, endDate: string, ownerId: string e."exifImageWidth", e."exifImageHeight", e."dateTimeOriginal", - e."orientation" + e."orientation", + e."city", + e."country" FROM asset a LEFT JOIN @@ -35,16 +51,22 @@ const SELECT_ORPHAN_RANGE = (startDate: string, endDate: string, ownerId: string AND a."ownerId" = '${ownerId}' AND e."dateTimeOriginal"::date BETWEEN '${startDate}' AND '${endDate}' AND a."visibility" = 'timeline' + ${cityClause} ORDER BY e."dateTimeOriginal" ASC `); +}; export default async function handler(req: NextApiRequest, res: NextApiResponse) { try { const currentUser = await getCurrentUser(req); if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); - const { startDate, endDate } = req.query as { startDate?: string; endDate?: string }; + const { startDate, endDate, city } = req.query as { + startDate?: string; + endDate?: string; + city?: string; + }; if (!startDate || !endDate) { return res.status(400).json({ error: "startDate and endDate are required (YYYY-MM-DD)" }); } @@ -56,7 +78,9 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) return res.status(400).json({ error: "Invalid date format, expected YYYY-MM-DD" }); } - const { rows } = await db.execute(SELECT_ORPHAN_RANGE(startDate, endDate, currentUser.id)); + const { rows } = await db.execute( + SELECT_ORPHAN_RANGE(startDate, endDate, currentUser.id, city ?? null) + ); const cleaned = rows.map((row: any) => ({ ...row, From 09decb719817bdb96b54120039709612086cdae5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Gil=20P=C3=A9rez?= Date: Mon, 20 Apr 2026 23:19:24 +0200 Subject: [PATCH 3/6] fix(potential-trips): pre-fill suggested album name reliably The previous guard 'only set if formData.albumName is empty' lost races against the dialog mount cycle: in some orderings the formData starts empty, the effect fires while config.suggestedAlbumName is undefined, then later when the suggestion arrives the guard refuses to update because prev.albumName == ''. Net effect: the user clicks a trip, selects photos, opens Add to Album, and the Album Name field is empty. Track the last applied suggestion via a ref and write the value whenever the suggestion changes to a new non-empty string. Doesn't overwrite mid-typing because the suggestion only flips when the user picks a different trip; doesn't overwrite when the user picks the same trip twice; works on mount-after-suggestion (which was the broken path). --- src/components/albums/AlbumSelectorDialog.tsx | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/components/albums/AlbumSelectorDialog.tsx b/src/components/albums/AlbumSelectorDialog.tsx index 27309d6..749ad06 100644 --- a/src/components/albums/AlbumSelectorDialog.tsx +++ b/src/components/albums/AlbumSelectorDialog.tsx @@ -38,10 +38,17 @@ export default function AlbumSelectorDialog({ onSelected, onCreated, onSubmit, d albumName: defaultName ?? config.suggestedAlbumName ?? "", }); - // Sync the pre-fill if it changes after mount (e.g., user picks another trip) + // Track the previous suggestion so we only overwrite the user's typing when + // the suggestion itself changes (e.g. they picked a different trip), not on + // every render. This keeps "user is typing" stable while still flipping the + // input as soon as a trip selection arrives. + const lastSuggestionRef = React.useRef(null); useEffect(() => { const next = defaultName ?? config.suggestedAlbumName ?? ""; - setFormData((prev) => (prev.albumName ? prev : { albumName: next })); + if (!next) return; + if (lastSuggestionRef.current === next) return; + lastSuggestionRef.current = next; + setFormData({ albumName: next }); }, [defaultName, config.suggestedAlbumName]); const fetchData = () => { From a9d2adc6a1fc257690c13d7f6a4d50181b8d2f30 Mon Sep 17 00:00:00 2001 From: Varun Raj Date: Fri, 10 Jul 2026 15:53:04 +0000 Subject: [PATCH 4/6] fix: measure trip gap tolerance in real calendar days, not array-index distance clusterTrips's gap check compared array-index adjacency between DaySignal entries. Since `days` only contains dates with >=1 photo (GROUP BY DATE(...) with no zero-photo rows), two trips separated by months with no photos in between were array-adjacent (gapLen=0) and got merged into one bogus trip. Compare actual elapsed calendar days between the last and next away day instead. --- src/helpers/trips.helper.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/helpers/trips.helper.ts b/src/helpers/trips.helper.ts index 00c2f87..4fde3e4 100644 --- a/src/helpers/trips.helper.ts +++ b/src/helpers/trips.helper.ts @@ -8,6 +8,8 @@ * Pure functions — no DB, no network. Easy to unit-test. */ +import { differenceInCalendarDays, parseISO } from "date-fns"; + export interface DaySignal { /** YYYY-MM-DD */ date: string; @@ -160,12 +162,16 @@ export function clusterTrips(days: DaySignal[], opts: ClusterOptions): Trip[] { k += 1; continue; } - // Count consecutive non-away days - const gapStart = k; + // Skip consecutive non-away days, then compare actual elapsed calendar + // days (not array-index distance) against the next away day — `days` + // only contains dates with ≥1 photo, so a months-long photo-less gap + // must not look "adjacent" just because no entries sit between them. while (k < sorted.length && !away[k]) k += 1; - const gapLen = k - gapStart; - if (gapLen > opts.gapTolerance) break; // close trip at endIdx - // else tolerated; `k` now points at next away day (or end) + if (k < sorted.length) { + const gapDays = differenceInCalendarDays(parseISO(sorted[k].date), parseISO(sorted[endIdx].date)); + if (gapDays > opts.gapTolerance) break; // close trip at endIdx + } + // else tolerated (or no more away days left); `k` now points at next away day (or end) } const slice = sorted.slice(i, endIdx + 1); From ef3ce79c5b57442871ba6a6f11a013e3a978f8e1 Mon Sep 17 00:00:00 2001 From: Varun Raj Date: Fri, 10 Jul 2026 15:55:41 +0000 Subject: [PATCH 5/6] =?UTF-8?q?fix:=20drop=20asset.deviceId=20from=20raw?= =?UTF-8?q?=20SQL=20select=20=E2=80=94=20column=20removed=20in=20Immich=20?= =?UTF-8?q?v3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Immich v3 dropped asset.deviceId/deviceAssetId (af4cfce on main). This branch predates that migration, so its own SELECT_ORPHAN_RANGE query still referenced the column, which would 500 on any current Immich v3 instance. Match the field list already used by the sibling potential-albums-assets.ts endpoint, which was updated for v3. --- src/pages/api/albums/potential-trip-assets.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/pages/api/albums/potential-trip-assets.ts b/src/pages/api/albums/potential-trip-assets.ts index ec6bd9e..c7bf238 100644 --- a/src/pages/api/albums/potential-trip-assets.ts +++ b/src/pages/api/albums/potential-trip-assets.ts @@ -24,7 +24,6 @@ const SELECT_ORPHAN_RANGE = ( SELECT a."id", a."ownerId", - a."deviceId", a."type", a."originalPath", a."isFavorite", From a5a4528962b7ac555a76ef40d7b04433581d57c2 Mon Sep 17 00:00:00 2001 From: Varun Raj Date: Fri, 10 Jul 2026 16:11:22 +0000 Subject: [PATCH 6/6] refactor: consolidate day/trip grouping into shared endpoints via groupBy param MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merges potential-trips + potential-trip-assets into potential-albums-dates + potential-albums-assets respectively, keyed by a new ?groupBy=day|trip query param. The actual grouping logic is extracted into two new helper files (potentialAlbumsGrouping.helper.ts, potentialAlbumsAssets.helper.ts), each holding a day-mode and trip-mode function the unified handlers call into. Client-facing functions (listPotentialTrips, listPotentialTripAssets) keep their existing names/signatures — only their internal path and a groupBy param changed — so no frontend component call sites need updating. Also drops the two now-unused LIST_POTENTIAL_TRIP*_PATH route constants. Addresses the maintainer's open caching-strategy question by removing the need for a second endpoint/cache entirely: one endpoint per concern, two grouping strategies. --- src/config/routes.ts | 4 +- src/handlers/api/album.handler.ts | 8 +- src/helpers/potentialAlbumsAssets.helper.ts | 103 ++++++++++++++++++ src/helpers/potentialAlbumsGrouping.helper.ts | 92 ++++++++++++++++ .../api/albums/potential-albums-assets.ts | 81 ++++++-------- .../api/albums/potential-albums-dates.ts | 43 ++++---- src/pages/api/albums/potential-trip-assets.ts | 94 ---------------- src/pages/api/albums/potential-trips.ts | 80 -------------- 8 files changed, 253 insertions(+), 252 deletions(-) create mode 100644 src/helpers/potentialAlbumsAssets.helper.ts create mode 100644 src/helpers/potentialAlbumsGrouping.helper.ts delete mode 100644 src/pages/api/albums/potential-trip-assets.ts delete mode 100644 src/pages/api/albums/potential-trips.ts diff --git a/src/config/routes.ts b/src/config/routes.ts index 008cc52..1c82744 100644 --- a/src/config/routes.ts +++ b/src/config/routes.ts @@ -17,10 +17,10 @@ export const MERGE_PERSON_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/people/ export const EXIF_DISTRIBUTION_PATH = (column: string) => BASE_API_ENDPOINT + "/analytics/exif/" + column; // Albums +// Potential-albums grouping (day vs trip) and asset-detail (single day vs +// date range) share one endpoint each, distinguished by a `groupBy` param. export const LIST_POTENTIAL_ALBUMS_DATES_PATH = BASE_API_ENDPOINT + "/albums/potential-albums-dates"; export const LIST_POTENTIAL_ALBUMS_ASSETS_PATH = BASE_API_ENDPOINT + "/albums/potential-albums-assets"; -export const LIST_POTENTIAL_TRIPS_PATH = BASE_API_ENDPOINT + "/albums/potential-trips"; -export const LIST_POTENTIAL_TRIP_ASSETS_PATH = BASE_API_ENDPOINT + "/albums/potential-trip-assets"; export const LIST_ALBUMS_PATH = BASE_API_ENDPOINT + "/albums/list"; export const ALBUM_INFO_PATH = (id: string) => BASE_API_ENDPOINT + "/albums/" + id + "/info"; diff --git a/src/handlers/api/album.handler.ts b/src/handlers/api/album.handler.ts index 32d26ec..944d2f5 100644 --- a/src/handlers/api/album.handler.ts +++ b/src/handlers/api/album.handler.ts @@ -1,4 +1,4 @@ -import { ADD_ASSETS_ALBUMS_PATH, ALBUM_ASSETS_PATH, ALBUM_INFO_PATH, ALBUM_PEOPLE_PATH, CREATE_ALBUM_PATH, DELETE_ALBUMS_PATH, LIST_ALBUMS_PATH, LIST_POTENTIAL_ALBUMS_ASSETS_PATH, LIST_POTENTIAL_ALBUMS_DATES_PATH, LIST_POTENTIAL_TRIPS_PATH, LIST_POTENTIAL_TRIP_ASSETS_PATH, MERGE_ALBUMS_PATH, SHARE_ALBUMS_PATH } from "@/config/routes"; +import { ADD_ASSETS_ALBUMS_PATH, ALBUM_ASSETS_PATH, ALBUM_INFO_PATH, ALBUM_PEOPLE_PATH, CREATE_ALBUM_PATH, DELETE_ALBUMS_PATH, LIST_ALBUMS_PATH, LIST_POTENTIAL_ALBUMS_ASSETS_PATH, LIST_POTENTIAL_ALBUMS_DATES_PATH, MERGE_ALBUMS_PATH, SHARE_ALBUMS_PATH } from "@/config/routes"; import { cleanUpAsset } from "@/helpers/asset.helper"; import API from "@/lib/api"; import { IAlbumCreate } from "@/types/album"; @@ -47,7 +47,7 @@ export interface IPotentialTripsResponse { } export const listPotentialTrips = async (filters?: IPotentialTripsFilters): Promise => { - return API.get(LIST_POTENTIAL_TRIPS_PATH, filters); + return API.get(LIST_POTENTIAL_ALBUMS_DATES_PATH, { ...filters, groupBy: "trip" }); } export const listPotentialTripAssets = async ( @@ -55,9 +55,9 @@ export const listPotentialTripAssets = async ( endDate: string, city?: string | null, ): Promise => { - const params: Record = { startDate, endDate }; + const params: Record = { startDate, endDate, groupBy: "trip" }; if (city) params.city = city; - return API.get(LIST_POTENTIAL_TRIP_ASSETS_PATH, params).then((assets) => assets.map(cleanUpAsset)); + return API.get(LIST_POTENTIAL_ALBUMS_ASSETS_PATH, params).then((assets) => assets.map(cleanUpAsset)); } export const listAlbums = async (filters?: { sortBy?: string, sortOrder?: string }) => { diff --git a/src/helpers/potentialAlbumsAssets.helper.ts b/src/helpers/potentialAlbumsAssets.helper.ts new file mode 100644 index 0000000..5c0dc98 --- /dev/null +++ b/src/helpers/potentialAlbumsAssets.helper.ts @@ -0,0 +1,103 @@ +// Asset-detail fetchers for the Potential Albums right-panel grid: either +// a single day, or a date range (trip). Both share one endpoint +// (potential-albums-assets.ts) via a `groupBy` param — this file holds the +// two DB-querying implementations. +import { db } from "@/config/db"; +import { isFlipped } from "@/helpers/asset.helper"; +import { sql } from "drizzle-orm"; + +const cleanRows = (rows: any[]) => + rows.map((row: any) => ({ + ...row, + exifImageWidth: isFlipped(row.orientation || 0) ? row.exifImageHeight : row.exifImageWidth, + exifImageHeight: isFlipped(row.orientation || 0) ? row.exifImageWidth : row.exifImageHeight, + })); + +const SELECT_ORPHAN_DAY = (date: string, ownerId: string) => + sql.raw(` + SELECT + a."id", + a."ownerId", + a."type", + a."originalPath", + a."isFavorite", + a."duration", + a."originalFileName", + a."thumbhash", + a."deletedAt", + e."exifImageWidth", + e."exifImageHeight", + e."dateTimeOriginal", + e."orientation" + FROM + asset a + LEFT JOIN + album_asset aaa + ON a.id = aaa."assetId" + LEFT JOIN + asset_exif e + ON a.id = e."assetId" + WHERE + aaa."albumId" IS NULL + AND a."ownerId" = '${ownerId}' + AND e."dateTimeOriginal"::date = '${date}' + AND a."visibility" = 'timeline' + ORDER BY + e."dateTimeOriginal" DESC +`); + +export const fetchDayAssets = async (ownerId: string, date: string) => { + const { rows } = await db.execute(SELECT_ORPHAN_DAY(date, ownerId)); + return cleanRows(rows); +}; + +// Optional `city` narrows the result to assets whose EXIF city matches the +// trip's dominant city. Assets with NULL city are included alongside the +// match: they may be photos taken during the trip but without GPS metadata +// (screenshots, edited copies, older devices, etc.) and excluding them would +// lose real trip content. If `city` is not provided the date range alone +// determines membership. +const SELECT_ORPHAN_RANGE = (startDate: string, endDate: string, ownerId: string, city: string | null) => { + const cityClause = city + ? `AND (e."city" = '${city.replace(/'/g, "''")}' OR e."city" IS NULL)` + : ""; + return sql.raw(` + SELECT + a."id", + a."ownerId", + a."type", + a."originalPath", + a."isFavorite", + a."duration", + a."originalFileName", + a."thumbhash", + a."deletedAt", + e."exifImageWidth", + e."exifImageHeight", + e."dateTimeOriginal", + e."orientation", + e."city", + e."country" + FROM + asset a + LEFT JOIN + album_asset aaa + ON a.id = aaa."assetId" + LEFT JOIN + asset_exif e + ON a.id = e."assetId" + WHERE + aaa."albumId" IS NULL + AND a."ownerId" = '${ownerId}' + AND e."dateTimeOriginal"::date BETWEEN '${startDate}' AND '${endDate}' + AND a."visibility" = 'timeline' + ${cityClause} + ORDER BY + e."dateTimeOriginal" ASC +`); +}; + +export const fetchTripAssets = async (ownerId: string, startDate: string, endDate: string, city: string | null) => { + const { rows } = await db.execute(SELECT_ORPHAN_RANGE(startDate, endDate, ownerId, city)); + return cleanRows(rows); +}; diff --git a/src/helpers/potentialAlbumsGrouping.helper.ts b/src/helpers/potentialAlbumsGrouping.helper.ts new file mode 100644 index 0000000..d456110 --- /dev/null +++ b/src/helpers/potentialAlbumsGrouping.helper.ts @@ -0,0 +1,92 @@ +// Grouping strategies for the Potential Albums list panel: group orphan +// assets either by single day, or by multi-day "trip" (consecutive away +// days). Both share one endpoint (potential-albums-dates.ts) via a +// `groupBy` param — this file holds the two DB-querying implementations. +import { db } from "@/config/db"; +import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; +import { assets } from "@/schema/assets.schema"; +import { exif } from "@/schema/exif.schema"; +import { and, avg, count, eq, isNotNull, isNull, sql } from "drizzle-orm"; +import { + ClusterOptions, + DaySignal, + DEFAULT_CLUSTER_OPTIONS, + clusterTrips, + computeHome, +} from "./trips.helper"; + +export interface DayGroupRow { + date: string; + asset_count: number; +} + +export const fetchDayGroups = async (ownerId: string): Promise => { + const rows = await db.select({ + date: sql`DATE(${exif.dateTimeOriginal})`, + asset_count: count(assets.id), + }).from(assets) + .leftJoin(albumsAssetsAssets, eq(assets.id, albumsAssetsAssets.assetId)) + .leftJoin(exif, eq(assets.id, exif.assetId)) + .where(and( + eq(assets.ownerId, ownerId), + eq(assets.visibility, "timeline"), + isNull(albumsAssetsAssets.albumId), + isNotNull(exif.dateTimeOriginal), + )) + .groupBy(sql`DATE(${exif.dateTimeOriginal})`) as DayGroupRow[]; + + return rows; +}; + +export interface TripGroupOptions extends Partial {} + +export const fetchTripGroups = async (ownerId: string, opts: TripGroupOptions = {}) => { + // Per-day aggregation: count, centroid, dominant city/country via PG MODE(). + const rows = (await db + .select({ + date: sql`TO_CHAR(DATE(${exif.dateTimeOriginal}), 'YYYY-MM-DD')`, + assetCount: count(assets.id), + centroidLat: avg(exif.latitude), + centroidLon: avg(exif.longitude), + cityMode: sql`MODE() WITHIN GROUP (ORDER BY ${exif.city})`, + countryMode: sql`MODE() WITHIN GROUP (ORDER BY ${exif.country})`, + }) + .from(assets) + .leftJoin(albumsAssetsAssets, eq(assets.id, albumsAssetsAssets.assetId)) + .leftJoin(exif, eq(assets.id, exif.assetId)) + .where( + and( + eq(assets.ownerId, ownerId), + eq(assets.visibility, "timeline"), + isNull(albumsAssetsAssets.albumId), + isNotNull(exif.dateTimeOriginal) + ) + ) + .groupBy(sql`DATE(${exif.dateTimeOriginal})`)) as Array<{ + date: string; + assetCount: number | string; + centroidLat: string | null; + centroidLon: string | null; + cityMode: string | null; + countryMode: string | null; + }>; + + const days: DaySignal[] = rows.map((r) => ({ + date: r.date, + assetCount: Number(r.assetCount), + cityMode: r.cityMode, + countryMode: r.countryMode, + centroidLat: r.centroidLat == null ? null : Number(r.centroidLat), + centroidLon: r.centroidLon == null ? null : Number(r.centroidLon), + })); + + const home = computeHome(days); + const trips = clusterTrips(days, { + home, + homeRadiusKm: opts.homeRadiusKm ?? DEFAULT_CLUSTER_OPTIONS.homeRadiusKm, + minTripDays: opts.minTripDays ?? DEFAULT_CLUSTER_OPTIONS.minTripDays, + gapTolerance: opts.gapTolerance ?? DEFAULT_CLUSTER_OPTIONS.gapTolerance, + }); + + return { home, trips }; +}; diff --git a/src/pages/api/albums/potential-albums-assets.ts b/src/pages/api/albums/potential-albums-assets.ts index 10832cc..933a3b1 100644 --- a/src/pages/api/albums/potential-albums-assets.ts +++ b/src/pages/api/albums/potential-albums-assets.ts @@ -1,61 +1,44 @@ -import { db } from "@/config/db"; +// Fetches orphan assets for the Potential Albums right-panel grid, either +// for a single day (default) or a date range (`?groupBy=trip`) — see +// src/helpers/potentialAlbumsAssets.helper.ts for the two implementations. import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; -import { isFlipped } from "@/helpers/asset.helper"; -import { sql } from "drizzle-orm"; +import { fetchDayAssets, fetchTripAssets } from "@/helpers/potentialAlbumsAssets.helper"; import type { NextApiRequest, NextApiResponse } from "next"; -const SELECT_ORPHAN_PHOTOS = (date: string, ownerId: string) => - sql.raw(` - SELECT - a."id", - a."ownerId", - a."deviceId", - a."type", - a."originalPath", - a."isFavorite", - a."duration", - a."originalFileName", - - a."thumbhash", - a."deletedAt", - e."exifImageWidth", - e."exifImageHeight", - e."dateTimeOriginal", - e."orientation" - FROM - asset a - LEFT JOIN - album_asset aaa - ON a.id = aaa."assetId" - LEFT JOIN - asset_exif e - ON a.id = e."assetId" - WHERE - aaa."albumId" IS NULL - AND a."ownerId" = '${ownerId}' - AND e."dateTimeOriginal"::date = '${date}' - AND a."visibility" = 'timeline' - ORDER BY - e."dateTimeOriginal" DESC -`); - export default async function handler( req: NextApiRequest, res: NextApiResponse ) { try { - const currentUser = await getCurrentUser(req) - const { startDate } = req.query as { startDate: string }; - const { rows } = await db.execute(SELECT_ORPHAN_PHOTOS(startDate, currentUser.id)); + const currentUser = await getCurrentUser(req); + if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); - const cleanedRows = rows.map((row: any) => { - return { - ...row, - exifImageWidth: isFlipped(row.orientation || 0) ? row.exifImageHeight : row.exifImageWidth, - exifImageHeight: isFlipped(row.orientation || 0) ? row.exifImageWidth : row.exifImageHeight, - }; - }); - return res.status(200).json(cleanedRows); + const { groupBy = "day", startDate, endDate, city } = req.query as { + groupBy?: string; + startDate?: string; + endDate?: string; + city?: string; + }; + + if (groupBy === "trip") { + if (!startDate || !endDate) { + return res.status(400).json({ error: "startDate and endDate are required (YYYY-MM-DD)" }); + } + // Interpolated into raw SQL below, so reject anything that isn't a + // plain date to keep this endpoint from becoming an injection vector. + const DATE_RE = /^\d{4}-\d{2}-\d{2}$/; + if (!DATE_RE.test(startDate) || !DATE_RE.test(endDate)) { + return res.status(400).json({ error: "Invalid date format, expected YYYY-MM-DD" }); + } + const cleaned = await fetchTripAssets(currentUser.id, startDate, endDate, city ?? null); + return res.status(200).json(cleaned); + } + + if (!startDate) { + return res.status(400).json({ error: "startDate is required (YYYY-MM-DD)" }); + } + const cleaned = await fetchDayAssets(currentUser.id, startDate); + return res.status(200).json(cleaned); } catch (error: any) { console.error(error); res.status(500).json({ diff --git a/src/pages/api/albums/potential-albums-dates.ts b/src/pages/api/albums/potential-albums-dates.ts index e9670aa..e612c76 100644 --- a/src/pages/api/albums/potential-albums-dates.ts +++ b/src/pages/api/albums/potential-albums-dates.ts @@ -1,37 +1,34 @@ // Next.js API route support: https://nextjs.org/docs/api-routes/introduction -import { db } from "@/config/db"; -import { IPotentialAlbumsDatesResponse } from "@/handlers/api/album.handler"; +// Groups orphan assets for the Potential Albums list panel, either by single +// day (default) or by trip (`?groupBy=trip`, consecutive away days) — see +// src/helpers/potentialAlbumsGrouping.helper.ts for the two implementations. import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; import { parseDate } from "@/helpers/date.helper"; -import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; -import { assets } from "@/schema/assets.schema"; -import { exif } from "@/schema/exif.schema"; -import { and, count, desc, eq, isNotNull, isNull, sql } from "drizzle-orm"; +import { fetchDayGroups, fetchTripGroups } from "@/helpers/potentialAlbumsGrouping.helper"; import type { NextApiRequest, NextApiResponse } from "next"; - export default async function handler( req: NextApiRequest, res: NextApiResponse ) { try { - const { sortBy = "date", sortOrder = "desc", minAssets = 1 } = req.query as any; - const currentUser = await getCurrentUser(req) - const rows = await db.select({ - date: sql`DATE(${exif.dateTimeOriginal})`, - asset_count: desc(count(assets.id)), - }).from(assets) - .leftJoin(albumsAssetsAssets, eq(assets.id, albumsAssetsAssets.assetId)) - .leftJoin(exif, eq(assets.id, exif.assetId)) - .where(and ( - eq(assets.ownerId, currentUser.id), - eq(assets.visibility, "timeline"), - isNull(albumsAssetsAssets.albumId), - isNotNull(exif.dateTimeOriginal), + const currentUser = await getCurrentUser(req); + if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); - )) - .groupBy(sql`DATE(${exif.dateTimeOriginal})`) as IPotentialAlbumsDatesResponse[]; - + const { groupBy = "day" } = req.query as { groupBy?: string }; + + if (groupBy === "trip") { + const { homeRadiusKm, minTripDays, gapTolerance } = req.query as Record; + const result = await fetchTripGroups(currentUser.id, { + homeRadiusKm: homeRadiusKm !== undefined ? Number(homeRadiusKm) : undefined, + minTripDays: minTripDays !== undefined ? Number(minTripDays) : undefined, + gapTolerance: gapTolerance !== undefined ? Number(gapTolerance) : undefined, + }); + return res.status(200).json(result); + } + + const { sortBy = "date", sortOrder = "desc", minAssets = 1 } = req.query as any; + const rows = await fetchDayGroups(currentUser.id); const filteredRows = rows.filter((row) => Number(row.asset_count) >= Number(minAssets)); if (sortBy === "date") { diff --git a/src/pages/api/albums/potential-trip-assets.ts b/src/pages/api/albums/potential-trip-assets.ts deleted file mode 100644 index c7bf238..0000000 --- a/src/pages/api/albums/potential-trip-assets.ts +++ /dev/null @@ -1,94 +0,0 @@ -// Fetch orphan assets that fall within a date range (for the Potential Trips view). -import { db } from "@/config/db"; -import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; -import { isFlipped } from "@/helpers/asset.helper"; -import { sql } from "drizzle-orm"; -import type { NextApiRequest, NextApiResponse } from "next"; - -// Optional `city` narrows the result to assets whose EXIF city matches the -// trip's dominant city. Assets with NULL city are included alongside the -// match: they may be photos taken during the trip but without GPS metadata -// (screenshots, edited copies, older devices, etc.) and excluding them would -// lose real trip content. If `city` is not provided the date range alone -// determines membership. -const SELECT_ORPHAN_RANGE = ( - startDate: string, - endDate: string, - ownerId: string, - city: string | null -) => { - const cityClause = city - ? `AND (e."city" = '${city.replace(/'/g, "''")}' OR e."city" IS NULL)` - : ""; - return sql.raw(` - SELECT - a."id", - a."ownerId", - a."type", - a."originalPath", - a."isFavorite", - a."duration", - a."originalFileName", - a."thumbhash", - a."deletedAt", - e."exifImageWidth", - e."exifImageHeight", - e."dateTimeOriginal", - e."orientation", - e."city", - e."country" - FROM - asset a - LEFT JOIN - album_asset aaa - ON a.id = aaa."assetId" - LEFT JOIN - asset_exif e - ON a.id = e."assetId" - WHERE - aaa."albumId" IS NULL - AND a."ownerId" = '${ownerId}' - AND e."dateTimeOriginal"::date BETWEEN '${startDate}' AND '${endDate}' - AND a."visibility" = 'timeline' - ${cityClause} - ORDER BY - e."dateTimeOriginal" ASC -`); -}; - -export default async function handler(req: NextApiRequest, res: NextApiResponse) { - try { - const currentUser = await getCurrentUser(req); - if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); - - const { startDate, endDate, city } = req.query as { - startDate?: string; - endDate?: string; - city?: string; - }; - if (!startDate || !endDate) { - return res.status(400).json({ error: "startDate and endDate are required (YYYY-MM-DD)" }); - } - // Basic format sanity (the strings are interpolated into the SQL literal, so - // reject anything that isn't YYYY-MM-DD to keep this endpoint from becoming - // an injection vector — same shape check the single-date endpoint should have.) - const DATE_RE = /^\d{4}-\d{2}-\d{2}$/; - if (!DATE_RE.test(startDate) || !DATE_RE.test(endDate)) { - return res.status(400).json({ error: "Invalid date format, expected YYYY-MM-DD" }); - } - - const { rows } = await db.execute( - SELECT_ORPHAN_RANGE(startDate, endDate, currentUser.id, city ?? null) - ); - - const cleaned = rows.map((row: any) => ({ - ...row, - exifImageWidth: isFlipped(row.orientation || 0) ? row.exifImageHeight : row.exifImageWidth, - exifImageHeight: isFlipped(row.orientation || 0) ? row.exifImageWidth : row.exifImageHeight, - })); - return res.status(200).json(cleaned); - } catch (error: any) { - console.error(error); - return res.status(500).json({ error: error?.message }); - } -} diff --git a/src/pages/api/albums/potential-trips.ts b/src/pages/api/albums/potential-trips.ts deleted file mode 100644 index ce59041..0000000 --- a/src/pages/api/albums/potential-trips.ts +++ /dev/null @@ -1,80 +0,0 @@ -// Potential trips — multi-day stretches of photos away from home. -// Companion to /api/albums/potential-albums-dates (which groups by single day). -import { db } from "@/config/db"; -import { getCurrentUser } from "@/handlers/serverUtils/user.utils"; -import { - DaySignal, - DEFAULT_CLUSTER_OPTIONS, - clusterTrips, - computeHome, -} from "@/helpers/trips.helper"; -import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema"; -import { assets } from "@/schema/assets.schema"; -import { exif } from "@/schema/exif.schema"; -import { and, avg, count, eq, isNotNull, isNull, sql } from "drizzle-orm"; -import type { NextApiRequest, NextApiResponse } from "next"; - -export default async function handler(req: NextApiRequest, res: NextApiResponse) { - try { - const { - homeRadiusKm = DEFAULT_CLUSTER_OPTIONS.homeRadiusKm, - minTripDays = DEFAULT_CLUSTER_OPTIONS.minTripDays, - gapTolerance = DEFAULT_CLUSTER_OPTIONS.gapTolerance, - } = req.query as Record; - - const currentUser = await getCurrentUser(req); - if (!currentUser) return res.status(401).json({ message: "Unauthorized" }); - - // Per-day aggregation: count, centroid, dominant city/country via PG MODE(). - const rows = (await db - .select({ - date: sql`TO_CHAR(DATE(${exif.dateTimeOriginal}), 'YYYY-MM-DD')`, - assetCount: count(assets.id), - centroidLat: avg(exif.latitude), - centroidLon: avg(exif.longitude), - cityMode: sql`MODE() WITHIN GROUP (ORDER BY ${exif.city})`, - countryMode: sql`MODE() WITHIN GROUP (ORDER BY ${exif.country})`, - }) - .from(assets) - .leftJoin(albumsAssetsAssets, eq(assets.id, albumsAssetsAssets.assetId)) - .leftJoin(exif, eq(assets.id, exif.assetId)) - .where( - and( - eq(assets.ownerId, currentUser.id), - eq(assets.visibility, "timeline"), - isNull(albumsAssetsAssets.albumId), - isNotNull(exif.dateTimeOriginal) - ) - ) - .groupBy(sql`DATE(${exif.dateTimeOriginal})`)) as Array<{ - date: string; - assetCount: number | string; - centroidLat: string | null; - centroidLon: string | null; - cityMode: string | null; - countryMode: string | null; - }>; - - const days: DaySignal[] = rows.map((r) => ({ - date: r.date, - assetCount: Number(r.assetCount), - cityMode: r.cityMode, - countryMode: r.countryMode, - centroidLat: r.centroidLat == null ? null : Number(r.centroidLat), - centroidLon: r.centroidLon == null ? null : Number(r.centroidLon), - })); - - const home = computeHome(days); - const trips = clusterTrips(days, { - home, - homeRadiusKm: Number(homeRadiusKm), - minTripDays: Number(minTripDays), - gapTolerance: Number(gapTolerance), - }); - - return res.status(200).json({ home, trips }); - } catch (error: any) { - console.error(error); - return res.status(500).json({ error: error?.message }); - } -}