mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
feat(journey): create draft entries from gallery photos
Groups the gallery photos on no entry by local day, then by time gap and distance, names each group through the geocoder (capped per preview, with the country or the day as fallback) and writes the groups the traveller keeps as draft entries with their photos in one transaction. Photos put on an entry meanwhile or named twice are left out and reported; existing entries are never touched. REST routes under /api/journeys/:id/entries/from-photos and the MCP tools preview_journey_entries_from_photos and create_journey_entries_from_photos share one service and the journey edit right (#1920).
This commit is contained in:
@@ -43,6 +43,18 @@ export interface JourneyPublicAssetValidationRow {
|
||||
journey_owner_id: number;
|
||||
}
|
||||
|
||||
/** A gallery photo on no entry, as {@link JourneyPhotosRepository.listOffEntries} reads it. */
|
||||
export interface JourneyPhotoOffEntryRow {
|
||||
/** The gallery row (journey photo id). */
|
||||
id: number;
|
||||
photo_id: number;
|
||||
/** ISO capture instant; null when the photo does not know it (an empty value reads as null). */
|
||||
taken_at: string | null;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
media_type: string;
|
||||
}
|
||||
|
||||
/** `GALLERY_SELECT`'s exact column list (`journey-domain.service.ts`'s module const), aliased `gp`/`tp` — shared by every gallery-shaped read below. */
|
||||
const GALLERY_COLUMNS = [
|
||||
'gp.id',
|
||||
@@ -420,6 +432,41 @@ export class JourneyPhotosRepository extends TrekRepository<JourneyPhotos> {
|
||||
return row as GalleryPhoto | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The gallery photos of a journey that sit on no entry (of any kind, a
|
||||
* suggestion included), with when and where they were taken: what the
|
||||
* journal can still make entries of (#1920). A photo without a capture
|
||||
* time comes back too, with `taken_at` null, so the caller can count it.
|
||||
* In gallery-row order, which the caller re-sorts by capture time.
|
||||
*/
|
||||
async listOffEntries(journeyId: number): Promise<JourneyPhotoOffEntryRow[]> {
|
||||
const rows = await this.kysely<GalleryKyselyDB>()
|
||||
.selectFrom('journey_photos as gp')
|
||||
.innerJoin('trek_photos as tp', 'tp.id', 'gp.photo_id')
|
||||
.select(['gp.id', 'gp.photo_id', 'tp.taken_at', 'tp.lat', 'tp.lng', 'tp.media_type'])
|
||||
.where('gp.journey_id', '=', journeyId)
|
||||
.where((eb) =>
|
||||
eb.not(
|
||||
eb.exists(
|
||||
eb
|
||||
.selectFrom('journey_entry_photos as jep')
|
||||
.select('jep.entry_id')
|
||||
.whereRef('jep.journey_photo_id', '=', 'gp.id'),
|
||||
),
|
||||
),
|
||||
)
|
||||
.orderBy('gp.id', 'asc')
|
||||
.execute();
|
||||
return rows.map((row) => ({
|
||||
id: row.id,
|
||||
photo_id: row.photo_id,
|
||||
taken_at: row.taken_at || null,
|
||||
lat: row.lat ?? null,
|
||||
lng: row.lng ?? null,
|
||||
media_type: row.media_type,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* JG19 — `getJourneyFull`'s gallery read, folding in `GALLERY_CHRONOLOGICAL_ORDER`
|
||||
* (R1). Task 1's report left this raw for this task to finish (its own
|
||||
|
||||
@@ -59,6 +59,7 @@ import { AirtrailModule } from './integrations/airtrail.module';
|
||||
import { DawarichModule } from './integrations/dawarich.module';
|
||||
import { JourneyRecordingsModule } from './journey-recordings/journey-recordings.module';
|
||||
import { JourneyAccessModule } from './journey/journey-access.module';
|
||||
import { JourneyEntriesFromPhotosModule } from './journey/journey-entries-from-photos.module';
|
||||
import { JourneyModule } from './journey/journey.module';
|
||||
import { TripJournalLinkModule } from './journey/trip-journal-link.module';
|
||||
import { LlmParseModule } from './llm-parse/llm-parse.module';
|
||||
@@ -206,6 +207,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
|
||||
DawarichModule,
|
||||
JourneyModule,
|
||||
JourneyRecordingsModule,
|
||||
JourneyEntriesFromPhotosModule,
|
||||
TripJournalLinkModule,
|
||||
CollectionsModule,
|
||||
PlacesLibraryModule,
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { User } from '../../types';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { rowId } from '../common/row-id.pipe';
|
||||
import { JourneyEntriesFromPhotosService } from './journey-entries-from-photos.service';
|
||||
import { JourneyEntriesFromPhotosCreateDto, JourneyEntriesFromPhotosPreviewDto } from './journey.dto';
|
||||
import { Body, Controller, Headers, HttpCode, Param, Post, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
journeyEntriesFromPhotosCreateResponseSchema,
|
||||
journeyEntriesFromPhotosPreviewResponseSchema,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* Draft entries made from the photos of a journey's gallery (#1920), at
|
||||
* `/api/journeys/:id/entries/from-photos`. Both need the right to edit the
|
||||
* journey (404 for one the caller cannot see, 403 for a viewer). The preview
|
||||
* is a POST because it takes options and asks the geocoder; it writes
|
||||
* nothing. The create answers 200 with what it wrote and what it left out.
|
||||
*/
|
||||
@Controller('api/journeys/:id/entries/from-photos')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard)
|
||||
@RequireAddon(ADDON_IDS.JOURNEY, 'Journey')
|
||||
export class JourneyEntriesFromPhotosController {
|
||||
constructor(private readonly fromPhotos: JourneyEntriesFromPhotosService) {}
|
||||
|
||||
@Post('preview')
|
||||
@HttpCode(200)
|
||||
@ResponseContract(journeyEntriesFromPhotosPreviewResponseSchema)
|
||||
async preview(
|
||||
@CurrentUser() user: User,
|
||||
@Param('id', rowId('Journey not found')) id: number,
|
||||
@Body() body: JourneyEntriesFromPhotosPreviewDto,
|
||||
) {
|
||||
return await this.fromPhotos.preview(user.id, id, body);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@HttpCode(200)
|
||||
@ResponseContract(journeyEntriesFromPhotosCreateResponseSchema)
|
||||
async create(
|
||||
@CurrentUser() user: User,
|
||||
@Param('id', rowId('Journey not found')) id: number,
|
||||
@Body() body: JourneyEntriesFromPhotosCreateDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return await this.fromPhotos.create(user.id, id, body, socketId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
import { haversineKm } from '../common/geo';
|
||||
import { localParts, resolveTimeZone } from '../common/timezoneService';
|
||||
|
||||
/**
|
||||
* The pure half of making journal entries from gallery photos (#1920): when
|
||||
* each photo was taken on the local clock, and how a day's photos fall into
|
||||
* groups. No database, no network; the service and its tests share it.
|
||||
*/
|
||||
|
||||
/** A gallery photo on no entry that knows when it was taken. */
|
||||
export interface FromPhotosPhoto {
|
||||
/** The gallery row (journey photo id). */
|
||||
id: number;
|
||||
/** The capture instant as stored: ISO 8601, with `Z`, an offset or neither. */
|
||||
takenAt: string;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
mediaType: string;
|
||||
}
|
||||
|
||||
/** A photo placed on the local clock of the zone its day is read in. */
|
||||
export interface LocalCapture extends FromPhotosPhoto {
|
||||
/** Milliseconds since the epoch. */
|
||||
instant: number;
|
||||
/** `YYYY-MM-DD` and `HH:MM` on that clock. */
|
||||
date: string;
|
||||
time: string;
|
||||
/** An IANA zone name, or `UTC+02:00` for an offset the capture time carried. */
|
||||
zone: string;
|
||||
/** Whether lat/lng are a usable position. */
|
||||
located: boolean;
|
||||
}
|
||||
|
||||
interface ClusterThresholds {
|
||||
maxGapMinutes: number;
|
||||
maxDistanceKm: number;
|
||||
}
|
||||
|
||||
/** What one group of photos becomes, before it has a title. */
|
||||
export interface ClusterSummary {
|
||||
date: string;
|
||||
startTime: string;
|
||||
endTime: string;
|
||||
zone: string;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
photoIds: number[];
|
||||
coverPhotoId: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* How far in time the nearest geotagged photo may be for a photo without a
|
||||
* position to borrow its zone. Further away, it may well have been taken
|
||||
* somewhere else, and the caller's zone is as good a guess.
|
||||
*/
|
||||
const BORROWED_ZONE_WINDOW_MS = 72 * 60 * 60 * 1000;
|
||||
|
||||
/** An offset written after a clock time: `+02:00`, `-0530`. `Z` is not one (see {@link carriedOffsetMinutes}). */
|
||||
const CARRIED_OFFSET = /T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?([+-])(\d{2}):?(\d{2})$/;
|
||||
|
||||
/**
|
||||
* The offset a stored capture time carries, in minutes east of UTC, or null.
|
||||
*
|
||||
* `Z` counts as no offset on purpose: TREK's own EXIF reader and the photo
|
||||
* libraries hand over the instant converted to UTC, so a `Z` says nothing
|
||||
* about the clock the photo was taken on. An explicit `+02:00` does.
|
||||
*/
|
||||
export function carriedOffsetMinutes(takenAt: string): number | null {
|
||||
const m = CARRIED_OFFSET.exec(takenAt.trim());
|
||||
if (!m) return null;
|
||||
const hours = Number(m[2]);
|
||||
const minutes = Number(m[3]);
|
||||
if (hours > 14 || minutes > 59) return null;
|
||||
return (m[1] === '-' ? -1 : 1) * (hours * 60 + minutes);
|
||||
}
|
||||
|
||||
/** Whether a pair is a position: finite, on the globe, and not the 0,0 a receiver without a fix writes. */
|
||||
export function isLocated(lat: number | null, lng: number | null): boolean {
|
||||
if (lat === null || lng === null || !Number.isFinite(lat) || !Number.isFinite(lng)) return false;
|
||||
if (Math.abs(lat) > 90 || Math.abs(lng) > 180) return false;
|
||||
return !(lat === 0 && lng === 0);
|
||||
}
|
||||
|
||||
function offsetLabel(minutes: number): string {
|
||||
const sign = minutes < 0 ? '-' : '+';
|
||||
const abs = Math.abs(minutes);
|
||||
const hh = String(Math.floor(abs / 60)).padStart(2, '0');
|
||||
const mm = String(abs % 60).padStart(2, '0');
|
||||
return `UTC${sign}${hh}:${mm}`;
|
||||
}
|
||||
|
||||
/** The local date and time of an instant at a fixed offset. */
|
||||
function atOffset(instant: number, minutes: number): { date: string; time: string } {
|
||||
const shifted = new Date(instant + minutes * 60_000).toISOString();
|
||||
return { date: shifted.slice(0, 10), time: shifted.slice(11, 16) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Every photo on the clock its day is read on. In order of preference: the
|
||||
* offset its capture time carries; the zone of the place it was taken; the
|
||||
* zone of the geotagged photo of the same set nearest in time (within three
|
||||
* days), since TREK keeps no zone on a journey or a trip; `fallbackZone` (the
|
||||
* caller's device zone, already checked to be a known one); UTC. A photo
|
||||
* whose capture time does not parse is left out.
|
||||
*/
|
||||
export function localCaptures(photos: readonly FromPhotosPhoto[], fallbackZone: string | null): LocalCapture[] {
|
||||
const parsed = photos
|
||||
.map((photo) => ({ photo, instant: Date.parse(photo.takenAt) }))
|
||||
.filter((p) => Number.isFinite(p.instant));
|
||||
// The zones the photos' own positions name, for those without one to borrow.
|
||||
const geoZones = parsed
|
||||
.map((p) => ({
|
||||
instant: p.instant,
|
||||
zone: isLocated(p.photo.lat, p.photo.lng) ? resolveTimeZone(p.photo.lat, p.photo.lng) : null,
|
||||
}))
|
||||
.filter((z): z is { instant: number; zone: string } => z.zone !== null);
|
||||
|
||||
const borrowed = (instant: number): string | null => {
|
||||
let best: { distance: number; zone: string } | null = null;
|
||||
for (const candidate of geoZones) {
|
||||
const distance = Math.abs(candidate.instant - instant);
|
||||
if (distance <= BORROWED_ZONE_WINDOW_MS && (!best || distance < best.distance)) {
|
||||
best = { distance, zone: candidate.zone };
|
||||
}
|
||||
}
|
||||
return best?.zone ?? null;
|
||||
};
|
||||
|
||||
return parsed.map(({ photo, instant }) => {
|
||||
const located = isLocated(photo.lat, photo.lng);
|
||||
const offset = carriedOffsetMinutes(photo.takenAt);
|
||||
if (offset !== null) return { ...photo, instant, ...atOffset(instant, offset), zone: offsetLabel(offset), located };
|
||||
const zone = (located ? resolveTimeZone(photo.lat, photo.lng) : null) ?? borrowed(instant) ?? fallbackZone ?? 'UTC';
|
||||
const parts = localParts(new Date(instant).toISOString(), zone);
|
||||
// localParts answers nulls only for a zone the runtime does not know; UTC then.
|
||||
if (!parts.date || !parts.time) return { ...photo, instant, ...atOffset(instant, 0), zone: 'UTC', located };
|
||||
return { ...photo, instant, date: parts.date, time: parts.time, zone, located };
|
||||
});
|
||||
}
|
||||
|
||||
const byInstant = (a: LocalCapture, b: LocalCapture) => a.instant - b.instant || a.id - b.id;
|
||||
|
||||
/**
|
||||
* The photos of one local day in groups. The geotagged ones are walked in
|
||||
* the order they were taken, and a new group starts where the time to the
|
||||
* previous one exceeds the gap or the distance to the previous one exceeds
|
||||
* the distance. A photo without a position then joins the group of its day
|
||||
* nearest to it in time (one it falls inside of first, the earlier one on a
|
||||
* tie). A day with no geotagged photo at all is cut by time alone.
|
||||
*/
|
||||
function clusterDay(day: LocalCapture[], thresholds: ClusterThresholds): LocalCapture[][] {
|
||||
const gapMs = thresholds.maxGapMinutes * 60_000;
|
||||
const located = day.filter((c) => c.located);
|
||||
const unlocated = day.filter((c) => !c.located);
|
||||
const clusters: LocalCapture[][] = [];
|
||||
const walk = (photos: LocalCapture[], byDistance: boolean) => {
|
||||
let current: LocalCapture[] = [];
|
||||
for (const photo of photos) {
|
||||
const last = current[current.length - 1];
|
||||
const tooLate = last !== undefined && photo.instant - last.instant > gapMs;
|
||||
const tooFar =
|
||||
byDistance &&
|
||||
last !== undefined &&
|
||||
haversineKm(last.lat as number, last.lng as number, photo.lat as number, photo.lng as number) >
|
||||
thresholds.maxDistanceKm;
|
||||
if (last !== undefined && (tooLate || tooFar)) {
|
||||
clusters.push(current);
|
||||
current = [];
|
||||
}
|
||||
current.push(photo);
|
||||
}
|
||||
if (current.length) clusters.push(current);
|
||||
};
|
||||
|
||||
if (!located.length) {
|
||||
walk(unlocated, false);
|
||||
return clusters;
|
||||
}
|
||||
walk(located, true);
|
||||
for (const photo of unlocated) {
|
||||
let best: { distance: number; cluster: LocalCapture[] } | null = null;
|
||||
for (const cluster of clusters) {
|
||||
const first = (cluster[0] as LocalCapture).instant;
|
||||
const last = (cluster[cluster.length - 1] as LocalCapture).instant;
|
||||
const distance = photo.instant < first ? first - photo.instant : Math.max(0, photo.instant - last);
|
||||
if (!best || distance < best.distance) best = { distance, cluster };
|
||||
}
|
||||
(best as { cluster: LocalCapture[] }).cluster.push(photo);
|
||||
}
|
||||
for (const cluster of clusters) cluster.sort(byInstant);
|
||||
return clusters;
|
||||
}
|
||||
|
||||
/** The photos in groups: by local day first, then by time and distance inside a day, in the order they were lived. */
|
||||
export function clusterCaptures(captures: readonly LocalCapture[], thresholds: ClusterThresholds): LocalCapture[][] {
|
||||
const days = new Map<string, LocalCapture[]>();
|
||||
for (const capture of [...captures].sort(byInstant)) {
|
||||
const day = days.get(capture.date);
|
||||
if (day) day.push(capture);
|
||||
else days.set(capture.date, [capture]);
|
||||
}
|
||||
return [...days.values()]
|
||||
.flatMap((day) => clusterDay(day, thresholds))
|
||||
.sort((a, b) => byInstant(a[0] as LocalCapture, b[0] as LocalCapture));
|
||||
}
|
||||
|
||||
const round6 = (value: number) => Math.round(value * 1e6) / 1e6;
|
||||
|
||||
/**
|
||||
* The middle of the geotagged photos, or null. The longitude is a circular
|
||||
* mean, so a group either side of the antimeridian is not put on the far
|
||||
* side of the globe.
|
||||
*/
|
||||
export function centroid(points: readonly { lat: number; lng: number }[]): { lat: number; lng: number } | null {
|
||||
if (!points.length) return null;
|
||||
const toRad = Math.PI / 180;
|
||||
let lat = 0;
|
||||
let sin = 0;
|
||||
let cos = 0;
|
||||
for (const p of points) {
|
||||
lat += p.lat;
|
||||
sin += Math.sin(p.lng * toRad);
|
||||
cos += Math.cos(p.lng * toRad);
|
||||
}
|
||||
return { lat: round6(lat / points.length), lng: round6(Math.atan2(sin, cos) / toRad) };
|
||||
}
|
||||
|
||||
/**
|
||||
* One group's day, times, middle and cover. The group's day and zone are its
|
||||
* first photo's; its photos are in the order they were taken. The cover is
|
||||
* its first picture, a clip only when it holds nothing else.
|
||||
*/
|
||||
export function summarizeCluster(cluster: readonly LocalCapture[]): ClusterSummary {
|
||||
const sorted = [...cluster].sort(byInstant);
|
||||
const first = sorted[0] as LocalCapture;
|
||||
const last = sorted[sorted.length - 1] as LocalCapture;
|
||||
const middle = centroid(sorted.filter((c) => c.located) as { lat: number; lng: number }[]);
|
||||
const cover = sorted.find((c) => c.mediaType !== 'video') ?? first;
|
||||
return {
|
||||
date: first.date,
|
||||
startTime: first.time,
|
||||
endTime: last.date === first.date ? last.time : first.time,
|
||||
zone: first.zone,
|
||||
lat: middle?.lat ?? null,
|
||||
lng: middle?.lng ?? null,
|
||||
photoIds: sorted.map((c) => c.id),
|
||||
coverPhotoId: cover.id,
|
||||
};
|
||||
}
|
||||
|
||||
/** Intl.DisplayNames for the language, English when the runtime does not know it, null without ICU data. */
|
||||
function regionNames(lang: string | undefined): Intl.DisplayNames | null {
|
||||
for (const locale of [lang, 'en']) {
|
||||
if (!locale) continue;
|
||||
try {
|
||||
return new Intl.DisplayNames([locale], { type: 'region', fallback: 'none' });
|
||||
} catch {
|
||||
// An unknown tag: the next one.
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** A date written out in the language ('14 May 2026'), the ISO day when the runtime cannot. */
|
||||
function spelledDate(date: string, lang: string | undefined): string {
|
||||
for (const locale of [lang, 'en']) {
|
||||
if (!locale) continue;
|
||||
try {
|
||||
return new Intl.DateTimeFormat(locale, {
|
||||
day: 'numeric',
|
||||
month: 'long',
|
||||
year: 'numeric',
|
||||
timeZone: 'UTC',
|
||||
}).format(new Date(`${date}T00:00:00Z`));
|
||||
} catch {
|
||||
// An unknown tag: the next one.
|
||||
}
|
||||
}
|
||||
return date;
|
||||
}
|
||||
|
||||
/**
|
||||
* The title a group gets when no place name was found for it: the country it
|
||||
* lies in, named in the language, else its day written out.
|
||||
*/
|
||||
export function fallbackTitle(
|
||||
countryCode: string | null,
|
||||
date: string,
|
||||
lang: string | undefined,
|
||||
): { title: string; source: 'country' | 'date' } {
|
||||
const tag = intlLanguage(lang);
|
||||
if (countryCode) {
|
||||
const name = regionNames(tag)?.of(countryCode.toUpperCase());
|
||||
if (name) return { title: name, source: 'country' };
|
||||
}
|
||||
return { title: spelledDate(date, tag), source: 'date' };
|
||||
}
|
||||
|
||||
/**
|
||||
* The two TREK language codes that are not the BCP-47 tag of their language:
|
||||
* `br` is Brazilian Portuguese (bare `br` is Breton) and `gr` is Greek. An MCP
|
||||
* client may send either; the app sends the BCP-47 locale.
|
||||
*/
|
||||
const TREK_LANGUAGE_TAGS: Readonly<Record<string, string>> = { br: 'pt-BR', gr: 'el' };
|
||||
|
||||
/** The BCP-47 tag Intl reads for a language a caller named. */
|
||||
export function intlLanguage(lang: string | undefined): string | undefined {
|
||||
if (!lang) return undefined;
|
||||
return TREK_LANGUAGE_TAGS[lang] ?? lang;
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import {
|
||||
McpController,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
Tool,
|
||||
ok,
|
||||
type McpContext,
|
||||
} from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { JourneyEntriesFromPhotosService } from './journey-entries-from-photos.service';
|
||||
import {
|
||||
idSchema,
|
||||
journeyEntriesFromPhotosCreateRequestSchema,
|
||||
journeyEntriesFromPhotosPreviewRequestSchema,
|
||||
type JourneyEntriesFromPhotosCreateRequest,
|
||||
type JourneyEntriesFromPhotosPreviewRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
const journeyAddonOn = addonGate(ADDON_IDS.JOURNEY);
|
||||
|
||||
/**
|
||||
* Draft entries made from the photos of a journey's gallery (#1920) over MCP:
|
||||
* the same service, the same edit right on the journey and the same events as
|
||||
* POST `/api/journeys/:id/entries/from-photos/preview` and
|
||||
* POST `/api/journeys/:id/entries/from-photos`.
|
||||
*/
|
||||
@McpController()
|
||||
export class JourneyEntriesFromPhotosMcp {
|
||||
constructor(
|
||||
private readonly fromPhotos: JourneyEntriesFromPhotosService,
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'preview_journey_entries_from_photos',
|
||||
description:
|
||||
"Group the photos of a journey's gallery that are on no entry yet and know when they were taken into proposed journal entries, without writing anything. Photos are grouped by local day (read in the offset the capture time carries, else the zone of the place it was taken, else the zone of the journey's geotagged photo nearest in time, else timezone, else UTC), then split inside a day where two photos are more than maxGapMinutes (default 180) or two geotagged ones more than maxDistanceKm (default 20) apart; a photo without a position joins the group of its day nearest in time. Each group has its date, start and end time, the middle of its geotagged photos with the country, a suggested title (a place name in lang, else the country, else the day), the journey photo ids and a cover photo. withoutCaptureTime counts the photos that belong to no group. Needs edit access to the journey.",
|
||||
inputSchema: { journeyId: idSchema, ...journeyEntriesFromPhotosPreviewRequestSchema.shape },
|
||||
// Asks the geocoder for place names; nothing of the journey changes.
|
||||
annotations: { ...TOOL_ANNOTATIONS_READONLY, openWorldHint: true },
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'read' },
|
||||
})
|
||||
async previewEntriesFromPhotos(
|
||||
{ journeyId, ...request }: { journeyId: number } & JourneyEntriesFromPhotosPreviewRequest,
|
||||
ctx: McpContext,
|
||||
) {
|
||||
return ok(await this.fromPhotos.preview(ctx.userId, journeyId, request));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'create_journey_entries_from_photos',
|
||||
description:
|
||||
"Write draft journal entries from groups of gallery photos, after the traveller chose them in preview_journey_entries_from_photos: one draft per group, dated and timed by its first photo, placed at the middle of its geotagged photos, with its photos on it. Pass each group as photoIds (journey photo ids), with title (the suggested title or the traveller's own; the country or day when left out) and locationName (the place name the preview found). Send the same timezone as the preview. All entries are written in one change; a photo that was put on an entry meanwhile, or is named twice, is left out and listed in skippedPhotoIds, and a group left without photos writes no entry. Existing entries are never changed, and drafts never appear on shared pages.",
|
||||
inputSchema: { journeyId: idSchema, ...journeyEntriesFromPhotosCreateRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'write' },
|
||||
})
|
||||
async createEntriesFromPhotos(
|
||||
{ journeyId, ...request }: { journeyId: number } & JourneyEntriesFromPhotosCreateRequest,
|
||||
ctx: McpContext,
|
||||
) {
|
||||
return ok(await this.fromPhotos.create(ctx.userId, journeyId, request));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { JourneyEntryPhotos } from '../../db/entities/JourneyEntryPhotos.entity';
|
||||
import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { MapsModule } from '../maps/maps.module';
|
||||
import { JourneyDomainModule } from './journey-domain.module';
|
||||
import { JourneyEntriesFromPhotosController } from './journey-entries-from-photos.controller';
|
||||
import { JourneyEntriesFromPhotosMcp } from './journey-entries-from-photos.mcp';
|
||||
import { JourneyEntriesFromPhotosService } from './journey-entries-from-photos.service';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* Draft entries made from the photos of a journey's gallery (#1920): its
|
||||
* routes, its MCP tools and the service behind both.
|
||||
*
|
||||
* A module of its own because it names its groups through the geocoder
|
||||
* (MapsModule, a leaf), which JourneyDomainModule stays free of on purpose.
|
||||
* The entries go through JourneyDomainService; the gallery and the entry
|
||||
* links are read and written through their repositories here, inside the
|
||||
* one transaction the service opens.
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
JourneyDomainModule,
|
||||
MapsModule,
|
||||
AddonsModule,
|
||||
MikroOrmModule.forFeature([JourneyPhotos, JourneyEntryPhotos]),
|
||||
],
|
||||
controllers: [JourneyEntriesFromPhotosController],
|
||||
providers: [JourneyEntriesFromPhotosService, JourneyEntriesFromPhotosMcp],
|
||||
})
|
||||
export class JourneyEntriesFromPhotosModule {}
|
||||
@@ -0,0 +1,258 @@
|
||||
import { JourneyEntryPhotos } from '../../db/entities/JourneyEntryPhotos.entity';
|
||||
import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
|
||||
import type { JourneyEntryPhotosRepository } from '../../db/repositories/JourneyEntryPhotos.repository';
|
||||
import type { JourneyPhotoOffEntryRow, JourneyPhotosRepository } from '../../db/repositories/JourneyPhotos.repository';
|
||||
import { getCountryFromCoords } from '../../utils/country-borders';
|
||||
import { forbidden, notFound } from '../common/domain-error';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { MapsService } from '../maps/maps.service';
|
||||
import { JourneyDomainService } from './journey-domain.service';
|
||||
import {
|
||||
clusterCaptures,
|
||||
fallbackTitle,
|
||||
localCaptures,
|
||||
summarizeCluster,
|
||||
type ClusterSummary,
|
||||
type FromPhotosPhoto,
|
||||
type LocalCapture,
|
||||
} from './journey-entries-from-photos.helpers';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import {
|
||||
JOURNEY_FROM_PHOTOS_DEFAULT_DISTANCE_KM,
|
||||
JOURNEY_FROM_PHOTOS_DEFAULT_GAP_MINUTES,
|
||||
type JourneyEntriesFromPhotosCluster,
|
||||
type JourneyEntriesFromPhotosCreateRequest,
|
||||
type JourneyEntriesFromPhotosCreateResponse,
|
||||
type JourneyEntriesFromPhotosPreviewRequest,
|
||||
type JourneyEntriesFromPhotosPreviewResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** The most groups one preview asks the geocoder to name; the rest are named by country or day. */
|
||||
export const FROM_PHOTOS_MAX_GEOCODED = 25;
|
||||
/** How long one preview spends naming places before it names the rest by country or day. */
|
||||
const FROM_PHOTOS_GEOCODE_BUDGET_MS = 20_000;
|
||||
/** The deadline of one place lookup, after the geocoder's own rate-limit wait. */
|
||||
const GEOCODE_TIMEOUT_MS = 8_000;
|
||||
|
||||
type CreatedEntry = NonNullable<Awaited<ReturnType<JourneyDomainService['createEntry']>>>;
|
||||
|
||||
/** The country a point falls in, from the bundled borders; null without a point or without the asset. */
|
||||
function countryOf(lat: number | null, lng: number | null): string | null {
|
||||
if (lat === null || lng === null) return null;
|
||||
try {
|
||||
return getCountryFromCoords(lat, lng);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The photos of the gallery on no entry, as the clustering reads them; the ones without a capture time apart. */
|
||||
function capturedOf(rows: readonly JourneyPhotoOffEntryRow[]): { captured: FromPhotosPhoto[]; withoutTime: number } {
|
||||
const captured: FromPhotosPhoto[] = [];
|
||||
let withoutTime = 0;
|
||||
for (const row of rows) {
|
||||
if (!row.taken_at) {
|
||||
withoutTime++;
|
||||
continue;
|
||||
}
|
||||
captured.push({ id: row.id, takenAt: row.taken_at, lat: row.lat, lng: row.lng, mediaType: row.media_type });
|
||||
}
|
||||
return { captured, withoutTime };
|
||||
}
|
||||
|
||||
/**
|
||||
* Journal entries made from the photos of a journey's gallery (#1920).
|
||||
*
|
||||
* The preview reads the gallery photos on no entry that know when they were
|
||||
* taken, puts each on the clock of its local day (the helpers say which zone
|
||||
* that is), groups them by day and, inside a day, by time and distance, and
|
||||
* names every group: a place name from the geocoder (the same client, cache
|
||||
* and rate limit as everywhere else, capped per preview), else the country,
|
||||
* else the day. It writes nothing.
|
||||
*
|
||||
* The create takes the groups the traveller kept, each a list of gallery
|
||||
* photo ids with an optional title, and writes one draft entry per group with
|
||||
* its photos linked, all in one transaction. The photos are read again inside
|
||||
* it, so one put on an entry since the preview (or named twice) is left out
|
||||
* and reported instead of linked twice, and a group left with none writes no
|
||||
* entry. Entries that existed before are never touched. The new entries are
|
||||
* announced after the commit, as every entry creation is.
|
||||
*
|
||||
* The journey's `photo_location` switch is not consulted: it decides whether
|
||||
* an existing entry without a place takes one from a photo added to it, and
|
||||
* these entries are written with their place from the start.
|
||||
*/
|
||||
@Injectable()
|
||||
export class JourneyEntriesFromPhotosService {
|
||||
private readonly logger = new Logger(JourneyEntriesFromPhotosService.name);
|
||||
|
||||
constructor(
|
||||
private readonly journeys: JourneyDomainService,
|
||||
private readonly maps: MapsService,
|
||||
private readonly uow: UnitOfWork,
|
||||
@InjectRepository(JourneyPhotos) private readonly photosRepo: JourneyPhotosRepository,
|
||||
@InjectRepository(JourneyEntryPhotos) private readonly entryPhotosRepo: JourneyEntryPhotosRepository,
|
||||
) {}
|
||||
|
||||
/** The journey's people may read it; only those who may edit it make entries. */
|
||||
private async requireEditable(journeyId: number, userId: number): Promise<void> {
|
||||
if (!(await this.journeys.canAccessJourney(journeyId, userId))) throw notFound('Journey not found');
|
||||
if (!(await this.journeys.canEdit(journeyId, userId))) throw forbidden('Not allowed');
|
||||
}
|
||||
|
||||
async preview(
|
||||
userId: number,
|
||||
journeyId: number,
|
||||
request: JourneyEntriesFromPhotosPreviewRequest,
|
||||
): Promise<JourneyEntriesFromPhotosPreviewResponse> {
|
||||
await this.requireEditable(journeyId, userId);
|
||||
const thresholds = {
|
||||
maxGapMinutes: request.maxGapMinutes ?? JOURNEY_FROM_PHOTOS_DEFAULT_GAP_MINUTES,
|
||||
maxDistanceKm: request.maxDistanceKm ?? JOURNEY_FROM_PHOTOS_DEFAULT_DISTANCE_KM,
|
||||
};
|
||||
const { captured, withoutTime } = capturedOf(await this.photosRepo.listOffEntries(journeyId));
|
||||
const summaries = clusterCaptures(localCaptures(captured, request.timezone ?? null), thresholds).map(
|
||||
summarizeCluster,
|
||||
);
|
||||
const names = await this.placeNames(summaries, request.lang);
|
||||
const clusters = summaries.map((summary, index): JourneyEntriesFromPhotosCluster => {
|
||||
const countryCode = countryOf(summary.lat, summary.lng);
|
||||
const placeName = names[index] ?? null;
|
||||
const fallback = fallbackTitle(countryCode, summary.date, request.lang);
|
||||
return {
|
||||
date: summary.date,
|
||||
startTime: summary.startTime,
|
||||
endTime: summary.endTime,
|
||||
timezone: summary.zone,
|
||||
lat: summary.lat,
|
||||
lng: summary.lng,
|
||||
countryCode,
|
||||
locationName: placeName,
|
||||
suggestedTitle: placeName ?? fallback.title,
|
||||
titleSource: placeName ? 'place' : fallback.source,
|
||||
photoIds: summary.photoIds,
|
||||
photoCount: summary.photoIds.length,
|
||||
coverPhotoId: summary.coverPhotoId,
|
||||
};
|
||||
});
|
||||
return { clusters, withoutCaptureTime: withoutTime, ...thresholds };
|
||||
}
|
||||
|
||||
/**
|
||||
* A place name for every group with a middle, from the geocoder, one point
|
||||
* asked once. Best effort: at most {@link FROM_PHOTOS_MAX_GEOCODED} points
|
||||
* and {@link FROM_PHOTOS_GEOCODE_BUDGET_MS} per preview, one after the other
|
||||
* so the geocoder's own rate limit is kept; a point it did not name (no
|
||||
* answer, an error, past the budget) gets null, and its group is named by
|
||||
* country or day instead.
|
||||
*/
|
||||
private async placeNames(summaries: readonly ClusterSummary[], lang: string | undefined): Promise<(string | null)[]> {
|
||||
const started = Date.now();
|
||||
const byPoint = new Map<string, string | null>();
|
||||
const names: (string | null)[] = [];
|
||||
for (const summary of summaries) {
|
||||
if (summary.lat === null || summary.lng === null) {
|
||||
names.push(null);
|
||||
continue;
|
||||
}
|
||||
// About a kilometre: two groups of the same town share one lookup.
|
||||
const key = `${summary.lat.toFixed(2)},${summary.lng.toFixed(2)}`;
|
||||
if (!byPoint.has(key)) {
|
||||
const withinBudget =
|
||||
byPoint.size < FROM_PHOTOS_MAX_GEOCODED && Date.now() - started < FROM_PHOTOS_GEOCODE_BUDGET_MS;
|
||||
byPoint.set(key, withinBudget ? await this.placeName(summary.lat, summary.lng, lang) : null);
|
||||
}
|
||||
names.push(byPoint.get(key) ?? null);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
private async placeName(lat: number, lng: number, lang: string | undefined): Promise<string | null> {
|
||||
try {
|
||||
const where = await this.maps.reverseGeocode(String(lat), String(lng), lang, {
|
||||
lane: 'interactive',
|
||||
timeoutMs: GEOCODE_TIMEOUT_MS,
|
||||
locality: true,
|
||||
});
|
||||
const name = (where.name ?? '').trim();
|
||||
return name ? name.slice(0, 255) : null;
|
||||
} catch (err) {
|
||||
this.logger.warn(`place name for photos failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async create(
|
||||
userId: number,
|
||||
journeyId: number,
|
||||
request: JourneyEntriesFromPhotosCreateRequest,
|
||||
socketId?: string,
|
||||
): Promise<JourneyEntriesFromPhotosCreateResponse> {
|
||||
await this.requireEditable(journeyId, userId);
|
||||
|
||||
const done = await this.uow.transactional(async () => {
|
||||
// Read inside the transaction: a photo put on an entry since the preview is not on this list.
|
||||
const { captured } = capturedOf(await this.photosRepo.listOffEntries(journeyId));
|
||||
const captures = new Map<number, LocalCapture>(
|
||||
localCaptures(captured, request.timezone ?? null).map((capture) => [capture.id, capture]),
|
||||
);
|
||||
const claimed = new Set<number>();
|
||||
const skipped: number[] = [];
|
||||
const written: Array<{ entry: CreatedEntry; photoCount: number }> = [];
|
||||
for (const group of request.groups) {
|
||||
const photos: LocalCapture[] = [];
|
||||
for (const id of group.photoIds) {
|
||||
const capture = captures.get(id);
|
||||
if (!capture || claimed.has(id)) {
|
||||
skipped.push(id);
|
||||
continue;
|
||||
}
|
||||
claimed.add(id);
|
||||
photos.push(capture);
|
||||
}
|
||||
if (!photos.length) continue;
|
||||
const summary = summarizeCluster(photos);
|
||||
const countryCode = countryOf(summary.lat, summary.lng);
|
||||
const entry = await this.journeys.createEntry(
|
||||
journeyId,
|
||||
userId,
|
||||
{
|
||||
type: 'entry',
|
||||
title: group.title ?? fallbackTitle(countryCode, summary.date, request.lang).title,
|
||||
entry_date: summary.date,
|
||||
entry_time: summary.startTime,
|
||||
location_name: group.locationName || undefined,
|
||||
location_lat: summary.lat ?? undefined,
|
||||
location_lng: summary.lng ?? undefined,
|
||||
is_draft: true,
|
||||
},
|
||||
undefined,
|
||||
// Announced below, once every entry of the call is committed.
|
||||
false,
|
||||
);
|
||||
if (!entry) throw forbidden('Not allowed');
|
||||
const now = Date.now();
|
||||
for (const [index, photoId] of summary.photoIds.entries()) {
|
||||
await this.entryPhotosRepo.insertIgnore(entry.id, photoId, index, now);
|
||||
}
|
||||
written.push({ entry, photoCount: summary.photoIds.length });
|
||||
}
|
||||
return { written, skipped };
|
||||
});
|
||||
|
||||
for (const { entry } of done.written) {
|
||||
await this.journeys.broadcastJourneyEvent(journeyId, 'journey:entry:created', { entry }, socketId);
|
||||
}
|
||||
return {
|
||||
entries: done.written.map(({ entry, photoCount }) => ({
|
||||
id: entry.id,
|
||||
title: entry.title ?? null,
|
||||
entry_date: entry.entry_date,
|
||||
entry_time: entry.entry_time ?? null,
|
||||
photoCount,
|
||||
})),
|
||||
skippedPhotoIds: [...new Set(done.skipped)],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
journeyContributorRequestSchema,
|
||||
journeyContributorUpdateRequestSchema,
|
||||
journeyCreateRequestSchema,
|
||||
journeyEntriesFromPhotosCreateRequestSchema,
|
||||
journeyEntriesFromPhotosPreviewRequestSchema,
|
||||
journeyEntryCreateRequestSchema,
|
||||
journeyEntryPhotoUploadRequestSchema,
|
||||
journeyEntryUpdateRequestSchema,
|
||||
@@ -61,6 +63,9 @@ export class JourneyPhotosMoveDto extends createZodDto(journeyPhotosMoveRequestS
|
||||
export class JourneyEntryPhotoUploadDto extends createZodDto(journeyEntryPhotoUploadRequestSchema) {}
|
||||
export class JourneyGalleryPhotoUploadDto extends createZodDto(journeyGalleryPhotoUploadRequestSchema) {}
|
||||
export class JourneyGalleryVideoDto extends createZodDto(journeyGalleryVideoRequestSchema) {}
|
||||
/** Draft entries from gallery photos (#1920): strict, new routes with nothing older to keep answering. */
|
||||
export class JourneyEntriesFromPhotosPreviewDto extends createZodDto(journeyEntriesFromPhotosPreviewRequestSchema) {}
|
||||
export class JourneyEntriesFromPhotosCreateDto extends createZodDto(journeyEntriesFromPhotosCreateRequestSchema) {}
|
||||
|
||||
/** A Studio book save — the whole document, plus the version it was made against. */
|
||||
export class BookSaveDto extends createZodDto(bookSaveRequestSchema) {}
|
||||
|
||||
Reference in New Issue
Block a user