Merge pull request #268 from dgilperez/feat/potential-trips
feat(potential-albums): add Trips view that groups consecutive away days
This commit is contained in:
12 files changed
+691
-82
No files matched your search
@@ -20,18 +20,37 @@ interface IProps {
|
||||
onSelected: (album: IAlbum) => Promise<void>;
|
||||
onCreated?: (album: IAlbum) => Promise<void>;
|
||||
onSubmit?: (data: IAlbumCreate) => Promise<any>;
|
||||
/**
|
||||
* 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<IAlbum[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(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<string | null>(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()
|
||||
|
||||
@@ -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<string | null>(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 (
|
||||
|
||||
@@ -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<IPotentialTripsResponse | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(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 (
|
||||
<div className="p-4 flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader className="h-4 w-4 animate-spin" /> Computing trips…
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (errorMessage) {
|
||||
return <p className="p-4 text-sm text-destructive">{errorMessage}</p>;
|
||||
}
|
||||
|
||||
if (!data || data.trips.length === 0) {
|
||||
return (
|
||||
<div className="p-4 text-sm text-muted-foreground">
|
||||
<p className="mb-2">No trips detected.</p>
|
||||
<p className="text-xs">
|
||||
A trip is ≥{" "}
|
||||
<span className="font-mono">
|
||||
{data?.home?.city ? "2" : "—"}
|
||||
</span>{" "}
|
||||
consecutive days of photos taken away from your home location
|
||||
{data?.home?.city ? (
|
||||
<>
|
||||
{" "}
|
||||
(currently <span className="font-mono">{data.home.city}</span>)
|
||||
</>
|
||||
) : null}
|
||||
. If your library has no GPS data, this view will stay empty — use
|
||||
the <em>Days</em> tab instead.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col divide-y">
|
||||
{data.trips.map((t) => {
|
||||
const isActive = activeStart === t.startDate && activeEnd === t.endDate;
|
||||
return (
|
||||
<button
|
||||
key={`${t.startDate}-${t.endDate}`}
|
||||
type="button"
|
||||
onClick={() => handleSelect(t)}
|
||||
className={`flex flex-col items-start gap-0.5 px-4 py-3 text-left hover:bg-zinc-100 dark:hover:bg-zinc-900 ${
|
||||
isActive ? "bg-zinc-100 dark:bg-zinc-900" : ""
|
||||
}`}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<Plane className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span className="text-sm font-semibold">{t.suggestedName}</span>
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground flex items-center gap-2 pl-5">
|
||||
<span>
|
||||
{format(parseISO(t.startDate), "MMM d")} –{" "}
|
||||
{format(parseISO(t.endDate), "MMM d, yyyy")}
|
||||
</span>
|
||||
<span>·</span>
|
||||
<span>{t.assetCount} assets</span>
|
||||
<span>·</span>
|
||||
<span>{t.dayCount} days</span>
|
||||
</div>
|
||||
{t.cityName || t.countryName ? (
|
||||
<div className="text-xs text-muted-foreground flex items-center gap-1 pl-5">
|
||||
<MapPin className="h-3 w-3" />
|
||||
{[t.cityName, t.countryName].filter(Boolean).join(", ")}
|
||||
</div>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{data.home.city ? (
|
||||
<div className="px-4 py-2 text-[11px] text-muted-foreground border-t">
|
||||
Home: <span className="font-mono">{data.home.city}</span>
|
||||
{data.home.lat != null && data.home.lon != null ? (
|
||||
<>
|
||||
{" "}
|
||||
({data.home.lat.toFixed(2)}, {data.home.lon.toFixed(2)})
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<IPotentialTripsResponse> => {
|
||||
return API.get(LIST_POTENTIAL_ALBUMS_DATES_PATH, { ...filters, groupBy: "trip" });
|
||||
}
|
||||
|
||||
export const listPotentialTripAssets = async (
|
||||
startDate: string,
|
||||
endDate: string,
|
||||
city?: string | null,
|
||||
): Promise<IAsset[]> => {
|
||||
const params: Record<string, string> = { 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);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
};
|
||||
@@ -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<DayGroupRow[]> => {
|
||||
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<ClusterOptions> {}
|
||||
|
||||
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<string>`TO_CHAR(DATE(${exif.dateTimeOriginal}), 'YYYY-MM-DD')`,
|
||||
assetCount: count(assets.id),
|
||||
centroidLat: avg(exif.latitude),
|
||||
centroidLon: avg(exif.longitude),
|
||||
cityMode: sql<string | null>`MODE() WITHIN GROUP (ORDER BY ${exif.city})`,
|
||||
countryMode: sql<string | null>`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 };
|
||||
};
|
||||
@@ -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<ClusterOptions, "home"> = {
|
||||
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<string, number>();
|
||||
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<T, K>(items: T[], weight: (t: T) => number, key: (t: T) => K | null): K | null {
|
||||
const counts = new Map<K, number>();
|
||||
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;
|
||||
}
|
||||
@@ -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<IPhotoSelectionContext>({
|
||||
selectedIds: [],
|
||||
assets: [],
|
||||
config: {
|
||||
startDate: startDate || undefined,
|
||||
endDate: endDate || undefined,
|
||||
minAssets: 1,
|
||||
},
|
||||
updateContext: (newConfig: Partial<IPhotoSelectionContext>) => {
|
||||
@@ -140,7 +143,30 @@ export default function PotentialAlbums() {
|
||||
}}
|
||||
>
|
||||
<div className="flex divide-y">
|
||||
<PotentialAlbumsDates />
|
||||
<Tabs defaultValue={endDate ? "trips" : "days"} className="min-w-[280px] max-w-[340px] border-r">
|
||||
<TabsList className="w-full grid grid-cols-2 rounded-none">
|
||||
<TabsTrigger value="days">Days</TabsTrigger>
|
||||
<TabsTrigger value="trips">Trips</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="days" className="m-0">
|
||||
<PotentialAlbumsDates />
|
||||
</TabsContent>
|
||||
<TabsContent value="trips" className="m-0">
|
||||
<PotentialTrips
|
||||
onSelectTrip={(trip: IPotentialTrip) =>
|
||||
updateContext({
|
||||
config: {
|
||||
...contextState.config,
|
||||
startDate: trip.startDate,
|
||||
endDate: trip.endDate,
|
||||
tripCity: trip.cityName,
|
||||
suggestedAlbumName: trip.suggestedName,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<PotentialAlbumsAssets />
|
||||
</div>
|
||||
{selectedAssets.length > 0 &&
|
||||
@@ -175,7 +201,11 @@ export default function PotentialAlbums() {
|
||||
Select all
|
||||
</Button>
|
||||
)}
|
||||
<AlbumSelectorDialog onSelected={handleSelect} onSubmit={handleCreate} />
|
||||
<AlbumSelectorDialog
|
||||
onSelected={handleSelect}
|
||||
onSubmit={handleCreate}
|
||||
defaultName={contextState.config.suggestedAlbumName}
|
||||
/>
|
||||
<AssetOffsetDialog assets={selectedAssets} onComplete={handleOffsetComplete} />
|
||||
<div className="h-[10px] w-[1px] bg-zinc-500 dark:bg-zinc-600"></div>
|
||||
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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<string, string | undefined>;
|
||||
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") {
|
||||
|
||||
Reference in new issue
Block a user