mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 22:57:32 +00:00
feat(tours): import KML and KMZ routes as tours, with a preview first
A route planned in Google My Maps or Google Earth can now become a tour without converting it to GPX first. The import button and a file dropped on the tours workspace take .kml and .kmz files beside .gpx, through the same preview, the same import routes and the same transaction as a GPX file. The preview shows every line of the file on its own, numbered, with its distance and heights; two lines of one placemark are numbered after its name and never joined. Heights count only where they are heights: kept for an absolute line, dropped for any other altitude mode and for the all-zero placeholder My Maps writes, so a missing height stays unknown. What the file holds besides its lines (pins, areas, overlays, links to other files) is counted in a dashed card, and nothing is fetched from elsewhere. The KML reading reuses the place import's codec. A KMZ only ever has its KML entry unpacked, counted byte by byte against the decompressed cap whatever its header claims. A file that cannot be read is refused with its reason (damaged, an archive without KML, too large unpacked), and the toast names the file and the reason. A KML or KMZ import keeps the gpx origin of a file import; its provenance names the real format from the stored file name.
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* The names an import gives the lines of one file. Routes and tracks rarely
|
||||
* carry their own name. Without one they would all fall back to the same
|
||||
* generic label, so name-based dedup would drop every import after the first.
|
||||
* The base is the source file's name (without its extension) and an index
|
||||
* keeps several unnamed lines of one file distinct: `walk`, `walk 2`, `walk 3`.
|
||||
*/
|
||||
type GeometryNamer = (explicit: string | null, fallback: string) => string;
|
||||
|
||||
export function createGeometryNamer(defaultName: string | null | undefined): GeometryNamer {
|
||||
const rawName = defaultName != null ? String(defaultName).trim() : null;
|
||||
const baseName = rawName ? rawName.replace(/\.[^.]+$/, '').trim() || rawName : null;
|
||||
let unnamed = 0;
|
||||
return (explicit, fallback) => {
|
||||
if (explicit) return explicit;
|
||||
unnamed++;
|
||||
const base = baseName || fallback;
|
||||
return unnamed === 1 ? base : `${base} ${unnamed}`;
|
||||
};
|
||||
}
|
||||
@@ -8,12 +8,24 @@
|
||||
* either a point or a path's first point plus the path as route geometry.
|
||||
* Which placemarks become places, and under which category, is the importing
|
||||
* domain's decision.
|
||||
*
|
||||
* The Tours import reads the same document for its lines instead (IO-02):
|
||||
* every LineString and gx:Track, also inside a MultiGeometry or gx:MultiTrack,
|
||||
* as a line of its own, and a count of what it leaves out.
|
||||
*/
|
||||
import { stripHtmlTags } from '../common/stripHtmlTags';
|
||||
import type { KmlDocumentRead, KmlImportSummary, ParsedKmlPlacemark } from './place-import.types';
|
||||
import {
|
||||
KmlReadError,
|
||||
type KmlDocumentRead,
|
||||
type KmlImportSummary,
|
||||
type KmlLeftOut,
|
||||
type KmlLineRead,
|
||||
type KmlLinesRead,
|
||||
type ParsedKmlPlacemark,
|
||||
} from './place-import.types';
|
||||
|
||||
import { XMLParser, XMLValidator } from 'fast-xml-parser';
|
||||
import unzipper from 'unzipper';
|
||||
import unzipper, { type File as ZipEntry } from 'unzipper';
|
||||
import { TextDecoder } from 'util';
|
||||
|
||||
export type { ParsedKmlPlacemark } from './place-import.types';
|
||||
@@ -52,6 +64,15 @@ function asArray<T>(value: T | T[] | null | undefined): T[] {
|
||||
return Array.isArray(value) ? value : [value];
|
||||
}
|
||||
|
||||
/** One parsed element: its children and attributes by name. */
|
||||
type KmlNode = Readonly<Record<string, unknown>>;
|
||||
|
||||
const isKmlNode = (value: unknown): value is KmlNode =>
|
||||
value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
|
||||
/** A child of a parsed element by name; nothing for text or an empty element. */
|
||||
const field = (value: unknown, name: string): unknown => (isKmlNode(value) ? value[name] : undefined);
|
||||
|
||||
function asTrimmedString(value: unknown): string | null {
|
||||
if (value == null) return null;
|
||||
// Parsed objects (mixed-content XML parsed without stopNodes) must not
|
||||
@@ -111,7 +132,9 @@ export function sanitizeKmlDescription(value: unknown): string | null {
|
||||
return decoded || null;
|
||||
}
|
||||
|
||||
function parseKmlLineStringCoordinates(value: unknown): Array<{ lat: number; lng: number; ele: number | null }> | null {
|
||||
type LinePoint = { lat: number; lng: number; ele: number | null };
|
||||
|
||||
function parseKmlLineStringCoordinates(value: unknown): LinePoint[] | null {
|
||||
const coordinates = asTrimmedString(value);
|
||||
if (!coordinates) return null;
|
||||
|
||||
@@ -126,7 +149,7 @@ function parseKmlLineStringCoordinates(value: unknown): Array<{ lat: number; lng
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return null;
|
||||
return { lat, lng, ele: Number.isFinite(eleRaw) ? eleRaw : null };
|
||||
})
|
||||
.filter((p): p is { lat: number; lng: number; ele: number | null } => p !== null);
|
||||
.filter((p): p is LinePoint => p !== null);
|
||||
|
||||
return points.length >= 2 ? points : null;
|
||||
}
|
||||
@@ -156,19 +179,15 @@ function createKmlImportSummary(totalPlacemarks: number): KmlImportSummary {
|
||||
};
|
||||
}
|
||||
|
||||
export function extractKmlPlacemarkNodes(kmlRoot: any): KmlPlacemarkNode[] {
|
||||
const nodes: KmlPlacemarkNode[] = [];
|
||||
|
||||
const visitNode = (node: any, currentFolderName: string | null): void => {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
|
||||
for (const placemark of asArray(node.Placemark)) {
|
||||
nodes.push({ placemark, folderName: currentFolderName });
|
||||
}
|
||||
/** Every container of a document (the root, its Documents and Folders), each before its own, with its folder name. */
|
||||
function visitKmlContainers(kmlRoot: unknown, visit: (node: KmlNode, folderName: string | null) => void): void {
|
||||
const visitNode = (node: unknown, currentFolderName: string | null): void => {
|
||||
if (!isKmlNode(node)) return;
|
||||
visit(node, currentFolderName);
|
||||
|
||||
for (const folder of asArray(node.Folder)) {
|
||||
// Nested folders inherit/override folder context used for category matching.
|
||||
const folderName = asTrimmedString(folder?.name) || currentFolderName;
|
||||
const folderName = asTrimmedString(field(folder, 'name')) || currentFolderName;
|
||||
visitNode(folder, folderName);
|
||||
}
|
||||
|
||||
@@ -178,6 +197,15 @@ export function extractKmlPlacemarkNodes(kmlRoot: any): KmlPlacemarkNode[] {
|
||||
};
|
||||
|
||||
visitNode(kmlRoot, null);
|
||||
}
|
||||
|
||||
export function extractKmlPlacemarkNodes(kmlRoot: any): KmlPlacemarkNode[] {
|
||||
const nodes: KmlPlacemarkNode[] = [];
|
||||
visitKmlContainers(kmlRoot, (node, folderName) => {
|
||||
for (const placemark of asArray(node.Placemark)) {
|
||||
nodes.push({ placemark, folderName });
|
||||
}
|
||||
});
|
||||
return nodes;
|
||||
}
|
||||
|
||||
@@ -206,39 +234,165 @@ export function parsePlacemarkNode(node: KmlPlacemarkNode): ParsedKmlPlacemark {
|
||||
}
|
||||
|
||||
/**
|
||||
* A KML document as its placemarks (each level's own before its folders'), with the summary the
|
||||
* import fills in. Throws the two messages the import route has always
|
||||
* answered for a broken file.
|
||||
* A KML file as its parsed root element. Throws the two messages the import
|
||||
* route has always answered for a broken file.
|
||||
*/
|
||||
export function readKmlDocument(fileBuffer: Buffer): KmlDocumentRead {
|
||||
function parseKmlRoot(fileBuffer: Buffer): { kmlRoot: KmlNode; warning: string | null } {
|
||||
const decoded = decodeUtf8WithWarning(fileBuffer);
|
||||
|
||||
const validationResult = XMLValidator.validate(decoded.text);
|
||||
if (validationResult !== true) {
|
||||
throw new Error('Malformed KML: invalid XML structure');
|
||||
throw new KmlReadError('malformed', 'Malformed KML: invalid XML structure');
|
||||
}
|
||||
|
||||
const parsed = kmlParser.parse(decoded.text);
|
||||
const kmlRoot = parsed?.kml ?? parsed;
|
||||
const parsed: unknown = kmlParser.parse(decoded.text);
|
||||
const kmlRoot = field(parsed, 'kml') ?? parsed;
|
||||
|
||||
if (!kmlRoot || typeof kmlRoot !== 'object') {
|
||||
throw new Error('Malformed KML: could not parse XML');
|
||||
if (!isKmlNode(kmlRoot)) {
|
||||
throw new KmlReadError('malformed', 'Malformed KML: could not parse XML');
|
||||
}
|
||||
|
||||
return { kmlRoot, warning: decoded.warning };
|
||||
}
|
||||
|
||||
/**
|
||||
* A KML document as its placemarks (each level's own before its folders'), with the summary the
|
||||
* import fills in.
|
||||
*/
|
||||
export function readKmlDocument(fileBuffer: Buffer): KmlDocumentRead {
|
||||
const { kmlRoot, warning } = parseKmlRoot(fileBuffer);
|
||||
|
||||
const placemarkNodes = extractKmlPlacemarkNodes(kmlRoot);
|
||||
const summary = createKmlImportSummary(placemarkNodes.length);
|
||||
|
||||
if (decoded.warning) {
|
||||
summary.warnings.push(decoded.warning);
|
||||
if (warning) {
|
||||
summary.warnings.push(warning);
|
||||
}
|
||||
|
||||
return { placemarks: placemarkNodes.map(parsePlacemarkNode), summary };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Lines for the Tours import (IO-02)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** What a document holds besides placemarks that the Tours import never reads: overlays, and links it never follows. */
|
||||
const LEFT_OUT_FEATURES = ['NetworkLink', 'GroundOverlay', 'ScreenOverlay', 'PhotoOverlay'] as const;
|
||||
|
||||
/** The points of a gx:Track, each `<gx:coord>` written `lng lat alt` with spaces. */
|
||||
function parseKmlTrackCoordinates(value: unknown): LinePoint[] | null {
|
||||
const points = asArray(value).flatMap((coord): LinePoint[] => {
|
||||
const [lng = Number.NaN, lat = Number.NaN, ele = Number.NaN] = (asTrimmedString(coord) ?? '')
|
||||
.split(/\s+/)
|
||||
.map((part) => Number.parseFloat(part));
|
||||
if (!Number.isFinite(lat) || !Number.isFinite(lng)) return [];
|
||||
return [{ lat, lng, ele: Number.isFinite(ele) ? ele : null }];
|
||||
});
|
||||
return points.length >= 2 ? points : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A line as route geometry, `[lat, lng, ele]` only where its heights can be
|
||||
* trusted as heights. KML's default altitude mode is clampToGround, under
|
||||
* which an altitude means nothing, and Google My Maps writes a 0 for every
|
||||
* point. So the heights are kept when the line says `absolute`, dropped when
|
||||
* it names any other mode, and without a mode kept unless every one is 0. A
|
||||
* line with a point lacking one keeps none, as a GPX track does.
|
||||
*/
|
||||
export function kmlLineGeometry(points: LinePoint[], altitudeMode: string | null): number[][] {
|
||||
const complete = points.every((p) => p.ele !== null);
|
||||
const meaningful = altitudeMode === null ? points.some((p) => p.ele !== 0) : altitudeMode === 'absolute';
|
||||
return points.map((p) => (complete && meaningful && p.ele !== null ? [p.lat, p.lng, p.ele] : [p.lat, p.lng]));
|
||||
}
|
||||
|
||||
/** One geometry element of a placemark taken apart into its lines; what is not a line is counted as left out. */
|
||||
function collectKmlLines(node: KmlNode, inheritedMode: string | null, lines: number[][][], leftOut: KmlLeftOut): void {
|
||||
const mode = asTrimmedString(node.altitudeMode) ?? inheritedMode;
|
||||
const shapes = [
|
||||
...asArray(node.LineString).map((line) => ({
|
||||
line,
|
||||
points: parseKmlLineStringCoordinates(field(line, 'coordinates')),
|
||||
})),
|
||||
...asArray(node.Track).map((line) => ({ line, points: parseKmlTrackCoordinates(field(line, 'coord')) })),
|
||||
];
|
||||
for (const { line, points } of shapes) {
|
||||
if (points) lines.push(kmlLineGeometry(points, asTrimmedString(field(line, 'altitudeMode')) ?? mode));
|
||||
else leftOut.other += 1;
|
||||
}
|
||||
for (const group of [...asArray(node.MultiGeometry), ...asArray(node.MultiTrack)]) {
|
||||
if (isKmlNode(group)) collectKmlLines(group, mode, lines, leftOut);
|
||||
}
|
||||
leftOut.points += asArray(node.Point).length;
|
||||
leftOut.areas += asArray(node.Polygon).length;
|
||||
leftOut.other += asArray(node.Model).length + asArray(node.LinearRing).length;
|
||||
}
|
||||
|
||||
const leftOutTotal = (leftOut: KmlLeftOut) => leftOut.points + leftOut.areas + leftOut.other;
|
||||
|
||||
/**
|
||||
* A placemark's lines, each kept apart: two lines of one placemark are never
|
||||
* joined into one, they are numbered after its name instead.
|
||||
*/
|
||||
function placemarkLines(placemark: unknown, leftOut: KmlLeftOut): KmlLineRead[] {
|
||||
const geometries: number[][][] = [];
|
||||
const before = leftOutTotal(leftOut);
|
||||
if (isKmlNode(placemark)) collectKmlLines(placemark, null, geometries, leftOut);
|
||||
// A placemark that held nothing at all, not even something left out, is counted once.
|
||||
if (geometries.length === 0 && leftOutTotal(leftOut) === before) leftOut.other += 1;
|
||||
|
||||
const name = asTrimmedString(field(placemark, 'name'));
|
||||
const description = sanitizeKmlDescription(field(placemark, 'description'));
|
||||
return geometries.map((geometry, index) => ({
|
||||
name: name && geometries.length > 1 ? `${name} (${index + 1}/${geometries.length})` : name,
|
||||
description,
|
||||
geometry,
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* A KML document as the lines a tour can be made of, in document order, and a
|
||||
* count of what it holds besides: single points, areas, and everything else
|
||||
* (models, overlays, links to other files, which are never followed, and
|
||||
* lines too short to be one).
|
||||
*/
|
||||
export function readKmlLines(fileBuffer: Buffer): KmlLinesRead {
|
||||
const { kmlRoot, warning } = parseKmlRoot(fileBuffer);
|
||||
const leftOut: KmlLeftOut = { points: 0, areas: 0, other: 0 };
|
||||
const lines = extractKmlPlacemarkNodes(kmlRoot).flatMap(({ placemark }) => placemarkLines(placemark, leftOut));
|
||||
visitKmlContainers(kmlRoot, (node) => {
|
||||
for (const feature of LEFT_OUT_FEATURES) leftOut.other += asArray(node[feature]).length;
|
||||
});
|
||||
return { lines, leftOut, warnings: warning ? [warning] : [] };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// KMZ unpacking
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const tooLarge = () =>
|
||||
new KmlReadError('archive_too_large', 'KMZ archive exceeds the maximum allowed decompressed size.');
|
||||
|
||||
/**
|
||||
* An archive entry decompressed, stopped as soon as it passes the limit. The
|
||||
* size an entry's header states is only a claim, so the bytes themselves are
|
||||
* counted: a crafted archive cannot unpack more than the limit by lying.
|
||||
*/
|
||||
export async function readKmzEntryCapped(entry: Pick<ZipEntry, 'stream'>, limit: number): Promise<Buffer> {
|
||||
const chunks: Buffer[] = [];
|
||||
let size = 0;
|
||||
for await (const chunk of entry.stream()) {
|
||||
const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array);
|
||||
size += bytes.length;
|
||||
if (size > limit) throw tooLarge();
|
||||
chunks.push(bytes);
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
/**
|
||||
* The KML a KMZ archive carries. Only that one entry is read: images and
|
||||
* other files beside it are never unpacked, run or fetched.
|
||||
*/
|
||||
export async function unpackKmzToKml(
|
||||
kmzBuffer: Buffer,
|
||||
decompressedSizeLimit = KMZ_DECOMPRESSED_SIZE_LIMIT,
|
||||
@@ -247,21 +401,27 @@ export async function unpackKmzToKml(
|
||||
try {
|
||||
zip = await unzipper.Open.buffer(kmzBuffer);
|
||||
} catch {
|
||||
throw new Error('Invalid KMZ archive.');
|
||||
throw new KmlReadError('archive_invalid', 'Invalid KMZ archive.');
|
||||
}
|
||||
|
||||
const kmlEntries = zip.files.filter(
|
||||
(entry) => !entry.path.endsWith('/') && entry.path.toLowerCase().endsWith('.kml'),
|
||||
);
|
||||
if (kmlEntries.length === 0) {
|
||||
throw new Error('KMZ archive does not contain a KML file.');
|
||||
throw new KmlReadError('archive_without_kml', 'KMZ archive does not contain a KML file.');
|
||||
}
|
||||
|
||||
const preferredEntry = kmlEntries.find((entry) => entry.path.toLowerCase().endsWith('doc.kml')) || kmlEntries[0];
|
||||
|
||||
if (preferredEntry.uncompressedSize > decompressedSizeLimit) {
|
||||
throw new Error('KMZ archive exceeds the maximum allowed decompressed size.');
|
||||
throw tooLarge();
|
||||
}
|
||||
|
||||
return preferredEntry.buffer();
|
||||
try {
|
||||
return await readKmzEntryCapped(preferredEntry, decompressedSizeLimit);
|
||||
} catch (err) {
|
||||
if (err instanceof KmlReadError) throw err;
|
||||
// A damaged entry fails while it inflates, not while the directory is read.
|
||||
throw new KmlReadError('archive_invalid', 'Invalid KMZ archive.');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
GoogleListPlace,
|
||||
GpxImportOptions,
|
||||
KmlDocumentRead,
|
||||
KmlTracksRead,
|
||||
ListImportError,
|
||||
ListRead,
|
||||
NaverListPlace,
|
||||
@@ -109,6 +110,11 @@ export class PlaceImportService {
|
||||
return this.kml.readKml(fileBuffer);
|
||||
}
|
||||
|
||||
/** IO-02: the lines of a .kml or .kmz upload as tour rows, and what it holds besides. Throws KmlReadError. */
|
||||
readMapFileTracks(fileBuffer: Buffer, filename: string): Promise<KmlTracksRead> {
|
||||
return this.kml.readTracks(fileBuffer, filename);
|
||||
}
|
||||
|
||||
// ── Shared lists ───────────────────────────────────────────────────────────
|
||||
|
||||
/** A Google Maps list, or the directions link a short link turned out to be. */
|
||||
|
||||
@@ -56,6 +56,53 @@ export interface KmlDocumentRead {
|
||||
summary: KmlImportSummary;
|
||||
}
|
||||
|
||||
/** What a KML document holds that a line import leaves out, counted by kind. */
|
||||
export interface KmlLeftOut {
|
||||
/** Single points (pins). */
|
||||
points: number;
|
||||
/** Polygons. */
|
||||
areas: number;
|
||||
/** Everything else: models, overlays, links to other files, placemarks without a geometry, too short lines. */
|
||||
other: number;
|
||||
}
|
||||
|
||||
/** One line of a KML document: a LineString or a gx:Track, as route geometry `[lat, lng]` or `[lat, lng, ele]`. */
|
||||
export interface KmlLineRead {
|
||||
name: string | null;
|
||||
description: string | null;
|
||||
geometry: number[][];
|
||||
}
|
||||
|
||||
/** A KML document read for its lines (IO-02). */
|
||||
export interface KmlLinesRead {
|
||||
lines: KmlLineRead[];
|
||||
leftOut: KmlLeftOut;
|
||||
warnings: string[];
|
||||
}
|
||||
|
||||
/** The lines of a KML or KMZ file as the rows a Tours import stores, and what it leaves out. */
|
||||
export interface KmlTracksRead {
|
||||
tracks: PreparedGpxPlace[];
|
||||
leftOut: KmlLeftOut;
|
||||
}
|
||||
|
||||
/** Why a KML or KMZ file could not be read. */
|
||||
export type KmlReadFailure = 'malformed' | 'archive_invalid' | 'archive_without_kml' | 'archive_too_large';
|
||||
|
||||
/**
|
||||
* A KML or KMZ file that could not be read, with the message the place import
|
||||
* route has always answered and the reason a caller can tell apart.
|
||||
*/
|
||||
export class KmlReadError extends Error {
|
||||
constructor(
|
||||
readonly reason: KmlReadFailure,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'KmlReadError';
|
||||
}
|
||||
}
|
||||
|
||||
/** An import that could not happen, with the status and the exact message the route answers. */
|
||||
export interface ListImportError {
|
||||
error: string;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createGeometryNamer } from '../geometry-names';
|
||||
import { coord, gpxGeometryParser, writeGpx } from '../gpx.codec';
|
||||
import type { GpxImportOptions, PreparedGpxPlace } from '../place-import.types';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
@@ -249,19 +250,7 @@ function prepareGpxRows(fileBuffer: Buffer, opts: GpxImportOptions = {}): Prepar
|
||||
return Number.isNaN(n) ? null : n;
|
||||
};
|
||||
|
||||
// Routes and tracks rarely carry their own <name>. Without one they all fall back to the
|
||||
// same generic label, so name-based dedup drops every import after the first. Derive a
|
||||
// base from the source filename (the requested behaviour) and suffix an index so multiple
|
||||
// geometries from one file stay distinct.
|
||||
const rawName = str(defaultName);
|
||||
const baseName = rawName ? rawName.replace(/\.[^.]+$/, '').trim() || rawName : null;
|
||||
let geoSeq = 0;
|
||||
const geoName = (explicit: string | null, fallback: string): string => {
|
||||
if (explicit) return explicit;
|
||||
geoSeq++;
|
||||
const base = baseName || fallback;
|
||||
return geoSeq === 1 ? base : `${base} ${geoSeq}`;
|
||||
};
|
||||
const geoName = createGeometryNamer(defaultName);
|
||||
|
||||
const waypoints: PreparedGpxPlace[] = [];
|
||||
|
||||
|
||||
@@ -2,15 +2,22 @@
|
||||
* A KML or KMZ map file (Google My Maps, Google Earth), read through kml.codec
|
||||
* into its placemarks. The file type is the upload's extension, as it has
|
||||
* always been; anything else is refused with the route's own message.
|
||||
*
|
||||
* The Tours import reads the same file for its lines (IO-02): each one a row
|
||||
* the GPX import's persistence takes as it takes a track, named the way a GPX
|
||||
* track without a name is.
|
||||
*/
|
||||
import { readKmlDocument, unpackKmzToKml } from '../kml.codec';
|
||||
import type { KmlDocumentRead } from '../place-import.types';
|
||||
import { createGeometryNamer } from '../geometry-names';
|
||||
import { readKmlDocument, readKmlLines, unpackKmzToKml } from '../kml.codec';
|
||||
import type { KmlDocumentRead, KmlTracksRead, PreparedGpxPlace } from '../place-import.types';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
const extensionOf = (filename: string) => filename.toLowerCase().split('.').pop();
|
||||
|
||||
@Injectable()
|
||||
export class KmlProvider {
|
||||
async readMapFile(fileBuffer: Buffer, filename: string): Promise<KmlDocumentRead> {
|
||||
const ext = filename.toLowerCase().split('.').pop();
|
||||
const ext = extensionOf(filename);
|
||||
if (ext === 'kmz') return this.readKmz(fileBuffer);
|
||||
if (ext === 'kml') return this.readKml(fileBuffer);
|
||||
throw new Error(`Unsupported map file format: .${ext}. Please upload a .kml or .kmz file.`);
|
||||
@@ -23,4 +30,23 @@ export class KmlProvider {
|
||||
readKml(fileBuffer: Buffer): KmlDocumentRead {
|
||||
return readKmlDocument(fileBuffer);
|
||||
}
|
||||
|
||||
/** The lines of a .kml or, by its extension, a .kmz file as tour rows, and what the file holds besides. */
|
||||
async readTracks(fileBuffer: Buffer, filename: string): Promise<KmlTracksRead> {
|
||||
const kml = extensionOf(filename) === 'kmz' ? await unpackKmzToKml(fileBuffer) : fileBuffer;
|
||||
const { lines, leftOut } = readKmlLines(kml);
|
||||
const nameOf = createGeometryNamer(filename);
|
||||
const tracks = lines.map((line): PreparedGpxPlace => {
|
||||
// A line has at least two points, so its start is always there.
|
||||
const [lat, lng] = line.geometry[0];
|
||||
return {
|
||||
name: nameOf(line.name, 'KML Track'),
|
||||
lat,
|
||||
lng,
|
||||
description: line.description,
|
||||
routeGeometry: JSON.stringify(line.geometry),
|
||||
};
|
||||
});
|
||||
return { tracks, leftOut };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* IO-02: the file a Tours import reads, whichever of the three formats it is.
|
||||
* A GPX file gives its tracks and routes, a KML or KMZ file its lines; both
|
||||
* come back as the same rows, so the preview, the duplicate rule and the one
|
||||
* transaction that stores them are the GPX import's own. Loose points are
|
||||
* never a tour: a GPX file's waypoints are skipped as they always were, and a
|
||||
* KML file's pins, areas and the rest are counted for the preview to name.
|
||||
*/
|
||||
import { DomainError } from '../common/domain-error';
|
||||
import type { PlaceImportService } from '../place-import/place-import.service';
|
||||
import { KmlReadError, type PreparedGpxPlace } from '../place-import/place-import.types';
|
||||
import type { TourFileLeftOut } from '@trek/shared';
|
||||
|
||||
type TourFileFormat = 'gpx' | 'kml' | 'kmz';
|
||||
|
||||
/** A file read for a Tours import: the rows it would store, and for a KML or KMZ file what it holds besides. */
|
||||
export interface TourFileRead {
|
||||
rows: PreparedGpxPlace[];
|
||||
leftOut?: TourFileLeftOut;
|
||||
}
|
||||
|
||||
/** The format by the upload's extension; anything else is read as GPX, as every Tours import was before. */
|
||||
function tourFileFormat(fileName: string | undefined): TourFileFormat {
|
||||
const ext = fileName?.toLowerCase().split('.').pop();
|
||||
return ext === 'kml' || ext === 'kmz' ? ext : 'gpx';
|
||||
}
|
||||
|
||||
/**
|
||||
* The refusal for a file without a single line. A GPX file is answered with
|
||||
* the body the route has always sent; a KML or KMZ file names its own format
|
||||
* and carries the code the client tells the case by.
|
||||
*/
|
||||
export function noTrackFound(fileName: string | undefined): DomainError {
|
||||
const format = tourFileFormat(fileName);
|
||||
if (format === 'gpx') return new DomainError(400, 'No track or route found in GPX file', { code: 'no_track' });
|
||||
return new DomainError(400, `No line found in ${format.toUpperCase()} file`, {
|
||||
code: 'no_track',
|
||||
details: { code: 'no_track' },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows a Tours import stores from this file. A KML or KMZ file that cannot
|
||||
* be read is a 400 whose `code` says why (malformed, archive_invalid,
|
||||
* archive_without_kml, archive_too_large).
|
||||
*/
|
||||
export async function readTourFile(
|
||||
placeImport: PlaceImportService,
|
||||
fileBuffer: Buffer,
|
||||
fileName: string | undefined,
|
||||
): Promise<TourFileRead> {
|
||||
if (tourFileFormat(fileName) === 'gpx') {
|
||||
const rows = placeImport.readGpx(fileBuffer, {
|
||||
importWaypoints: false,
|
||||
importRoutes: true,
|
||||
importTracks: true,
|
||||
defaultName: fileName,
|
||||
});
|
||||
return { rows };
|
||||
}
|
||||
try {
|
||||
const { tracks, leftOut } = await placeImport.readMapFileTracks(fileBuffer, fileName ?? '');
|
||||
return { rows: tracks, leftOut };
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof KmlReadError) {
|
||||
throw new DomainError(400, err.message, { code: 'tour_file_unreadable', details: { code: err.reason } });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { PlacesService } from '../places/places.service';
|
||||
import { TourGpxImportFieldsDto } from './dto/tour-gpx-import.dto';
|
||||
import { noTrackFound } from './tour-file-import.helpers';
|
||||
import { ToursService } from './tours.service';
|
||||
import {
|
||||
Body,
|
||||
@@ -25,11 +26,12 @@ import { tourGpxPreviewResponseSchema, tourImportGpxResponseSchema } from '@trek
|
||||
import { memoryStorage } from 'multer';
|
||||
|
||||
const UPLOAD = { storage: memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 } };
|
||||
const NO_TRACK = 'No track or route found in GPX file';
|
||||
|
||||
/**
|
||||
* POST /api/trips/:tripId/tours/import/gpx: the tours-mode GPX import, and
|
||||
* POST /api/trips/:tripId/tours/import/gpx: the tours-mode file import, and
|
||||
* POST .../import/gpx/preview: the same file read and shown, nothing stored.
|
||||
* Both read a GPX file, or by its extension a KML or KMZ file (IO-02); the
|
||||
* paths keep the name they were published under.
|
||||
*
|
||||
* A controller of its own because it must not sit behind ToursController's
|
||||
* AddonGuard and TripAccessGuard: a guard answers before multer has read the
|
||||
@@ -78,7 +80,7 @@ export class ToursImportController {
|
||||
const buffer = await this.checkedFile(user, tripId, file);
|
||||
const preview = await this.tours.previewGpx(tripId, buffer, file?.originalname);
|
||||
if (!preview) {
|
||||
throw new HttpException({ error: NO_TRACK }, 400);
|
||||
throw noTrackFound(file?.originalname);
|
||||
}
|
||||
return preview;
|
||||
}
|
||||
@@ -97,7 +99,7 @@ export class ToursImportController {
|
||||
const buffer = await this.checkedFile(user, tripId, file);
|
||||
const result = await this.tours.importGpxAsTour(tripId, buffer, file?.originalname, socketId, fields);
|
||||
if (!result) {
|
||||
throw new HttpException({ error: NO_TRACK }, 400);
|
||||
throw noTrackFound(file?.originalname);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -101,7 +101,7 @@ export class ToursMcp {
|
||||
@Tool({
|
||||
name: 'list_tours',
|
||||
description:
|
||||
'List the saved tours of a trip (hikes, city walks, runs, bike tours, paddle tours, rides on horseback and ski tracks planned or imported in the Tours addon): name, type (hike, walk for a city walk, run, bike, kayak for a paddle tour, horse for a ride, or ski for a ski track; a ride has no riding time worked out, so its duration is null), where it came from (origin: trek, gpx or wanderer), distance in km, ascent and descent in metres, the stored routing limit of a hike (max_hiking_difficulty, SAC T1 to T6) and its route choices (hiking_preferences: avoid_climbs for gentler ways, avoid_steps, avoid_ferries; weightings, never a grade of the path), the profile a bike tour is routed for (bike_profile: touring for paved cycle paths and quiet roads, road for asphalt, gravel for gravel and farm tracks, mtb for rough tracks; a routing preference, never a statement that a way is rideable or safe), the winter label of a hike (winter_activity: winter_hike or snowshoe, null for none; a label the travellers chose, while the route and its time are planned as for any hike, never a statement that a way can be walked in winter or anything about snow or avalanches), the profile and pace of a run (run_profile: running for runnable, mostly paved ways in towns and parks, trail for forest tracks and natural paths up to mountain paths (T2); a routing preference, never a statement that a way can be run; run_pace_seconds_per_km, the pace the runners planned with, null while they entered none; its duration is the distance at that pace and nothing else, no climb, descent or difficulty is in it, and it is a plan, never a recorded time), the classification of a ski track (ski_discipline: alpine, snowboard, cross_country or touring for ski touring; ski_technique for cross-country only: classic, skating or unknown when the travellers did not know; a ski track is imported from a GPX file and kept as recorded, never routed, its distance and heights come from the file, it has no ski time worked out, and nothing in it says anything about snow, avalanches or whether a run or trail is open), the boat, water and chosen speed of a paddle tour (boat_type, water_context, paddle_speed_kmh in km/h, null while the suggested speed of the boat applies), the check bench of a paddle tour (paddle_check: how far the OpenStreetMap obstacle data covers its line and how many obstacles are open, to check again or decided by the travellers; a planning status, never a safety or legal clearance), for a city walk the number of its stations (station_count: its points without the shaping points and the way back of a loop), their stays as far as entered (station_stay_minutes) and how many have none (station_stays_unknown), whether a tour still waits for its way to be planned (route_pending: saved with its points only, so its distance and walking time stay null until someone opens it in the planner and saves it), for a multi-day tour the number of stages its route is split into (stage_count: one route planned whole, each stage ending at a stop marked as its end; null for a tour of one day) and the stops they run between (stage_stops, in route order with key and coordinates: stage n runs from stop n-1 to stop n, and is known by the key of the stop it starts at), the revision (raised by every saved change of the tour), the recorded tracks assigned to a tour (activity_tracks) and, for a recorded track, the tour it documents (activity_of), when an imported track was recorded (track_started_at, track_ended_at; null when the file carried no times), and the days of the trip each tour is on (tour_stage_key names the stage a day holds by its starting stop, null where the day holds the whole tour; a stage may also be on no day yet).',
|
||||
'List the saved tours of a trip (hikes, city walks, runs, bike tours, paddle tours, rides on horseback and ski tracks planned or imported in the Tours addon): name, type (hike, walk for a city walk, run, bike, kayak for a paddle tour, horse for a ride, or ski for a ski track; a ride has no riding time worked out, so its duration is null), where it came from (origin: trek, gpx for an imported GPX, KML or KMZ file, or wanderer), distance in km, ascent and descent in metres, the stored routing limit of a hike (max_hiking_difficulty, SAC T1 to T6) and its route choices (hiking_preferences: avoid_climbs for gentler ways, avoid_steps, avoid_ferries; weightings, never a grade of the path), the profile a bike tour is routed for (bike_profile: touring for paved cycle paths and quiet roads, road for asphalt, gravel for gravel and farm tracks, mtb for rough tracks; a routing preference, never a statement that a way is rideable or safe), the winter label of a hike (winter_activity: winter_hike or snowshoe, null for none; a label the travellers chose, while the route and its time are planned as for any hike, never a statement that a way can be walked in winter or anything about snow or avalanches), the profile and pace of a run (run_profile: running for runnable, mostly paved ways in towns and parks, trail for forest tracks and natural paths up to mountain paths (T2); a routing preference, never a statement that a way can be run; run_pace_seconds_per_km, the pace the runners planned with, null while they entered none; its duration is the distance at that pace and nothing else, no climb, descent or difficulty is in it, and it is a plan, never a recorded time), the classification of a ski track (ski_discipline: alpine, snowboard, cross_country or touring for ski touring; ski_technique for cross-country only: classic, skating or unknown when the travellers did not know; a ski track is imported from a GPX file and kept as recorded, never routed, its distance and heights come from the file, it has no ski time worked out, and nothing in it says anything about snow, avalanches or whether a run or trail is open), the boat, water and chosen speed of a paddle tour (boat_type, water_context, paddle_speed_kmh in km/h, null while the suggested speed of the boat applies), the check bench of a paddle tour (paddle_check: how far the OpenStreetMap obstacle data covers its line and how many obstacles are open, to check again or decided by the travellers; a planning status, never a safety or legal clearance), for a city walk the number of its stations (station_count: its points without the shaping points and the way back of a loop), their stays as far as entered (station_stay_minutes) and how many have none (station_stays_unknown), whether a tour still waits for its way to be planned (route_pending: saved with its points only, so its distance and walking time stay null until someone opens it in the planner and saves it), for a multi-day tour the number of stages its route is split into (stage_count: one route planned whole, each stage ending at a stop marked as its end; null for a tour of one day) and the stops they run between (stage_stops, in route order with key and coordinates: stage n runs from stop n-1 to stop n, and is known by the key of the stop it starts at), the revision (raised by every saved change of the tour), the recorded tracks assigned to a tour (activity_tracks) and, for a recorded track, the tour it documents (activity_of), when an imported track was recorded (track_started_at, track_ended_at; null when the file carried no times), and the days of the trip each tour is on (tour_stage_key names the stage a day holds by its starting stop, null where the day holds the whole tour; a stage may also be on no day yet).',
|
||||
inputSchema: { tripId: idSchema },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
|
||||
@@ -30,6 +30,7 @@ import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { PlaceImportService } from '../place-import/place-import.service';
|
||||
import { PlacesService } from '../places/places.service';
|
||||
import { activityFacts, toActivity, trackTimesFor } from './tour-activities.helpers';
|
||||
import { readTourFile } from './tour-file-import.helpers';
|
||||
import { TourPaddleCheckService } from './tour-paddle-check.service';
|
||||
import { advanceTourRevision } from './tour-revision';
|
||||
import { toVisit } from './tour-visits.service';
|
||||
@@ -88,7 +89,7 @@ export interface ImportGpxAsTourResult {
|
||||
/**
|
||||
* Tours domain: the `tours` facet table (place_id PK/FK) carries tour-specific
|
||||
* metadata while existing places and day assignments are reused.
|
||||
* GPX parsing goes through PlaceImportService.readGpx, persistence through
|
||||
* A GPX, KML or KMZ file is read through PlaceImportService (readTourFile), persistence goes through
|
||||
* PlacesService.importPreparedGpx. Places and facet rows are persisted in one transaction,
|
||||
* with tour metrics derived from each place's route_geometry.
|
||||
*/
|
||||
@@ -949,10 +950,11 @@ export class ToursService {
|
||||
}
|
||||
|
||||
/**
|
||||
* The tours-mode GPX import reads rows through PlaceImportService.readGpx
|
||||
* with waypoints excluded. PlacesService.importPreparedGpx persists the places
|
||||
* in the same transaction as their `tours` facet rows, whose metrics are
|
||||
* derived from route_geometry.
|
||||
* The tours-mode file import reads rows through readTourFile: a GPX file's
|
||||
* tracks and routes with its waypoints excluded, a KML or KMZ file's lines
|
||||
* (IO-02). PlacesService.importPreparedGpx persists the places in the same
|
||||
* transaction as their `tours` facet rows, whose metrics are derived from
|
||||
* route_geometry, so a failure leaves no tour half stored.
|
||||
*
|
||||
* Missing or implausible metrics do not block import:
|
||||
* a track without elevation still imports, just flagged with a low
|
||||
@@ -965,7 +967,7 @@ export class ToursService {
|
||||
socketId?: string,
|
||||
fields: TourGpxImportFields = HIKE_IMPORT,
|
||||
): Promise<ImportGpxAsTourResult | null> {
|
||||
const rows = this.readGpxTracks(fileBuffer, fileName);
|
||||
const { rows } = await readTourFile(this.placeImport, fileBuffer, fileName);
|
||||
if (rows.length === 0) return null;
|
||||
await this.assertTourTypeEnabled(fields.tour_type);
|
||||
// What the type adds to each imported tour: a bike tour and a run their profile, a paddle tour its boat and water,
|
||||
@@ -1004,7 +1006,7 @@ export class ToursService {
|
||||
match_confidence: matchConfidence,
|
||||
max_hiking_difficulty: null,
|
||||
origin: 'gpx',
|
||||
origin_file_name: gpxFileName(fileName),
|
||||
origin_file_name: importFileName(fileName),
|
||||
track_started_at: recorded?.started ?? null,
|
||||
track_ended_at: recorded?.ended ?? null,
|
||||
});
|
||||
@@ -1063,12 +1065,13 @@ export class ToursService {
|
||||
}
|
||||
|
||||
/**
|
||||
* PAD-02: what a GPX file would import, read with the import's own parser
|
||||
* and duplicate rule and written nowhere. Null when the file holds no track
|
||||
* or route, the import's own refusal.
|
||||
* PAD-02: what a file would import, read with the import's own parser and
|
||||
* duplicate rule and written nowhere. Null when the file holds no track or
|
||||
* route, the import's own refusal. A KML or KMZ file also says what it holds
|
||||
* besides its lines (IO-02).
|
||||
*/
|
||||
async previewGpx(tripId: string, fileBuffer: Buffer, fileName?: string): Promise<TourGpxPreviewResponse | null> {
|
||||
const rows = this.readGpxTracks(fileBuffer, fileName);
|
||||
const { rows, leftOut } = await readTourFile(this.placeImport, fileBuffer, fileName);
|
||||
if (rows.length === 0) return null;
|
||||
const duplicates = await this.places.gpxDuplicates(tripId, rows);
|
||||
return {
|
||||
@@ -1087,18 +1090,9 @@ export class ToursService {
|
||||
duplicate: duplicates[index] ?? false,
|
||||
};
|
||||
}),
|
||||
...(leftOut ? { left_out: leftOut } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/** The tracks and routes of a GPX file, never its loose waypoints: the reading every Tours import shares. */
|
||||
private readGpxTracks(fileBuffer: Buffer, fileName?: string) {
|
||||
return this.placeImport.readGpx(fileBuffer, {
|
||||
importWaypoints: false,
|
||||
importRoutes: true,
|
||||
importTracks: true,
|
||||
defaultName: fileName,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Where a tour without a line starts (CW-11): at its first point. */
|
||||
@@ -1107,8 +1101,8 @@ function firstPointOf(points: readonly { lat: number; lng: number }[]): [number,
|
||||
return point ? [point.lat, point.lng] : undefined;
|
||||
}
|
||||
|
||||
/** The file name a GPX import keeps: the name as uploaded, without a path, cut to what the column shows. */
|
||||
function gpxFileName(name: string | undefined): string | null {
|
||||
/** The file name a file import keeps: the name as uploaded, without a path, cut to what the column shows. */
|
||||
function importFileName(name: string | undefined): string | null {
|
||||
const base = name?.split('/').pop()?.trim();
|
||||
return base ? base.slice(0, 255) : null;
|
||||
}
|
||||
|
||||
@@ -46,8 +46,10 @@ import { keyed } from '../helpers/tour-keys';
|
||||
import { sessionCookie } from './harness';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import archiver from 'archiver';
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import { PassThrough } from 'stream';
|
||||
import request from 'supertest';
|
||||
import { describe, it, expect, beforeAll, afterAll, afterEach, beforeEach, vi, type MockInstance } from 'vitest';
|
||||
|
||||
@@ -1032,6 +1034,107 @@ describe('Tours e2e (real guards + temp SQLite)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('KML and KMZ preview and import (IO-02)', () => {
|
||||
const MAP_KML = `<?xml version="1.0"?><kml xmlns="http://www.opengis.net/kml/2.2"><Document>
|
||||
<Placemark><name>Coast walk</name><LineString><coordinates>12,49,0 12.01,49.01,0 12.02,49.02,0</coordinates>
|
||||
</LineString></Placemark>
|
||||
<Placemark><name>Summit</name><LineString><altitudeMode>absolute</altitudeMode>
|
||||
<coordinates>13,50,100 13.01,50.01,180 13.02,50.02,150</coordinates></LineString></Placemark>
|
||||
<Placemark><name>Hut</name><Point><coordinates>12,49</coordinates></Point></Placemark>
|
||||
<Placemark><name>Lake</name><Polygon><outerBoundaryIs><LinearRing>
|
||||
<coordinates>1,1 2,2 3,1 1,1</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>
|
||||
<NetworkLink><Link><href>https://example.test/more.kml</href></Link></NetworkLink>
|
||||
</Document></kml>`;
|
||||
|
||||
/** A KMZ archive holding these entries. */
|
||||
async function kmz(entries: Record<string, string>): Promise<Buffer> {
|
||||
const chunks: Buffer[] = [];
|
||||
const output = new PassThrough();
|
||||
output.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
const archive = archiver('zip', { zlib: { level: 1 } });
|
||||
archive.pipe(output);
|
||||
for (const [name, content] of Object.entries(entries)) archive.append(Buffer.from(content), { name });
|
||||
await archive.finalize();
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
const upload = (
|
||||
bytes: Buffer,
|
||||
filename: string,
|
||||
path = 'import/gpx/preview',
|
||||
fields: Record<string, string> = {},
|
||||
) => {
|
||||
let req = request(server).post(`/api/trips/5/tours/${path}`).set('Cookie', sessionCookie(OWNER));
|
||||
for (const [key, value] of Object.entries(fields)) req = req.field(key, value);
|
||||
return req.attach('file', bytes, { filename, contentType: 'application/octet-stream' });
|
||||
};
|
||||
|
||||
it('shows each line apart with the heights it has, counts what it leaves out, and stores nothing', async () => {
|
||||
const res = await upload(Buffer.from(MAP_KML), 'alps.kml');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.tracks.map((track: { name: string }) => track.name)).toEqual(['Coast walk', 'Summit']);
|
||||
// Google My Maps writes 0 for every height: that is no height, not a flat walk.
|
||||
expect(res.body.tracks[0]).toMatchObject({ point_count: 3, elevation_gain_m: null, elevation_loss_m: null });
|
||||
expect(res.body.tracks[1]).toMatchObject({ point_count: 3, elevation_gain_m: 80, elevation_loss_m: 30 });
|
||||
expect(res.body.left_out).toEqual({ points: 1, areas: 1, other: 1 });
|
||||
expect(await countRows(orm, Places)).toBe(0);
|
||||
expect(broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('imports the lines as tours of the chosen type, keeps the file name, skips them the second time', async () => {
|
||||
const res = await upload(Buffer.from(MAP_KML), 'alps.kml', 'import/gpx', {
|
||||
tour_type: 'kayak',
|
||||
boat_type: 'canoe',
|
||||
water_context: 'river',
|
||||
});
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.tours.map((tour: { name: string }) => tour.name)).toEqual(['Coast walk', 'Summit']);
|
||||
expect(res.body.tours[0]).toMatchObject({ tour_type: 'kayak', boat_type: 'canoe', origin: 'gpx' });
|
||||
expect(res.body.caution).toBe(true);
|
||||
expect(await countRows(orm, Tours)).toBe(2);
|
||||
const placeId = res.body.tours[1].place_id as number;
|
||||
const detail = await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER));
|
||||
expect(detail.body.provenance.source).toEqual({ kind: 'gpx', fileName: 'alps.kml' });
|
||||
|
||||
const again = await upload(Buffer.from(MAP_KML), 'alps.kml', 'import/gpx');
|
||||
expect(again.body).toMatchObject({ tours: [], skipped: 2 });
|
||||
expect(await countRows(orm, Tours)).toBe(2);
|
||||
});
|
||||
|
||||
it('reads a KMZ archive through its KML', async () => {
|
||||
const archive = await kmz({ 'doc.kml': MAP_KML, 'files/photo.jpg': 'jpeg' });
|
||||
const res = await upload(archive, 'alps.kmz');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.tracks).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('400 with a reason for a broken KML, a broken or empty archive and a file without a line', async () => {
|
||||
const PINS_ONLY = '<kml><Placemark><Point><coordinates>1,2</coordinates></Point></Placemark></kml>';
|
||||
const answers = [
|
||||
await upload(Buffer.from('<kml><Placemark></kml>'), 'broken.kml'),
|
||||
await upload(Buffer.from('not a zip'), 'broken.kmz', 'import/gpx'),
|
||||
await upload(await kmz({ 'photo.jpg': 'jpeg' }), 'photos.kmz'),
|
||||
await upload(Buffer.from(PINS_ONLY), 'pins.kml'),
|
||||
];
|
||||
expect(answers.map((res) => [res.status, res.body])).toEqual([
|
||||
[400, { error: 'Malformed KML: invalid XML structure', code: 'malformed' }],
|
||||
[400, { error: 'Invalid KMZ archive.', code: 'archive_invalid' }],
|
||||
[400, { error: 'KMZ archive does not contain a KML file.', code: 'archive_without_kml' }],
|
||||
[400, { error: 'No line found in KML file', code: 'no_track' }],
|
||||
]);
|
||||
expect(await countRows(orm, Places)).toBe(0);
|
||||
});
|
||||
|
||||
it('a member without place_edit gets 403 for a KML file too', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/trips/5/tours/import/gpx')
|
||||
.set('Cookie', sessionCookie(VIEWER))
|
||||
.attach('file', Buffer.from(MAP_KML), { filename: 'alps.kml', contentType: 'application/octet-stream' });
|
||||
expect(res.status).toBe(403);
|
||||
expect(await countRows(orm, Places)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('provenance (P2C-02)', () => {
|
||||
const detail = async (placeId: number) =>
|
||||
(await request(server).get(`/api/trips/5/tours/${placeId}`).set('Cookie', sessionCookie(OWNER))).body;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
/**
|
||||
* IO-02: a KML or KMZ file read for the lines a Tours import stores. Each line
|
||||
* becomes one row in the shape the GPX import hands its persistence, named
|
||||
* after its placemark or, without a name, after the file as a GPX track is;
|
||||
* a KMZ is unpacked first, and what the file holds besides is counted.
|
||||
*/
|
||||
import { createGeometryNamer } from '../../../../src/nest/place-import/geometry-names';
|
||||
import { KmlReadError } from '../../../../src/nest/place-import/place-import.types';
|
||||
import { KmlProvider } from '../../../../src/nest/place-import/providers/kml.provider';
|
||||
import { buildPlaceImportService } from '../../../helpers/place-import';
|
||||
|
||||
import archiver from 'archiver';
|
||||
import { PassThrough } from 'stream';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const KML = `<?xml version="1.0"?><kml xmlns="http://www.opengis.net/kml/2.2"><Document>
|
||||
<Placemark><name>Coast</name><description>Windy</description>
|
||||
<LineString><altitudeMode>absolute</altitudeMode><coordinates>11,48,5 11.01,48.01,9</coordinates></LineString>
|
||||
</Placemark>
|
||||
<Placemark><LineString><coordinates>12,49 12.01,49.01</coordinates></LineString></Placemark>
|
||||
<Placemark><LineString><coordinates>13,50 13.01,50.01</coordinates></LineString></Placemark>
|
||||
<Placemark><name>Hut</name><Point><coordinates>12,49</coordinates></Point></Placemark>
|
||||
</Document></kml>`;
|
||||
|
||||
/** A KMZ archive holding these entries. */
|
||||
async function kmz(entries: Record<string, string>): Promise<Buffer> {
|
||||
const chunks: Buffer[] = [];
|
||||
const output = new PassThrough();
|
||||
output.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
const archive = archiver('zip', { zlib: { level: 1 } });
|
||||
archive.pipe(output);
|
||||
for (const [name, content] of Object.entries(entries)) archive.append(Buffer.from(content), { name });
|
||||
await archive.finalize();
|
||||
return Buffer.concat(chunks);
|
||||
}
|
||||
|
||||
describe('KmlProvider.readTracks', () => {
|
||||
const provider = new KmlProvider();
|
||||
|
||||
it('KML-TRACKS-001: makes a row of each line, starting where it starts, and counts the pin left out', async () => {
|
||||
const read = await provider.readTracks(Buffer.from(KML), 'alps.kml');
|
||||
expect(read.tracks).toEqual([
|
||||
{
|
||||
name: 'Coast',
|
||||
lat: 48,
|
||||
lng: 11,
|
||||
description: 'Windy',
|
||||
routeGeometry: JSON.stringify([
|
||||
[48, 11, 5],
|
||||
[48.01, 11.01, 9],
|
||||
]),
|
||||
},
|
||||
{ name: 'alps', lat: 49, lng: 12, description: null, routeGeometry: '[[49,12],[49.01,12.01]]' },
|
||||
{ name: 'alps 2', lat: 50, lng: 13, description: null, routeGeometry: '[[50,13],[50.01,13.01]]' },
|
||||
]);
|
||||
expect(read.leftOut).toEqual({ points: 1, areas: 0, other: 0 });
|
||||
});
|
||||
|
||||
it('KML-TRACKS-002: unpacks a KMZ by its extension and reads its doc.kml', async () => {
|
||||
const archive = await kmz({ 'files/notes.kml': '<kml/>', 'doc.kml': KML, 'files/photo.jpg': 'jpeg' });
|
||||
const read = await provider.readTracks(archive, 'Alps.KMZ');
|
||||
expect(read.tracks.map((track) => track.name)).toEqual(['Coast', 'Alps', 'Alps 2']);
|
||||
});
|
||||
|
||||
it('KML-TRACKS-003: an archive without a KML file is refused with its reason', async () => {
|
||||
const archive = await kmz({ 'photo.jpg': 'jpeg' });
|
||||
await expect(provider.readTracks(archive, 'trip.kmz')).rejects.toBeInstanceOf(KmlReadError);
|
||||
await expect(provider.readTracks(archive, 'trip.kmz')).rejects.toMatchObject({ reason: 'archive_without_kml' });
|
||||
});
|
||||
|
||||
it('KML-TRACKS-004: the facade hands the call to the provider', async () => {
|
||||
const read = await buildPlaceImportService().readMapFileTracks(Buffer.from(KML), 'alps.kml');
|
||||
expect(read.tracks).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createGeometryNamer', () => {
|
||||
it('GEO-NAME-001: keeps a line its own name and numbers the unnamed ones after the file', () => {
|
||||
const name = createGeometryNamer('walks/harbour.gpx');
|
||||
expect([name('Pier', 'Track'), name(null, 'Track'), name(null, 'Track')]).toEqual([
|
||||
'Pier',
|
||||
'walks/harbour',
|
||||
'walks/harbour 2',
|
||||
]);
|
||||
});
|
||||
|
||||
it('GEO-NAME-002: without a file name falls back to the label it is given', () => {
|
||||
const name = createGeometryNamer(' ');
|
||||
expect([name(null, 'KML Track'), name(null, 'KML Track')]).toEqual(['KML Track', 'KML Track 2']);
|
||||
expect(createGeometryNamer('.kml')(null, 'Track')).toBe('.kml');
|
||||
});
|
||||
});
|
||||
@@ -1,18 +1,24 @@
|
||||
import {
|
||||
decodeUtf8WithWarning,
|
||||
extractKmlPlacemarkNodes,
|
||||
kmlLineGeometry,
|
||||
KMZ_DECOMPRESSED_SIZE_LIMIT,
|
||||
parseKmlPointCoordinates,
|
||||
parsePlacemarkNode,
|
||||
readKmlDocument,
|
||||
readKmlLines,
|
||||
readKmzEntryCapped,
|
||||
sanitizeKmlDescription,
|
||||
unpackKmzToKml,
|
||||
} from '../../../../src/nest/place-import/kml.codec';
|
||||
import { KmlReadError } from '../../../../src/nest/place-import/place-import.types';
|
||||
import { buildCategoryNameLookup, resolveCategoryIdForFolder } from '../../../../src/nest/places/places.helpers';
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { PassThrough, Readable } from 'stream';
|
||||
import unzipper, { type Entry } from 'unzipper';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
describe('kmlImportUtils', () => {
|
||||
it('sanitizes HTML descriptions with br to newline', () => {
|
||||
@@ -183,3 +189,199 @@ describe('readKmlDocument', () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
const kml = (body: string) =>
|
||||
Buffer.from(`<?xml version="1.0"?><kml xmlns="http://www.opengis.net/kml/2.2"
|
||||
xmlns:gx="http://www.google.com/kml/ext/2.2"><Document>${body}</Document></kml>`);
|
||||
|
||||
/** An archive entry whose stream yields these chunks, or fails after them. */
|
||||
const fakeEntry = (chunks: Buffer[], fail?: Error) => ({
|
||||
stream: () => {
|
||||
const out = new PassThrough();
|
||||
for (const chunk of chunks) out.write(chunk);
|
||||
if (fail) setImmediate(() => out.destroy(fail));
|
||||
else out.end();
|
||||
return out as unknown as Entry;
|
||||
},
|
||||
});
|
||||
|
||||
describe('readKmlLines (IO-02)', () => {
|
||||
it('KML-LINES-001: reads every LineString and gx:Track in document order, each a line of its own', () => {
|
||||
const read = readKmlLines(
|
||||
kml(`<Placemark><name>Coast</name><description>Along the & sea</description>
|
||||
<LineString><coordinates>11,48 11.01,48.01</coordinates></LineString></Placemark>
|
||||
<Folder><name>Recorded</name><Placemark><name>Morning</name><gx:Track><altitudeMode>absolute</altitudeMode>
|
||||
<when>2026-01-01T08:00:00Z</when><when>2026-01-01T08:05:00Z</when>
|
||||
<gx:coord>12 49 400</gx:coord><gx:coord>12.01 49.01 420.5</gx:coord></gx:Track></Placemark></Folder>`),
|
||||
);
|
||||
expect(read.lines).toEqual([
|
||||
{
|
||||
name: 'Coast',
|
||||
description: 'Along the & sea',
|
||||
geometry: [
|
||||
[48, 11],
|
||||
[48.01, 11.01],
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Morning',
|
||||
description: null,
|
||||
geometry: [
|
||||
[49, 12, 400],
|
||||
[49.01, 12.01, 420.5],
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(read.leftOut).toEqual({ points: 0, areas: 0, other: 0 });
|
||||
expect(read.warnings).toEqual([]);
|
||||
});
|
||||
|
||||
it('KML-LINES-002: keeps the lines of one placemark apart and numbers them, never joins them', () => {
|
||||
const read = readKmlLines(
|
||||
kml(`<Placemark><name>Ferry day</name><MultiGeometry>
|
||||
<LineString><coordinates>11,48 11.01,48.01</coordinates></LineString>
|
||||
<MultiGeometry><LineString><coordinates>11.5,48.5 11.51,48.51</coordinates></LineString>
|
||||
<Point><coordinates>11.5,48.5</coordinates></Point></MultiGeometry>
|
||||
</MultiGeometry></Placemark>
|
||||
<Placemark><gx:MultiTrack><altitudeMode>absolute</altitudeMode>
|
||||
<gx:Track><gx:coord>12 49 1</gx:coord><gx:coord>12.1 49.1 2</gx:coord></gx:Track>
|
||||
<gx:Track><gx:coord>13 50 3</gx:coord><gx:coord>13.1 50.1 4</gx:coord></gx:Track></gx:MultiTrack></Placemark>`),
|
||||
);
|
||||
expect(read.lines.map((line) => [line.name, line.geometry.length, line.geometry[0]])).toEqual([
|
||||
['Ferry day (1/2)', 2, [48, 11]],
|
||||
['Ferry day (2/2)', 2, [48.5, 11.5]],
|
||||
[null, 2, [49, 12, 1]],
|
||||
[null, 2, [50, 13, 3]],
|
||||
]);
|
||||
expect(read.leftOut).toEqual({ points: 1, areas: 0, other: 0 });
|
||||
});
|
||||
|
||||
it('KML-LINES-003: counts what it leaves out: pins, areas, models, overlays, links, empty and short ones', () => {
|
||||
const read = readKmlLines(
|
||||
kml(`<Placemark><name>Hut</name><Point><coordinates>11,48</coordinates></Point></Placemark>
|
||||
<Placemark><Polygon><outerBoundaryIs><LinearRing><coordinates>1,1 2,2 3,1 1,1</coordinates></LinearRing>
|
||||
</outerBoundaryIs></Polygon></Placemark>
|
||||
<Placemark><Model><Link><href>house.dae</href></Link></Model></Placemark>
|
||||
<Placemark><name>Nothing</name></Placemark>
|
||||
<Placemark><LineString><coordinates>11,48</coordinates></LineString></Placemark>
|
||||
<Placemark><gx:Track><gx:coord>12 49 1</gx:coord></gx:Track></Placemark>
|
||||
<NetworkLink><Link><href>https://example.test/more.kml</href></Link></NetworkLink>
|
||||
<Folder><GroundOverlay><Icon><href>map.png</href></Icon></GroundOverlay><ScreenOverlay/></Folder>`),
|
||||
);
|
||||
expect(read.lines).toEqual([]);
|
||||
// other: the model, the empty placemark, the short line, the short track, the link and two overlays.
|
||||
expect(read.leftOut).toEqual({ points: 1, areas: 1, other: 7 });
|
||||
});
|
||||
|
||||
it('KML-LINES-004: says when the file is not valid UTF-8, as the place import does', () => {
|
||||
const bytes = Buffer.concat([
|
||||
Buffer.from('<kml><Placemark><name>'),
|
||||
Buffer.from([0xff]),
|
||||
Buffer.from('</name><LineString><coordinates>1,1 2,2</coordinates></LineString></Placemark></kml>'),
|
||||
]);
|
||||
const read = readKmlLines(bytes);
|
||||
expect(read.lines).toHaveLength(1);
|
||||
expect(read.warnings).toEqual(['The uploaded file is not valid UTF-8. Some characters may be shown incorrectly.']);
|
||||
});
|
||||
|
||||
it('KML-LINES-005: refuses a document that is not well-formed XML with the reason malformed', () => {
|
||||
let error: unknown;
|
||||
try {
|
||||
readKmlLines(Buffer.from('<kml><Placemark></kml>'));
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
expect(error).toBeInstanceOf(KmlReadError);
|
||||
expect(error).toMatchObject({ reason: 'malformed', message: 'Malformed KML: invalid XML structure' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('kmlLineGeometry (IO-02): heights only where they are heights', () => {
|
||||
const points = (...eles: Array<number | null>) => eles.map((ele, i) => ({ lat: 47 + i, lng: 11, ele }));
|
||||
|
||||
it('KML-HEIGHTS-001: keeps the heights of an absolute line, also when they are 0', () => {
|
||||
expect(kmlLineGeometry(points(0, 0), 'absolute')).toEqual([
|
||||
[47, 11, 0],
|
||||
[48, 11, 0],
|
||||
]);
|
||||
});
|
||||
|
||||
it('KML-HEIGHTS-002: drops them under any other altitude mode', () => {
|
||||
for (const mode of ['clampToGround', 'relativeToGround', 'clampToSeaFloor']) {
|
||||
expect(kmlLineGeometry(points(400, 420), mode)).toEqual([
|
||||
[47, 11],
|
||||
[48, 11],
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it('KML-HEIGHTS-003: without a mode keeps them unless every one is 0, the placeholder Google My Maps writes', () => {
|
||||
expect(kmlLineGeometry(points(0, 0, 0), null)).toEqual([
|
||||
[47, 11],
|
||||
[48, 11],
|
||||
[49, 11],
|
||||
]);
|
||||
expect(kmlLineGeometry(points(0, 12), null)).toEqual([
|
||||
[47, 11, 0],
|
||||
[48, 11, 12],
|
||||
]);
|
||||
});
|
||||
|
||||
it('KML-HEIGHTS-004: a line with a point lacking its height keeps none', () => {
|
||||
expect(kmlLineGeometry(points(400, null), 'absolute')).toEqual([
|
||||
[47, 11],
|
||||
[48, 11],
|
||||
]);
|
||||
});
|
||||
|
||||
it('KML-HEIGHTS-005: an altitude mode around the lines is inherited by them', () => {
|
||||
const read = readKmlLines(
|
||||
kml(`<Placemark><MultiGeometry><altitudeMode>clampToGround</altitudeMode>
|
||||
<LineString><coordinates>11,48,300 11.01,48.01,310</coordinates></LineString></MultiGeometry></Placemark>`),
|
||||
);
|
||||
expect(read.lines[0]?.geometry).toEqual([
|
||||
[48, 11],
|
||||
[48.01, 11.01],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('KMZ unpacking limits (IO-02)', () => {
|
||||
it('KMZ-CAP-001: counts the bytes it inflates and stops past the limit, whatever the header claims', async () => {
|
||||
const entry = fakeEntry([Buffer.alloc(6, 'a'), Buffer.alloc(6, 'b')]);
|
||||
await expect(readKmzEntryCapped(entry, 10)).rejects.toMatchObject({ reason: 'archive_too_large' });
|
||||
expect((await readKmzEntryCapped(entry, 12)).toString()).toBe('aaaaaabbbbbb');
|
||||
});
|
||||
|
||||
it('KMZ-CAP-002: names the reason for each archive it cannot read', async () => {
|
||||
await expect(unpackKmzToKml(Buffer.from('this is not a zip'))).rejects.toMatchObject({ reason: 'archive_invalid' });
|
||||
await expect(unpackKmzToKml(fs.readFileSync(KMZ_FIXTURE), 1)).rejects.toMatchObject({
|
||||
reason: 'archive_too_large',
|
||||
});
|
||||
});
|
||||
|
||||
it('KMZ-CAP-003: a KML entry that breaks while it inflates is an invalid archive', async () => {
|
||||
const broken = { path: 'doc.kml', uncompressedSize: 10, ...fakeEntry([Buffer.from('<kml>')], new Error('bad')) };
|
||||
const open = vi.spyOn(unzipper.Open, 'buffer').mockResolvedValueOnce({ files: [broken] } as never);
|
||||
await expect(unpackKmzToKml(Buffer.from('zip'))).rejects.toMatchObject({
|
||||
reason: 'archive_invalid',
|
||||
message: 'Invalid KMZ archive.',
|
||||
});
|
||||
open.mockRestore();
|
||||
});
|
||||
|
||||
it('KMZ-CAP-004: reads only the KML entry of an archive, never the files beside it', async () => {
|
||||
const image = { path: 'files/photo.jpg', uncompressedSize: 1, stream: vi.fn() };
|
||||
const doc = { path: 'doc.kml', uncompressedSize: 5, ...fakeEntry([Buffer.from('<kml/>')]) };
|
||||
const open = vi.spyOn(unzipper.Open, 'buffer').mockResolvedValueOnce({ files: [image, doc] } as never);
|
||||
expect((await unpackKmzToKml(Buffer.from('zip'))).toString()).toBe('<kml/>');
|
||||
expect(image.stream).not.toHaveBeenCalled();
|
||||
open.mockRestore();
|
||||
});
|
||||
|
||||
it('KMZ-CAP-005: takes chunks that come as plain byte arrays', async () => {
|
||||
const chunks = [new Uint8Array([60, 107]), Buffer.from('ml/>')];
|
||||
const entry = { stream: () => Readable.from(chunks) as unknown as Entry };
|
||||
expect((await readKmzEntryCapped(entry, 10)).toString()).toBe('<kml/>');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -92,7 +92,7 @@ function importFixture(
|
||||
canEdit: vi.fn(async () => o.canEdit ?? true),
|
||||
};
|
||||
const result = 'result' in o ? o.result : { tours: [{ place_id: 42 }], caution: false, skipped: 0 };
|
||||
const tours = { importGpxAsTour: vi.fn(async () => result) };
|
||||
const tours = { importGpxAsTour: vi.fn(async () => result), previewGpx: vi.fn(async () => result) };
|
||||
const controller = new ToursImportController(
|
||||
tours as unknown as ToursService,
|
||||
places as unknown as PlacesService,
|
||||
@@ -278,4 +278,28 @@ describe('ToursImportController (POST /api/trips/:tripId/tours/import/gpx)', ()
|
||||
body: { error: 'No track or route found in GPX file' },
|
||||
});
|
||||
});
|
||||
|
||||
it('TOURS-IMP-009: a KML or KMZ file without a line names its format and carries the code (IO-02)', async () => {
|
||||
const { controller, tours } = importFixture({ result: null });
|
||||
const kml = { buffer: Buffer.from('<kml/>'), originalname: 'pins.kml' } as Express.Multer.File;
|
||||
const kmz = { buffer: Buffer.from('zip'), originalname: 'pins.kmz' } as Express.Multer.File;
|
||||
|
||||
expect(await thrownAsync(() => controller.importGpx(user, '7', kml))).toEqual({
|
||||
status: 400,
|
||||
body: { error: 'No line found in KML file', code: 'no_track' },
|
||||
});
|
||||
expect(await thrownAsync(() => controller.previewGpx(user, '7', kmz))).toEqual({
|
||||
status: 400,
|
||||
body: { error: 'No line found in KMZ file', code: 'no_track' },
|
||||
});
|
||||
expect(tours.previewGpx).toHaveBeenCalledWith('7', kmz.buffer, 'pins.kmz');
|
||||
});
|
||||
|
||||
it('TOURS-IMP-010: the preview hands the file on and returns what the service read', async () => {
|
||||
const preview = { tracks: [], left_out: { points: 2, areas: 0, other: 1 } };
|
||||
const { controller, tours } = importFixture({ result: preview });
|
||||
|
||||
expect(await controller.previewGpx(user, '7', file)).toBe(preview);
|
||||
expect(tours.previewGpx).toHaveBeenCalledWith('7', file.buffer, 'ridge.gpx');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* IO-02: the file a Tours import reads. A GPX file goes through the GPX reader
|
||||
* without its waypoints, as it always did; a KML or KMZ file, by its
|
||||
* extension, through the KML reader for its lines and what it leaves out. A
|
||||
* file that cannot be read is a 400 that names its reason, and a file without
|
||||
* a line answers GPX's body as before and a format-named one with a code.
|
||||
*/
|
||||
import type { PlaceImportService } from '../../../src/nest/place-import/place-import.service';
|
||||
import { KmlReadError } from '../../../src/nest/place-import/place-import.types';
|
||||
import { noTrackFound, readTourFile } from '../../../src/nest/tours/tour-file-import.helpers';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import { HttpException } from '@nestjs/common';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const GPX = Buffer.from(`<gpx><wpt lat="1" lon="2"><name>Hut</name></wpt>
|
||||
<trk><trkseg><trkpt lat="48" lon="11"/><trkpt lat="48.01" lon="11.01"/></trkseg></trk></gpx>`);
|
||||
const KML = Buffer.from(`<kml><Placemark><name>Coast</name>
|
||||
<LineString><coordinates>11,48 11.01,48.01</coordinates></LineString></Placemark>
|
||||
<Placemark><Polygon/></Placemark></kml>`);
|
||||
|
||||
describe('readTourFile', () => {
|
||||
it('TOUR-FILE-001: reads a GPX file for its tracks, never its waypoints, and counts nothing left out', async () => {
|
||||
const read = await readTourFile(buildPlaceImportService(), GPX, 'ridge.gpx');
|
||||
expect(read.rows.map((row) => row.name)).toEqual(['ridge']);
|
||||
expect(read.leftOut).toBeUndefined();
|
||||
});
|
||||
|
||||
it('TOUR-FILE-002: reads a file without a known extension, or without a name, as GPX as before', async () => {
|
||||
expect((await readTourFile(buildPlaceImportService(), GPX, 'track.xml')).rows).toHaveLength(1);
|
||||
expect((await readTourFile(buildPlaceImportService(), GPX, undefined)).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('TOUR-FILE-003: reads a KML file for its lines and says what it held besides', async () => {
|
||||
const read = await readTourFile(buildPlaceImportService(), KML, 'coast.KML');
|
||||
expect(read.rows.map((row) => row.name)).toEqual(['Coast']);
|
||||
expect(read.leftOut).toEqual({ points: 0, areas: 1, other: 0 });
|
||||
});
|
||||
|
||||
it('TOUR-FILE-004: a file it cannot read is a 400 carrying the reason as its code', async () => {
|
||||
let error: unknown;
|
||||
try {
|
||||
await readTourFile(buildPlaceImportService(), Buffer.from('not a zip'), 'trip.kmz');
|
||||
} catch (err) {
|
||||
error = err;
|
||||
}
|
||||
expect(error).toBeInstanceOf(HttpException);
|
||||
expect((error as HttpException).getStatus()).toBe(400);
|
||||
expect((error as HttpException).getResponse()).toEqual({ error: 'Invalid KMZ archive.', code: 'archive_invalid' });
|
||||
});
|
||||
|
||||
it('TOUR-FILE-005: any other failure passes through as it is', async () => {
|
||||
const placeImport = {
|
||||
readMapFileTracks: vi.fn().mockRejectedValue(new Error('disk gone')),
|
||||
} as unknown as PlaceImportService;
|
||||
await expect(readTourFile(placeImport, KML, 'coast.kml')).rejects.toThrow('disk gone');
|
||||
const refused = { readMapFileTracks: vi.fn().mockRejectedValue(new KmlReadError('archive_too_large', 'Too big')) };
|
||||
await expect(readTourFile(refused as unknown as PlaceImportService, KML, 'x.kmz')).rejects.toMatchObject({
|
||||
code: 'tour_file_unreadable',
|
||||
message: 'Too big',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('noTrackFound', () => {
|
||||
it('TOUR-FILE-006: answers a GPX file with the body the route has always sent', () => {
|
||||
const error = noTrackFound('ridge.gpx');
|
||||
expect(error.getStatus()).toBe(400);
|
||||
expect(error.getResponse()).toEqual({ error: 'No track or route found in GPX file' });
|
||||
expect(noTrackFound(undefined).getResponse()).toEqual({ error: 'No track or route found in GPX file' });
|
||||
});
|
||||
|
||||
it('TOUR-FILE-007: names the format of a KML or KMZ file and carries the code', () => {
|
||||
expect(noTrackFound('pins.kml').getResponse()).toEqual({ error: 'No line found in KML file', code: 'no_track' });
|
||||
expect(noTrackFound('pins.kmz').getResponse()).toEqual({ error: 'No line found in KMZ file', code: 'no_track' });
|
||||
});
|
||||
});
|
||||
@@ -441,3 +441,43 @@ describe('Tours GPX atomic persistence and postcommit publication', () => {
|
||||
expect(broadcast.mock.calls.map((call) => call[1])).toEqual(['tours:changed', 'place:created']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Tours KML import through the same persistence (IO-02)', () => {
|
||||
const twoLines = Buffer.from(`<kml><Document>
|
||||
<Placemark><name>Coast</name><LineString><coordinates>11,48,0 11.01,48.01,0</coordinates></LineString></Placemark>
|
||||
<Placemark><name>Ridge</name><LineString><altitudeMode>absolute</altitudeMode>
|
||||
<coordinates>12,49,100 12.01,49.01,150</coordinates></LineString></Placemark>
|
||||
<Placemark><name>Hut</name><Point><coordinates>12,49</coordinates></Point></Placemark>
|
||||
</Document></kml>`);
|
||||
|
||||
it('stores each line as a tour of its own, heights only where the file has them', async () => {
|
||||
const result = (await tours.importGpxAsTour(tripId, twoLines, 'alps.kml', 'socket'))!;
|
||||
|
||||
expect(result.tours.map((tour) => [tour.name, tour.origin, tour.elevation_gain])).toEqual([
|
||||
['Coast', 'gpx', null],
|
||||
['Ridge', 'gpx', 50],
|
||||
]);
|
||||
expect(result.caution).toBe(true);
|
||||
expect(await count('places')).toBe(2);
|
||||
expect(await count('tours')).toBe(2);
|
||||
});
|
||||
|
||||
it('rolls every line back when a later one fails, and stores nothing', async () => {
|
||||
testDb.exec(`CREATE TRIGGER fail_place BEFORE INSERT ON places WHEN NEW.name = 'Ridge'
|
||||
BEGIN SELECT RAISE(ABORT, 'place failure'); END;`);
|
||||
await expect(tours.importGpxAsTour(tripId, twoLines, 'alps.kml')).rejects.toThrow('place failure');
|
||||
for (const table of ['places', 'tours', 'tour_waypoints'] as const) expect(await count(table)).toBe(0);
|
||||
expect(broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses a broken file before any transaction', async () => {
|
||||
const transactional = vi.spyOn(uow, 'transactional');
|
||||
const broken = Buffer.from('<kml><Placemark></kml>');
|
||||
await expect(tours.importGpxAsTour(tripId, broken, 'broken.kml')).rejects.toMatchObject({
|
||||
code: 'tour_file_unreadable',
|
||||
message: 'Malformed KML: invalid XML structure',
|
||||
});
|
||||
expect(transactional).not.toHaveBeenCalled();
|
||||
expect(await count('places')).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user