signalk-chiplog 2.7.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +74 -1
  2. package/README.md +152 -45
  3. package/docs/screenshots/05-stats.png +0 -0
  4. package/docs/screenshots/06-3d-animation.png +0 -0
  5. package/index.js +241 -4
  6. package/lib/api.js +123 -2
  7. package/lib/cloud-pairing.js +172 -0
  8. package/lib/cloud-restore.js +416 -0
  9. package/lib/cloud-sync.js +455 -0
  10. package/lib/database.js +50 -1
  11. package/lib/detection.js +4 -0
  12. package/lib/events.js +84 -20
  13. package/lib/export.js +1 -1
  14. package/lib/mail.js +162 -0
  15. package/lib/passage-map.js +342 -0
  16. package/lib/passage-summary.js +169 -0
  17. package/lib/places.js +6 -0
  18. package/lib/png.js +295 -0
  19. package/lib/qr.js +266 -0
  20. package/lib/smtp.js +242 -0
  21. package/lib/summary-mailer.js +286 -0
  22. package/package.json +2 -1
  23. package/public/app.css +94 -0
  24. package/public/entry/entry.css +94 -1
  25. package/public/entry/icons/apple-touch-icon.png +0 -0
  26. package/public/entry/icons/icon-192.png +0 -0
  27. package/public/entry/icons/icon-512.png +0 -0
  28. package/public/entry/index.html +2 -2
  29. package/public/entry/js/components/Dialogs.mjs +82 -16
  30. package/public/entry/js/components/Icons.mjs +33 -0
  31. package/public/entry/js/components/NotePanel.mjs +21 -3
  32. package/public/entry/js/components/RecentList.mjs +2 -3
  33. package/public/entry/js/journal.mjs +24 -7
  34. package/public/entry/js/main.mjs +27 -18
  35. package/public/entry/manifest.webmanifest +1 -1
  36. package/public/entry/sw.js +2 -0
  37. package/public/icon-small.svg +37 -0
  38. package/public/icon.svg +82 -6
  39. package/public/index.html +1 -1
  40. package/public/js/components/CloudBackup.mjs +298 -0
  41. package/public/js/components/ExportView.mjs +3 -0
  42. package/public/js/components/LogView.mjs +63 -6
  43. package/public/js/components/PassageView.mjs +4 -3
  44. package/public/js/components/Timeline.mjs +40 -14
  45. package/public/js/context.mjs +22 -3
  46. package/public/js/format.mjs +34 -0
  47. package/public/js/i18n.mjs +107 -2
  48. package/public/js/log-lines.mjs +5 -0
  49. package/public/js/main.mjs +1 -1
  50. package/public/js/view-memory.mjs +39 -0
package/lib/mail.js ADDED
@@ -0,0 +1,162 @@
1
+ const crypto = require('node:crypto');
2
+
3
+ // Building the message itself: addresses, headers, and the MIME tree a mail
4
+ // reader needs to show an HTML summary with the map inside it rather than as an
5
+ // attachment hanging off the bottom.
6
+
7
+ const LINE = 76;
8
+
9
+ // "Nom du bord <log@example.org>", or just the address.
10
+ function parseAddress(text) {
11
+ const trimmed = String(text).trim();
12
+ const angled = /^(.*)<([^<>]+)>$/s.exec(trimmed);
13
+ if (!angled) {
14
+ return trimmed === '' ? null : { name: null, address: trimmed };
15
+ }
16
+ const name = angled[1]
17
+ .trim()
18
+ .replace(/^"(.*)"$/s, '$1')
19
+ .trim();
20
+ return { name: name === '' ? null : name, address: angled[2].trim() };
21
+ }
22
+
23
+ // A comma-separated setting, as the plugin's configuration takes recipients.
24
+ // Commas inside a quoted display name are left to whoever needs them: the
25
+ // boat's logbook goes to a handful of plain addresses.
26
+ function parseAddressList(text) {
27
+ return String(text ?? '')
28
+ .split(/[,;]/)
29
+ .map((part) => parseAddress(part))
30
+ .filter((address) => address !== null && address.address.includes('@'));
31
+ }
32
+
33
+ function base64Lines(buffer) {
34
+ const encoded = buffer.toString('base64');
35
+ const lines = [];
36
+ for (let at = 0; at < encoded.length; at += LINE) {
37
+ lines.push(encoded.slice(at, at + LINE));
38
+ }
39
+ return lines.join('\r\n');
40
+ }
41
+
42
+ // RFC 2047: a header carrying anything but US-ASCII is encoded whole, in
43
+ // base64, which keeps an accented place name readable in the subject line.
44
+ function encodeHeaderText(text) {
45
+ if (/^[\x20-\x7e]*$/.test(text)) {
46
+ return text;
47
+ }
48
+ // Each encoded word must fit in 75 characters including the wrapper, so the
49
+ // text is cut into pieces whose base64 stays under that -- on whole
50
+ // characters, never mid-codepoint.
51
+ const words = [];
52
+ let piece = '';
53
+ for (const character of text) {
54
+ if (Buffer.byteLength(piece + character) > 36) {
55
+ words.push(piece);
56
+ piece = '';
57
+ }
58
+ piece += character;
59
+ }
60
+ words.push(piece);
61
+ return words.map((word) => `=?UTF-8?B?${Buffer.from(word).toString('base64')}?=`).join('\r\n ');
62
+ }
63
+
64
+ function formatAddress({ name, address }) {
65
+ return name ? `${encodeHeaderText(name)} <${address}>` : address;
66
+ }
67
+
68
+ function headerLines(headers) {
69
+ return Object.entries(headers)
70
+ .filter(([, value]) => value !== null && value !== undefined && value !== '')
71
+ .map(([name, value]) => `${name}: ${value}`);
72
+ }
73
+
74
+ function part(headers, body) {
75
+ return [...headerLines(headers), '', body].join('\r\n');
76
+ }
77
+
78
+ function textPart(contentType, body) {
79
+ return part(
80
+ {
81
+ 'Content-Type': `${contentType}; charset=utf-8`,
82
+ 'Content-Transfer-Encoding': 'base64'
83
+ },
84
+ base64Lines(Buffer.from(body, 'utf8'))
85
+ );
86
+ }
87
+
88
+ function multipart(subtype, parts, extra = {}) {
89
+ const boundary = `----=_chiplog_${crypto.randomUUID()}`;
90
+ const body = [...parts.map((item) => `--${boundary}\r\n${item}`), `--${boundary}--`, ''].join(
91
+ '\r\n'
92
+ );
93
+ return {
94
+ contentType: Object.entries({ boundary: `"${boundary}"`, ...extra })
95
+ .map(([key, value]) => `; ${key}=${value}`)
96
+ .join(''),
97
+ header: `multipart/${subtype}`,
98
+ body
99
+ };
100
+ }
101
+
102
+ // `inlineImages` are referenced from the HTML as `cid:<their id>`.
103
+ // Returns the message ready for SMTP DATA, CRLF throughout.
104
+ function buildMessage({
105
+ from,
106
+ to,
107
+ subject,
108
+ text,
109
+ html,
110
+ inlineImages = [],
111
+ date = new Date(),
112
+ messageId = `${crypto.randomUUID()}@signalk-chiplog`
113
+ }) {
114
+ const alternative = multipart('alternative', [
115
+ textPart('text/plain', text),
116
+ textPart('text/html', html)
117
+ ]);
118
+
119
+ let body = alternative;
120
+ if (inlineImages.length > 0) {
121
+ body = multipart(
122
+ 'related',
123
+ [
124
+ `Content-Type: ${alternative.header}${alternative.contentType}\r\n\r\n${alternative.body}`,
125
+ ...inlineImages.map((image) =>
126
+ part(
127
+ {
128
+ 'Content-Type': `${image.contentType}; name="${image.filename}"`,
129
+ 'Content-Transfer-Encoding': 'base64',
130
+ 'Content-ID': `<${image.cid}>`,
131
+ 'Content-Disposition': `inline; filename="${image.filename}"`
132
+ },
133
+ base64Lines(image.content)
134
+ )
135
+ )
136
+ ],
137
+ { type: '"multipart/alternative"' }
138
+ );
139
+ }
140
+
141
+ const headers = headerLines({
142
+ From: formatAddress(from),
143
+ To: to.map(formatAddress).join(', '),
144
+ Subject: encodeHeaderText(subject),
145
+ Date: date.toUTCString().replace('GMT', '+0000'),
146
+ 'Message-ID': `<${messageId}>`,
147
+ 'MIME-Version': '1.0',
148
+ 'Content-Type': `${body.header}${body.contentType}`
149
+ });
150
+
151
+ return `${headers.join('\r\n')}\r\n\r\n${body.body}`;
152
+ }
153
+
154
+ function escapeHtml(value) {
155
+ return String(value)
156
+ .replace(/&/g, '&amp;')
157
+ .replace(/</g, '&lt;')
158
+ .replace(/>/g, '&gt;')
159
+ .replace(/"/g, '&quot;');
160
+ }
161
+
162
+ module.exports = { buildMessage, parseAddress, parseAddressList, escapeHtml, encodeHeaderText };
@@ -0,0 +1,342 @@
1
+ const path = require('node:path');
2
+ const { pathToFileURL } = require('node:url');
3
+ const { decodePng, encodePng } = require('./png');
4
+
5
+ // The map picture of a passage, for the summary email (SPEC §4.16): the track
6
+ // drawn over raster tiles, as a PNG. The projection comes from the webapp's own
7
+ // `animation/mercator.mjs`, so the email and the animation put a track in the
8
+ // same place; everything else is here.
9
+
10
+ const TILE_SIZE = 256;
11
+ const MAP_DEFAULTS = { width: 760, height: 440 };
12
+
13
+ const MAX_ZOOM = 16;
14
+ const MIN_ZOOM = 2;
15
+ // Room around the track so it does not run into the frame.
16
+ const PADDING = 26;
17
+ const REQUEST_TIMEOUT_MS = 15 * 1000;
18
+ // The OpenStreetMap tile usage policy asks for restraint; a frame this size is
19
+ // a dozen tiles, once per passage, which is far less than a reader panning the
20
+ // Leaflet map of the same passage.
21
+ const TILE_CONCURRENCY = 4;
22
+
23
+ // The webapp's own colours (components/TrackMap.mjs), so the email looks like
24
+ // the passage page.
25
+ const SEA = [0xdd, 0xe8, 0xf0];
26
+ const TRACK = [0xe8, 0x59, 0x0c];
27
+ const DEPARTURE = [0x2b, 0x8a, 0x3e];
28
+ const ARRIVAL = [0xc9, 0x2a, 0x2a];
29
+ const MARK_EDGE = [0xff, 0xff, 0xff];
30
+ const TRACK_WIDTH = 3;
31
+ const MARK_RADIUS = 4.5;
32
+ const MARK_EDGE_WIDTH = 1.75;
33
+
34
+ let mercator = null;
35
+
36
+ function loadMercator() {
37
+ mercator ??= import(
38
+ pathToFileURL(path.join(__dirname, '..', 'public', 'js', 'animation', 'mercator.mjs')).href
39
+ );
40
+ return mercator;
41
+ }
42
+
43
+ // A canvas of 8-bit RGB, filled with the sea colour: what shows through where
44
+ // no tile arrived.
45
+ function createCanvas(width, height, fill) {
46
+ const data = Buffer.allocUnsafe(width * height * 3);
47
+ for (let i = 0; i < data.length; i += 3) {
48
+ data[i] = fill[0];
49
+ data[i + 1] = fill[1];
50
+ data[i + 2] = fill[2];
51
+ }
52
+ return { width, height, data };
53
+ }
54
+
55
+ function blend(canvas, x, y, r, g, b, alpha) {
56
+ if (alpha <= 0 || x < 0 || y < 0 || x >= canvas.width || y >= canvas.height) {
57
+ return;
58
+ }
59
+ const at = (y * canvas.width + x) * 3;
60
+ if (alpha >= 1) {
61
+ canvas.data[at] = r;
62
+ canvas.data[at + 1] = g;
63
+ canvas.data[at + 2] = b;
64
+ return;
65
+ }
66
+ canvas.data[at] += Math.round((r - canvas.data[at]) * alpha);
67
+ canvas.data[at + 1] += Math.round((g - canvas.data[at + 1]) * alpha);
68
+ canvas.data[at + 2] += Math.round((b - canvas.data[at + 2]) * alpha);
69
+ }
70
+
71
+ // Copies a decoded tile onto the canvas at an integer offset, over whatever is
72
+ // already there -- a seamark overlay is mostly transparent.
73
+ function drawTile(canvas, tile, left, top) {
74
+ for (let y = 0; y < tile.height; y += 1) {
75
+ for (let x = 0; x < tile.width; x += 1) {
76
+ const from = (y * tile.width + x) * 4;
77
+ blend(
78
+ canvas,
79
+ left + x,
80
+ top + y,
81
+ tile.data[from],
82
+ tile.data[from + 1],
83
+ tile.data[from + 2],
84
+ tile.data[from + 3] / 255
85
+ );
86
+ }
87
+ }
88
+ }
89
+
90
+ // A shape is drawn in two passes: coverage is accumulated here, pixel by pixel,
91
+ // then painted in one go. Stamping straight onto the canvas instead would blend
92
+ // the same pixel twice wherever two segments of the track meet, leaving a seam
93
+ // at every join.
94
+ function createMask(width, height) {
95
+ return new Float32Array(width * height);
96
+ }
97
+
98
+ // How much of the pixel a shape `distance` away from its edge covers: the
99
+ // one-pixel ramp that passes for antialiasing at this size.
100
+ const coverage = (distance) => Math.max(0, Math.min(1, 0.5 - distance));
101
+
102
+ function stamp(mask, width, height, box, distanceTo) {
103
+ const firstX = Math.max(0, Math.floor(box.minX));
104
+ const lastX = Math.min(width - 1, Math.ceil(box.maxX));
105
+ const firstY = Math.max(0, Math.floor(box.minY));
106
+ const lastY = Math.min(height - 1, Math.ceil(box.maxY));
107
+ for (let y = firstY; y <= lastY; y += 1) {
108
+ for (let x = firstX; x <= lastX; x += 1) {
109
+ const value = coverage(distanceTo(x + 0.5, y + 0.5));
110
+ const at = y * width + x;
111
+ if (value > mask[at]) {
112
+ mask[at] = value;
113
+ }
114
+ }
115
+ }
116
+ }
117
+
118
+ function stampDisc(mask, width, height, cx, cy, radius) {
119
+ stamp(
120
+ mask,
121
+ width,
122
+ height,
123
+ { minX: cx - radius - 1, maxX: cx + radius + 1, minY: cy - radius - 1, maxY: cy + radius + 1 },
124
+ (x, y) => Math.hypot(x - cx, y - cy) - radius
125
+ );
126
+ }
127
+
128
+ // Distance to the segment, so the stroke gets round caps and joins for free.
129
+ function stampSegment(mask, width, height, from, to, radius) {
130
+ const dx = to.x - from.x;
131
+ const dy = to.y - from.y;
132
+ const lengthSquared = dx * dx + dy * dy;
133
+ if (lengthSquared === 0) {
134
+ stampDisc(mask, width, height, from.x, from.y, radius);
135
+ return;
136
+ }
137
+ stamp(
138
+ mask,
139
+ width,
140
+ height,
141
+ {
142
+ minX: Math.min(from.x, to.x) - radius - 1,
143
+ maxX: Math.max(from.x, to.x) + radius + 1,
144
+ minY: Math.min(from.y, to.y) - radius - 1,
145
+ maxY: Math.max(from.y, to.y) + radius + 1
146
+ },
147
+ (x, y) => {
148
+ const ratio = Math.max(
149
+ 0,
150
+ Math.min(1, ((x - from.x) * dx + (y - from.y) * dy) / lengthSquared)
151
+ );
152
+ return Math.hypot(x - (from.x + ratio * dx), y - (from.y + ratio * dy)) - radius;
153
+ }
154
+ );
155
+ }
156
+
157
+ function paint(canvas, mask, [r, g, b]) {
158
+ for (let y = 0; y < canvas.height; y += 1) {
159
+ for (let x = 0; x < canvas.width; x += 1) {
160
+ blend(canvas, x, y, r, g, b, mask[y * canvas.width + x]);
161
+ }
162
+ }
163
+ }
164
+
165
+ function drawPolyline(canvas, points, width, colour) {
166
+ const mask = createMask(canvas.width, canvas.height);
167
+ const radius = width / 2;
168
+ if (points.length === 1) {
169
+ stampDisc(mask, canvas.width, canvas.height, points[0].x, points[0].y, radius);
170
+ }
171
+ for (let i = 1; i < points.length; i += 1) {
172
+ stampSegment(mask, canvas.width, canvas.height, points[i - 1], points[i], radius);
173
+ }
174
+ paint(canvas, mask, colour);
175
+ }
176
+
177
+ function drawMark(canvas, point, colour) {
178
+ for (const [radius, fill] of [
179
+ [MARK_RADIUS + MARK_EDGE_WIDTH, MARK_EDGE],
180
+ [MARK_RADIUS, colour]
181
+ ]) {
182
+ const mask = createMask(canvas.width, canvas.height);
183
+ stampDisc(mask, canvas.width, canvas.height, point.x, point.y, radius);
184
+ paint(canvas, mask, fill);
185
+ }
186
+ }
187
+
188
+ // The whole-world Mercator fractions of the track, longitudes unwrapped so a
189
+ // passage across the antimeridian stays in one piece.
190
+ function projectTrack(points, { worldX, worldY, unwrapLongitude }) {
191
+ let lon = points[0].lon;
192
+ return points.map((point) => {
193
+ lon = unwrapLongitude(lon, point.lon);
194
+ return { wx: worldX(lon), wy: worldY(point.lat) };
195
+ });
196
+ }
197
+
198
+ // The highest zoom at which the track, plus its padding, fits the frame.
199
+ function chooseView(world, { width, height }) {
200
+ const xs = world.map((point) => point.wx);
201
+ const ys = world.map((point) => point.wy);
202
+ const span = {
203
+ x: Math.max(...xs) - Math.min(...xs),
204
+ y: Math.max(...ys) - Math.min(...ys)
205
+ };
206
+ const centre = {
207
+ wx: (Math.max(...xs) + Math.min(...xs)) / 2,
208
+ wy: (Math.max(...ys) + Math.min(...ys)) / 2
209
+ };
210
+ const usableWidth = Math.max(1, width - 2 * PADDING);
211
+ const usableHeight = Math.max(1, height - 2 * PADDING);
212
+
213
+ let zoom = MIN_ZOOM;
214
+ for (let candidate = MAX_ZOOM; candidate > MIN_ZOOM; candidate -= 1) {
215
+ const scale = TILE_SIZE * 2 ** candidate;
216
+ if (span.x * scale <= usableWidth && span.y * scale <= usableHeight) {
217
+ zoom = candidate;
218
+ break;
219
+ }
220
+ }
221
+ return { zoom, centre };
222
+ }
223
+
224
+ function tileUrl(template, { z, x, y }) {
225
+ const count = 2 ** z;
226
+ const wrapped = ((x % count) + count) % count;
227
+ return template
228
+ .replace('{z}', String(z))
229
+ .replace('{x}', String(wrapped))
230
+ .replace('{y}', String(y));
231
+ }
232
+
233
+ // Fetches the tiles covering the frame, a few at a time, and draws each as it
234
+ // arrives. A tile that does not come back is simply missing: the sea colour
235
+ // shows through and the track is still readable, which is what keeps the map
236
+ // usable on a boat with a thin connection.
237
+ async function drawTiles(canvas, { template, zoom, originX, originY, fetchImpl, userAgent, log }) {
238
+ const count = 2 ** zoom;
239
+ const wanted = [];
240
+ for (
241
+ let y = Math.max(0, Math.floor(originY / TILE_SIZE));
242
+ y <= Math.min(count - 1, Math.floor((originY + canvas.height - 1) / TILE_SIZE));
243
+ y += 1
244
+ ) {
245
+ for (
246
+ let x = Math.floor(originX / TILE_SIZE);
247
+ x <= Math.floor((originX + canvas.width - 1) / TILE_SIZE);
248
+ x += 1
249
+ ) {
250
+ wanted.push({ x, y });
251
+ }
252
+ }
253
+
254
+ let next = 0;
255
+ let failures = 0;
256
+ const worker = async () => {
257
+ while (next < wanted.length) {
258
+ const { x, y } = wanted[next];
259
+ next += 1;
260
+ const url = tileUrl(template, { z: zoom, x, y });
261
+ try {
262
+ const response = await fetchImpl(url, {
263
+ headers: { 'User-Agent': userAgent, Accept: 'image/png' },
264
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
265
+ });
266
+ if (!response.ok) {
267
+ throw new Error(`HTTP ${response.status}`);
268
+ }
269
+ const tile = decodePng(Buffer.from(await response.arrayBuffer()));
270
+ drawTile(canvas, tile, x * TILE_SIZE - originX, y * TILE_SIZE - originY);
271
+ } catch (err) {
272
+ failures += 1;
273
+ log('debug', `Map tile ${zoom}/${x}/${y} unavailable: ${err.message}`);
274
+ }
275
+ }
276
+ };
277
+ await Promise.all(
278
+ Array.from({ length: Math.min(TILE_CONCURRENCY, wanted.length) }, () => worker())
279
+ );
280
+ return { tiles: wanted.length, missing: failures };
281
+ }
282
+
283
+ // `trackPoints` are the passage's, in order; an empty `tileUrlTemplate` draws
284
+ // the track on a plain background, which is also what an unreachable tile
285
+ // server amounts to. Returns `{ png, width, height, zoom, tiles, missing }`, or
286
+ // null when there is no position to draw.
287
+ async function renderPassageMap(
288
+ trackPoints,
289
+ {
290
+ width = MAP_DEFAULTS.width,
291
+ height = MAP_DEFAULTS.height,
292
+ tileUrlTemplate = null,
293
+ fetchImpl = globalThis.fetch,
294
+ userAgent = 'signalk-chiplog',
295
+ log = () => {}
296
+ } = {}
297
+ ) {
298
+ const points = (trackPoints ?? []).filter(
299
+ (point) => Number.isFinite(point.lat) && Number.isFinite(point.lon)
300
+ );
301
+ if (points.length === 0) {
302
+ return null;
303
+ }
304
+
305
+ const projection = await loadMercator();
306
+ const world = projectTrack(points, projection);
307
+ const { zoom, centre } = chooseView(world, { width, height });
308
+ const scale = TILE_SIZE * 2 ** zoom;
309
+ // Where the frame's top-left corner sits in the zoom level's pixel plane.
310
+ // Whole pixels: a tile is copied, not resampled, so it has to land on the
311
+ // grid, and half a pixel of framing makes no difference to the track.
312
+ const originX = Math.round(centre.wx * scale - width / 2);
313
+ const originY = Math.round(centre.wy * scale - height / 2);
314
+
315
+ const canvas = createCanvas(width, height, SEA);
316
+ let coverageReport = { tiles: 0, missing: 0 };
317
+ if (tileUrlTemplate) {
318
+ coverageReport = await drawTiles(canvas, {
319
+ template: tileUrlTemplate,
320
+ zoom,
321
+ originX,
322
+ originY,
323
+ fetchImpl,
324
+ userAgent,
325
+ log
326
+ });
327
+ }
328
+
329
+ const pixels = world.map((point) => ({
330
+ x: point.wx * scale - originX,
331
+ y: point.wy * scale - originY
332
+ }));
333
+ drawPolyline(canvas, pixels, TRACK_WIDTH, TRACK);
334
+ drawMark(canvas, pixels[0], DEPARTURE);
335
+ if (pixels.length > 1) {
336
+ drawMark(canvas, pixels[pixels.length - 1], ARRIVAL);
337
+ }
338
+
339
+ return { png: encodePng(canvas), width, height, zoom, ...coverageReport };
340
+ }
341
+
342
+ module.exports = { renderPassageMap, MAP_DEFAULTS };
@@ -0,0 +1,169 @@
1
+ const path = require('node:path');
2
+ const { pathToFileURL } = require('node:url');
3
+ const { escapeHtml } = require('./mail');
4
+
5
+ // What the summary email says about a passage (SPEC §4.16). Like the PDF
6
+ // logbook, its wording and units come from the webapp's own pure modules, so
7
+ // the mail, the passage page and the logbook all put the same figures the same
8
+ // way.
9
+
10
+ const MAP_CID = 'passage-map';
11
+
12
+ // Inline styles throughout: a mail reader keeps no stylesheet, and several
13
+ // strip <style> altogether.
14
+ const STYLE = {
15
+ body: 'margin:0;padding:16px;background:#f4f6f8;font-family:Helvetica,Arial,sans-serif;color:#1f2933;',
16
+ card: 'max-width:792px;margin:0 auto;background:#ffffff;border-radius:8px;padding:20px;',
17
+ title: 'margin:0 0 4px;font-size:20px;line-height:1.3;color:#102a43;',
18
+ when: 'margin:0 0 16px;font-size:14px;color:#52606d;',
19
+ map: 'display:block;width:100%;max-width:760px;height:auto;border-radius:6px;',
20
+ table: 'width:100%;border-collapse:collapse;margin-top:16px;font-size:14px;',
21
+ label: 'padding:6px 12px 6px 0;color:#52606d;white-space:nowrap;',
22
+ value: 'padding:6px 0;text-align:right;font-weight:bold;color:#102a43;',
23
+ footer: 'margin:18px 0 0;font-size:12px;color:#7b8794;'
24
+ };
25
+
26
+ let sharedModules = null;
27
+
28
+ function loadShared() {
29
+ const load = (file) =>
30
+ import(pathToFileURL(path.join(__dirname, '..', 'public', 'js', file)).href);
31
+ sharedModules ??= Promise.all([load('i18n.mjs'), load('format.mjs')]).then(([i18n, format]) => ({
32
+ i18n,
33
+ format
34
+ }));
35
+ return sharedModules;
36
+ }
37
+
38
+ function placeName(name, pending, t) {
39
+ if (!name) {
40
+ return t('place.unknown');
41
+ }
42
+ return pending ? `${name} (?)` : name;
43
+ }
44
+
45
+ // Departure and arrival, each with its date and time; the day is repeated on
46
+ // the arrival only when the passage ran past midnight, as the logbook shows it.
47
+ function endpoints(entry, { t, format }) {
48
+ const sameDay =
49
+ entry.endTime !== null && format.dayKey(entry.startTime) === format.dayKey(entry.endTime);
50
+ return [
51
+ {
52
+ label: t('passage.departure'),
53
+ place: placeName(entry.startPlaceName, entry.startPlacePending, t),
54
+ when: `${format.date(entry.startTime)} ${format.time(entry.startTime)}`
55
+ },
56
+ {
57
+ label: t('passage.arrival'),
58
+ place: placeName(entry.endPlaceName, entry.endPlacePending, t),
59
+ when:
60
+ entry.endTime === null
61
+ ? ''
62
+ : sameDay
63
+ ? format.time(entry.endTime)
64
+ : `${format.date(entry.endTime)} ${format.time(entry.endTime)}`
65
+ }
66
+ ];
67
+ }
68
+
69
+ // The figures the summary is asked for, in the order the passage page shows
70
+ // them. A figure with nothing behind it is left out rather than printed empty.
71
+ function figures(entry, { t, format }) {
72
+ const underway = (entry.engineDuration ?? 0) + (entry.sailDuration ?? 0);
73
+ const elapsed =
74
+ entry.endTime === null
75
+ ? null
76
+ : Math.max(0, (Date.parse(entry.endTime) - Date.parse(entry.startTime)) / 1000);
77
+ const rows = [
78
+ [t('passage.distance'), format.distance(entry.distance)],
79
+ [t('passage.duration'), format.duration(elapsed)],
80
+ [t('passage.underway'), format.duration(underway)],
81
+ [t('passage.engine'), format.duration(entry.engineDuration)],
82
+ [t('passage.sail'), format.duration(entry.sailDuration)]
83
+ ];
84
+ if (underway > 0 && entry.distance !== null) {
85
+ rows.push([t('passage.averageSpeed'), format.speed(entry.distance / underway)]);
86
+ }
87
+ if (entry.maxSpeed !== null && entry.maxSpeed !== undefined) {
88
+ rows.push([t('passage.maxSpeed'), format.speed(entry.maxSpeed)]);
89
+ }
90
+ if (entry.maxWindSpeed !== null && entry.maxWindSpeed !== undefined) {
91
+ rows.push([
92
+ t('passage.maxWind'),
93
+ entry.maxWindApparent
94
+ ? `${format.speed(entry.maxWindSpeed)} ${t('timeline.apparent')}`
95
+ : format.speed(entry.maxWindSpeed)
96
+ ]);
97
+ }
98
+ return rows.filter(([, value]) => value !== '');
99
+ }
100
+
101
+ function htmlRow(label, value) {
102
+ return `<tr><td style="${STYLE.label}">${escapeHtml(label)}</td><td style="${STYLE.value}">${escapeHtml(value)}</td></tr>`;
103
+ }
104
+
105
+ // `mapAvailable` says whether an image part accompanies the message; without
106
+ // one the <img> would show as a broken attachment.
107
+ async function renderPassageSummary(
108
+ { entry, trackPoints = [] },
109
+ { language = 'en', timeZone, vesselName = null, mapAvailable = false } = {}
110
+ ) {
111
+ const { i18n, format: formatModule } = await loadShared();
112
+ const t = i18n.createTranslator(language);
113
+ const format = formatModule.createFormatter({
114
+ locale: language,
115
+ units: { knots: t('unit.knots'), nauticalMiles: t('unit.nauticalMiles') },
116
+ timeZone
117
+ });
118
+ const context = { t, format };
119
+
120
+ const from = placeName(entry.startPlaceName, entry.startPlacePending, t);
121
+ const to = placeName(entry.endPlaceName, entry.endPlacePending, t);
122
+ const route = `${from} → ${to}`;
123
+ const subject = vesselName
124
+ ? t('mail.subjectVessel', { vessel: vesselName, route })
125
+ : t('mail.subject', { route });
126
+ const when = t('mail.when', {
127
+ date: format.date(entry.startTime),
128
+ zone: format.utcOffset(entry.startTime)
129
+ });
130
+
131
+ const lines = endpoints(entry, context);
132
+ const facts = figures(entry, context);
133
+
134
+ const text = [
135
+ route,
136
+ when,
137
+ '',
138
+ ...lines.map(({ label, place, when: at }) => `${label}: ${place}${at ? ` — ${at}` : ''}`),
139
+ '',
140
+ ...facts.map(([label, value]) => `${label}: ${value}`),
141
+ ...(trackPoints.length === 0 ? ['', t('passage.noTrack')] : []),
142
+ '',
143
+ t('mail.footer')
144
+ ].join('\n');
145
+
146
+ const html = `<!doctype html>
147
+ <html lang="${language}"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width" /><title>${escapeHtml(subject)}</title></head>
148
+ <body style="${STYLE.body}">
149
+ <div style="${STYLE.card}">
150
+ <h1 style="${STYLE.title}">${escapeHtml(route)}</h1>
151
+ <p style="${STYLE.when}">${escapeHtml(when)}</p>
152
+ ${
153
+ mapAvailable
154
+ ? `<img src="cid:${MAP_CID}" alt="${escapeHtml(t('mail.mapAlt'))}" style="${STYLE.map}" />`
155
+ : `<p style="${STYLE.when}">${escapeHtml(t('passage.noTrack'))}</p>`
156
+ }
157
+ <table style="${STYLE.table}" role="presentation">
158
+ ${lines.map(({ label, place, when: at }) => htmlRow(label, at ? `${place} — ${at}` : place)).join('\n')}
159
+ ${facts.map(([label, value]) => htmlRow(label, value)).join('\n')}
160
+ </table>
161
+ <p style="${STYLE.footer}">${escapeHtml(t('mail.footer'))}</p>
162
+ </div>
163
+ </body></html>
164
+ `;
165
+
166
+ return { subject, text, html };
167
+ }
168
+
169
+ module.exports = { renderPassageSummary, MAP_CID };
package/lib/places.js CHANGED
@@ -119,7 +119,13 @@ function deletePlace(db, id) {
119
119
  db.prepare('DELETE FROM places WHERE id = ?').run(id);
120
120
  }
121
121
 
122
+ // Every place, oldest first: what the online backup sends (SPEC §4.17).
123
+ function allPlaces(db) {
124
+ return db.prepare('SELECT * FROM places ORDER BY id').all().map(toPlace);
125
+ }
126
+
122
127
  module.exports = {
128
+ allPlaces,
123
129
  distanceBetween,
124
130
  findNearestPlace,
125
131
  listPlaces,