feat(journey): read what a journey map shows beside its entries, and share its plan and recorded days on purpose

GET /api/journeys/:id/map-layers answers the planned places of the linked
trips (one per place, with every day the plan puts it on and the entry
written about it), the trips' GPX routes while the track switch is on, and
the located stays entries were taken over from. It goes through
journey_trips, so a trip nobody wrote about yet shows its plan too. Every
source is read on its own: one that fails says unavailable and the others
still draw. A position that is not one is left out, never moved.

GET /api/public/journey/:token/map-layers cuts the same on the server by the
link: nothing while the map is not shared, the plan and its routes only with
share_plan, the recorded days only with share_recordings and only beside a
published entry, stays only of published entries. Migration 046190 adds both
flags to journey_share_tokens, off by default, so a journey that is public
already shows what it showed before. The share link REST route and the MCP
share tool take them alike; get_journey_map_layers reads the layers over MCP
on the same access, a route by its size only.
This commit is contained in:
Maurice
2026-10-21 18:15:24 +02:00
parent bb10b94046
commit 9b71948497
35 changed files with 1465 additions and 41 deletions
@@ -16,6 +16,8 @@ export class JourneyShareTokens {
share_map?: number | null = 1;
created_at?: string | null;
newest_first: number & Opt = 0;
share_plan: number & Opt = 0;
share_recordings: number & Opt = 0;
createdByRef!: Ref<Users>;
}
@@ -34,6 +36,8 @@ export const JourneyShareTokensSchema = defineEntity({
share_map: p.integer().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
newest_first: p.integer().default(0),
share_plan: p.integer().default(0),
share_recordings: p.integer().default(0),
createdByRef: () => p.manyToOne(Users).ref().joinColumn('created_by').hidden().index('idx_journey_share_tokens_created_by'),
},
});
@@ -12,4 +12,6 @@ export interface JourneyShareTokensTable {
share_map: InsertOptional<number | null>;
created_at: InsertOptional<string | null>;
newest_first: InsertOptional<number>;
share_plan: InsertOptional<number>;
share_recordings: InsertOptional<number>;
}
@@ -0,0 +1,26 @@
import { addColumnIfMissing } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* JRN-04: a journey's public link can also show the trips' plan and the
* recorded days on its map.
*
* `share_plan` puts the places of the linked trips (and their GPX tracks) on
* the public map, `share_recordings` the days of route the journey keeps.
* Both are off by default, so a journey that is public already shows exactly
* what it showed before this step, and neither shows anything while the map
* itself is not shared.
*/
export class Migration20200101046190_a_journey_share_can_show_its_plan_and_recordings extends Migration {
override name = 'Migration20200101046190_a_journey_share_can_show_its_plan_and_recordings';
override async up(): Promise<void> {
await addColumnIfMissing(this, 'journey_share_tokens', 'share_plan', 'share_plan INTEGER NOT NULL DEFAULT 0');
await addColumnIfMissing(
this,
'journey_share_tokens',
'share_recordings',
'share_recordings INTEGER NOT NULL DEFAULT 0',
);
}
}
@@ -20,6 +20,17 @@ export interface JourneyEntryStayWrite {
user_id: number;
}
/** A located stay of a journey, as its map draws it (JRN-04). */
export interface JourneyEntryStayMapRow {
id: number;
entry_id: number;
name: string;
lat: number;
lng: number;
started_at: string;
ended_at: string;
}
/** A stay a journey holds, with the entry that holds it. */
interface JourneyEntryStayHeld {
source_visit_id: string;
@@ -60,4 +71,18 @@ export class JourneyEntryStaysRepository extends TrekRepository<JourneyEntryStay
.where('s.source_visit_id', 'in', sourceVisitIds)
.execute();
}
/** The journey's stays that carry a position, by entry and in the order they were lived. */
async listLocatedForJourney(journeyId: number): Promise<JourneyEntryStayMapRow[]> {
const rows = await this.db()
.selectFrom('journey_entry_stays as s')
.select(['s.id', 's.entry_id', 's.name', 's.lat', 's.lng', 's.started_at', 's.ended_at'])
.where('s.journey_id', '=', journeyId)
.where('s.lat', 'is not', null)
.where('s.lng', 'is not', null)
.orderBy('s.entry_id', 'asc')
.orderBy('s.sort_order', 'asc')
.execute();
return rows.map((row) => ({ ...row, lat: row.lat as number, lng: row.lng as number }));
}
}
@@ -8,6 +8,8 @@ export interface JourneyShareLinkFlagsRow {
share_gallery: number | null;
share_map: number | null;
newest_first: number;
share_plan: number;
share_recordings: number;
}
/** JS4/JS11's full-row shape (`getJourneyShareLink`, `getPublicJourney`'s entrypoint read). */
@@ -21,6 +23,18 @@ export interface JourneyShareTokenRow {
share_map: number | null;
created_at: string | null;
newest_first: number;
share_plan: number;
share_recordings: number;
}
/** Every flag of a link, as stored (0/1). */
export interface JourneyShareFlags {
share_timeline: number;
share_gallery: number;
share_map: number;
newest_first: number;
share_plan: number;
share_recordings: number;
}
/** JS6/JS9's narrow token-lookup projection — the anonymous photo/asset validators. */
@@ -82,7 +96,15 @@ export class JourneyShareTokensRepository extends TrekRepository<JourneyShareTok
/** JS1 — `createOrUpdateJourneyShareLink`'s existing-link read: `SELECT token, share_timeline, share_gallery, share_map, newest_first FROM journey_share_tokens WHERE journey_id = ?`. */
async findFlagsByJourneyId(journeyId: number): Promise<JourneyShareLinkFlagsRow | undefined> {
return await this.qb('jst')
.select(['jst.token', 'jst.share_timeline', 'jst.share_gallery', 'jst.share_map', 'jst.newest_first'])
.select([
'jst.token',
'jst.share_timeline',
'jst.share_gallery',
'jst.share_map',
'jst.newest_first',
'jst.share_plan',
'jst.share_recordings',
])
.where({ journey: journeyId })
.execute<JourneyShareLinkFlagsRow | undefined>('get', false);
}
@@ -90,25 +112,17 @@ export class JourneyShareTokensRepository extends TrekRepository<JourneyShareTok
/**
* JS2 — the update branch: `UPDATE journey_share_tokens SET
* share_timeline=?, share_gallery=?, share_map=?, newest_first=? WHERE
* journey_id=?`. A plain 4-column write, NOT a `presenceSet` call — the
* journey_id=?` (and the two map flags of JRN-04). A plain write, NOT a `presenceSet` call — the
* service resolves every flag's final value (the `permissions.X ?? !!
* existing.X` fallback merge) before calling this, so every call writes
* all four columns, present or not.
* every column, present or not.
*/
async updateFlags(
journeyId: number,
flags: { share_timeline: number; share_gallery: number; share_map: number; newest_first: number },
): Promise<void> {
async updateFlags(journeyId: number, flags: JourneyShareFlags): Promise<void> {
await this.nativeUpdate({ journey: journeyId }, flags);
}
/** JS3 — the create branch: `INSERT INTO journey_share_tokens (journey_id, token, created_by, share_timeline, share_gallery, share_map, newest_first) VALUES (?,?,?,?,?,?,?)`. */
async insertLink(
journeyId: number,
token: string,
createdBy: number,
flags: { share_timeline: number; share_gallery: number; share_map: number; newest_first: number },
): Promise<void> {
async insertLink(journeyId: number, token: string, createdBy: number, flags: JourneyShareFlags): Promise<void> {
await this.insert({ journey: journeyId, token, createdByRef: createdBy, ...flags });
}
@@ -48,6 +48,32 @@ export interface AssignmentTimeRow {
/** The `places`/`day_assignments`/`days` tables the sync-engine reads read. */
type SyncPlacesKyselyDB = Pick<DB, 'places' | 'day_assignments' | 'days'>;
/** One day a linked trip's plan puts a located place on (JRN-04), {@link JourneyTripsRepository.listMapPlacesForJourney}. */
export interface JourneyMapPlaceRow {
place_id: number;
trip_id: number;
trip_title: string;
name: string;
lat: number;
lng: number;
day_date: string | null;
time: string | null;
category_color: string | null;
category_icon: string | null;
}
/** A place of a linked trip that carries a route (JRN-04), {@link JourneyTripsRepository.listRouteSourcesForJourney}. */
export interface JourneyRouteSourceRow {
place_id: number;
trip_id: number;
name: string;
route_color: string | null;
route_geometry: string;
}
/** The tables the journey map's plan reads join. */
type JourneyMapKyselyDB = Pick<DB, 'journey_trips' | 'trips' | 'places' | 'day_assignments' | 'days' | 'categories'>;
/**
* `journey_trips` — a genuine TWO-column composite primary key (`journey` +
* `trip`, both `.primary()`, R3 — pinned against
@@ -180,4 +206,70 @@ export class JourneyTripsRepository extends TrekRepository<JourneyTrips> {
.execute();
return rows as AssignmentTimeRow[];
}
/**
* The located places the linked trips plan on a day, one row per day they
* stand on, in plan order (JRN-04). Through `journey_trips`, so a linked
* trip nobody has written about yet still shows its plan; a place without
* coordinates is left out rather than put anywhere.
*/
async listMapPlacesForJourney(journeyId: number): Promise<JourneyMapPlaceRow[]> {
const rows = await this.kysely<JourneyMapKyselyDB>()
.selectFrom('journey_trips as jt')
.innerJoin('trips as t', 't.id', 'jt.trip_id')
.innerJoin('places as p', 'p.trip_id', 'jt.trip_id')
.innerJoin('day_assignments as da', 'da.place_id', 'p.id')
.innerJoin('days as d', 'd.id', 'da.day_id')
.leftJoin('categories as c', 'c.id', 'p.category_id')
.select([
'p.id as place_id',
'p.trip_id',
't.title as trip_title',
'p.name',
'p.lat',
'p.lng',
'd.date as day_date',
'da.assignment_time',
'p.place_time',
'c.color as category_color',
'c.icon as category_icon',
])
.where('jt.journey_id', '=', journeyId)
.where('p.lat', 'is not', null)
.where('p.lng', 'is not', null)
.orderBy('t.start_date', 'asc')
.orderBy('d.day_number', 'asc')
.orderBy('da.order_index', 'asc')
.execute();
return rows.map((row) => ({
place_id: row.place_id,
trip_id: row.trip_id,
trip_title: row.trip_title,
name: row.name,
lat: row.lat as number,
lng: row.lng as number,
day_date: row.day_date,
time: row.assignment_time ?? row.place_time,
category_color: row.category_color,
category_icon: row.category_icon,
}));
}
/**
* The places of the linked trips that carry a route (JRN-04). Unlike the
* entries' `listTracksSource`, which `/tracks` and Studio read and which
* stays as it is, this goes through `journey_trips`.
*/
async listRouteSourcesForJourney(journeyId: number): Promise<JourneyRouteSourceRow[]> {
const rows = await this.kysely<JourneyMapKyselyDB>()
.selectFrom('journey_trips as jt')
.innerJoin('places as p', 'p.trip_id', 'jt.trip_id')
.select(['p.id as place_id', 'p.trip_id', 'p.name', 'p.route_color', 'p.route_geometry'])
.where('jt.journey_id', '=', journeyId)
.where('p.route_geometry', 'is not', null)
.orderBy('p.trip_id', 'asc')
.orderBy('p.id', 'asc')
.execute();
return rows as JourneyRouteSourceRow[];
}
}
@@ -130,6 +130,7 @@ export const PUBLIC_ROUTE_ALLOW_LIST: string[] = [
// Share-token validated.
'JourneyPublicController.get',
'JourneyPublicController.legacyPhoto',
'JourneyPublicController.mapLayers',
'JourneyPublicController.photo',
// The MCP transport — bearer tokens are verified inside the handler.
// The same documents under the resource URL, for clients that append the
@@ -16,6 +16,7 @@ import { RealtimeModule } from '../realtime/realtime.module';
import { SettingsModule } from '../settings/settings.module';
import { JourneyDomainService } from './journey-domain.service';
import { JourneyEntryStaysService } from './journey-entry-stays.service';
import { JourneyMapService } from './journey-map.service';
import { JourneyRecordedDaysService } from './journey-recorded-days.service';
import { JourneyRecordingPrepService } from './journey-recording-prep.service';
import { JourneyShareService } from './journey-share.service';
@@ -75,6 +76,9 @@ import { Module } from '@nestjs/common';
* `JourneyRecordingPrep` (JRN-03) is how far preparing a journey's recorded
* days got for each person; `JourneyRecordingPrepService` keeps it and tells
* the Dawarich sync which journeys to read.
* `JourneyMapService` (JRN-04) reads what the journey map shows besides its
* entries and photos, for the journey's people and for its share link, from
* the tables already registered here.
*/
@Module({
imports: [
@@ -103,6 +107,7 @@ import { Module } from '@nestjs/common';
JourneyRecordedDaysService,
JourneyEntryStaysService,
JourneyRecordingPrepService,
JourneyMapService,
],
exports: [
JourneyDomainService,
@@ -110,6 +115,7 @@ import { Module } from '@nestjs/common';
JourneyRecordedDaysService,
JourneyEntryStaysService,
JourneyRecordingPrepService,
JourneyMapService,
],
})
export class JourneyDomainModule {}
@@ -28,6 +28,7 @@ import type { TripsRepository } from '../../db/repositories/Trips.repository';
import { Places } from '../../db/entities/Places.entity';
import type { PlacesRepository } from '../../db/repositories/Places.repository';
import { presenceSet } from '../../db/repositories/_shared/presence-set';
import { parseRouteGeometry } from './journey-geometry';
/**
* English country names for whatever codes a journey turned up.
@@ -914,25 +915,10 @@ export class JourneyDomainService {
const tracks: JourneyTrack[] = [];
for (const row of rows) {
let parsed: unknown;
try {
parsed = JSON.parse(row.route_geometry);
} catch {
continue; // A geometry that is not JSON is not worth failing the whole map over.
}
if (!Array.isArray(parsed)) continue;
const points: [number, number][] = [];
for (const entry of parsed) {
if (!Array.isArray(entry) || entry.length < 2) continue;
const lat = Number(entry[0]);
const lng = Number(entry[1]);
if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue;
points.push([lat, lng]);
}
// A single point is a pin, not a line, and the map already has the entry markers.
if (points.length < 2) continue;
// A geometry that is not JSON, or a single point (a pin, not a line), is
// not worth failing the whole map over.
const points = parseRouteGeometry(row.route_geometry);
if (!points) continue;
tracks.push({
place_id: row.place_id,
trip_id: row.trip_id,
@@ -0,0 +1,36 @@
/** A coordinate pair that is a place on Earth: finite, and within latitude and longitude. */
export function isValidGeoPoint(lat: unknown, lng: unknown): lat is number {
return (
typeof lat === 'number' &&
typeof lng === 'number' &&
Number.isFinite(lat) &&
Number.isFinite(lng) &&
Math.abs(lat) <= 90 &&
Math.abs(lng) <= 180
);
}
/**
* A place's stored route geometry as `[lat, lng]` points, the way the GPX
* importer wrote it; elevation, where kept, is dropped. Points that are not
* numbers are skipped, and a text that is not JSON, or that leaves fewer than
* two points, is no line: null, so one broken geometry never fails a map.
*/
export function parseRouteGeometry(text: string): [number, number][] | null {
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch {
return null;
}
if (!Array.isArray(parsed)) return null;
const points: [number, number][] = [];
for (const entry of parsed) {
if (!Array.isArray(entry) || entry.length < 2) continue;
const lat = Number(entry[0]);
const lng = Number(entry[1]);
if (!Number.isFinite(lat) || !Number.isFinite(lng)) continue;
points.push([lat, lng]);
}
return points.length < 2 ? null : points;
}
@@ -0,0 +1,29 @@
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 { JourneyMapService } from './journey-map.service';
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
import { journeyMapLayersResponseSchema } from '@trek/shared';
/**
* GET /api/journeys/:id/map-layers (JRN-04): the plan, the routes and the
* stays the journey map can show beside its entries, each source answering on
* its own. Read-only and derived, like `/tracks`; the journey's own access
* applies, a stranger gets the same 404 as for the journey itself.
*/
@Controller('api/journeys')
@UseGuards(AddonGuard, JwtAuthGuard)
@RequireAddon(ADDON_IDS.JOURNEY, 'Journey')
export class JourneyMapController {
constructor(private readonly map: JourneyMapService) {}
@Get(':id/map-layers')
@ResponseContract(journeyMapLayersResponseSchema)
async layers(@CurrentUser() user: User, @Param('id') id: string) {
return this.map.mapLayers(Number(id), user.id);
}
}
@@ -0,0 +1,49 @@
import { ADDON_IDS } from '../../addons';
import { McpController, TOOL_ANNOTATIONS_READONLY, Tool, ok, type McpContext } from '../../nest-mcp';
import { addonGate } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { JourneyMapService } from './journey-map.service';
import { idSchema, type JourneyMapLayerResult } from '@trek/shared';
const journeyAddonOn = addonGate(ADDON_IDS.JOURNEY);
/**
* The journey map's layers (JRN-04) over MCP: the same service and the same
* journey access as GET `/api/journeys/:id/map-layers`. The places and stays
* come with their positions; a route answers with its name and size, never
* its geometry.
*/
@McpController()
export class JourneyMapMcp {
constructor(
private readonly map: JourneyMapService,
readonly addons: AddonsService,
) {}
@Tool({
name: 'get_journey_map_layers',
description:
"What a journey's map shows besides its entries and photos: the planned places of its linked trips (with the days the plan puts each on and, when one exists, the journal entry written about it; a planned place alone is no proof of a visit), the GPX routes of those trips while the journey's track switch is on, and the stays journal entries were taken over from (several per day report, each where it was recorded). Each source answers ok, or unavailable when it could not be read. The recorded days are listed by list_journey_recorded_days.",
inputSchema: { journeyId: idSchema },
annotations: TOOL_ANNOTATIONS_READONLY,
when: journeyAddonOn,
access: { group: 'journey', mode: 'read' },
})
async getJourneyMapLayers({ journeyId }: { journeyId: number }, ctx: McpContext) {
const layers = await this.map.mapLayers(journeyId, ctx.userId);
return ok({
places: layers.places,
routes: mapItems(layers.routes, (route) => ({
place_id: route.place_id,
trip_id: route.trip_id,
name: route.name,
points: route.points.length,
})),
stays: layers.stays,
});
}
}
function mapItems<T, U>(layer: JourneyMapLayerResult<T>, as: (item: T) => U): JourneyMapLayerResult<U> {
return layer.status === 'ok' ? { status: 'ok', items: layer.items.map(as) } : layer;
}
@@ -0,0 +1,188 @@
import { JourneyEntries } from '../../db/entities/JourneyEntries.entity';
import { JourneyEntryStays } from '../../db/entities/JourneyEntryStays.entity';
import { JourneyShareTokens } from '../../db/entities/JourneyShareTokens.entity';
import { JourneyTrips } from '../../db/entities/JourneyTrips.entity';
import { Journeys } from '../../db/entities/Journeys.entity';
import type { JourneyEntriesRepository } from '../../db/repositories/JourneyEntries.repository';
import type { JourneyEntryStaysRepository } from '../../db/repositories/JourneyEntryStays.repository';
import type { JourneyShareTokensRepository } from '../../db/repositories/JourneyShareTokens.repository';
import type { JourneyTripsRepository } from '../../db/repositories/JourneyTrips.repository';
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
import { logWarn } from '../audit/audit-log.logger';
import { notFound } from '../common/domain-error';
import { JourneyDomainService } from './journey-domain.service';
import { isValidGeoPoint, parseRouteGeometry } from './journey-geometry';
import { JourneyRecordedDaysService } from './journey-recorded-days.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import type {
JourneyMapLayerResult,
JourneyMapLayersResponse,
JourneyMapPlace,
JourneyMapRecording,
JourneyMapStay,
JourneyPublicMapLayersResponse,
JourneyTrack,
} from '@trek/shared';
/** The entries a map may tie its plan and its stays to: who can read them is decided by the caller. */
interface EntryRef {
id: number;
source_place_id?: number | null;
entry_date: string;
type: string;
}
const WITHHELD = { status: 'withheld' } as const;
/**
* What the journey map shows besides its entries and photos (JRN-04): the plan
* of the linked trips, their GPX routes, the days of route the journey keeps
* and the stays its entries were taken over from.
*
* Every source is read on its own, and one that fails answers `unavailable`
* while the others still draw. Nothing is stored here and nothing is written:
* a layer switched on in a browser only ever hides what the reader may see.
* The public answer is cut on the server, by the link's flags, never by the
* client: the map switched off shares nothing of it.
*/
@Injectable()
export class JourneyMapService {
constructor(
private readonly journeys: JourneyDomainService,
private readonly recordedDays: JourneyRecordedDaysService,
@InjectRepository(JourneyTrips) private readonly tripsRepo: JourneyTripsRepository,
@InjectRepository(JourneyEntries) private readonly entriesRepo: JourneyEntriesRepository,
@InjectRepository(JourneyEntryStays) private readonly staysRepo: JourneyEntryStaysRepository,
@InjectRepository(JourneyShareTokens) private readonly shareTokensRepo: JourneyShareTokensRepository,
@InjectRepository(Journeys) private readonly journeysRepo: JourneysRepository,
) {}
/** The map layers of a journey for one of its people: the owner or a contributor. */
async mapLayers(journeyId: number, userId: number): Promise<JourneyMapLayersResponse> {
const journey = await this.journeys.canAccessJourney(journeyId, userId);
if (!journey) throw notFound('Journey not found');
const entries = await this.entriesRepo.listForJourney(journeyId);
// A skeleton is the plan mirrored into the timeline, not something written.
const written = entries.filter((entry) => entry.type !== 'skeleton');
const [places, routes, stays] = await Promise.all([
this.layer('places', journeyId, () => this.places(journeyId, written)),
this.layer('routes', journeyId, () => (journey.show_trip_tracks ? this.routes(journeyId) : Promise.resolve([]))),
this.layer('stays', journeyId, () => this.stays(journeyId, written)),
]);
return { places, routes, stays };
}
/**
* The map layers a share link shows, null for a link that does not exist.
* Drafts never reach it: the entries it ties places and stays to are the
* published ones, and a recorded day shows only beside a published entry.
*/
async publicMapLayers(token: string): Promise<JourneyPublicMapLayersResponse | null> {
const link = await this.shareTokensRepo.findByToken(token);
if (!link) return null;
const journey = await this.journeysRepo.findById(link.journey_id);
if (!journey) return null;
if (!link.share_map) return { places: WITHHELD, routes: WITHHELD, stays: WITHHELD, recordings: WITHHELD };
const journeyId = link.journey_id;
const published = await this.entriesRepo.listPublicEntries(journeyId);
const sharePlan = !!link.share_plan;
const [places, routes, stays, recordings] = await Promise.all([
sharePlan ? this.layer('places', journeyId, () => this.places(journeyId, published)) : WITHHELD,
sharePlan && journey.show_trip_tracks ? this.layer('routes', journeyId, () => this.routes(journeyId)) : WITHHELD,
this.layer('stays', journeyId, () => this.stays(journeyId, published)),
link.share_recordings
? this.layer('recordings', journeyId, () => this.recordings(journeyId, published))
: WITHHELD,
]);
return { places, routes, stays, recordings };
}
private async layer<T>(name: string, journeyId: number, read: () => Promise<T[]>): Promise<JourneyMapLayerResult<T>> {
try {
return { status: 'ok', items: await read() };
} catch (err) {
logWarn(`[journey-map] the ${name} of journey ${journeyId} could not be read: ${(err as Error).message}`);
return { status: 'unavailable' };
}
}
/**
* One pin per planned place, with every day the plan puts it on. A place an
* entry came from points at that entry, the earliest one when several did,
* so the map can show plan and memory as one; a plan alone proves no visit.
*/
private async places(journeyId: number, entries: EntryRef[]): Promise<JourneyMapPlace[]> {
const rows = await this.tripsRepo.listMapPlacesForJourney(journeyId);
const entryByPlace = new Map<number, number>();
for (const entry of [...entries].sort((a, b) => a.entry_date.localeCompare(b.entry_date))) {
if (entry.source_place_id != null && !entryByPlace.has(entry.source_place_id)) {
entryByPlace.set(entry.source_place_id, entry.id);
}
}
const byPlace = new Map<number, JourneyMapPlace>();
for (const row of rows) {
if (!isValidGeoPoint(row.lat, row.lng)) continue;
const known = byPlace.get(row.place_id);
if (known) {
if (row.day_date && !known.days.includes(row.day_date)) known.days.push(row.day_date);
continue;
}
byPlace.set(row.place_id, {
place_id: row.place_id,
trip_id: row.trip_id,
trip_title: row.trip_title,
name: row.name,
lat: row.lat,
lng: row.lng,
days: row.day_date ? [row.day_date] : [],
time: row.time,
category_color: row.category_color,
category_icon: row.category_icon,
entry_id: entryByPlace.get(row.place_id) ?? null,
});
}
for (const place of byPlace.values()) place.days.sort();
return [...byPlace.values()];
}
private async routes(journeyId: number): Promise<JourneyTrack[]> {
const tracks: JourneyTrack[] = [];
for (const row of await this.tripsRepo.listRouteSourcesForJourney(journeyId)) {
const points = parseRouteGeometry(row.route_geometry);
if (!points) continue;
tracks.push({
place_id: row.place_id,
trip_id: row.trip_id,
name: row.name,
color: row.route_color,
points,
kind: 'trip_gpx',
});
}
return tracks;
}
/** The located stays of the given entries, each where it was recorded; one without a place is left out. */
private async stays(journeyId: number, entries: EntryRef[]): Promise<JourneyMapStay[]> {
const visible = new Set(entries.map((entry) => entry.id));
return (await this.staysRepo.listLocatedForJourney(journeyId)).filter(
(stay) => visible.has(stay.entry_id) && isValidGeoPoint(stay.lat, stay.lng),
);
}
/** The kept days that have one of the given entries on them, their pieces apart. */
private async recordings(journeyId: number, entries: EntryRef[]): Promise<JourneyMapRecording[]> {
const days = new Set(entries.map((entry) => entry.entry_date));
return (await this.recordedDays.list(journeyId))
.filter((day) => days.has(day.date))
.map((day) => ({
date: day.date,
pieces: day.segments
.map((segment) => segment.points.filter(([lat, lng]) => isValidGeoPoint(lat, lng)))
.filter((points) => points.length > 1),
distance_m: day.stats.distanceMeters,
}));
}
}
@@ -2,9 +2,11 @@ import { ADDON_IDS } from '../../addons';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { Public } from '../auth-core/public.decorator';
import { ResponseContract } from '../common/response-contract';
import { StorageService } from '../storage/storage.service';
import { JourneyService } from './journey.service';
import { Controller, Get, HttpException, Param, Res, UseGuards } from '@nestjs/common';
import { journeyPublicMapLayersResponseSchema } from '@trek/shared';
import type { Response } from 'express';
import path from 'node:path';
@@ -42,6 +44,20 @@ export class JourneyPublicController {
return data;
}
/**
* What the shared map shows beside the entries and photos (JRN-04), cut to
* the link's flags on the server: nothing while the map is not shared.
*/
@Get(':token/map-layers')
@ResponseContract(journeyPublicMapLayersResponseSchema)
async mapLayers(@Param('token') token: string) {
const layers = await this.journey.getPublicMapLayers(token);
if (!layers) {
throw new HttpException({ error: 'Not found' }, 404);
}
return layers;
}
@Get(':token/photos/:photoId/:kind')
async photo(
@Param('token') token: string,
@@ -26,6 +26,10 @@ interface JourneySharePermissions {
share_map?: boolean;
/** Read the journey newest-first, like a blog, rather than in trip order. */
newest_first?: boolean;
/** The trips' plan on the shared map (JRN-04); off unless asked for. */
share_plan?: boolean;
/** The recorded days on the shared map (JRN-04); off unless asked for. */
share_recordings?: boolean;
}
interface JourneyShareTokenInfo {
@@ -35,6 +39,8 @@ interface JourneyShareTokenInfo {
share_gallery: boolean;
share_map: boolean;
newest_first: boolean;
share_plan: boolean;
share_recordings: boolean;
}
/**
@@ -105,19 +111,30 @@ export class JourneyShareService {
const share_gallery = permissions.share_gallery ?? !!existing.share_gallery;
const share_map = permissions.share_map ?? !!existing.share_map;
const newest_first = permissions.newest_first ?? !!existing.newest_first;
const share_plan = permissions.share_plan ?? !!existing.share_plan;
const share_recordings = permissions.share_recordings ?? !!existing.share_recordings;
// JS2 — the SERVICE resolves the final value of every flag (above); the
// repository writes exactly those four already-resolved booleans, a
// plain 4-column UPDATE, not a presence-sentinel one.
// repository writes exactly those already-resolved booleans, a plain
// UPDATE, not a presence-sentinel one.
await this.shareTokensRepo.updateFlags(journeyId, {
share_timeline: share_timeline ? 1 : 0,
share_gallery: share_gallery ? 1 : 0,
share_map: share_map ? 1 : 0,
newest_first: newest_first ? 1 : 0,
share_plan: share_plan ? 1 : 0,
share_recordings: share_recordings ? 1 : 0,
});
return { token: existing.token, created: false };
}
const { share_timeline = true, share_gallery = true, share_map = true, newest_first = false } = permissions;
const {
share_timeline = true,
share_gallery = true,
share_map = true,
newest_first = false,
share_plan = false,
share_recordings = false,
} = permissions;
const token = crypto.randomBytes(24).toString('base64url');
// JS3.
@@ -126,6 +143,8 @@ export class JourneyShareService {
share_gallery: share_gallery ? 1 : 0,
share_map: share_map ? 1 : 0,
newest_first: newest_first ? 1 : 0,
share_plan: share_plan ? 1 : 0,
share_recordings: share_recordings ? 1 : 0,
});
return { token, created: true };
});
@@ -160,6 +179,8 @@ export class JourneyShareService {
share_gallery: !!row.share_gallery,
share_map: !!row.share_map,
newest_first: !!row.newest_first,
share_plan: !!row.share_plan,
share_recordings: !!row.share_recordings,
};
}
@@ -848,6 +848,8 @@ export class JourneyController {
share_gallery: body.share_gallery as boolean | undefined,
share_map: body.share_map as boolean | undefined,
newest_first: body.newest_first as boolean | undefined,
share_plan: body.share_plan,
share_recordings: body.share_recordings,
});
if (!result) {
throw new HttpException({ error: 'Not allowed' }, 403);
+6 -2
View File
@@ -17,7 +17,7 @@ import { AddonsService } from '../addons/addons.service';
import { JourneyDomainService } from './journey-domain.service';
import { JourneyPhotoCaptureService } from './journey-photo-capture.service';
import { JourneyShareService } from './journey-share.service';
import { idSchema, journeyUpdateRequestSchema } from '@trek/shared';
import { idSchema, journeyShareLinkRequestSchema, journeyUpdateRequestSchema } from '@trek/shared';
import { z } from 'zod';
@@ -780,13 +780,15 @@ export class JourneyMcp {
@Tool({
name: 'create_journey_share_link',
description:
'Create or update the public share link for a journey. Owner only. Flags left out keep their current value on an existing link; a new link defaults to timeline/gallery/map on.',
'Create or update the public share link for a journey. Owner only. Flags left out keep their current value on an existing link; a new link defaults to timeline/gallery/map on and plan/recordings off. share_plan puts the planned places and GPX tracks on the shared map, share_recordings the recorded days that have a published entry; neither shows anything while share_map is off.',
inputSchema: {
journeyId: idSchema,
share_timeline: z.boolean().optional(),
share_gallery: z.boolean().optional(),
share_map: z.boolean().optional(),
newest_first: z.boolean().optional(),
share_plan: journeyShareLinkRequestSchema.shape.share_plan,
share_recordings: journeyShareLinkRequestSchema.shape.share_recordings,
},
annotations: TOOL_ANNOTATIONS_WRITE,
when: journeyAddonOn,
@@ -802,6 +804,8 @@ export class JourneyMcp {
share_gallery?: boolean;
share_map?: boolean;
newest_first?: boolean;
share_plan?: boolean;
share_recordings?: boolean;
},
ctx: McpContext,
) {
+4 -2
View File
@@ -10,6 +10,8 @@ import { StorageModule } from '../storage/storage.module';
import { StorageService } from '../storage/storage.service';
import { JourneyBookService } from './journey-book.service';
import { JourneyDomainModule } from './journey-domain.module';
import { JourneyMapController } from './journey-map.controller';
import { JourneyMapMcp } from './journey-map.mcp';
import { JourneyPhotoCaptureModule } from './journey-photo-capture.module';
import { JourneyPublicController } from './journey-public.controller';
import { JourneyController } from './journey.controller';
@@ -50,7 +52,7 @@ import { MulterModule } from '@nestjs/platform-express';
// for its own providers only, per that module's own docstring).
MikroOrmModule.forFeature([Users, JourneyBooks]),
],
controllers: [JourneyController, JourneyPublicController],
providers: [JourneyService, JourneyBookService, JourneyMcp],
controllers: [JourneyController, JourneyMapController, JourneyPublicController],
providers: [JourneyService, JourneyBookService, JourneyMcp, JourneyMapMcp],
})
export class JourneyModule {}
@@ -5,6 +5,7 @@ import { ImmichService } from '../memories/immich.service';
import { PhotoProviderRegistry } from '../memories/photo-provider.registry';
import { PhotoResolverService } from '../memories/photo-resolver.service';
import { JourneyDomainService } from './journey-domain.service';
import { JourneyMapService } from './journey-map.service';
import { JourneyShareService } from './journey-share.service';
import { Injectable } from '@nestjs/common';
@@ -26,6 +27,7 @@ export class JourneyService {
private readonly journey: JourneyDomainService,
private readonly share: JourneyShareService,
private readonly immichRepo: UserImmichRepository,
private readonly map: JourneyMapService,
) {}
async journeyAddonEnabled(): Promise<boolean> {
@@ -198,6 +200,9 @@ export class JourneyService {
async getPublicJourney(token: string) {
return this.share.getPublicJourney(token);
}
getPublicMapLayers(token: string) {
return this.map.publicMapLayers(token);
}
validateShareTokenForPhoto(token: string, photoId: number) {
return this.share.validateShareTokenForPhoto(token, photoId);
}