diff --git a/src/components/albums/AlbumSelectorDialog.tsx b/src/components/albums/AlbumSelectorDialog.tsx index 2f8b7b3..749ad06 100644 --- a/src/components/albums/AlbumSelectorDialog.tsx +++ b/src/components/albums/AlbumSelectorDialog.tsx @@ -20,18 +20,37 @@ 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 ?? "", }); + // 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 ?? ""; + if (!next) return; + if (lastSuggestionRef.current === next) return; + lastSuggestionRef.current = next; + setFormData({ 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..c261847 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, tripCity } = 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, tripCity) + : 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, tripCity]); 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 2a6478e..5111d13 100644 --- a/src/config/routes.ts +++ b/src/config/routes.ts @@ -18,6 +18,8 @@ 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_ALBUMS_PATH = BASE_API_ENDPOINT + "/albums/list"; diff --git a/src/contexts/PhotoSelectionContext.tsx b/src/contexts/PhotoSelectionContext.tsx index b70bef8..e9f6acf 100644 --- a/src/contexts/PhotoSelectionContext.tsx +++ b/src/contexts/PhotoSelectionContext.tsx @@ -6,6 +6,11 @@ import { createContext, useContext } from "react"; 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; // MissingLocation specific config albumId?: string; diff --git a/src/handlers/api/album.handler.ts b/src/handlers/api/album.handler.ts index 2179afb..944d2f5 100644 --- a/src/handlers/api/album.handler.ts +++ b/src/handlers/api/album.handler.ts @@ -24,6 +24,42 @@ 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_ALBUMS_DATES_PATH, { ...filters, groupBy: "trip" }); +} + +export const listPotentialTripAssets = async ( + startDate: string, + endDate: string, + city?: string | null, +): Promise => { + const params: Record = { startDate, endDate, groupBy: "trip" }; + if (city) params.city = city; + return API.get(LIST_POTENTIAL_ALBUMS_ASSETS_PATH, params).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/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/helpers/trips.helper.ts b/src/helpers/trips.helper.ts new file mode 100644 index 0000000..4fde3e4 --- /dev/null +++ b/src/helpers/trips.helper.ts @@ -0,0 +1,205 @@ +/** + * 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. + */ + +import { differenceInCalendarDays, parseISO } from "date-fns"; + +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; + } + // 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; + 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); + 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..f03c48f 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,30 @@ export default function PotentialAlbums() { }} >
- + + + Days + Trips + + + + + + + updateContext({ + config: { + ...contextState.config, + startDate: trip.startDate, + endDate: trip.endDate, + tripCity: trip.cityName, + suggestedAlbumName: trip.suggestedName, + }, + }) + } + /> + +
{selectedAssets.length > 0 && @@ -175,7 +201,11 @@ export default function PotentialAlbums() { Select all )} - +
diff --git a/src/pages/api/albums/potential-albums-assets.ts b/src/pages/api/albums/potential-albums-assets.ts index 89d078f..933a3b1 100644 --- a/src/pages/api/albums/potential-albums-assets.ts +++ b/src/pages/api/albums/potential-albums-assets.ts @@ -1,60 +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."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") {