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:
Maurice
2026-10-20 12:28:57 +02:00
parent f57a0dbd31
commit 3659297af1
58 changed files with 1883 additions and 400 deletions
+103
View File
@@ -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 &amp; 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);
});
});