-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
gpx.ts
274 lines (237 loc) · 9.13 KB
/
gpx.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import { asyncIteratorToArray, asyncIteratorToStream, getZipEncodeStream, indentStream, stringToStream, type ZipEncodeStreamItem } from "../utils/streams.js";
import Database from "../database/database.js";
import type { Field, Line, Marker, MapId, TrackPoint, Type } from "facilmap-types";
import { compileExpression, getSafeFilename, normalizeLineName, normalizeMarkerName, normalizeMapName, quoteHtml } from "facilmap-utils";
import type { LineWithTrackPoints } from "../database/line.js";
import { keyBy } from "lodash-es";
import type { ReadableStream } from "stream/web";
import { getI18n } from "../i18n.js";
const gpxHeader = (
`<?xml version="1.0" encoding="UTF-8"?>\n` +
`<gpx xmlns="http://www.topografix.com/GPX/1/1" creator="FacilMap" version="1.1" xmlns:osmand="https://osmand.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">`
);
const gpxFooter = (
`</gpx>`
);
const markerShapeToOsmand: Record<string, string> = {
"drop": "circle",
"rectangle-marker": "square",
"circle": "circle",
"rectangle": "square",
"diamond": "octagon",
"pentagon": "octagon",
"hexagon": "octagon",
"triangle": "circle",
"triangle-down": "circle",
"star": "octagon"
};
function dataToText(fields: Field[], data: Record<string, string>) {
if(fields.length == 1 && fields[0].name == "Description")
return data["Description"] || "";
const text = [ ];
for(let i=0; i<fields.length; i++) {
text.push(fields[i].name + ": " + (data[fields[i].name] || ""));
}
return text.join('\n\n');
}
function getMetadataGpx(data: { name: string; extensions?: Record<string, string> }, otherExtensions?: Record<string, string>): string {
const { extensions, ...otherData } = data;
return (
`<metadata>\n` +
Object.entries({
time: new Date().toISOString(),
...otherData
}).map(([k, v]) => `\t<${quoteHtml(k)}>${quoteHtml(v)}</${quoteHtml(k)}>\n`).join("") +
(extensions && Object.keys(extensions).length > 0 ? (
`\t<extensions>\n` +
Object.entries(extensions).map(([k, v]) => `\t\t<${quoteHtml(k)}>${quoteHtml(v)}</${quoteHtml(k)}>\n`).join("") +
`\t</extensions>\n`
) : "") +
`</metadata>` +
(otherExtensions && Object.keys(otherExtensions).length > 0 ? (
`\n` +
`<extensions>\n` +
Object.entries(otherExtensions).map(([k, v]) => `\t<${quoteHtml(k)}>${quoteHtml(v)}</${quoteHtml(k)}>\n`).join("") +
`</extensions>`
) : "")
);
}
function getMarkerGpx(marker: Marker, type: Type): ReadableStream<string> {
const osmandBackground = markerShapeToOsmand[marker.shape || "drop"];
return stringToStream(
`<wpt lat="${quoteHtml(marker.lat)}" lon="${quoteHtml(marker.lon)}"${marker.ele != null ? ` ele="${quoteHtml(marker.ele)}"` : ""}>\n` +
`\t<name>${quoteHtml(normalizeMarkerName(marker.name))}</name>\n` +
`\t<desc>${quoteHtml(dataToText(type.fields, marker.data))}</desc>\n` +
`\t<extensions>\n` +
(osmandBackground ? `\t\t<osmand:background>${osmandBackground}</osmand:background>\n` : "") +
`\t\t<osmand:color>#aa${marker.colour}</osmand:color>\n` +
`\t</extensions>\n` +
`</wpt>`
);
}
function getLineRouteGpx(line: LineForExport, type: Type | undefined): ReadableStream<string> {
return stringToStream(
`<rte>\n` +
`\t<name>${quoteHtml(normalizeLineName(line.name))}</name>\n` +
(type ? `\t<desc>${quoteHtml(dataToText(type.fields, line.data ?? {}))}</desc>\n` : "") +
line.routePoints.map((routePoint) => (
`\t<rtept lat="${quoteHtml(routePoint.lat)}" lon="${quoteHtml(routePoint.lon)}" />\n`
)).join("") +
`</rte>`
);
}
function getLineTrackGpx(line: LineForExport, type: Type | undefined, trackPoints: AsyncIterable<TrackPoint>): ReadableStream<string> {
return asyncIteratorToStream((async function*() {
yield (
`<trk>\n` +
`\t<name>${quoteHtml(normalizeLineName(line.name))}</name>\n` +
(type ? `\t<desc>${quoteHtml(dataToText(type.fields, line.data ?? {}))}</desc>\n` : "") +
`\t<trkseg>\n`
);
for await (const trackPoint of trackPoints) {
yield `\t\t<trkpt lat="${quoteHtml(trackPoint.lat)}" lon="${quoteHtml(trackPoint.lon)}"${trackPoint.ele != null ? ` ele="${quoteHtml(trackPoint.ele)}"` : ""} />\n`;
}
yield (
`\t</trkseg>\n` +
`</trk>`
);
})());
}
export function exportGpx(database: Database, mapId: MapId, useTracks: boolean, filter?: string): ReadableStream<string> {
return asyncIteratorToStream((async function* () {
const filterFunc = compileExpression(filter);
const [mapData, types] = await Promise.all([
database.maps.getMapData(mapId),
asyncIteratorToArray(database.types.getTypes(mapId)).then((types) => keyBy(types, 'id'))
]);
if (!mapData)
throw new Error(getI18n().t("map-not-found-error", { mapId }));
yield (
`${gpxHeader}\n` +
`\t${getMetadataGpx({ name: normalizeMapName(mapData.name) }).replaceAll("\n", "\n\t")}\n`
);
for await (const marker of database.markers.getMapMarkers(mapId)) {
if (filterFunc(marker, types[marker.typeId])) {
for await (const chunk of indentStream(getMarkerGpx(marker, types[marker.typeId]), { indent: "\t", indentFirst: true, addNewline: true })) {
yield chunk;
}
}
}
for await (const line of database.lines.getMapLines(mapId)) {
if (filterFunc(line, types[line.typeId])) {
if (useTracks || line.mode == "track") {
const trackPoints = database.lines.getAllLinePoints(line.id);
for await (const chunk of indentStream(getLineTrackGpx(line, types[line.typeId], trackPoints), { indent: "\t", indentFirst: true, addNewline: true })) {
yield chunk;
}
} else {
for await (const chunk of indentStream(getLineRouteGpx(line, types[line.typeId]), { indent: "\t", indentFirst: true, addNewline: true })) {
yield chunk;
}
}
}
}
yield gpxFooter;
})());
}
export function exportGpxZip(database: Database, mapId: MapId, useTracks: boolean, filter?: string): ReadableStream<Uint8Array> {
const encodeZipStream = getZipEncodeStream();
void asyncIteratorToStream((async function*(): AsyncIterable<ZipEncodeStreamItem> {
const filterFunc = compileExpression(filter);
const [mapData, types] = await Promise.all([
database.maps.getMapData(mapId),
asyncIteratorToArray(database.types.getTypes(mapId)).then((types) => keyBy(types, 'id'))
]);
if (!mapData) {
throw new Error(getI18n().t("map-not-found-error", { mapId }));
}
yield {
filename: "markers.gpx",
data: asyncIteratorToStream((async function*() {
yield (
`${gpxHeader}\n` +
`\t${getMetadataGpx({ name: normalizeMapName(mapData.name) }).replaceAll("\n", "\n\t")}\n`
);
for await (const marker of database.markers.getMapMarkers(mapId)) {
if (filterFunc(marker, types[marker.typeId])) {
for await (const chunk of indentStream(getMarkerGpx(marker, types[marker.typeId]), { indent: "\t", indentFirst: true, addNewline: true })) {
yield chunk;
}
}
}
yield gpxFooter;
})())
};
yield {
filename: "lines/",
data: null
};
const names = new Set<string>();
for await (const line of database.lines.getMapLines(mapId)) {
if (filterFunc(line, types[line.typeId])) {
const lineName = normalizeLineName(line.name);
let name = lineName;
for (let i = 1; names.has(name); i++) {
name = `${lineName} (${i})`;
}
names.add(name);
const filename = `lines/${getSafeFilename(name)}.gpx`;
if (useTracks || line.mode == "track") {
const trackPoints = database.lines.getAllLinePoints(line.id);
yield {
filename,
data: exportLineToTrackGpx(line, types[line.typeId], trackPoints)
};
} else {
yield {
filename,
data: exportLineToRouteGpx(line, types[line.typeId])
};
}
}
}
})()).pipeTo(encodeZipStream.writable);
return encodeZipStream.readable;
}
type LineForExport = Pick<LineWithTrackPoints, "name" | "data" | "mode" | "routePoints"> & Partial<Pick<Line, "colour" | "width">>;
function getLineMetadataGpx(line: LineForExport, type: Type | undefined): string {
return getMetadataGpx({
name: normalizeLineName(line.name),
extensions: {
...(type ? {
"osmand:desc": dataToText(type.fields, line.data)
} : {})
}
}, {
...(line.colour ? {
"osmand:color": `#aa${line.colour}`
} : {}),
...(line.width ? {
"osmand:width": `${line.width}`
} : {})
});
}
export function exportLineToTrackGpx(line: LineForExport, type: Type | undefined, trackPoints: AsyncIterable<TrackPoint>): ReadableStream<string> {
return asyncIteratorToStream((async function*() {
yield (
`${gpxHeader}\n` +
`\t${getLineMetadataGpx(line, type).replaceAll("\n", "\n\t")}\n`
);
for await (const chunk of indentStream(getLineTrackGpx(line, type, trackPoints), { indent: "\t", indentFirst: true, addNewline: true })) {
yield chunk;
}
yield gpxFooter;
})());
}
export function exportLineToRouteGpx(line: LineForExport, type: Type | undefined): ReadableStream<string> {
return asyncIteratorToStream((async function*() {
yield (
`${gpxHeader}\n` +
`\t${getLineMetadataGpx(line, type).replaceAll("\n", "\n\t")}\n`
);
for await (const chunk of indentStream(getLineRouteGpx(line, type), { indent: "\t", indentFirst: true, addNewline: true })) {
yield chunk;
}
yield gpxFooter;
})());
}