Tours: day GPX import, wanderer trails and planning over an import

- GPX files drop onto the map or a day; the import lands on that day
- wanderer connection per user in Integrations; the workspace offers the
  user's own trails only, behind an admin switch under the Tours addon
- wanderer difficulty is stored on the SAC scale (T1 to T3), backfilled
- a GPX or wanderer import can be planned as an editable tour, either in
  place (the recorded track is kept and can be restored) or as a new tour
  that remembers the import it came from
- rails, rows and detail dialog follow the plan sidebar's cards and badges
- admin addon shelves with more than one row fold, collapsed by default
- reverse-geocoded waypoint names are cached on the device
This commit is contained in:
Maurice
2026-10-15 17:44:15 +02:00
parent 31ffcf1228
commit 782e613506
237 changed files with 13023 additions and 1049 deletions
+2
View File
@@ -69,6 +69,7 @@ export class Places {
reservations_collection = new Collection<Reservations>(this);
roadtrip_day_tracks_collection = new Collection<RoadtripDayTracks>(this);
tours: Ref<Tours> | null = null;
tours_collection = new Collection<Tours>(this);
trip_files_collection = new Collection<TripFiles>(this);
}
@@ -125,6 +126,7 @@ export const PlacesSchema = defineEntity({
reservations_collection: () => p.oneToMany(Reservations).mappedBy('place').hidden(),
roadtrip_day_tracks_collection: () => p.oneToMany(RoadtripDayTracks).mappedBy('place').hidden(),
tours: () => p.oneToOne(Tours).ref().mappedBy('place').hidden(),
tours_collection: () => p.oneToMany(Tours).mappedBy('derivedFromPlace').hidden(),
trip_files_collection: () => p.oneToMany(TripFiles).mappedBy('place').hidden(),
},
});
@@ -0,0 +1,47 @@
import { EntityRepositoryType, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TourSourcesRepository } from '../repositories/TourSources.repository';
import { DbTimestampType } from '../types';
import { Tours } from './Tours.entity';
import { Users } from './Users.entity';
export class TourSources {
[EntityRepositoryType]?: TourSourcesRepository;
[PrimaryKeyProp]?: 'place';
place?: Ref<Tours> | null;
place_id?: number | null;
provider!: string;
instance!: string;
external_id!: string;
external_url?: string | null;
external_updated?: string | null;
content_hash!: string;
local_hash!: string;
imported_at?: string | null;
imported_by?: number | null;
importedByRef?: Ref<Users> | null;
}
export const TourSourcesSchema = defineEntity({
class: TourSources,
repository: () => TourSourcesRepository,
indexes: [
{
name: 'idx_tour_sources_external',
properties: ['provider', 'instance', 'external_id'],
},
],
properties: {
place: () => p.oneToOne(Tours).primary().ref().name('place_id').deleteRule('cascade').nullable().hidden(),
place_id: p.integer().nullable().persist(false),
provider: p.text(),
instance: p.text(),
external_id: p.text(),
external_url: p.text().nullable(),
external_updated: p.text().nullable(),
content_hash: p.text(),
local_hash: p.text(),
imported_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
imported_by: p.integer().nullable().persist(false).index('idx_tour_sources_imported_by'),
importedByRef: () => p.manyToOne(Users).ref().joinColumn('imported_by').nullable().hidden().index('idx_tour_sources_imported_by'),
},
});
+16
View File
@@ -1,6 +1,7 @@
import { Collection, EntityRepositoryType, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { ToursRepository } from '../repositories/Tours.repository';
import { Places } from './Places.entity';
import { TourSources } from './TourSources.entity';
import { TourTypes } from './TourTypes.entity';
import { TourWaypoints } from './TourWaypoints.entity';
@@ -21,13 +22,24 @@ export class Tours {
max_hiking_difficulty?: number | null = 2;
planned_duration_minutes?: number | null;
break_additional_minutes?: number | null;
derivedFromPlace?: Ref<Places> | null;
derived_from_place_id?: number | null;
recorded_route_geometry?: string | null;
tourTypeRef!: Ref<TourTypes>;
tour_sources: Ref<TourSources> | null = null;
tour_waypoints_collection = new Collection<TourWaypoints>(this);
}
export const ToursSchema = defineEntity({
class: Tours,
repository: () => ToursRepository,
indexes: [
{
name: 'idx_tours_derived_from_place_id',
where: 'derived_from_place_id IS NOT NULL',
properties: ['derived_from_place_id'],
},
],
properties: {
place: () => p.oneToOne(Places).primary().ref().deleteRule('cascade').nullable().hidden(),
place_id: p.integer().nullable().persist(false),
@@ -43,7 +55,11 @@ export const ToursSchema = defineEntity({
max_hiking_difficulty: p.integer().nullable(),
planned_duration_minutes: p.integer().nullable(),
break_additional_minutes: p.integer().nullable(),
derivedFromPlace: () => p.manyToOne(Places).ref().nullable().hidden(),
derived_from_place_id: p.integer().nullable().persist(false),
recorded_route_geometry: p.text().nullable(),
tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_tours_tour_type'),
tour_sources: () => p.oneToOne(TourSources).ref().mappedBy('place').hidden(),
tour_waypoints_collection: () => p.oneToMany(TourWaypoints).mappedBy('place').hidden(),
},
});
+6
View File
@@ -51,6 +51,7 @@ import { ShareTokens } from './ShareTokens.entity';
import { Tags } from './Tags.entity';
import { TodoCategoryAssignees } from './TodoCategoryAssignees.entity';
import { TodoItems } from './TodoItems.entity';
import { TourSources } from './TourSources.entity';
import { TrekPhotos } from './TrekPhotos.entity';
import { TripAlbumLinks } from './TripAlbumLinks.entity';
import { TripDocumentLinks } from './TripDocumentLinks.entity';
@@ -70,6 +71,7 @@ import { VacayUserSettings } from './VacayUserSettings.entity';
import { VacayUserYears } from './VacayUserYears.entity';
import { VisitedCountries } from './VisitedCountries.entity';
import { VisitedRegions } from './VisitedRegions.entity';
import { WandererConnections } from './WandererConnections.entity';
import { WebauthnChallenges } from './WebauthnChallenges.entity';
import { WebauthnCredentials } from './WebauthnCredentials.entity';
@@ -174,6 +176,7 @@ export class Users {
tags_collection = new Collection<Tags>(this);
todo_category_assignees_collection = new Collection<TodoCategoryAssignees>(this);
todo_items_collection = new Collection<TodoItems>(this);
tour_sources_collection = new Collection<TourSources>(this);
trek_photos_collection = new Collection<TrekPhotos>(this);
trip_album_links_collection = new Collection<TripAlbumLinks>(this);
trip_document_links_collection = new Collection<TripDocumentLinks>(this);
@@ -195,6 +198,7 @@ export class Users {
vacay_user_years_collection = new Collection<VacayUserYears>(this);
visited_countries_collection = new Collection<VisitedCountries>(this);
visited_regions_collection = new Collection<VisitedRegions>(this);
wanderer_connections: Ref<WandererConnections> | null = null;
webauthn_challenges_collection = new Collection<WebauthnChallenges>(this);
webauthn_credentials_collection = new Collection<WebauthnCredentials>(this);
}
@@ -315,6 +319,7 @@ export const UsersSchema = defineEntity({
tags_collection: () => p.oneToMany(Tags).mappedBy('user').hidden(),
todo_category_assignees_collection: () => p.oneToMany(TodoCategoryAssignees).mappedBy('user').hidden(),
todo_items_collection: () => p.oneToMany(TodoItems).mappedBy('assignedUser').hidden(),
tour_sources_collection: () => p.oneToMany(TourSources).mappedBy('importedByRef').hidden(),
trek_photos_collection: () => p.oneToMany(TrekPhotos).mappedBy('owner').hidden(),
trip_album_links_collection: () => p.oneToMany(TripAlbumLinks).mappedBy('user').hidden(),
trip_document_links_collection: () => p.oneToMany(TripDocumentLinks).mappedBy('createdByRef').hidden(),
@@ -336,6 +341,7 @@ export const UsersSchema = defineEntity({
vacay_user_years_collection: () => p.oneToMany(VacayUserYears).mappedBy('user').hidden(),
visited_countries_collection: () => p.oneToMany(VisitedCountries).mappedBy('user').hidden(),
visited_regions_collection: () => p.oneToMany(VisitedRegions).mappedBy('user').hidden(),
wanderer_connections: () => p.oneToOne(WandererConnections).ref().mappedBy('user').hidden(),
webauthn_challenges_collection: () => p.oneToMany(WebauthnChallenges).mappedBy('user').hidden(),
webauthn_credentials_collection: () => p.oneToMany(WebauthnCredentials).mappedBy('user').hidden(),
},
@@ -0,0 +1,36 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { WandererConnectionsRepository } from '../repositories/WandererConnections.repository';
import { DbTimestampType } from '../types';
import { Users } from './Users.entity';
export class WandererConnections {
[EntityRepositoryType]?: WandererConnectionsRepository;
[PrimaryKeyProp]?: 'user';
user?: Ref<Users> | null;
user_id?: number | null;
url!: string;
token?: string | null;
allow_insecure_tls: number & Opt = 0;
last_checked_at?: string | null;
last_check_ok?: number | null;
last_check_error?: string | null;
created_at?: string | null;
updated_at?: string | null;
}
export const WandererConnectionsSchema = defineEntity({
class: WandererConnections,
repository: () => WandererConnectionsRepository,
properties: {
user: () => p.oneToOne(Users).primary().ref().deleteRule('cascade').nullable().hidden(),
user_id: p.integer().nullable().persist(false),
url: p.text(),
token: p.text().nullable(),
allow_insecure_tls: p.integer().default(0),
last_checked_at: p.text().nullable(),
last_check_ok: p.integer().nullable(),
last_check_error: p.text().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
+4
View File
@@ -103,6 +103,7 @@ import { ShareTokensSchema } from './ShareTokens.entity';
import { TagsSchema } from './Tags.entity';
import { TodoCategoryAssigneesSchema } from './TodoCategoryAssignees.entity';
import { TodoItemsSchema } from './TodoItems.entity';
import { TourSourcesSchema } from './TourSources.entity';
import { TourTypesSchema } from './TourTypes.entity';
import { TourWaypointsSchema } from './TourWaypoints.entity';
import { ToursSchema } from './Tours.entity';
@@ -130,6 +131,7 @@ import { VacayUserYearsSchema } from './VacayUserYears.entity';
import { VacayYearsSchema } from './VacayYears.entity';
import { VisitedCountriesSchema } from './VisitedCountries.entity';
import { VisitedRegionsSchema } from './VisitedRegions.entity';
import { WandererConnectionsSchema } from './WandererConnections.entity';
import { WebauthnChallengesSchema } from './WebauthnChallenges.entity';
import { WebauthnCredentialsSchema } from './WebauthnCredentials.entity';
@@ -238,6 +240,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
TagsSchema,
TodoCategoryAssigneesSchema,
TodoItemsSchema,
TourSourcesSchema,
TourTypesSchema,
TourWaypointsSchema,
ToursSchema,
@@ -265,6 +268,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
VacayYearsSchema,
VisitedCountriesSchema,
VisitedRegionsSchema,
WandererConnectionsSchema,
WebauthnChallengesSchema,
WebauthnCredentialsSchema,
];
+16
View File
@@ -0,0 +1,16 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface TourSourcesTable {
place_id: InsertOptional<number>;
provider: string;
instance: string;
external_id: string;
external_url: InsertOptional<string | null>;
external_updated: InsertOptional<string | null>;
content_hash: string;
local_hash: string;
imported_at: InsertOptional<string | null>;
imported_by: InsertOptional<number | null>;
}
+2
View File
@@ -16,4 +16,6 @@ export interface ToursTable {
max_hiking_difficulty: InsertOptional<number | null>;
planned_duration_minutes: InsertOptional<number | null>;
break_additional_minutes: InsertOptional<number | null>;
derived_from_place_id: InsertOptional<number | null>;
recorded_route_geometry: InsertOptional<string | null>;
}
@@ -0,0 +1,15 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface WandererConnectionsTable {
user_id: InsertOptional<number>;
url: string;
token: InsertOptional<string | null>;
allow_insecure_tls: InsertOptional<number>;
last_checked_at: InsertOptional<string | null>;
last_check_ok: InsertOptional<number | null>;
last_check_error: InsertOptional<string | null>;
created_at: InsertOptional<string | null>;
updated_at: InsertOptional<string | null>;
}
+4
View File
@@ -109,6 +109,7 @@ import type { ShareTokensTable } from './ShareTokens.table';
import type { TagsTable } from './Tags.table';
import type { TodoCategoryAssigneesTable } from './TodoCategoryAssignees.table';
import type { TodoItemsTable } from './TodoItems.table';
import type { TourSourcesTable } from './TourSources.table';
import type { TourTypesTable } from './TourTypes.table';
import type { TourWaypointsTable } from './TourWaypoints.table';
import type { ToursTable } from './Tours.table';
@@ -136,6 +137,7 @@ import type { VacayUserYearsTable } from './VacayUserYears.table';
import type { VacayYearsTable } from './VacayYears.table';
import type { VisitedCountriesTable } from './VisitedCountries.table';
import type { VisitedRegionsTable } from './VisitedRegions.table';
import type { WandererConnectionsTable } from './WandererConnections.table';
import type { WebauthnChallengesTable } from './WebauthnChallenges.table';
import type { WebauthnCredentialsTable } from './WebauthnCredentials.table';
@@ -250,6 +252,7 @@ export interface DB {
tags: TagsTable;
todo_category_assignees: TodoCategoryAssigneesTable;
todo_items: TodoItemsTable;
tour_sources: TourSourcesTable;
tour_types: TourTypesTable;
tour_waypoints: TourWaypointsTable;
tours: ToursTable;
@@ -277,6 +280,7 @@ export interface DB {
vacay_years: VacayYearsTable;
visited_countries: VisitedCountriesTable;
visited_regions: VisitedRegionsTable;
wanderer_connections: WandererConnectionsTable;
webauthn_challenges: WebauthnChallengesTable;
webauthn_credentials: WebauthnCredentialsTable;
}
@@ -0,0 +1,53 @@
import { Migration } from '@mikro-orm/migrations';
/**
* A personal wanderer connection, and where an imported tour came from.
*
* `wanderer_connections` holds one user's instance address and API token, the
* token encrypted like every other integration credential. It is the user's
* own and is never shared with a trip; what a trip gets is the snapshot.
*
* `tour_sources` records, for a tour copied in from an outside source, which
* source it was (the provider, the instance, the trail's id there), when it was
* copied and two fingerprints: the content as the source delivered it, to tell
* on a later import whether the source changed, and the tour as it was saved
* here, to tell whether it was changed since. It is not wanderer-specific, so
* other sources can record their provenance the same way. It goes with its tour.
*/
export class Migration20200101043400_wanderer_connection_and_tour_sources extends Migration {
override name = 'Migration20200101043400_wanderer_connection_and_tour_sources';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS wanderer_connections (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
url TEXT NOT NULL,
token TEXT,
allow_insecure_tls INTEGER NOT NULL DEFAULT 0,
last_checked_at TEXT,
last_check_ok INTEGER,
last_check_error TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
this.addSql(`
CREATE TABLE IF NOT EXISTS tour_sources (
place_id INTEGER PRIMARY KEY REFERENCES tours(place_id) ON DELETE CASCADE,
provider TEXT NOT NULL,
instance TEXT NOT NULL,
external_id TEXT NOT NULL,
external_url TEXT,
external_updated TEXT,
content_hash TEXT NOT NULL,
local_hash TEXT NOT NULL,
imported_at DATETIME DEFAULT CURRENT_TIMESTAMP,
imported_by INTEGER REFERENCES users(id) ON DELETE SET NULL
)
`);
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_tour_sources_external ON tour_sources(provider, instance, external_id)',
);
this.addSql('CREATE INDEX IF NOT EXISTS idx_tour_sources_imported_by ON tour_sources(imported_by)');
}
}
@@ -0,0 +1,22 @@
import { Migration } from '@mikro-orm/migrations';
/**
* Tours imported from wanderer carry wanderer's own word for how hard they are
* (`difficulty`: easy, moderate, difficult), and tours show one scale only, the
* SAC grade in `max_hiking_difficulty`. An import now writes both; this gives
* the imports made before that their grade the same way: easy is T1, moderate
* T2, difficult T3. A grade someone already set is left as it is.
*/
export class Migration20200101043500_wanderer_difficulty_on_the_sac_scale extends Migration {
override name = 'Migration20200101043500_wanderer_difficulty_on_the_sac_scale';
override up(): void {
this.addSql(`
UPDATE tours
SET max_hiking_difficulty = CASE difficulty WHEN 'easy' THEN 1 WHEN 'moderate' THEN 2 WHEN 'difficult' THEN 3 END
WHERE wanderer_ref IS NOT NULL
AND max_hiking_difficulty IS NULL
AND difficulty IN ('easy', 'moderate', 'difficult')
`);
}
}
@@ -0,0 +1,18 @@
import { Migration } from '@mikro-orm/migrations';
/**
* A tour planned from an imported one (a GPX file or a wanderer snapshot,
* re-routed through control points taken from its track) remembers which import
* it came from, so the tour can say so. The import stays as it was; deleting it
* leaves the derived tour standing and only forgets where it came from.
*/
export class Migration20200101043600_a_tour_remembers_the_import_it_was_derived_from extends Migration {
override name = 'Migration20200101043600_a_tour_remembers_the_import_it_was_derived_from';
override up(): void {
this.addSql('ALTER TABLE tours ADD COLUMN derived_from_place_id INTEGER REFERENCES places(id) ON DELETE SET NULL');
this.addSql(
'CREATE INDEX IF NOT EXISTS idx_tours_derived_from_place_id ON tours(derived_from_place_id) WHERE derived_from_place_id IS NOT NULL',
);
}
}
@@ -0,0 +1,15 @@
import { Migration } from '@mikro-orm/migrations';
/**
* An import (a GPX file or a wanderer snapshot) can be planned over in place:
* the tour keeps its id, its days and its notes, and gets waypoints and a line
* routed through them. The track it was recorded with is kept here the first
* time that happens, so the tour can go back to it whenever its owner wants.
*/
export class Migration20200101043700_an_import_planned_over_keeps_its_recorded_track extends Migration {
override name = 'Migration20200101043700_an_import_planned_over_keeps_its_recorded_track';
override up(): void {
this.addSql('ALTER TABLE tours ADD COLUMN recorded_route_geometry TEXT');
}
}
@@ -0,0 +1,79 @@
import type { TourSources } from '../entities/TourSources.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/** Where an imported tour came from, as it is written once at the import. */
export interface TourSourceInsert {
place_id: number;
provider: string;
instance: string;
external_id: string;
external_url: string | null;
external_updated: string | null;
content_hash: string;
local_hash: string;
imported_by: number;
}
/** A snapshot of an outside source in a trip, with the tour as it stands now. */
export interface TourSnapshotRow {
place_id: number;
external_id: string;
content_hash: string;
local_hash: string;
imported_at: string | null;
name: string;
description: string | null;
route_geometry: string | null;
}
type SourcesDB = Pick<DB, 'tour_sources' | 'places'>;
/**
* `tour_sources`: the provenance of tours copied in from outside, one row per
* tour, gone with the tour. The source's own id is not unique here on purpose:
* importing a changed trail again makes a second snapshot beside the first.
*/
export class TourSourcesRepository extends TrekRepository<TourSources> {
private db() {
return this.kysely<SourcesDB>();
}
/** Written in the same transaction as the tour it describes. */
async insertSource(row: TourSourceInsert): Promise<void> {
await this.db().insertInto('tour_sources').values(row).execute();
}
/**
* Every snapshot in the trip of the given trails of one instance, newest
* first, with the tour's current name and line for comparing.
*/
async listSnapshots(
tripId: number,
provider: string,
instance: string,
externalIds: readonly string[],
): Promise<TourSnapshotRow[]> {
if (externalIds.length === 0) return [];
return await this.db()
.selectFrom('tour_sources as s')
.innerJoin('places as p', 'p.id', 's.place_id')
.select([
's.place_id',
's.external_id',
's.content_hash',
's.local_hash',
's.imported_at',
'p.name',
'p.description',
'p.route_geometry',
])
.where('p.trip_id', '=', tripId)
.where('s.provider', '=', provider)
.where('s.instance', '=', instance)
.where('s.external_id', 'in', [...externalIds])
.orderBy('s.imported_at', 'desc')
.orderBy('s.place_id', 'desc')
.execute();
}
}
+75 -3
View File
@@ -25,6 +25,8 @@ export interface TourListRow {
wanderer_ref: string | null;
match_confidence: number | null;
max_hiking_difficulty: number | null;
derived_from_place_id: number | null;
has_recorded_track: number;
planned: number;
has_waypoints: number;
}
@@ -44,6 +46,8 @@ export interface TourRow {
match_confidence: number | null;
created_at: string | null;
max_hiking_difficulty: number | null;
derived_from_place_id: number | null;
recorded_route_geometry: string | null;
}
const _tourRowKeys: AssertRowKeys<TourRow, Tours> = true;
@@ -105,6 +109,8 @@ export class ToursRepository extends TrekRepository<Tours> {
't.wanderer_ref as wanderer_ref',
't.match_confidence as match_confidence',
't.max_hiking_difficulty as max_hiking_difficulty',
't.derived_from_place_id as derived_from_place_id',
eb('t.recorded_route_geometry', 'is not', null).as('has_recorded_track'),
eb
.exists(eb.selectFrom('day_assignments as da').select('da.id').whereRef('da.place_id', '=', 'p.id'))
.as('planned'),
@@ -184,8 +190,21 @@ export class ToursRepository extends TrekRepository<Tours> {
}
/** TO7 — `INSERT INTO tours (place_id, tour_type, distance, ...) VALUES (...)`. */
async insertTour(input: TourInsert): Promise<void> {
/**
* `wanderer_ref` and `difficulty` are set only by an import from a source that
* carries them, `derived_from_place_id` only by a tour planned from an import.
*/
async insertTour(
input: TourInsert & {
wanderer_ref?: string | null;
difficulty?: string | null;
derived_from_place_id?: number | null;
},
): Promise<void> {
await this.insert({
derivedFromPlace: input.derived_from_place_id ?? null,
wanderer_ref: input.wanderer_ref ?? null,
difficulty: input.difficulty ?? null,
place: input.place_id,
tourTypeRef: input.tour_type,
distance: input.distance,
@@ -238,10 +257,63 @@ export class ToursRepository extends TrekRepository<Tours> {
.executeTakeFirst();
return Number(result.numUpdatedRows ?? 0) > 0;
}
/**
* Keeps an import's recorded line before it is planned over for the first
* time: copies the place's line into the tour while the tour has no
* waypoints and nothing kept yet. One statement, so it cannot keep a line
* that a concurrent edit already replaced.
*/
async keepRecordedTrack(place_id: number): Promise<void> {
await this.db()
.updateTable('tours')
.set((eb) => ({
recorded_route_geometry: eb
.selectFrom('places')
.select('places.route_geometry')
.where('places.id', '=', place_id),
}))
.where('place_id', '=', place_id)
.where('recorded_route_geometry', 'is', null)
.where((eb) =>
eb.not(
eb.exists(
eb.selectFrom('tour_waypoints').select('tour_waypoints.id').where('tour_waypoints.place_id', '=', place_id),
),
),
)
.execute();
}
/** The recorded line kept for a tour of the trip, or null when it has none. */
async findRecordedTrack(trip_id: number, place_id: number): Promise<string | null> {
const row = await this.db()
.selectFrom('tours as t')
.innerJoin('places as p', 'p.id', 't.place_id')
.select('t.recorded_route_geometry')
.where('t.place_id', '=', place_id)
.where('p.trip_id', '=', trip_id)
.executeTakeFirst();
return row?.recorded_route_geometry ?? null;
}
/** Forgets the kept line once the tour has gone back to it. */
async clearRecordedTrack(place_id: number): Promise<void> {
await this.nativeUpdate({ place: place_id }, { recorded_route_geometry: null });
}
}
function toListRow<
R extends Omit<TourListRow, 'planned' | 'has_waypoints'> & { planned: unknown; has_waypoints: unknown },
R extends Omit<TourListRow, 'planned' | 'has_waypoints' | 'has_recorded_track'> & {
planned: unknown;
has_waypoints: unknown;
has_recorded_track: unknown;
},
>(r: R): TourListRow {
return { ...r, planned: Number(r.planned), has_waypoints: Number(r.has_waypoints) };
return {
...r,
planned: Number(r.planned),
has_waypoints: Number(r.has_waypoints),
has_recorded_track: Number(r.has_recorded_track),
};
}
@@ -0,0 +1,87 @@
import { currentTimestampKysely } from '../dialect/kysely-functions';
import { currentTimestamp } from '../dialect/sql-functions';
import type { WandererConnections } from '../entities/WandererConnections.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
/**
* One user's wanderer connection as stored. `token` is the still-encrypted
* value; the service decrypts it for a call and never hands it on.
*/
export interface WandererConnectionRow {
user_id: number;
url: string;
token: string | null;
allow_insecure_tls: number;
last_checked_at: string | null;
last_check_ok: number | null;
last_check_error: string | null;
}
/**
* `wanderer_connections`: one row per user who connected an instance, the
* user id its primary key. Only the owner's own requests read or write it.
*/
export class WandererConnectionsRepository extends TrekRepository<WandererConnections> {
private db() {
return this.kysely<Pick<DB, 'wanderer_connections'>>();
}
private platform() {
return this.getEntityManager().getPlatform();
}
async findRow(userId: number): Promise<WandererConnectionRow | null> {
const row = await this.db()
.selectFrom('wanderer_connections')
.select(['user_id', 'url', 'token', 'allow_insecure_tls', 'last_checked_at', 'last_check_ok', 'last_check_error'])
.where('user_id', '=', userId)
.executeTakeFirst();
return row ?? null;
}
/**
* Write the address and the TLS choice, and the token when one is given:
* `undefined` keeps the stored token, `null` drops it. A changed address
* clears what the last check said, since it said it about another server.
*/
async save(
userId: number,
data: { url: string; allowInsecureTls: boolean; token?: string | null; hostChanged: boolean },
): Promise<void> {
const platform = this.platform();
const tokenColumns = data.token !== undefined ? { token: data.token } : {};
const checkColumns = data.hostChanged ? { last_checked_at: null, last_check_ok: null, last_check_error: null } : {};
await this.db()
.insertInto('wanderer_connections')
.values({
user_id: userId,
url: data.url,
allow_insecure_tls: data.allowInsecureTls ? 1 : 0,
...tokenColumns,
updated_at: currentTimestampKysely(platform),
})
.onConflict((oc) =>
oc.column('user_id').doUpdateSet({
url: data.url,
allow_insecure_tls: data.allowInsecureTls ? 1 : 0,
...tokenColumns,
...checkColumns,
updated_at: () => currentTimestampKysely(platform),
}),
)
.execute();
}
/** What the last test or call against the instance said, for the settings card. */
async recordCheck(userId: number, ok: boolean, error: string | null): Promise<void> {
await this.nativeUpdate(
{ user: userId },
{ last_checked_at: currentTimestamp(this.platform()), last_check_ok: ok ? 1 : 0, last_check_error: error },
);
}
async remove(userId: number): Promise<void> {
await this.nativeDelete({ user: userId });
}
}
+17
View File
@@ -67,6 +67,22 @@ export class AddonsService {
return { enabled: !!enabled };
}
/** The admin's switch for wanderer under Tours, as stored; whether Tours is on is asked apart. */
async getToursWanderer() {
const value = await readAppSetting(this.appSettings, 'tours_wanderer_enabled');
return { enabled: value === 'true' };
}
async updateToursWanderer(enabled: boolean) {
await this.appSettings.setValue('tours_wanderer_enabled', enabled ? 'true' : 'false');
return { enabled: !!enabled };
}
/** wanderer may be used: Tours is on and the admin allowed it under Tours. */
async isWandererAvailable(): Promise<boolean> {
return (await this.isAddonEnabled(ADDON_IDS.TOURS)) && (await this.getToursWanderer()).enabled;
}
/**
* `AppSettingsRepository.getValues` drops a key from the returned `Map`
* both when no row exists AND when the row's `value` is `NULL` (Task 0
@@ -146,6 +162,7 @@ export class AddonsService {
return {
collabFeatures: await this.getCollabFeatures(),
bagTracking: (await this.getBagTracking()).enabled,
toursWanderer: await this.isWandererAvailable(),
addons: [
// The repository row carries every scalar column (description, config,
// sort_order included); the legacy statement selected only these five,
+21
View File
@@ -10,6 +10,7 @@ import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { RegistrationInvitesService } from '../auth/registration-invites.service';
import { KitineraryExtractorService } from '../booking-import/kitinerary-extractor.service';
import { ManagedForbidden } from '../common/managed';
import { ResponseContract } from '../common/response-contract';
import { NotificationsService } from '../notifications/notifications.service';
import { OauthService } from '../oauth/oauth.service';
import { PluginRuntimeService } from '../plugins/plugin-runtime.service';
@@ -41,6 +42,7 @@ import {
Req,
UseGuards,
} from '@nestjs/common';
import { adminFeatureToggleResponseSchema } from '@trek/shared';
import type { Request } from 'express';
@@ -283,6 +285,25 @@ export class AdminController {
return result;
}
@Get('tours-wanderer')
@ResponseContract(adminFeatureToggleResponseSchema)
getToursWanderer() {
return this.addons.getToursWanderer();
}
@Put('tours-wanderer')
@ResponseContract(adminFeatureToggleResponseSchema)
async updateToursWanderer(@CurrentUser() user: User, @Body() body: AdminFeatureToggleDto, @Req() req: Request) {
const result = await this.addons.updateToursWanderer(body.enabled);
await this.audit.writeAudit({
userId: user.id,
action: 'admin.tours_wanderer',
ip: getClientIp(req),
details: { enabled: result.enabled },
});
return result;
}
@Get('places-photos')
getPlacesPhotos() {
return this.addons.getPlacesPhotos();
+2
View File
@@ -92,6 +92,7 @@ import { TransitModule } from './transit/transit.module';
import { TripInviteModule } from './trip-invite/trip-invite.module';
import { TripsModule } from './trips/trips.module';
import { VacayModule } from './vacay/vacay.module';
import { WandererModule } from './wanderer/wanderer.module';
import { WeatherModule } from './weather/weather.module';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
@@ -152,6 +153,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
PlacesModule,
RoadtripModule,
ToursModule,
WandererModule,
FerratasModule,
TripsModule,
CollabModule,
@@ -106,6 +106,8 @@ export const APP_SETTINGS = {
places_enrich_enabled: { schema: flag, default: 'true', publicConfig: true },
place_shadow_enabled: { schema: flag, default: 'false', publicConfig: true },
bag_tracking_enabled: { schema: flag, default: 'false' },
// Off until an admin allows it: every user's wanderer calls go out to an address of their choosing.
tours_wanderer_enabled: { schema: flag, default: 'false' },
route_usage_enabled: { schema: flag, default: 'false' },
airtrail_sync_enabled: { schema: flag, default: 'true' },
airtrail_poll_interval_minutes: { schema: intText, default: null },
@@ -0,0 +1,7 @@
import { wandererImportRequestSchema, wandererSearchRequestSchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
/** The trip-side wanderer routes' bodies, validated by the global Zod pipe against the shared contracts. */
export class WandererSearchDto extends createZodDto(wandererSearchRequestSchema) {}
export class WandererImportDto extends createZodDto(wandererImportRequestSchema) {}
@@ -0,0 +1,54 @@
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 { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
import { WandererEnabledGuard } from '../wanderer/wanderer-enabled.guard';
import { WandererImportDto, WandererSearchDto } from './dto/tours-wanderer.dto';
import { ToursWandererService } from './tours-wanderer.service';
import { Body, Controller, Get, Headers, HttpCode, Param, Post, UseGuards } from '@nestjs/common';
import { wandererImportPreviewSchema, wandererImportResponseSchema, wandererSearchResponseSchema } from '@trek/shared';
/**
* `/api/trips/:tripId/tours/wanderer`: the caller's wanderer trails, seen from
* a trip. Searching and previewing run on the caller's own connection, and
* only someone who may add places to the trip gets to look, since looking is
* the first step of importing. The import writes a tour like the GPX import
* does, so it asks the same right.
*/
@Controller('api/trips/:tripId/tours/wanderer')
@UseGuards(AddonGuard, JwtAuthGuard, WandererEnabledGuard, TripAccessGuard)
@RequireAddon(ADDON_IDS.TOURS, 'Tours')
export class ToursWandererController {
constructor(private readonly wanderer: ToursWandererService) {}
@RequirePermission('place_edit')
@Post('search')
@HttpCode(200)
@ResponseContract(wandererSearchResponseSchema)
search(@Param('tripId') tripId: string, @CurrentUser() user: User, @Body() body: WandererSearchDto) {
return this.wanderer.search(tripId, user.id, { q: body.q ?? '', page: body.page ?? 1, bbox: body.bbox });
}
@RequirePermission('place_edit')
@Get('trails/:trailId')
@ResponseContract(wandererImportPreviewSchema)
preview(@Param('tripId') tripId: string, @Param('trailId') trailId: string, @CurrentUser() user: User) {
return this.wanderer.preview(tripId, user.id, trailId);
}
@RequirePermission('place_edit')
@Post('import')
@ResponseContract(wandererImportResponseSchema)
import(
@Param('tripId') tripId: string,
@CurrentUser() user: User,
@Body() body: WandererImportDto,
@Headers('x-socket-id') socketId?: string,
) {
return this.wanderer.import(tripId, user.id, body, socketId);
}
}
@@ -0,0 +1,270 @@
import { Places } from '../../db/entities/Places.entity';
import { TourSources } from '../../db/entities/TourSources.entity';
import { Tours } from '../../db/entities/Tours.entity';
import type { PlacesRepository } from '../../db/repositories/Places.repository';
import type { TourSnapshotRow, TourSourcesRepository } from '../../db/repositories/TourSources.repository';
import type { ToursRepository } from '../../db/repositories/Tours.repository';
import { thinLine } from '../../utils/polyline';
import { DomainError } from '../common/domain-error';
import { toRowId } from '../common/row-id';
import { UnitOfWork } from '../database/unit-of-work';
import { PlaceImportService } from '../place-import/place-import.service';
import { PlacesService } from '../places/places.service';
import { WandererService } from '../wanderer/wanderer.service';
import { computeTourMetrics, parseRouteGeometry, type GeometryPoint } from './tours.helpers';
import { ToursService } from './tours.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable, Logger } from '@nestjs/common';
import type {
WandererImportPreview,
WandererImportRequest,
WandererImportResponse,
WandererSearchRequest,
WandererSearchResponse,
} from '@trek/shared';
import { wandererDifficultyToSac } from '@trek/shared';
import { createHash } from 'node:crypto';
const PROVIDER = 'wanderer';
/** The line the preview draws: the whole tour, thinned for the map. */
const PREVIEW_LINE_POINTS = 800;
/** A short stable fingerprint of one part of a trail. */
function fingerprint(value: unknown): string {
return createHash('sha256').update(JSON.stringify(value)).digest('hex').slice(0, 16);
}
/** Coordinates to five places (a metre) and heights to the metre, so a re-export with other float noise reads the same. */
function normalizedRoute(points: readonly GeometryPoint[]): number[][] {
return points.map(([lat, lng, ele]) =>
ele == null ? [+lat.toFixed(5), +lng.toFixed(5)] : [+lat.toFixed(5), +lng.toFixed(5), Math.round(ele)],
);
}
/** What the source delivered, part by part: `name.description.route`. */
function contentHashOf(name: string, description: string | null, route: readonly GeometryPoint[]): string {
return [fingerprint(name.trim()), fingerprint((description ?? '').trim()), fingerprint(normalizedRoute(route))].join(
'.',
);
}
/** The tour as saved here: `name.route`, to tell later whether it was edited. */
function localHashOf(name: string, route: readonly GeometryPoint[]): string {
return [fingerprint(name.trim()), fingerprint(normalizedRoute(route))].join('.');
}
const CONTENT_PARTS = ['name', 'description', 'route'] as const;
function changedParts(before: string, now: string): Array<(typeof CONTENT_PARTS)[number]> {
const a = before.split('.');
const b = now.split('.');
return CONTENT_PARTS.filter((_, i) => a[i] !== b[i]);
}
/** The trip id the guard already resolved; a malformed one never got this far, and still answers 404. */
function tripRowId(tripId: string): number {
const tid = toRowId(tripId);
if (tid === null) throw new DomainError(404, 'Trip not found');
return tid;
}
/**
* wanderer trails into a trip: the search marked with what the trip already
* holds, the preview of one trail measured from its original GPX and compared
* with an earlier snapshot, and the import that writes the snapshot.
*
* A snapshot is an independent tour. Nothing here updates, replaces or deletes
* one: a changed trail can only be imported again, as a new tour beside the old.
*/
@Injectable()
export class ToursWandererService {
private readonly logger = new Logger(ToursWandererService.name);
constructor(
private readonly uow: UnitOfWork,
private readonly wanderer: WandererService,
private readonly placeImport: PlaceImportService,
private readonly places: PlacesService,
private readonly tours: ToursService,
@InjectRepository(Tours) private readonly toursRepo: ToursRepository,
@InjectRepository(Places) private readonly placesRepo: PlacesRepository,
@InjectRepository(TourSources) private readonly sources: TourSourcesRepository,
) {}
async search(
tripId: string,
userId: number,
request: Required<Pick<WandererSearchRequest, 'q' | 'page'>> & Pick<WandererSearchRequest, 'bbox'>,
): Promise<WandererSearchResponse> {
const tid = tripRowId(tripId);
const found = await this.wanderer.search(userId, request);
const snapshots = await this.sources.listSnapshots(
tid,
PROVIDER,
found.instance,
found.trails.map((trail) => trail.id),
);
return {
trails: found.trails.map((trail) => ({
...trail,
importedAs: snapshots
.filter((snapshot) => snapshot.external_id === trail.id)
.map((snapshot) => snapshot.place_id),
})),
total: found.total,
page: request.page,
pageSize: found.pageSize,
};
}
/** Download and measure one trail, without writing anything. */
private async fetchTrail(userId: number, trailId: string) {
const summary = await this.wanderer.findTrail(userId, trailId);
if (!summary)
throw new DomainError(404, 'Trail not found', { code: 'wanderer_not_found', details: { code: 'not_found' } });
const { instance, trail, gpx } = await this.wanderer.download(userId, trailId);
const rows = this.placeImport.readGpx(Buffer.from(gpx, 'utf8'), {
importWaypoints: false,
importRoutes: true,
importTracks: true,
defaultName: trail.name,
});
// A trail with several segments arrives as several tracks; together they are the one tour.
const route = rows.flatMap((row) => parseRouteGeometry(row.routeGeometry));
if (route.length < 2) {
throw new DomainError(422, 'The trail has no track or route', {
code: 'wanderer_no_track',
details: { code: 'no_track' },
});
}
const description = trail.description?.trim() || null;
// The search index can lag behind an edit; the record itself is what gets imported.
return {
summary: { ...summary, name: trail.name, description },
instance,
trail,
route,
description,
contentHash: contentHashOf(trail.name, description, route),
};
}
/** Every snapshot of the trail in the trip, newest first. */
private async snapshotsOf(tid: number, instance: string, trailId: string): Promise<TourSnapshotRow[]> {
return await this.sources.listSnapshots(tid, PROVIDER, instance, [trailId]);
}
async preview(tripId: string, userId: number, trailId: string): Promise<WandererImportPreview> {
const tid = tripRowId(tripId);
const fetched = await this.fetchTrail(userId, trailId);
const metrics = computeTourMetrics(fetched.route);
const snapshots = await this.snapshotsOf(tid, fetched.instance, trailId);
const latest = snapshots[0];
const changes = latest ? changedParts(latest.content_hash, fetched.contentHash) : [];
return {
trail: { ...fetched.summary, importedAs: snapshots.map((row) => row.place_id) },
distanceKm: metrics.distanceKm ?? 0,
elevationGainM: metrics.elevationGainM,
elevationLossM: metrics.elevationLossM,
hasElevation: metrics.hasElevation,
points: fetched.route.length,
line: thinLine(fetched.route, PREVIEW_LINE_POINTS).map(([lat, lng]) => [lat, lng] as [number, number]),
contentHash: fetched.contentHash,
state: latest ? (changes.length === 0 ? 'unchanged' : 'changed') : 'new',
snapshot: latest
? {
placeId: latest.place_id,
name: latest.name,
importedAt: latest.imported_at ?? '',
// The tour as it stands now against the tour as it was saved at the import.
editedLocally: localHashOf(latest.name, parseRouteGeometry(latest.route_geometry)) !== latest.local_hash,
}
: null,
changes,
};
}
/**
* Write the snapshot: the place with the full line, its tour facet and its
* provenance, all or nothing. Refused when the trail is no longer what the
* preview showed, and when the trip holds a snapshot of exactly this content.
*/
async import(
tripId: string,
userId: number,
request: WandererImportRequest,
socketId?: string,
): Promise<WandererImportResponse> {
const tid = tripRowId(tripId);
const trailId = request.trailId;
const fetched = await this.fetchTrail(userId, trailId);
if (fetched.contentHash !== request.contentHash) {
throw new DomainError(409, 'The trail changed since the preview', {
code: 'wanderer_preview_stale',
details: { code: 'preview_stale' },
});
}
const same = (await this.snapshotsOf(tid, fetched.instance, trailId)).find(
(row) => row.content_hash === fetched.contentHash,
);
if (same) {
throw new DomainError(409, 'This trail is already in the trip', {
code: 'wanderer_already_imported',
details: { code: 'already_imported', placeId: same.place_id },
});
}
const metrics = computeTourMetrics(fetched.route);
const [startLat, startLng] = fetched.route[0];
const name = fetched.trail.name.trim().slice(0, 255) || fetched.summary.name;
const placeId = await this.uow.transactional(async () => {
const id = await this.placesRepo.insertTourPlace({
trip_id: tid,
name,
lat: startLat,
lng: startLng,
route_geometry: JSON.stringify(fetched.route),
description: fetched.description,
website: null,
});
await this.toursRepo.insertTour({
place_id: id,
tour_type: 'hike',
distance: metrics.distanceKm,
elevation_gain: metrics.elevationGainM,
elevation_loss: metrics.elevationLossM,
duration: null,
planned_duration_minutes: null,
break_additional_minutes: null,
match_confidence: metrics.hasElevation ? 1 : 0.3,
// The one scale tours use; the source's own word stays in `difficulty`.
max_hiking_difficulty: wandererDifficultyToSac(fetched.summary.difficulty),
wanderer_ref: `${fetched.instance}#${trailId}`,
difficulty: fetched.summary.difficulty,
});
await this.sources.insertSource({
place_id: id,
provider: PROVIDER,
instance: fetched.instance,
external_id: trailId,
external_url: fetched.summary.externalUrl,
external_updated: fetched.trail.updated ?? null,
content_hash: fetched.contentHash,
local_hash: localHashOf(name, fetched.route),
imported_by: userId,
});
return id;
});
const { tour } = await this.tours.getTour(tripId, String(placeId));
const place = await this.placesRepo.findWithTagsAndRatings(placeId);
try {
this.places.broadcast(tripId, 'tours:changed', { placeIds: [placeId] }, socketId);
if (place) this.places.broadcast(tripId, 'place:created', { place }, socketId);
} catch {
this.logger.warn(`Committed wanderer import ${placeId}: realtime notification failed`);
}
return { tour };
}
}
+16 -1
View File
@@ -2,10 +2,12 @@ import { ADDON_IDS } from '../../addons';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
import { TourCreateDto } from './dto/tour-create.dto';
import { ToursService } from './tours.service';
import { Body, Controller, Get, Headers, Param, Post, Put, UseGuards } from '@nestjs/common';
import { Body, Controller, Get, Headers, HttpCode, Param, Post, Put, UseGuards } from '@nestjs/common';
import { tourDetailResponseSchema } from '@trek/shared';
/**
* /api/trips/:tripId/tours: the Tours facet, read and route edits.
@@ -50,4 +52,17 @@ export class ToursController {
) {
return await this.tours.updateTour(tripId, placeId, body, socketId);
}
/** Takes an import planned over in place back to its recorded track; the planning is dropped. */
@RequirePermission('place_edit')
@Post(':placeId/restore-recorded')
@HttpCode(200)
@ResponseContract(tourDetailResponseSchema)
async restoreRecorded(
@Param('tripId') tripId: string,
@Param('placeId') placeId: string,
@Headers('x-socket-id') socketId?: string,
) {
return await this.tours.restoreRecordedTrack(tripId, placeId, socketId);
}
}
+9 -3
View File
@@ -1,4 +1,5 @@
import { Places } from '../../db/entities/Places.entity';
import { TourSources } from '../../db/entities/TourSources.entity';
import { TourTypes } from '../../db/entities/TourTypes.entity';
import { TourWaypoints } from '../../db/entities/TourWaypoints.entity';
import { Tours } from '../../db/entities/Tours.entity';
@@ -6,7 +7,10 @@ import { AddonsModule } from '../addons/addons.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { PlaceImportModule } from '../place-import/place-import.module';
import { PlacesModule } from '../places/places.module';
import { WandererModule } from '../wanderer/wanderer.module';
import { ToursImportController } from './tours-import.controller';
import { ToursWandererController } from './tours-wanderer.controller';
import { ToursWandererService } from './tours-wanderer.service';
import { ToursController } from './tours.controller';
import { ToursService } from './tours.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
@@ -26,9 +30,11 @@ import { Module } from '@nestjs/common';
PermissionsModule,
AddonsModule,
MikroOrmModule.forFeature([Tours, TourTypes, TourWaypoints, Places]),
// The wanderer import reads trails through the caller's own connection.
WandererModule,
MikroOrmModule.forFeature([Tours, TourTypes, TourWaypoints, TourSources, Places]),
],
controllers: [ToursController, ToursImportController],
providers: [ToursService],
controllers: [ToursController, ToursImportController, ToursWandererController],
providers: [ToursService, ToursWandererService],
})
export class ToursModule {}
+81
View File
@@ -6,6 +6,7 @@ import type { PlacesRepository } from '../../db/repositories/Places.repository';
import type { TourTypesRepository } from '../../db/repositories/TourTypes.repository';
import type { TourWaypointsRepository } from '../../db/repositories/TourWaypoints.repository';
import type { TourListRow, ToursRepository, TourUpdate } from '../../db/repositories/Tours.repository';
import { DomainError } from '../common/domain-error';
import { toRowId } from '../common/row-id';
import { UnitOfWork } from '../database/unit-of-work';
import { PlaceImportService } from '../place-import/place-import.service';
@@ -22,6 +23,8 @@ import {
type TourDetailResponse,
type TourListItem,
type TourWaypoint,
type WandererDifficulty,
wandererDifficultyToSac,
} from '@trek/shared';
export interface ImportGpxAsTourResult {
@@ -68,6 +71,8 @@ export class ToursService {
wanderer_ref: r.wanderer_ref,
match_confidence: r.match_confidence,
max_hiking_difficulty: r.max_hiking_difficulty,
derived_from_place_id: r.derived_from_place_id,
has_recorded_track: Boolean(r.has_recorded_track),
planned: Boolean(r.planned),
caution: r.match_confidence !== null && r.match_confidence < LOW_CONFIDENCE_THRESHOLD,
has_waypoints: Boolean(r.has_waypoints),
@@ -175,8 +180,17 @@ export class ToursService {
this.validatePlannedTimes(input);
const start = input.route_geometry[0];
const fields = this.routeFields(input);
const derivedFrom = input.derived_from_place_id ?? null;
const placeId = await this.uow.transactional(async () => {
// What it was planned from has to be an import (no waypoints of its own) of this same trip,
// read in the write so it cannot go meanwhile.
if (derivedFrom !== null) {
const source = await this.toursRepo.findInTrip(tid, derivedFrom);
if (!source || source.has_waypoints) {
throw new DomainError(400, 'derived_from_place_id is not an imported tour of this trip');
}
}
const id = await this.placesRepo.insertTourPlace({
trip_id: tid,
name: input.name,
@@ -191,6 +205,7 @@ export class ToursService {
...fields,
planned_duration_minutes: fields.planned_duration_minutes ?? null,
break_additional_minutes: fields.break_additional_minutes ?? null,
derived_from_place_id: derivedFrom,
});
await this.waypointsRepo.insertForPlace(id, input.waypoints);
return id;
@@ -212,6 +227,68 @@ export class ToursService {
return { tour: this.toItem(row), waypoints };
}
/**
* Takes an import that was planned over in place back to the track it was
* recorded with: its line, the measures read from that line and the grade
* its source gave, without the waypoints. The tour keeps its id, days and notes.
*/
async restoreRecordedTrack(tripId: string, placeId: string, socketId?: string): Promise<TourDetailResponse> {
const tid = toRowId(tripId);
const pid = toRowId(placeId);
if (tid === null || pid === null) throw new NotFoundException('Tour not found');
await this.uow.transactional(async () => {
const row = await this.toursRepo.findInTrip(tid, pid);
if (!row) throw new NotFoundException('Tour not found');
const recorded = await this.toursRepo.findRecordedTrack(tid, pid);
if (recorded === null) {
throw new DomainError(409, 'This tour keeps no recorded track to go back to', {
code: 'no_recorded_track',
details: { code: 'no_recorded_track' },
});
}
const geometry = parseRouteGeometry(recorded);
const start = geometry[0];
if (!start)
throw new DomainError(409, 'The recorded track of this tour is empty', {
code: 'no_recorded_track',
details: { code: 'no_recorded_track' },
});
const metrics = computeTourMetrics(geometry);
await this.placesRepo.updateTourRoute(pid, tid, {
name: row.name,
lat: start[0],
lng: start[1],
route_geometry: recorded,
});
await this.toursRepo.updateInTrip(tid, pid, {
tour_type: row.tour_type,
distance: metrics.distanceKm,
elevation_gain: metrics.elevationGainM,
elevation_loss: metrics.elevationLossM,
duration: null,
match_confidence: metrics.hasElevation ? 1 : 0.3,
// The grade its source gave, on the one scale tours use; a GPX file gives none.
max_hiking_difficulty: row.wanderer_ref
? wandererDifficultyToSac(row.difficulty as WandererDifficulty | null)
: null,
});
await this.waypointsRepo.deleteForPlace(pid);
await this.toursRepo.clearRecordedTrack(pid);
});
const result = await this.getTour(tripId, placeId);
const place = await this.placesRepo.findWithTagsAndRatings(pid);
if (!place) throw new Error('Restored tour could not be loaded');
this.broadcastToursChanged(tripId, [pid], socketId);
try {
this.places.broadcast(tripId, 'place:updated', { place }, socketId);
} catch {
this.logger.warn(`Committed Tour ${placeId}: place notification failed`);
}
return result;
}
/** Replace a saved tour's derived route and routing controls as one write. */
async updateTour(
tripId: string,
@@ -234,6 +311,8 @@ export class ToursService {
// one, and a place deleted meanwhile answers 404 instead of failing a
// waypoint insert on its foreign key.
if (!(await this.toursRepo.findInTrip(tid, pid))) throw new NotFoundException('Tour not found');
// An import planned over for the first time keeps the track it was recorded with.
await this.toursRepo.keepRecordedTrack(pid);
const placeUpdated = await this.placesRepo.updateTourRoute(pid, tid, {
name: input.name,
lat: start[0],
@@ -328,6 +407,8 @@ export class ToursService {
wanderer_ref: null,
match_confidence: matchConfidence,
max_hiking_difficulty: null,
derived_from_place_id: null,
has_recorded_track: 0,
planned: 0,
has_waypoints: 0,
}),
+1 -60
View File
@@ -98,63 +98,4 @@ export function deriveTransitStats(
};
}
/**
* Google-encoded polyline codec.
*
* The client carries its own decoder for drawing a journey on the map
* (client/src/components/Map/transitGeometry.ts). This pair exists for a
* different job the client never has: the Google backend receives a walk split
* across several navigation steps, each with its own polyline, and has to
* MERGE them into the single walk leg the rest of TREK expects — which needs an
* encoder to put the joined path back on the wire.
*/
export function decodePolyline(encoded: string, precision: number): [number, number][] {
const factor = 10 ** precision;
const points: [number, number][] = [];
let index = 0;
let lat = 0;
let lng = 0;
while (index < encoded.length) {
for (const axis of [0, 1] as const) {
let result = 0;
let shift = 0;
let byte = 0x20;
while (byte >= 0x20) {
if (index >= encoded.length) return points;
byte = (encoded.codePointAt(index++) ?? 0) - 63;
result |= (byte & 0x1f) << shift;
shift += 5;
}
const delta = result & 1 ? ~(result >> 1) : result >> 1;
if (axis === 0) lat += delta;
else lng += delta;
}
points.push([lat / factor, lng / factor]);
}
return points;
}
function encodeSigned(value: number): string {
let remaining = value < 0 ? ~(value << 1) : value << 1;
let out = '';
while (remaining >= 0x20) {
out += String.fromCharCode((0x20 | (remaining & 0x1f)) + 63);
remaining >>= 5;
}
return out + String.fromCharCode(remaining + 63);
}
export function encodePolyline(points: [number, number][], precision: number): string {
const factor = 10 ** precision;
let out = '';
let lastLat = 0;
let lastLng = 0;
for (const [lat, lng] of points) {
const scaledLat = Math.round(lat * factor);
const scaledLng = Math.round(lng * factor);
out += encodeSigned(scaledLat - lastLat) + encodeSigned(scaledLng - lastLng);
lastLat = scaledLat;
lastLng = scaledLng;
}
return out;
}
export { decodePolyline, encodePolyline } from '../../utils/polyline';
+245 -99
View File
@@ -1,31 +1,46 @@
import { Injectable } from '@nestjs/common';
import path from 'path';
import { EntityManager } from '@mikro-orm/core';
import { Trips } from '../../db/entities/Trips.entity';
import { Days } from '../../db/entities/Days.entity';
import { JourneyEntries } from '../../db/entities/JourneyEntries.entity';
import { Users } from '../../db/entities/Users.entity';
import { Places } from '../../db/entities/Places.entity';
import { DayAssignments } from '../../db/entities/DayAssignments.entity';
import { AssignmentParticipants } from '../../db/entities/AssignmentParticipants.entity';
import { Tags } from '../../db/entities/Tags.entity';
import { DayNotes } from '../../db/entities/DayNotes.entity';
import { RoadtripVias } from '../../db/entities/RoadtripVias.entity';
import { RoadtripDayTracks } from '../../db/entities/RoadtripDayTracks.entity';
import { RoadtripPreferences } from '../../db/entities/RoadtripPreferences.entity';
import { RoadtripDayBoundaries } from '../../db/entities/RoadtripDayBoundaries.entity';
import { DayAccommodations } from '../../db/entities/DayAccommodations.entity';
import { Reservations } from '../../db/entities/Reservations.entity';
import { BudgetItems } from '../../db/entities/BudgetItems.entity';
import { BudgetCategoryOrder } from '../../db/entities/BudgetCategoryOrder.entity';
import { BudgetItemMembers } from '../../db/entities/BudgetItemMembers.entity';
import { BudgetItemPayers } from '../../db/entities/BudgetItemPayers.entity';
import { BudgetCategoryOrder } from '../../db/entities/BudgetCategoryOrder.entity';
import { BudgetItems } from '../../db/entities/BudgetItems.entity';
import { DayAccommodations } from '../../db/entities/DayAccommodations.entity';
import { DayAssignments } from '../../db/entities/DayAssignments.entity';
import { DayNotes } from '../../db/entities/DayNotes.entity';
import { Days } from '../../db/entities/Days.entity';
import { JourneyEntries } from '../../db/entities/JourneyEntries.entity';
import { PackingBags } from '../../db/entities/PackingBags.entity';
import { PackingItems } from '../../db/entities/PackingItems.entity';
import { Places } from '../../db/entities/Places.entity';
import { Reservations } from '../../db/entities/Reservations.entity';
import { RoadtripDayBoundaries } from '../../db/entities/RoadtripDayBoundaries.entity';
import { RoadtripDayTracks } from '../../db/entities/RoadtripDayTracks.entity';
import { RoadtripPreferences } from '../../db/entities/RoadtripPreferences.entity';
import { RoadtripVias } from '../../db/entities/RoadtripVias.entity';
import { Tags } from '../../db/entities/Tags.entity';
import { TodoItems } from '../../db/entities/TodoItems.entity';
import { Tours } from '../../db/entities/Tours.entity';
import { TourWaypoints } from '../../db/entities/TourWaypoints.entity';
import { Tours } from '../../db/entities/Tours.entity';
import { Trips } from '../../db/entities/Trips.entity';
import { Users } from '../../db/entities/Users.entity';
import type { TourWaypointRow } from '../../db/repositories/TourWaypoints.repository';
import type { Trip, User } from '../../types';
import { BudgetService, type CurrencyRebase } from '../budget/budget.service';
import { NotFoundError, ValidationError } from '../common/domain-errors';
import { legacyBoundIntegerText } from '../common/row-id';
import { appClock } from '../common/timezoneService';
import { UnitOfWork } from '../database/unit-of-work';
import { DaysService } from '../days/days.service';
import { PermissionsService } from '../permissions/permissions.service';
import { escapeLikePattern } from '../places/places.helpers';
import { RealtimeService } from '../realtime/realtime.service';
import { ReservationsService } from '../reservations/reservations.service';
import { SettingsService } from '../settings/settings.service';
import { StorageService } from '../storage/storage.service';
import { UnsplashService } from '../unsplash/unsplash.service';
import { VacayService } from '../vacay/vacay.service';
import { assertTripSpan } from './trips.helpers';
import { EntityManager } from '@mikro-orm/core';
import { Injectable } from '@nestjs/common';
import {
addIsoDays,
planDayGrid,
@@ -36,22 +51,8 @@ import {
type TrekWsPayload,
type TrekWsTripEventName,
} from '@trek/shared';
import { RealtimeService } from '../realtime/realtime.service';
import { PermissionsService } from '../permissions/permissions.service';
import type { Trip, User } from '../../types';
import { DaysService } from '../days/days.service';
import { BudgetService, type CurrencyRebase } from '../budget/budget.service';
import { ReservationsService } from '../reservations/reservations.service';
import { VacayService } from '../vacay/vacay.service';
import { UnsplashService } from '../unsplash/unsplash.service';
import { StorageService } from '../storage/storage.service';
import { SettingsService } from '../settings/settings.service';
import { escapeLikePattern } from '../places/places.helpers';
import { NotFoundError, ValidationError } from '../common/domain-errors';
import { UnitOfWork } from '../database/unit-of-work';
import { legacyBoundIntegerText } from '../common/row-id';
import { appClock } from '../common/timezoneService';
import { assertTripSpan } from './trips.helpers';
import path from 'path';
interface CreateTripData {
title: string;
@@ -99,7 +100,14 @@ export interface DeleteTripInfo {
}
export interface AddMemberResult {
member: { id: number; username: string; email: string; avatar?: string | null; role: string; avatar_url: string | null };
member: {
id: number;
username: string;
email: string;
avatar?: string | null;
role: string;
avatar_url: string | null;
};
targetUserId: number;
tripTitle: string;
}
@@ -321,7 +329,12 @@ export class TripsService {
return this.permissions.checkPermission(action, role, ownerId, userId, isMember);
}
broadcast<E extends TrekWsTripEventName>(tripId: string, event: E, payload: TrekWsPayload<E>, socketId: string | undefined): void {
broadcast<E extends TrekWsTripEventName>(
tripId: string,
event: E,
payload: TrekWsPayload<E>,
socketId: string | undefined,
): void {
this.realtime.broadcast(tripId, event, payload, socketId);
}
@@ -341,28 +354,40 @@ export class TripsService {
* runs in one `uow.transactional` — a savepoint when `updateTrip`'s own
* block already holds the transaction, its own transaction from `create`.
*/
async generateDays(tripId: number | bigint | string, startDate: string | null, endDate: string | null, dayCount?: number): Promise<DayGridPlan> {
async generateDays(
tripId: number | bigint | string,
startDate: string | null,
endDate: string | null,
dayCount?: number,
): Promise<DayGridPlan> {
const trip_id = Number(tripId);
return await this.uow.transactional(async () => {
const existing = await this.daysRepo.listForDayGrid(trip_id); // TP77
const stays = await this.daysRepo.listDayGridStays(trip_id); // TP78
const plan = planDayGrid({
days: existing.map(d => ({ id: d.id, day_number: d.day_number, date: d.date, hasPlanItems: !!d.has_plan_items })),
days: existing.map((d) => ({
id: d.id,
day_number: d.day_number,
date: d.date,
hasPlanItems: !!d.has_plan_items,
})),
stays,
startDate,
endDate,
dayCount,
});
const dateBefore = new Map(existing.map(d => [d.id, d.date]));
const dateBefore = new Map(existing.map((d) => [d.id, d.date]));
for (let i = 0; i < existing.length; i++) await this.daysRepo.setDayNumber(existing[i].id, -(i + 1)); // TP2
for (let i = 0; i < plan.rows.length; i++) {
const row = plan.rows[i];
if (row.id === null) await this.daysRepo.insertDay({ trip_id, day_number: i + 1, date: row.date }); // TP10
if (row.id === null)
await this.daysRepo.insertDay({ trip_id, day_number: i + 1, date: row.date }); // TP10
// A row that had no date and gets none is only renumbered, so an odd
// stored value is left as it was, the way the rebuild always treated it.
else if (row.date === null && !dateBefore.get(row.id)) await this.daysRepo.setDayNumber(row.id, i + 1); // TP2
else if (row.date === null && !dateBefore.get(row.id))
await this.daysRepo.setDayNumber(row.id, i + 1); // TP2
else await this.daysRepo.setDayNumberAndDate(row.id, i + 1, row.date); // TP9
}
for (const gone of plan.removed) await this.daysRepo.deleteById(gone.id); // TP11
@@ -385,15 +410,19 @@ export class TripsService {
if (startDate && !endDate) endDate = addIsoDays(startDate, 6);
else if (!startDate && endDate) startDate = addIsoDays(endDate, -6);
if (startDate && endDate) assertTripSpan(startDate, endDate);
const rd = data.reminder_days !== undefined
? (Number(data.reminder_days) >= 0 && Number(data.reminder_days) <= 30 ? Number(data.reminder_days) : 3)
: 3;
const rd =
data.reminder_days !== undefined
? Number(data.reminder_days) >= 0 && Number(data.reminder_days) <= 30
? Number(data.reminder_days)
: 3
: 3;
const currency = data.currency || (await this.defaultCurrencyFor(userId));
// The trip and its days commit together: a failure in between used to leave
// a dated trip without a single day.
const tripId = await this.uow.transactional(async () => {
const id = await this.tripsRepo.insertTrip({ // TP18
const id = await this.tripsRepo.insertTrip({
// TP18
user_id: userId,
title: data.title,
description: data.description || null,
@@ -412,7 +441,7 @@ export class TripsService {
/** TP20 — `TripsRepository.findForViewer`: `TRIP_SELECT` scoped to one trip AND the access predicate. */
async get(tripId: string | number, userId: number) {
return await this.tripsRepo.findForViewer(tripId, userId) as Trip | undefined;
return (await this.tripsRepo.findForViewer(tripId, userId)) as Trip | undefined;
}
/**
@@ -428,7 +457,7 @@ export class TripsService {
*/
/** TP21 — `TripsRepository.activeTrip`: the triple `CASE WHEN … relevance` projection and the double-`CASE WHEN` `ORDER BY`. */
async activeTrip(userId: number, today = appClock().date) {
return await this.tripsRepo.activeTrip(userId, today) as ActiveTrip & { relevance: number } | undefined;
return (await this.tripsRepo.activeTrip(userId, today)) as (ActiveTrip & { relevance: number }) | undefined;
}
/**
@@ -472,8 +501,14 @@ export class TripsService {
* rebase, the trip row (TP25), the leave entries that follow its dates and the rebuilt day grid
* are one transaction, so a failing `generateDays` or booking resync leaves all of them as they were.
*/
async updateTrip(tripId: string | number, userId: number, data: UpdateTripData, userRole: string, rebase: CurrencyRebase | null = null): Promise<UpdateTripResult> {
const trip = await this.tripsRepo.findRaw(tripId) as (Trip & { reminder_days?: number }) | null; // TP24
async updateTrip(
tripId: string | number,
userId: number,
data: UpdateTripData,
userRole: string,
rebase: CurrencyRebase | null = null,
): Promise<UpdateTripResult> {
const trip = (await this.tripsRepo.findRaw(tripId)) as (Trip & { reminder_days?: number }) | null; // TP24
if (!trip) throw new NotFoundError('Trip not found');
const { title, description, currency, is_archived, cover_image, reminder_days } = data;
@@ -485,9 +520,12 @@ export class TripsService {
const newArchived = is_archived !== undefined ? (is_archived ? 1 : 0) : trip.is_archived;
const newCover = cover_image !== undefined ? cover_image : trip.cover_image;
const oldReminder = (trip as any).reminder_days ?? 3;
const newReminder = reminder_days !== undefined
? (Number(reminder_days) >= 0 && Number(reminder_days) <= 30 ? Number(reminder_days) : oldReminder)
: oldReminder;
const newReminder =
reminder_days !== undefined
? Number(reminder_days) >= 0 && Number(reminder_days) <= 30
? Number(reminder_days)
: oldReminder
: oldReminder;
const tripIdNum = Number(tripId); // safe: `trip` above only resolved through the raw-bind seam on a real row (Task 6 review's own ruling on this exact conversion)
// The row, the leave entries that follow its dates and the rebuilt day grid are
@@ -497,7 +535,8 @@ export class TripsService {
await this.uow.transactional(async () => {
// Before the row: the rebase reads the outgoing currency off it (#1543).
if (rebase) await this.budget.applyCurrencyRebase(tripId, rebase);
await this.tripsRepo.updateTripRow(tripIdNum, { // TP25
await this.tripsRepo.updateTripRow(tripIdNum, {
// TP25
title: newTitle,
description: newDesc ?? null,
start_date: newStart || null,
@@ -514,19 +553,24 @@ export class TripsService {
});
if (trip.start_date && trip.end_date && newStart && newStart !== trip.start_date)
vacayId = await this.vacay.shiftOwnerEntriesForTripWindow(trip.user_id, trip.start_date, trip.end_date, newStart);
vacayId = await this.vacay.shiftOwnerEntriesForTripWindow(
trip.user_id,
trip.start_date,
trip.end_date,
newStart,
);
if (regenerate) {
// Accommodations have no absolute date columns, so their pre-change dates must be
// snapshotted before generateDays re-dates the day rows in place.
const prevDays = await this.daysRepo.listOrderedForReorder(tripIdNum); // TP26
const prevDateByDayId = new Map(prevDays.map(d => [d.id, d.date]));
const prevDateByDayId = new Map(prevDays.map((d) => [d.id, d.date]));
removedDays = (await this.generateDays(tripId, newStart || null, newEnd || null, dayCount)).removed;
if (data.date_shift_mode === 'shift_all') {
// Explicit "shift everything": bookings stay glued to their (re-dated) day rows,
// so re-stamp reservation_time to follow — same rules as reorderDays/insertDay.
const newDays = await this.daysRepo.listOrderedForReorder(tripIdNum); // TP27
const newDateByDayId = new Map(newDays.map(d => [d.id, d.date]));
const newDateByDayId = new Map(newDays.map((d) => [d.id, d.date]));
await this.days.restampReservationDates(tripIdNum, prevDateByDayId, newDateByDayId);
} else {
// Default: generateDays re-dates day rows positionally; re-anchor dated bookings to
@@ -661,7 +705,8 @@ export class TripsService {
const newTitle = title || src.title;
return await this.uow.transactional(async () => {
const newTripId = await this.tripsRepo.insertTripCopy({ // TP37
const newTripId = await this.tripsRepo.insertTripCopy({
// TP37
user_id: newOwnerId,
title: newTitle,
description: src.description,
@@ -675,8 +720,13 @@ export class TripsService {
const oldDays = await this.daysRepo.listByTrip(Number(sourceTripId)); // TP38
const dayMap = new Map<number, number>();
for (const d of oldDays) {
const newDayId = await this.daysRepo.insertDayCopy({ // TP39
trip_id: newTripId, day_number: d.day_number, date: d.date, notes: d.notes, title: d.title,
const newDayId = await this.daysRepo.insertDayCopy({
// TP39
trip_id: newTripId,
day_number: d.day_number,
date: d.date,
notes: d.notes,
title: d.title,
});
dayMap.set(d.id, newDayId);
}
@@ -684,15 +734,35 @@ export class TripsService {
const oldPlaces = await this.placesRepo.listAllForTrip(sourceTripId); // TP40
const placeMap = new Map<number, number>();
for (const p of oldPlaces) {
const newPlaceId = await this.placesRepo.insertPlaceCopy({ // TP41
trip_id: newTripId, name: p.name, description: p.description, lat: p.lat, lng: p.lng,
address: p.address, category_id: p.category_id, price: p.price, currency: p.currency,
reservation_status: p.reservation_status, reservation_notes: p.reservation_notes,
reservation_datetime: p.reservation_datetime, place_time: p.place_time, end_time: p.end_time,
duration_minutes: p.duration_minutes, notes: p.notes, image_url: p.image_url,
google_place_id: p.google_place_id, google_ftid: p.google_ftid, website: p.website, phone: p.phone,
transport_mode: p.transport_mode, osm_id: p.osm_id, amap_poi_id: p.amap_poi_id,
route_geometry: p.route_geometry, route_color: p.route_color, stop_type: p.stop_type,
const newPlaceId = await this.placesRepo.insertPlaceCopy({
// TP41
trip_id: newTripId,
name: p.name,
description: p.description,
lat: p.lat,
lng: p.lng,
address: p.address,
category_id: p.category_id,
price: p.price,
currency: p.currency,
reservation_status: p.reservation_status,
reservation_notes: p.reservation_notes,
reservation_datetime: p.reservation_datetime,
place_time: p.place_time,
end_time: p.end_time,
duration_minutes: p.duration_minutes,
notes: p.notes,
image_url: p.image_url,
google_place_id: p.google_place_id,
google_ftid: p.google_ftid,
website: p.website,
phone: p.phone,
transport_mode: p.transport_mode,
osm_id: p.osm_id,
amap_poi_id: p.amap_poi_id,
route_geometry: p.route_geometry,
route_color: p.route_color,
stop_type: p.stop_type,
fill_percent: p.fill_percent,
});
placeMap.set(p.id, newPlaceId);
@@ -708,7 +778,13 @@ export class TripsService {
for (const v of oldVias) {
const newDayId = dayMap.get(v.day_id);
if (newDayId) {
await this.roadtripViasRepo.insertVia({ day_id: newDayId, after_order_index: v.after_order_index, sequence: v.sequence, lat: v.lat, lng: v.lng }); // TP43
await this.roadtripViasRepo.insertVia({
day_id: newDayId,
after_order_index: v.after_order_index,
sequence: v.sequence,
lat: v.lat,
lng: v.lng,
}); // TP43
}
}
@@ -743,7 +819,10 @@ export class TripsService {
for (const { place_id, ...tour } of oldTours) {
const newPlaceId = placeMap.get(place_id);
if (!newPlaceId) continue;
await this.toursRepo.insertCopy(newPlaceId, tour);
// A tour planned from an import points at the copied import, never back into the source trip.
const derivedFrom =
tour.derived_from_place_id === null ? null : (placeMap.get(tour.derived_from_place_id) ?? null);
await this.toursRepo.insertCopy(newPlaceId, { ...tour, derived_from_place_id: derivedFrom });
copiedTours.add(place_id);
}
@@ -764,11 +843,18 @@ export class TripsService {
const newDayId = dayMap.get(a.day_id);
const newPlaceId = placeMap.get(a.place_id);
if (newDayId && newPlaceId) {
const newAssignmentId = await this.dayAssignmentsRepo.insertAssignmentCopy({ // TP49
day_id: newDayId, place_id: newPlaceId, order_index: a.order_index, notes: a.notes,
reservation_status: a.reservation_status, reservation_notes: a.reservation_notes,
reservation_datetime: a.reservation_datetime, assignment_time: a.assignment_time,
assignment_end_time: a.assignment_end_time, end_day: a.end_day ?? 0,
const newAssignmentId = await this.dayAssignmentsRepo.insertAssignmentCopy({
// TP49
day_id: newDayId,
place_id: newPlaceId,
order_index: a.order_index,
notes: a.notes,
reservation_status: a.reservation_status,
reservation_notes: a.reservation_notes,
reservation_datetime: a.reservation_datetime,
assignment_time: a.assignment_time,
assignment_end_time: a.assignment_end_time,
end_day: a.end_day ?? 0,
});
assignmentMap.set(a.id, newAssignmentId);
}
@@ -787,7 +873,12 @@ export class TripsService {
// new trip's `roadtrip_day_boundaries` starts empty, same reasoning
// as the via/track upserts above.
if (from && to !== undefined) {
await this.roadtripDayBoundariesRepo.upsertBoundary(newTripId, { day_number: boundary.day_number, from_assignment_id: from, to_assignment_id: to, fraction: boundary.fraction }); // TP52
await this.roadtripDayBoundariesRepo.upsertBoundary(newTripId, {
day_number: boundary.day_number,
from_assignment_id: from,
to_assignment_id: to,
fraction: boundary.fraction,
}); // TP52
}
}
@@ -805,9 +896,17 @@ export class TripsService {
const newStartDay = dayMap.get(a.start_day_id);
const newEndDay = dayMap.get(a.end_day_id);
if (newPlaceId && newStartDay && newEndDay) {
const newAccomId = await this.dayAccommodationsRepo.insertStay({ // TP56
trip_id: newTripId, place_id: newPlaceId, start_day_id: newStartDay, end_day_id: newEndDay,
check_in: a.check_in, check_in_end: a.check_in_end, check_out: a.check_out, confirmation: a.confirmation, notes: a.notes,
const newAccomId = await this.dayAccommodationsRepo.insertStay({
// TP56
trip_id: newTripId,
place_id: newPlaceId,
start_day_id: newStartDay,
end_day_id: newEndDay,
check_in: a.check_in,
check_in_end: a.check_in_end,
check_out: a.check_out,
confirmation: a.confirmation,
notes: a.notes,
});
accomMap.set(a.id, newAccomId);
}
@@ -844,12 +943,22 @@ export class TripsService {
// the NEW value is re-formatted to the legacy raw-bound `'<id>.0'`
// TEXT shape on the way back out — see `legacyBoundIntegerText`.
accommodation_id: newAccomId != null ? legacyBoundIntegerText(newAccomId) : null,
title: r.title, reservation_time: r.reservation_time, reservation_end_time: r.reservation_end_time,
location: r.location, confirmation_number: r.confirmation_number, notes: r.notes, url: r.url, status: r.status, type: r.type,
title: r.title,
reservation_time: r.reservation_time,
reservation_end_time: r.reservation_end_time,
location: r.location,
confirmation_number: r.confirmation_number,
notes: r.notes,
url: r.url,
status: r.status,
type: r.type,
// ingest_state travels with the copy: a staged booking must not turn
// 'live' just because the trip was duplicated, or it lands in the
// duplicate's public feed.
metadata: r.metadata, day_plan_position: r.day_plan_position, needs_review: r.needs_review ?? 0, ingest_state: r.ingest_state ?? 'live',
metadata: r.metadata,
day_plan_position: r.day_plan_position,
needs_review: r.needs_review ?? 0,
ingest_state: r.ingest_state ?? 'live',
}); // TP59
reservationMap.set(r.id, newReservationId);
}
@@ -867,7 +976,7 @@ export class TripsService {
for (const row of [...oldBudgetMembers, ...oldBudgetPayers]) {
if (row.user_id !== newOwnerId) sharedWithOthers.add(row.budget_item_id);
}
const hasSplitRows = new Set(oldBudgetMembers.map(bm => bm.budget_item_id));
const hasSplitRows = new Set(oldBudgetMembers.map((bm) => bm.budget_item_id));
// TP60 — Plan 3e Task 2, converted.
const oldBudget = await this.budgetItemsRepo.listAllForTrip(sourceTripId);
@@ -878,11 +987,18 @@ export class TripsService {
// split is its member count and goes with it; a typed one stays. A receipt
// split names who had which line, so it goes as well.
const newItemId = await this.budgetItemsRepo.insertCopy({
trip_id: newTripId, category: b.category, name: b.name, total_price: b.total_price,
persons: planningOnly && hasSplitRows.has(b.id) ? null : b.persons, days: b.days,
note: b.note, sort_order: b.sort_order,
trip_id: newTripId,
category: b.category,
name: b.name,
total_price: b.total_price,
persons: planningOnly && hasSplitRows.has(b.id) ? null : b.persons,
days: b.days,
note: b.note,
sort_order: b.sort_order,
reservation_id: b.reservation_id ? (reservationMap.get(b.reservation_id) ?? null) : null,
currency: b.currency, exchange_rate: b.exchange_rate ?? 1, expense_date: b.expense_date,
currency: b.currency,
exchange_rate: b.exchange_rate ?? 1,
expense_date: b.expense_date,
ticket_json: planningOnly ? null : b.ticket_json,
paid_by_user_id: b.paid_by_user_id === newOwnerId ? b.paid_by_user_id : null,
});
@@ -893,14 +1009,25 @@ export class TripsService {
if (sharedWithOthers.has(bm.budget_item_id)) continue;
const newItemId = budgetMap.get(bm.budget_item_id);
// TP63 — Plan 3e Task 2, converted.
if (newItemId) await this.budgetItemMembersRepo.insertIgnore({ budget_item_id: newItemId, user_id: bm.user_id, paid: bm.paid ?? 0, amount: bm.amount });
if (newItemId)
await this.budgetItemMembersRepo.insertIgnore({
budget_item_id: newItemId,
user_id: bm.user_id,
paid: bm.paid ?? 0,
amount: bm.amount,
});
}
for (const bp of oldBudgetPayers) {
if (sharedWithOthers.has(bp.budget_item_id)) continue;
const newItemId = budgetMap.get(bp.budget_item_id);
// TP65 — Plan 3e Task 2, converted.
if (newItemId) await this.budgetItemPayersRepo.insertIgnore({ budget_item_id: newItemId, user_id: bp.user_id, amount: bp.amount ?? 0 });
if (newItemId)
await this.budgetItemPayersRepo.insertIgnore({
budget_item_id: newItemId,
user_id: bp.user_id,
amount: bp.amount ?? 0,
});
}
// TP66 — Plan 3e Task 3, converted.
@@ -909,7 +1036,11 @@ export class TripsService {
for (const bag of oldBags) {
// TP67 — Plan 3e Task 3, converted (`insertBag`, PK42's own column set).
const newBagId = await this.packingBagsRepo.insertBag({
trip_id: newTripId, name: bag.name, color: bag.color, sort_order: bag.sort_order, weight_limit_grams: bag.weight_limit_grams,
trip_id: newTripId,
name: bag.name,
color: bag.color,
sort_order: bag.sort_order,
weight_limit_grams: bag.weight_limit_grams,
});
bagMap.set(bag.id, newBagId);
}
@@ -926,9 +1057,14 @@ export class TripsService {
const isPrivate = p.is_private ? 1 : 0;
// TP69 — Plan 3e Task 3, converted.
await this.packingItemsRepo.insertCopy({
trip_id: newTripId, name: p.name, category: p.category, sort_order: p.sort_order, weight_grams: p.weight_grams,
trip_id: newTripId,
name: p.name,
category: p.category,
sort_order: p.sort_order,
weight_grams: p.weight_grams,
bag_id: p.bag_id ? (bagMap.get(p.bag_id) ?? null) : null,
is_private: isPrivate, owner_id: isPrivate ? newOwnerId : null,
is_private: isPrivate,
owner_id: isPrivate ? newOwnerId : null,
});
}
@@ -936,8 +1072,14 @@ export class TripsService {
for (const n of oldNotes) {
const newDayId = dayMap.get(n.day_id);
if (newDayId) {
await this.dayNotesRepo.insertNoteCopy({ // TP71
day_id: newDayId, trip_id: newTripId, text: n.text, time: n.time, icon: n.icon, sort_order: n.sort_order,
await this.dayNotesRepo.insertNoteCopy({
// TP71
day_id: newDayId,
trip_id: newTripId,
text: n.text,
time: n.time,
icon: n.icon,
sort_order: n.sort_order,
});
}
}
@@ -947,8 +1089,13 @@ export class TripsService {
for (const t of oldTodos) {
// TP73 — Plan 3e Task 4, converted (`assigned_user_id` deliberately not carried over).
await this.todoItemsRepo.insertCopy({
trip_id: newTripId, name: t.name, category: t.category, sort_order: t.sort_order,
due_date: t.due_date, description: t.description, priority: t.priority,
trip_id: newTripId,
name: t.name,
category: t.category,
sort_order: t.sort_order,
due_date: t.due_date,
description: t.description,
priority: t.priority,
});
}
@@ -967,7 +1114,6 @@ export class TripsService {
async getCopiedTrip(newTripId: number, userId: number) {
return await this.tripsRepo.findForViewer(newTripId, userId);
}
}
// Defined in common/ so calendar and maps can raise them without importing the
@@ -0,0 +1,23 @@
import { AddonsService } from '../addons/addons.service';
import { DomainError } from '../common/domain-error';
import { CanActivate, Injectable } from '@nestjs/common';
/**
* Lets a wanderer route through only while the admin allows wanderer under
* Tours (Admin, Addons, Tours). Runs after the Tours addon check, so with
* Tours off the caller still hears that Tours is off.
*/
@Injectable()
export class WandererEnabledGuard implements CanActivate {
constructor(private readonly addons: AddonsService) {}
async canActivate(): Promise<boolean> {
if (!(await this.addons.isWandererAvailable())) {
throw new DomainError(404, 'wanderer is not enabled', {
code: 'wanderer_disabled',
details: { code: 'disabled' },
});
}
return true;
}
}
+325
View File
@@ -0,0 +1,325 @@
import { readCappedJson } from '../../utils/cappedFetch';
import { ResponseTooLargeError, safeFetch, SsrfBlockedError } from '../../utils/ssrfGuard';
import { Injectable } from '@nestjs/common';
import { WANDERER_SEARCH_PAGE_SIZE, type WandererBbox, type WandererErrorCode } from '@trek/shared';
import { z } from 'zod';
/**
* The only place that talks to a user's wanderer instance.
*
* Verified against wanderer v0.21.0, its source and a running instance rather
* than its prose docs:
*
* - **Auth** is `Authorization: Bearer wanderer_key_...` on `/api/*`. The web
* hook only exchanges a token that starts with `wanderer_key`; anything else
* is quietly served as an anonymous visitor, and a revoked token answers
* HTTP 500 "Failed to verify API token ... Invalid or revoked API token".
* - So **HTTP 200 proves nothing**. The test lists the caller's own API tokens:
* authenticated, that list holds at least the token being used; anonymous,
* it is empty.
* - **Search** is `POST /api/v1/search/trails` (Meilisearch through the web
* app, scoped to what the caller may see). Its documents carry the trail's
* extent (`min_lat` ... `max_lon`), which is what the map search filters on,
* and a simplified line as an encoded polyline (precision 5).
* - The **original GPX** is a PocketBase file: `GET /api/v1/files/trails/{id}/{gpx}`.
*/
const TIMEOUT_MS = 15_000;
/** A page of twenty search hits with their lines is a few dozen kilobytes. */
const MAX_JSON_BYTES = 2 * 1024 * 1024;
/** The same ceiling the GPX upload has. */
const MAX_GPX_BYTES = 10 * 1024 * 1024;
export interface WandererCreds {
/** Instance origin, without /api. */
baseUrl: string;
token: string;
allowInsecureTls: boolean;
}
/** A failed call, its reason as a code the client translates; `detail` stays in the log. */
export class WandererError extends Error {
constructor(
readonly code: WandererErrorCode,
message: string,
readonly detail?: string,
) {
super(message);
this.name = 'WandererError';
}
}
const tokenListSchema = z.object({
items: z.array(z.object({ user: z.string().nullish() })),
totalItems: z.number().optional(),
});
/** A user record with the ActivityPub actors that stand for it; the local one authors the user's trails. */
const userActorsSchema = z.object({
expand: z
.object({
activitypub_actors_via_user: z.array(z.object({ id: z.string(), is_local: z.boolean().nullish() })).nullish(),
})
.nullish(),
});
const searchHitSchema = z.object({
id: z.string(),
name: z.string(),
description: z.string().nullish(),
location: z.string().nullish(),
distance: z.number().nullish(),
duration: z.number().nullish(),
elevation_gain: z.number().nullish(),
elevation_loss: z.number().nullish(),
difficulty: z.number().nullish(),
public: z.boolean().nullish(),
author_name: z.string().nullish(),
domain: z.string().nullish(),
polyline: z.string().nullish(),
});
export type WandererSearchHit = z.infer<typeof searchHitSchema>;
const searchResultSchema = z.object({
hits: z.array(searchHitSchema),
estimatedTotalHits: z.number().nullish(),
totalHits: z.number().nullish(),
});
const trailSchema = z.object({
id: z.string(),
name: z.string(),
description: z.string().nullish(),
gpx: z.string().nullish(),
updated: z.string().nullish(),
public: z.boolean().nullish(),
author: z.string().nullish(),
});
export type WandererTrailRecord = z.infer<typeof trailSchema>;
/**
* `https://host/sub` from what people paste: a trailing slash, `/api` or the
* full `/api/v1` are all taken off, so the client can append its own.
*/
export function instanceOrigin(baseUrl: string): string {
return baseUrl
.trim()
.replace(/\/+$/, '')
.replace(/\/api\/v1$/i, '')
.replace(/\/api$/i, '');
}
const TLS_CODES = new Set([
'CERT_HAS_EXPIRED',
'DEPTH_ZERO_SELF_SIGNED_CERT',
'SELF_SIGNED_CERT_IN_CHAIN',
'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',
'ERR_TLS_CERT_ALTNAME_INVALID',
]);
function networkFailure(err: unknown): WandererError {
if (err instanceof SsrfBlockedError)
return new WandererError('blocked_address', 'TREK may not reach that wanderer address', err.message);
const cause = (err as { cause?: { code?: string } })?.cause;
if (cause?.code && TLS_CODES.has(cause.code)) {
return new WandererError('tls', 'The wanderer certificate could not be verified', cause.code);
}
if (err instanceof ResponseTooLargeError) return new WandererError('too_large', 'wanderer sent more than expected');
return new WandererError('unreachable', 'Could not reach wanderer', err instanceof Error ? err.message : undefined);
}
async function failureOf(response: Response): Promise<WandererError> {
const text = await response.text().catch(() => '');
if (response.status === 401 || /api token/i.test(text)) {
return new WandererError('unauthorized', 'wanderer did not accept the API token', `HTTP ${response.status}`);
}
if (response.status === 403) return new WandererError('forbidden', 'wanderer refused access', 'HTTP 403');
if (response.status === 404) return new WandererError('not_found', 'wanderer has no such trail', 'HTTP 404');
return new WandererError('server_error', `wanderer answered HTTP ${response.status}`, text.slice(0, 200));
}
/** PocketBase record ids are short lowercase alphanumerics; anything else never reaches a filter or a path. */
export function isTrailId(value: string): boolean {
return /^[a-z0-9]{1,32}$/.test(value);
}
const DIFFICULTIES = ['easy', 'moderate', 'difficult'] as const;
/** wanderer indexes difficulty as 0, 1, 2. */
export function difficultyOf(value: number | null | undefined): (typeof DIFFICULTIES)[number] | null {
return value != null && value >= 0 && value < DIFFICULTIES.length ? DIFFICULTIES[value] : null;
}
/** The Meilisearch filter for trails by these authors; the ids are checked record ids, so they quote safely. */
function authorFilter(authors: readonly string[]): string {
return `author IN [${authors
.filter(isTrailId)
.map((id) => `'${id}'`)
.join(', ')}]`;
}
/** The Meilisearch filter for trails whose extent overlaps the box; a box over the antimeridian takes either side. */
export function bboxFilter(box: WandererBbox): string {
const lon =
box.west > box.east
? `(max_lon >= ${box.west} OR min_lon <= ${box.east})`
: `max_lon >= ${box.west} AND min_lon <= ${box.east}`;
return `max_lat >= ${box.south} AND min_lat <= ${box.north} AND ${lon}`;
}
@Injectable()
export class WandererClient {
private async call(
creds: WandererCreds,
path: string,
init: RequestInit = {},
maxBytes = MAX_JSON_BYTES,
): Promise<Response> {
let response: Response;
try {
response = await safeFetch(
`${instanceOrigin(creds.baseUrl)}${path}`,
{
...init,
headers: { ...(init.headers as Record<string, string>), Authorization: `Bearer ${creds.token}` },
signal: AbortSignal.timeout(TIMEOUT_MS),
},
{ rejectUnauthorized: !creds.allowInsecureTls, maxBytes },
);
} catch (err: unknown) {
throw networkFailure(err);
}
if (!response.ok) throw await failureOf(response);
return response;
}
private async json<T>(creds: WandererCreds, path: string, schema: z.ZodType<T>, init?: RequestInit): Promise<T> {
const response = await this.call(creds, path, {
...init,
headers: { Accept: 'application/json', ...(init?.headers as Record<string, string>) },
});
let body: unknown;
try {
body = await readCappedJson<unknown>(response, MAX_JSON_BYTES);
} catch (err: unknown) {
// An answer that is not JSON at all (a proxy's login page, say) is not a network failure.
if (err instanceof SyntaxError) {
throw new WandererError(
'invalid_response',
'wanderer answered with something TREK does not understand',
err.message,
);
}
throw networkFailure(err);
}
const parsed = schema.safeParse(body);
if (!parsed.success) {
throw new WandererError(
'invalid_response',
'wanderer answered with something TREK does not understand',
parsed.error.message.slice(0, 200),
);
}
return parsed.data;
}
/**
* Proves the token is accepted, and says how many trails it can see. The
* token list is the proof: see the class comment.
*/
async check(creds: WandererCreds): Promise<{ trailCount: number | null }> {
const authors = await this.ownActors(creds);
const count = await this.json(creds, '/api/v1/search/trails', searchResultSchema, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ q: '', options: { limit: 0, filter: [authorFilter(authors)] } }),
}).catch(() => null);
return { trailCount: count?.estimatedTotalHits ?? count?.totalHits ?? null };
}
/**
* The actors that author the token owner's trails. Only those trails are
* offered: the index also lists other people's public trails, and copying
* someone else's trail into a trip is not what a personal connection is for.
* The token list names its owner (an anonymous call lists none, see the
* class comment), and the owner's user record names its actors.
*/
async ownActors(creds: WandererCreds): Promise<string[]> {
const tokens = await this.json(creds, '/api/v1/api-token?perPage=1', tokenListSchema);
const userId = tokens.items[0]?.user;
if (!userId) throw new WandererError('unauthorized', 'wanderer did not accept the API token', 'anonymous');
if (!isTrailId(userId)) throw new WandererError('invalid_response', 'wanderer named its user oddly');
const user = await this.json(
creds,
`/api/v1/user/${encodeURIComponent(userId)}?expand=activitypub_actors_via_user`,
userActorsSchema,
);
const actors = (user.expand?.activitypub_actors_via_user ?? [])
.filter((actor) => actor.is_local !== false && isTrailId(actor.id))
.map((actor) => actor.id);
if (actors.length === 0) throw new WandererError('invalid_response', 'wanderer named no author for the token');
return actors;
}
async search(
creds: WandererCreds,
query: { q: string; page: number; bbox?: WandererBbox },
authors: readonly string[],
): Promise<{ hits: WandererSearchHit[]; total: number }> {
const result = await this.json(creds, '/api/v1/search/trails', searchResultSchema, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
q: query.q,
options: {
limit: WANDERER_SEARCH_PAGE_SIZE,
offset: (query.page - 1) * WANDERER_SEARCH_PAGE_SIZE,
filter: [authorFilter(authors), ...(query.bbox ? [bboxFilter(query.bbox)] : [])],
attributesToRetrieve: Object.keys(searchHitSchema.shape),
},
}),
});
return { hits: result.hits, total: result.estimatedTotalHits ?? result.totalHits ?? result.hits.length };
}
/** One of the owner's trails as the search shows it, or null when it is not theirs or the token cannot see it. */
async searchById(creds: WandererCreds, id: string, authors: readonly string[]): Promise<WandererSearchHit | null> {
if (!isTrailId(id)) return null;
const result = await this.json(creds, '/api/v1/search/trails', searchResultSchema, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
q: '',
options: {
limit: 1,
filter: [`id = '${id}'`, authorFilter(authors)],
attributesToRetrieve: Object.keys(searchHitSchema.shape),
},
}),
});
return result.hits[0] ?? null;
}
async trail(creds: WandererCreds, id: string): Promise<WandererTrailRecord> {
if (!isTrailId(id)) throw new WandererError('not_found', 'wanderer has no such trail');
return await this.json(creds, `/api/v1/trail/${encodeURIComponent(id)}`, trailSchema);
}
/** The trail's original GPX file, as text. */
async gpx(creds: WandererCreds, trail: WandererTrailRecord): Promise<string> {
if (!trail.gpx) throw new WandererError('not_found', 'The trail has no GPX file');
const response = await this.call(
creds,
`/api/v1/files/trails/${encodeURIComponent(trail.id)}/${encodeURIComponent(trail.gpx)}`,
{},
MAX_GPX_BYTES,
);
try {
return await response.text();
} catch (err: unknown) {
throw networkFailure(err);
}
}
}
@@ -0,0 +1,60 @@
import { ADDON_IDS } from '../../addons';
import type { User } from '../../types';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { getClientIp } from '../audit/client-ip';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { WandererEnabledGuard } from './wanderer-enabled.guard';
import { WandererSettingsDto, WandererTestDto } from './wanderer.dto';
import { WandererService } from './wanderer.service';
import { Body, Controller, Delete, Get, HttpCode, Post, Put, Req, UseGuards } from '@nestjs/common';
import {
successResponseSchema,
wandererConnectionSchema,
wandererSaveResponseSchema,
wandererTestResponseSchema,
} from '@trek/shared';
import type { Request } from 'express';
/**
* `/api/integrations/wanderer`: the caller's own wanderer connection. It belongs
* to the Tours addon, which is what it feeds, and only ever touches the
* caller's own row. The test answers 200 with the reason in the body, since a
* form showing someone their own typo needs a field to render, not an error.
*/
@Controller('api/integrations/wanderer')
@UseGuards(AddonGuard, JwtAuthGuard, WandererEnabledGuard)
@RequireAddon(ADDON_IDS.TOURS, 'Tours')
export class WandererController {
constructor(private readonly wanderer: WandererService) {}
@Get('settings')
@ResponseContract(wandererConnectionSchema)
getSettings(@CurrentUser() user: User) {
return this.wanderer.getConnection(user.id);
}
@Put('settings')
@ResponseContract(wandererSaveResponseSchema)
saveSettings(@CurrentUser() user: User, @Body() body: WandererSettingsDto, @Req() req: Request) {
return this.wanderer.save(user.id, body, getClientIp(req));
}
@Delete('settings')
@HttpCode(200)
@ResponseContract(successResponseSchema)
async disconnect(@CurrentUser() user: User, @Req() req: Request) {
await this.wanderer.disconnect(user.id, getClientIp(req));
return { success: true as const };
}
@Post('test')
@HttpCode(200)
@ResponseContract(wandererTestResponseSchema)
test(@CurrentUser() user: User, @Body() body: WandererTestDto) {
return this.wanderer.test(user.id, body);
}
}
+11
View File
@@ -0,0 +1,11 @@
/**
* createZodDto wrappers over the @trek/shared wanderer contracts, so the global
* ZodValidationPipe validates the bodies by metatype and the shared schemas
* stay the one source of truth.
*/
import { wandererSettingsRequestSchema, wandererTestRequestSchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class WandererSettingsDto extends createZodDto(wandererSettingsRequestSchema) {}
export class WandererTestDto extends createZodDto(wandererTestRequestSchema) {}
@@ -0,0 +1,11 @@
/** Two instance addresses point at the same server when they share protocol, host and port. */
export function sameHost(a: string | null, b: string): boolean {
if (!a) return false;
try {
const left = new URL(a);
const right = new URL(b);
return left.protocol === right.protocol && left.host === right.host;
} catch {
return false;
}
}
@@ -0,0 +1,21 @@
import { WandererConnections } from '../../db/entities/WandererConnections.entity';
import { AddonsModule } from '../addons/addons.module';
import { AuditModule } from '../audit/audit.module';
import { WandererClient } from './wanderer.client';
import { WandererController } from './wanderer.controller';
import { WandererService } from './wanderer.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
/**
* The wanderer integration: a user's own connection to their wanderer
* instance and the reads the Tours import builds on. Tours imports this module
* for `WandererService`; the trip-side routes live there.
*/
@Module({
imports: [MikroOrmModule.forFeature([WandererConnections]), AddonsModule, AuditModule],
controllers: [WandererController],
providers: [WandererClient, WandererService],
exports: [WandererService],
})
export class WandererModule {}
@@ -0,0 +1,249 @@
import { WandererConnections } from '../../db/entities/WandererConnections.entity';
import type { WandererConnectionsRepository } from '../../db/repositories/WandererConnections.repository';
import { decodePolyline, thinLine } from '../../utils/polyline';
import { checkSsrf } from '../../utils/ssrfGuard';
import { AuditService } from '../audit/audit.service';
import { decrypt_api_key, maybe_encrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { DomainError } from '../common/domain-error';
import {
difficultyOf,
instanceOrigin,
WandererClient,
WandererError,
type WandererCreds,
type WandererSearchHit,
type WandererTrailRecord,
} from './wanderer.client';
import { sameHost } from './wanderer.helpers';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import {
WANDERER_SEARCH_PAGE_SIZE,
WANDERER_TOKEN_MASK,
type WandererConnection,
type WandererErrorCode,
type WandererSaveResponse,
type WandererSearchRequest,
type WandererSettingsRequest,
type WandererTestRequest,
type WandererTestResponse,
type WandererTrailSummary,
} from '@trek/shared';
/** A list row's line: enough points to read the shape, few enough to send twenty of them. */
const SUMMARY_LINE_POINTS = 120;
/** A trail as found, before the trip says which of them it already holds. */
export type WandererTrailFound = Omit<WandererTrailSummary, 'importedAs'>;
/** What a trip-side caller needs to import a trail: where it is, the record and its GPX. */
export interface WandererTrailDownload {
instance: string;
trail: WandererTrailRecord;
gpx: string;
}
/** An upstream failure as the API answers it: never a 401, which the app reads as its own session ending. */
function refusalOf(err: WandererError): DomainError {
const status = err.code === 'not_found' ? 404 : err.code === 'forbidden' || err.code === 'not_own_trail' ? 403 : 502;
return new DomainError(status, err.message, { code: `wanderer_${err.code}`, details: { code: err.code } });
}
/**
* The wanderer connection of one user: their instance address and API token,
* the test, and the reads a trip's import builds on. The token is encrypted at
* rest and leaves only in the Authorization header of a call to the instance
* it was saved for.
*/
@Injectable()
export class WandererService {
constructor(
@InjectRepository(WandererConnections) private readonly connections: WandererConnectionsRepository,
private readonly client: WandererClient,
private readonly audit: AuditService,
) {}
async getConnection(userId: number): Promise<WandererConnection> {
const row = await this.connections.findRow(userId);
return {
url: row?.url ?? '',
tokenMasked: row?.token ? WANDERER_TOKEN_MASK : '',
allowInsecureTls: !!row?.allow_insecure_tls,
connected: !!(row?.url && row.token),
lastCheckedAt: row?.last_checked_at ?? null,
lastCheckOk: row?.last_check_ok == null ? null : row.last_check_ok === 1,
lastCheckError: (row?.last_check_error as WandererErrorCode | null | undefined) ?? null,
};
}
/**
* Save the address and, when a new one was typed, the token. A token belongs
* to the server it was minted on, so pointing the connection at another host
* without a new token drops the stored one rather than sending it there.
* A private address is saved with a warning: a home-network instance is the
* common case, not an attack.
*/
async save(userId: number, input: WandererSettingsRequest, clientIp: string | null): Promise<WandererSaveResponse> {
const url = instanceOrigin(input.url);
const ssrf = await checkSsrf(url);
if (!ssrf.allowed && !ssrf.isPrivate) {
throw new DomainError(400, ssrf.error ?? 'Invalid wanderer URL', {
code: 'wanderer_invalid_url',
details: { code: 'invalid_url' },
});
}
const previous = await this.connections.findRow(userId);
const typed = input.token && input.token !== WANDERER_TOKEN_MASK ? input.token : undefined;
const hostChanged = !!previous && !sameHost(previous.url, url);
const token = typed !== undefined ? maybe_encrypt_api_key(typed) : hostChanged ? null : undefined;
await this.connections.save(userId, { url, allowInsecureTls: input.allowInsecureTls, token, hostChanged });
await this.audit.writeAudit({
userId,
action: previous ? 'wanderer.updated' : 'wanderer.connected',
ip: clientIp,
details: { url, token_changed: typed !== undefined, ...(ssrf.isPrivate ? { resolved_ip: ssrf.resolvedIp } : {}) },
});
return ssrf.isPrivate ? { success: true, warning: 'private_ip' } : { success: true };
}
/** Forget the connection. Tours imported through it stay: they are the trip's own. */
async disconnect(userId: number, clientIp: string | null): Promise<void> {
await this.connections.remove(userId);
await this.audit.writeAudit({ userId, action: 'wanderer.disconnected', ip: clientIp, details: {} });
}
/**
* Test what the form holds, each field falling back to the saved one, and
* remember the outcome when it tested the saved connection itself.
*/
async test(userId: number, input: WandererTestRequest): Promise<WandererTestResponse> {
const saved = await this.connections.findRow(userId);
const url = input.url ? instanceOrigin(input.url) : saved?.url;
const typed = input.token && input.token !== WANDERER_TOKEN_MASK ? input.token : undefined;
const token =
typed ?? (saved?.token && (!input.url || sameHost(saved.url, url ?? '')) ? decrypt_api_key(saved.token) : null);
if (!url || !token) return { ok: false, code: 'not_connected' };
const ssrf = await checkSsrf(url);
if (!ssrf.allowed) return { ok: false, code: ssrf.isPrivate ? 'blocked_address' : 'invalid_url' };
const testsSaved = !!saved && typed === undefined && sameHost(saved.url, url);
try {
const { trailCount } = await this.client.check({
baseUrl: url,
token,
allowInsecureTls: input.allowInsecureTls ?? !!saved?.allow_insecure_tls,
});
if (testsSaved) await this.noteCheck(userId, true, null);
return { ok: true, trailCount };
} catch (err: unknown) {
if (!(err instanceof WandererError)) throw err;
if (testsSaved) await this.noteCheck(userId, false, err.code);
return { ok: false, code: err.code };
}
}
/** The saved connection ready for a call; a refusal the client can act on when there is none. */
private async credentials(userId: number): Promise<WandererCreds> {
const row = await this.connections.findRow(userId);
const token = row?.token ? decrypt_api_key(row.token) : null;
if (!row?.url || !token) {
throw new DomainError(409, 'wanderer is not connected', {
code: 'wanderer_not_connected',
details: { code: 'not_connected' },
});
}
return { baseUrl: row.url, token, allowInsecureTls: !!row.allow_insecure_tls };
}
/**
* Note on the connection what the instance last said, for its settings card.
* @txStandalone a status note that stands on its own: it is true whatever the call around it does next
*/
private async noteCheck(userId: number, ok: boolean, code: WandererErrorCode | null): Promise<void> {
await this.connections.recordCheck(userId, ok, code);
}
/** A failed call, with a rejected token noted on the connection so its card says so. */
private async failed(userId: number, err: unknown): Promise<never> {
if (!(err instanceof WandererError)) throw err;
if (err.code === 'unauthorized') await this.noteCheck(userId, false, err.code);
throw refusalOf(err);
}
/** The instance this user's connection points at, as the key a snapshot records. */
async instanceOf(userId: number): Promise<string> {
return instanceOrigin((await this.credentials(userId)).baseUrl);
}
async search(
userId: number,
request: Required<Pick<WandererSearchRequest, 'q' | 'page'>> & Pick<WandererSearchRequest, 'bbox'>,
): Promise<{ instance: string; trails: WandererTrailFound[]; total: number; pageSize: number }> {
const creds = await this.credentials(userId);
const instance = instanceOrigin(creds.baseUrl);
try {
const authors = await this.client.ownActors(creds);
const { hits, total } = await this.client.search(
creds,
{ q: request.q, page: request.page, bbox: request.bbox },
authors,
);
return {
instance,
trails: hits.map((hit) => summaryOf(instance, hit)),
total,
pageSize: WANDERER_SEARCH_PAGE_SIZE,
};
} catch (err: unknown) {
return await this.failed(userId, err);
}
}
/** One trail and its original GPX, for the import to measure and copy. */
async download(userId: number, trailId: string): Promise<WandererTrailDownload> {
const creds = await this.credentials(userId);
const instance = instanceOrigin(creds.baseUrl);
try {
const authors = await this.client.ownActors(creds);
const trail = await this.client.trail(creds, trailId);
// Only the connected account's own trails come in, whatever else its token can read.
if (!trail.author || !authors.includes(trail.author)) {
throw new WandererError('not_own_trail', 'Only your own wanderer trails can be imported');
}
const gpx = await this.client.gpx(creds, trail);
return { instance, trail, gpx };
} catch (err: unknown) {
return await this.failed(userId, err);
}
}
/** The list row of a trail by its id, as the search would show it. */
async findTrail(userId: number, trailId: string): Promise<WandererTrailFound | null> {
const creds = await this.credentials(userId);
const instance = instanceOrigin(creds.baseUrl);
try {
const hit = await this.client.searchById(creds, trailId, await this.client.ownActors(creds));
return hit ? summaryOf(instance, hit) : null;
} catch (err: unknown) {
return await this.failed(userId, err);
}
}
}
function summaryOf(instance: string, hit: WandererSearchHit): WandererTrailFound {
const author = hit.author_name ? (hit.domain ? `${hit.author_name}@${hit.domain}` : hit.author_name) : null;
return {
id: hit.id,
name: hit.name,
description: hit.description || null,
location: hit.location || null,
distanceM: hit.distance ?? null,
durationS: hit.duration || null,
elevationGainM: hit.elevation_gain ?? null,
elevationLossM: hit.elevation_loss ?? null,
difficulty: difficultyOf(hit.difficulty),
public: !!hit.public,
author,
line: hit.polyline ? thinLine(decodePolyline(hit.polyline, 5), SUMMARY_LINE_POINTS) : [],
externalUrl: `${instance}/trail/view/@${encodeURIComponent(author ?? '')}/${encodeURIComponent(hit.id)}`,
};
}
+65
View File
@@ -0,0 +1,65 @@
/**
* Google-encoded polyline codec, shared by the domains that read one: the
* transit backends (Google merges a walk split across several steps and needs
* the encoder to put the joined path back on the wire) and wanderer, whose
* search results carry each trail's simplified line this way. The client
* carries its own decoder for drawing on the map
* (client/src/components/Map/transitGeometry.ts).
*/
export function decodePolyline(encoded: string, precision: number): [number, number][] {
const factor = 10 ** precision;
const points: [number, number][] = [];
let index = 0;
let lat = 0;
let lng = 0;
while (index < encoded.length) {
for (const axis of [0, 1] as const) {
let result = 0;
let shift = 0;
let byte = 0x20;
while (byte >= 0x20) {
if (index >= encoded.length) return points;
byte = (encoded.codePointAt(index++) ?? 0) - 63;
result |= (byte & 0x1f) << shift;
shift += 5;
}
const delta = result & 1 ? ~(result >> 1) : result >> 1;
if (axis === 0) lat += delta;
else lng += delta;
}
points.push([lat / factor, lng / factor]);
}
return points;
}
function encodeSigned(value: number): string {
let remaining = value < 0 ? ~(value << 1) : value << 1;
let out = '';
while (remaining >= 0x20) {
out += String.fromCharCode((0x20 | (remaining & 0x1f)) + 63);
remaining >>= 5;
}
return out + String.fromCharCode(remaining + 63);
}
export function encodePolyline(points: [number, number][], precision: number): string {
const factor = 10 ** precision;
let out = '';
let lastLat = 0;
let lastLng = 0;
for (const [lat, lng] of points) {
const scaledLat = Math.round(lat * factor);
const scaledLng = Math.round(lng * factor);
out += encodeSigned(scaledLat - lastLat) + encodeSigned(scaledLng - lastLng);
lastLat = scaledLat;
lastLng = scaledLng;
}
return out;
}
/** At most `max` points, evenly picked, the first and the last always kept. */
export function thinLine<T>(points: readonly T[], max: number): T[] {
if (points.length <= max) return [...points];
const step = (points.length - 1) / (max - 1);
return Array.from({ length: max }, (_, i) => points[Math.round(i * step)]);
}