forked from SignalK/signalk-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunitpreferences-api.js
More file actions
651 lines (583 loc) · 19 KB
/
unitpreferences-api.js
File metadata and controls
651 lines (583 loc) · 19 KB
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
const express = require('express')
const fs = require('fs')
const path = require('path')
const busboy = require('busboy')
const { compile } = require('mathjs')
const { createDebug } = require('../debug')
const debug = createDebug('signalk-server:unitpreferences-api')
/**
* Validate a formula string by attempting to compile it with mathjs
* @param {string} formula - The formula to validate
* @returns {string|null} - Error message if invalid, null if valid
*/
function validateFormula(formula) {
try {
compile(formula)
return null
} catch (e) {
return e.message
}
}
const VALID_PRESET_NAME = /^[a-zA-Z0-9_-]+$/
/**
* Validate all formulas in a unit definitions object
* @param {object} definitions - The unit definitions to validate
* @returns {string|null} - Error message if any formula is invalid, null if all valid
*/
function validateDefinitions(definitions) {
for (const [siUnit, def] of Object.entries(definitions)) {
if (def.conversions) {
for (const [targetUnit, conversion] of Object.entries(def.conversions)) {
if (conversion.formula) {
const error = validateFormula(conversion.formula)
if (error) {
return `Invalid formula for ${siUnit} -> ${targetUnit}: ${error}`
}
}
if (conversion.inverseFormula) {
const error = validateFormula(conversion.inverseFormula)
if (error) {
return `Invalid inverseFormula for ${siUnit} -> ${targetUnit}: ${error}`
}
}
}
}
}
return null
}
/**
* Validate a preset JSON structure thoroughly
* @param {object} preset - The preset object to validate
* @param {object} definitions - Unit definitions for validation
* @returns {string|null} - Error message if invalid, null if valid
*/
function validatePreset(preset, definitions) {
const errors = []
if (!preset || typeof preset !== 'object' || Array.isArray(preset)) {
return 'Preset must be a JSON object'
}
if (!preset.version || typeof preset.version !== 'string') {
return 'Missing or invalid "version"'
}
if (!preset.name || typeof preset.name !== 'string') {
return 'Missing or invalid "name"'
}
if (
!preset.categories ||
typeof preset.categories !== 'object' ||
Array.isArray(preset.categories)
) {
return 'Missing or invalid "categories"'
}
if (Object.keys(preset.categories).length === 0) {
return 'categories cannot be empty'
}
for (const [name, cat] of Object.entries(preset.categories)) {
if (!cat || typeof cat !== 'object') {
errors.push(`"${name}": must be an object`)
continue
}
if (!cat.baseUnit) {
errors.push(`"${name}": missing baseUnit`)
continue
}
if (!cat.targetUnit) {
errors.push(`"${name}": missing targetUnit`)
continue
}
// Skip datetime validation for now - datetime formats are handled differently
const datetimeBaseUnits = [
'RFC 3339 (UTC)',
'ISO-8601 (UTC)',
'Epoch Seconds'
]
if (datetimeBaseUnits.includes(cat.baseUnit)) {
continue
}
const unitDef = definitions[cat.baseUnit]
if (!unitDef) {
errors.push(`"${name}": unknown baseUnit "${cat.baseUnit}"`)
continue
}
// targetUnit same as baseUnit means no conversion, which is valid
if (cat.targetUnit !== cat.baseUnit) {
if (!unitDef.conversions || !unitDef.conversions[cat.targetUnit]) {
const available = Object.keys(unitDef.conversions || {}).join(', ')
errors.push(
`"${name}": "${cat.targetUnit}" not in ${cat.baseUnit} conversions. Available: ${available}`
)
}
}
}
if (errors.length > 0) {
return errors.join('\n')
}
return null
}
const {
getConfig,
getCategories,
getCustomCategories,
getActivePreset,
getMergedDefinitions,
reloadPreset,
reloadCustomDefinitions,
reloadCustomCategories,
getDefaultCategory
} = require('../unitpreferences')
const PACKAGE_UNITPREFS_DIR = path.join(__dirname, '../../unitpreferences')
module.exports = function (app) {
const CONFIG_UNITPREFS_DIR = path.join(
app.config.configPath,
'unitpreferences'
)
function checkPresetExists(presetName) {
const builtInPath = path.join(
PACKAGE_UNITPREFS_DIR,
'presets',
`${presetName}.json`
)
if (fs.existsSync(builtInPath)) {
return { type: 'builtin' }
}
const customPath = path.join(
CONFIG_UNITPREFS_DIR,
'presets/custom',
`${presetName}.json`
)
if (fs.existsSync(customPath)) {
return { type: 'custom' }
}
return null
}
const router = express.Router()
// GET /signalk/v1/unitpreferences/config
router.get('/config', (req, res) => {
try {
const config = getConfig()
res.json(config)
} catch (err) {
debug('Error getting config:', err)
res.status(500).json({ error: 'Failed to get config' })
}
})
// PUT /signalk/v1/unitpreferences/config
router.put('/config', (req, res) => {
try {
const configPath = path.join(CONFIG_UNITPREFS_DIR, 'config.json')
fs.writeFileSync(configPath, JSON.stringify(req.body, null, 2))
reloadPreset()
app.emit('unitpreferencesChanged', { type: 'global' })
res.json({ success: true })
} catch (err) {
debug('Error saving config:', err)
res.status(500).json({ error: 'Failed to save config' })
}
})
// GET /signalk/v1/unitpreferences/categories
router.get('/categories', (req, res) => {
try {
const categories = getCategories()
res.json(categories)
} catch (err) {
debug('Error getting categories:', err)
res.status(500).json({ error: 'Failed to get categories' })
}
})
// GET /signalk/v1/unitpreferences/definitions
router.get('/definitions', (req, res) => {
try {
const definitions = getMergedDefinitions()
res.json(definitions)
} catch (err) {
debug('Error getting definitions:', err)
res.status(500).json({ error: 'Failed to get definitions' })
}
})
// GET /signalk/v1/unitpreferences/custom-definitions
router.get('/custom-definitions', (req, res) => {
try {
const customPath = path.join(
CONFIG_UNITPREFS_DIR,
'custom-units-definitions.json'
)
if (fs.existsSync(customPath)) {
const data = JSON.parse(fs.readFileSync(customPath, 'utf-8'))
res.json(data)
} else {
res.json({})
}
} catch (err) {
debug('Error getting custom definitions:', err)
res.status(500).json({ error: 'Failed to get custom definitions' })
}
})
// PUT /signalk/v1/unitpreferences/custom-definitions
router.put('/custom-definitions', (req, res) => {
try {
// Validate all formulas before saving
const validationError = validateDefinitions(req.body)
if (validationError) {
res.status(400).json({ error: validationError })
return
}
const customPath = path.join(
CONFIG_UNITPREFS_DIR,
'custom-units-definitions.json'
)
fs.writeFileSync(customPath, JSON.stringify(req.body, null, 2))
reloadCustomDefinitions()
app.emit('unitpreferencesChanged', { type: 'global' })
res.json({ success: true })
} catch (err) {
debug('Error saving custom definitions:', err)
res.status(500).json({ error: 'Failed to save custom definitions' })
}
})
// GET /signalk/v1/unitpreferences/custom-categories
router.get('/custom-categories', (req, res) => {
try {
const customCats = getCustomCategories()
res.json(customCats)
} catch (err) {
debug('Error getting custom categories:', err)
res.status(500).json({ error: 'Failed to get custom categories' })
}
})
// PUT /signalk/v1/unitpreferences/custom-categories
router.put('/custom-categories', (req, res) => {
try {
const customPath = path.join(
CONFIG_UNITPREFS_DIR,
'custom-categories.json'
)
fs.writeFileSync(customPath, JSON.stringify(req.body, null, 2))
reloadCustomCategories()
app.emit('unitpreferencesChanged', { type: 'global' })
res.json({ success: true })
} catch (err) {
debug('Error saving custom categories:', err)
res.status(500).json({ error: 'Failed to save custom categories' })
}
})
// GET /signalk/v1/unitpreferences/presets
router.get('/presets', (req, res) => {
try {
const presetsDir = path.join(PACKAGE_UNITPREFS_DIR, 'presets')
const customDir = path.join(CONFIG_UNITPREFS_DIR, 'presets', 'custom')
const builtIn = []
const custom = []
// List built-in presets from package dir
const builtInFiles = fs.readdirSync(presetsDir)
for (const file of builtInFiles) {
if (file.endsWith('.json')) {
const presetPath = path.join(presetsDir, file)
const preset = JSON.parse(fs.readFileSync(presetPath, 'utf-8'))
builtIn.push({
name: file.replace('.json', ''),
displayName: preset.name,
description: preset.description
})
}
}
// List custom presets from config dir
if (fs.existsSync(customDir)) {
const customFiles = fs.readdirSync(customDir)
for (const file of customFiles) {
if (file.endsWith('.json')) {
const presetPath = path.join(customDir, file)
const preset = JSON.parse(fs.readFileSync(presetPath, 'utf-8'))
custom.push({
name: file.replace('.json', ''),
displayName: preset.name,
description: preset.description
})
}
}
}
res.json({ builtIn, custom })
} catch (err) {
debug('Error listing presets:', err)
res.status(500).json({ error: 'Failed to list presets' })
}
})
// GET /signalk/v1/unitpreferences/presets/:name
router.get('/presets/:name', (req, res) => {
try {
const presetName = req.params.name
if (!VALID_PRESET_NAME.test(presetName)) {
res.status(400).json({ error: 'Invalid preset name' })
return
}
// Check custom presets in config dir first
const customPath = path.join(
CONFIG_UNITPREFS_DIR,
'presets/custom',
`${presetName}.json`
)
if (fs.existsSync(customPath)) {
const preset = JSON.parse(fs.readFileSync(customPath, 'utf-8'))
res.json(preset)
return
}
// Fall back to built-in in package dir
const builtInPath = path.join(
PACKAGE_UNITPREFS_DIR,
'presets',
`${presetName}.json`
)
if (fs.existsSync(builtInPath)) {
const preset = JSON.parse(fs.readFileSync(builtInPath, 'utf-8'))
res.json(preset)
return
}
res.status(404).json({ error: 'Preset not found' })
} catch (err) {
debug('Error getting preset:', err)
res.status(500).json({ error: 'Failed to get preset' })
}
})
// PUT /signalk/v1/unitpreferences/presets/custom/:name
router.put('/presets/custom/:name', (req, res) => {
try {
const presetName = req.params.name
if (!VALID_PRESET_NAME.test(presetName)) {
res.status(400).json({ error: 'Invalid preset name' })
return
}
// Prevent overwriting built-in presets
const builtInNames = ['metric', 'imperial-us', 'imperial-uk']
if (builtInNames.includes(presetName)) {
res.status(400).json({ error: 'Cannot overwrite built-in preset' })
return
}
// Validate preset structure
const definitions = getMergedDefinitions()
const validationError = validatePreset(req.body, definitions)
if (validationError) {
res.status(400).json({ error: validationError })
return
}
const customDir = path.join(CONFIG_UNITPREFS_DIR, 'presets/custom')
if (!fs.existsSync(customDir)) {
fs.mkdirSync(customDir, { recursive: true })
}
const presetPath = path.join(customDir, `${presetName}.json`)
fs.writeFileSync(presetPath, JSON.stringify(req.body, null, 2))
res.json({ success: true })
} catch (err) {
debug('Error saving custom preset:', err)
res.status(500).json({ error: 'Failed to save custom preset' })
}
})
// DELETE /signalk/v1/unitpreferences/presets/custom/:name
router.delete('/presets/custom/:name', (req, res) => {
try {
const presetName = req.params.name
if (!VALID_PRESET_NAME.test(presetName)) {
res.status(400).json({ error: 'Invalid preset name' })
return
}
const presetPath = path.join(
CONFIG_UNITPREFS_DIR,
'presets/custom',
`${presetName}.json`
)
if (!fs.existsSync(presetPath)) {
res.status(404).json({ error: 'Preset not found' })
return
}
fs.unlinkSync(presetPath)
res.json({ success: true })
} catch (err) {
debug('Error deleting preset:', err)
res.status(500).json({ error: 'Failed to delete preset' })
}
})
// GET /signalk/v1/unitpreferences/active
router.get('/active', (req, res) => {
try {
const preset = getActivePreset()
const definitions = getMergedDefinitions()
const result = {
...preset,
categories: { ...preset.categories }
}
for (const [category, catDef] of Object.entries(result.categories)) {
const unitDef = definitions[catDef.baseUnit]
const conversion = unitDef?.conversions?.[catDef.targetUnit]
if (conversion) {
result.categories[category] = {
...catDef,
formula: conversion.formula,
inverseFormula: conversion.inverseFormula,
symbol: conversion.symbol
}
}
}
res.json(result)
} catch (err) {
debug('Error getting active preset:', err)
res.status(500).json({ error: 'Failed to get active preset' })
}
})
// GET /signalk/v1/unitpreferences/default-categories
router.get('/default-categories', (req, res) => {
try {
const defaultCatPath = path.join(
PACKAGE_UNITPREFS_DIR,
'default-categories.json'
)
if (fs.existsSync(defaultCatPath)) {
const data = JSON.parse(fs.readFileSync(defaultCatPath, 'utf-8'))
res.json(data)
} else {
res.json({ categories: {} })
}
} catch (err) {
debug('Error getting default categories:', err)
res.status(500).json({ error: 'Failed to get default categories' })
}
})
// GET /signalk/v1/unitpreferences/default-category/:path
router.get('/default-category/*', (req, res) => {
try {
const signalkPath = req.params[0]
const category = getDefaultCategory(signalkPath)
res.json({ path: signalkPath, category: category || null })
} catch (err) {
debug('Error getting default category:', err)
res.status(500).json({ error: 'Failed to get default category' })
}
})
// POST /signalk/v1/unitpreferences/presets/custom/upload
const MAX_PRESET_SIZE = 100 * 1024 // 100KB
router.post('/presets/custom/upload', (req, res) => {
let responseSent = false
const sendResponse = (status, body) => {
if (responseSent) return
responseSent = true
res.status(status).json(body)
}
try {
const bb = busboy({
headers: req.headers,
limits: { fileSize: MAX_PRESET_SIZE }
})
let fileData = ''
let fileName = ''
let fileTruncated = false
bb.on('file', (fieldname, file, info) => {
fileName = info.filename || ''
if (!fileName.endsWith('.json')) {
sendResponse(400, { error: 'File must have .json extension' })
file.resume()
return
}
file.on('data', (data) => {
fileData += data.toString()
})
file.on('limit', () => {
fileTruncated = true
})
})
bb.on('finish', () => {
if (responseSent) return
if (fileTruncated) {
sendResponse(400, {
error: `File too large. Maximum size is ${MAX_PRESET_SIZE / 1024}KB`
})
return
}
if (!fileData) {
sendResponse(400, { error: 'No file uploaded' })
return
}
// Parse JSON
let preset
try {
preset = JSON.parse(fileData)
} catch (e) {
sendResponse(400, { error: `Invalid JSON: ${e.message}` })
return
}
// Validate preset structure
const definitions = getMergedDefinitions()
const validationError = validatePreset(preset, definitions)
if (validationError) {
sendResponse(400, { error: validationError })
return
}
// Derive preset name from filename or preset.name
let presetName = fileName.replace('.json', '')
if (!/^[a-zA-Z0-9_-]+$/.test(presetName)) {
// Fall back to sanitized preset.name
presetName = preset.name.replace(/[^a-zA-Z0-9_-]/g, '-').toLowerCase()
}
// Check for existing preset with same name
const existing = checkPresetExists(presetName)
if (existing) {
if (existing.type === 'builtin') {
sendResponse(400, {
error: `Cannot overwrite built-in preset "${presetName}"`
})
return
} else {
sendResponse(409, {
error: `duplicate`,
existingName: presetName
})
return
}
}
// Ensure custom directory exists
const customDir = path.join(CONFIG_UNITPREFS_DIR, 'presets/custom')
if (!fs.existsSync(customDir)) {
fs.mkdirSync(customDir, { recursive: true })
}
// Save the preset
const presetPath = path.join(customDir, `${presetName}.json`)
fs.writeFileSync(presetPath, JSON.stringify(preset, null, 2))
debug(`Custom preset uploaded: ${presetName}`)
sendResponse(200, {
success: true,
name: presetName,
displayName: preset.name,
isCustom: true
})
})
bb.on('error', (err) => {
debug('Error uploading preset:', err)
sendResponse(500, { error: 'Upload failed' })
})
req.pipe(bb)
} catch (err) {
debug('Error in preset upload:', err)
sendResponse(500, { error: 'Failed to upload preset' })
}
})
return {
start: function () {
if (!app.securityStrategy.isDummy()) {
app.securityStrategy.addAdminWriteMiddleware(
'/signalk/v1/unitpreferences/config'
)
app.securityStrategy.addAdminWriteMiddleware(
'/signalk/v1/unitpreferences/custom-definitions'
)
app.securityStrategy.addAdminWriteMiddleware(
'/signalk/v1/unitpreferences/custom-categories'
)
app.securityStrategy.addAdminWriteMiddleware(
'/signalk/v1/unitpreferences/presets/custom/upload'
)
// addAdminMiddleware protects all methods (including DELETE)
app.securityStrategy.addAdminMiddleware(
'/signalk/v1/unitpreferences/presets/custom/:name'
)
}
app.use('/signalk/v1/unitpreferences', router)
debug('Unit preferences API mounted at /signalk/v1/unitpreferences')
}
}
}