@tak-ps/node-cot 12.37.0 → 13.0.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.
package/lib/parser.ts ADDED
@@ -0,0 +1,906 @@
1
+ import protobuf from 'protobufjs';
2
+ import Err from '@openaddresses/batch-error';
3
+ import { xml2js, js2xml } from 'xml-js';
4
+ import { diff } from 'json-diff-ts';
5
+ import type { Static } from '@sinclair/typebox';
6
+ import type {
7
+ Feature,
8
+ Polygon,
9
+ FeaturePropertyMission,
10
+ FeaturePropertyMissionLayer,
11
+ } from './types/feature.js';
12
+ import type {
13
+ MartiDest,
14
+ MartiDestAttributes,
15
+ Link,
16
+ LinkAttributes,
17
+ } from './types/types.js'
18
+ import {
19
+ InputFeature,
20
+ } from './types/feature.js';
21
+ import type { AllGeoJSON } from "@turf/helpers";
22
+ import Ellipse from '@turf/ellipse';
23
+ import PointOnFeature from '@turf/point-on-feature';
24
+ import Truncate from '@turf/truncate';
25
+ import { destination } from '@turf/destination';
26
+ import Util from './utils/util.js';
27
+ import Color from './utils/color.js';
28
+ import JSONCoT, { Detail } from './types/types.js'
29
+ import CoT from './cot.js';
30
+ import type { CoTOptions } from './cot.js';
31
+ import AJV from 'ajv';
32
+ import fs from 'fs';
33
+ import path from 'node:path';
34
+ import { fileURLToPath } from 'node:url';
35
+
36
+ // GeoJSON Geospatial ops will truncate to the below
37
+ const COORDINATE_PRECISION = 6;
38
+
39
+ const protoPath = path.join(path.dirname(fileURLToPath(import.meta.url)), 'proto', 'takmessage.proto');
40
+ const RootMessage = await protobuf.load(protoPath);
41
+
42
+ const pkg = JSON.parse(String(fs.readFileSync(new URL('../package.json', import.meta.url))));
43
+
44
+ const checkXML = (new AJV({
45
+ allErrors: true,
46
+ coerceTypes: true,
47
+ allowUnionTypes: true
48
+ }))
49
+ .compile(JSONCoT);
50
+
51
+ const checkFeat = (new AJV({
52
+ allErrors: true,
53
+ coerceTypes: true,
54
+ allowUnionTypes: true
55
+ }))
56
+ .compile(InputFeature);
57
+
58
+ /**
59
+ * Convert to and from an XML CoT message
60
+ * @class
61
+ *
62
+ * @param cot A string/buffer containing the XML representation or the xml-js object tree
63
+ *
64
+ * @prop raw Raw XML-JS representation of CoT
65
+ */
66
+ export class CoTParser {
67
+ static validate(
68
+ cot: CoT,
69
+ opts: {
70
+ flow: boolean
71
+ } = {
72
+ flow: true
73
+ }
74
+ ): CoT {
75
+ if (opts.flow === undefined) opts.flow = true;
76
+
77
+ checkXML(cot.raw);
78
+ if (checkXML.errors) throw new Err(400, null, `${checkXML.errors[0].message} (${checkXML.errors[0].instancePath})`);
79
+
80
+ if (opts.flow) {
81
+ if (!cot.raw.event.detail) cot.raw.event.detail = {};
82
+
83
+ if (!cot.raw.event.detail['_flow-tags_']) {
84
+ cot.raw.event.detail['_flow-tags_'] = {};
85
+ }
86
+
87
+ cot.raw.event.detail['_flow-tags_'][`NodeCoT-${pkg.version}`] = new Date().toISOString()
88
+ }
89
+
90
+ return cot;
91
+ }
92
+
93
+ /**
94
+ * Detect difference between CoT messages
95
+ * Note: This diffs based on GeoJSON Representation of message
96
+ * So if unknown properties are present they will be excluded from the diff
97
+ */
98
+ static isDiff(
99
+ aCoT: CoT,
100
+ bCoT: CoT,
101
+ opts = {
102
+ diffMetadata: false,
103
+ diffStaleStartTime: false,
104
+ diffDest: false,
105
+ diffFlow: false
106
+ }
107
+ ): boolean {
108
+ const a = this.to_geojson(aCoT) as Static<typeof InputFeature>;
109
+ const b = this.to_geojson(bCoT) as Static<typeof InputFeature>;
110
+
111
+ if (!opts.diffDest) {
112
+ delete a.properties.dest;
113
+ delete b.properties.dest;
114
+ }
115
+
116
+ if (!opts.diffMetadata) {
117
+ delete a.properties.metadata;
118
+ delete b.properties.metadata;
119
+ }
120
+
121
+ if (!opts.diffFlow) {
122
+ delete a.properties.flow;
123
+ delete b.properties.flow;
124
+ }
125
+
126
+ if (!opts.diffStaleStartTime) {
127
+ delete a.properties.time;
128
+ delete a.properties.stale;
129
+ delete a.properties.start;
130
+ delete b.properties.time;
131
+ delete b.properties.stale;
132
+ delete b.properties.start;
133
+ }
134
+
135
+ const diffs = diff(a, b);
136
+
137
+ return diffs.length > 0;
138
+ }
139
+
140
+
141
+ static from_xml(
142
+ raw: Buffer | string,
143
+ opts: CoTOptions = {}
144
+ ): CoT {
145
+ const cot = new CoT(
146
+ xml2js(String(raw), { compact: true }) as Static<typeof JSONCoT>,
147
+ opts
148
+ );
149
+
150
+ return this.validate(cot);
151
+ }
152
+
153
+ static to_xml(cot: CoT): string {
154
+ return js2xml(cot.raw, { compact: true });
155
+ }
156
+
157
+ /**
158
+ * Return an ATAK Compliant Protobuf
159
+ */
160
+ static to_proto(cot: CoT, version = 1): Uint8Array {
161
+ if (version < 1 || version > 1) throw new Err(400, null, `Unsupported Proto Version: ${version}`);
162
+ const ProtoMessage = RootMessage.lookupType(`atakmap.commoncommo.protobuf.v${version}.TakMessage`)
163
+
164
+ // The spread operator is important to make sure the delete doesn't modify the underlying detail object
165
+ const detail = { ...cot.raw.event.detail };
166
+
167
+ const msg: any = {
168
+ cotEvent: {
169
+ ...cot.raw.event._attributes,
170
+ sendTime: new Date(cot.raw.event._attributes.time).getTime(),
171
+ startTime: new Date(cot.raw.event._attributes.start).getTime(),
172
+ staleTime: new Date(cot.raw.event._attributes.stale).getTime(),
173
+ ...cot.raw.event.point._attributes,
174
+ detail: {
175
+ xmlDetail: ''
176
+ }
177
+ }
178
+ };
179
+
180
+ let key: keyof Static<typeof Detail>;
181
+ for (key in detail) {
182
+ if(['contact', 'group', 'precisionlocation', 'status', 'takv', 'track'].includes(key)) {
183
+ msg.cotEvent.detail[key] = detail[key]._attributes;
184
+ delete detail[key]
185
+ }
186
+ }
187
+
188
+ msg.cotEvent.detail.xmlDetail = js2xml({
189
+ ...detail,
190
+ metadata: cot.metadata
191
+ }, { compact: true });
192
+
193
+ return ProtoMessage.encode(msg).finish();
194
+ }
195
+
196
+ /**
197
+ * Return a GeoJSON Feature from an XML CoT message
198
+ */
199
+ static to_geojson(cot: CoT): Static<typeof Feature> {
200
+ const raw: Static<typeof JSONCoT> = JSON.parse(JSON.stringify(cot.raw));
201
+ if (!raw.event.detail) raw.event.detail = {};
202
+ if (!raw.event.detail.contact) raw.event.detail.contact = { _attributes: { callsign: 'UNKNOWN' } };
203
+ if (!raw.event.detail.contact._attributes) raw.event.detail.contact._attributes = { callsign: 'UNKNOWN' };
204
+
205
+ const feat: Static<typeof Feature> = {
206
+ id: raw.event._attributes.uid,
207
+ type: 'Feature',
208
+ properties: {
209
+ callsign: raw.event.detail.contact._attributes.callsign || 'UNKNOWN',
210
+ center: [ Number(raw.event.point._attributes.lon), Number(raw.event.point._attributes.lat), Number(raw.event.point._attributes.hae) ],
211
+ type: raw.event._attributes.type,
212
+ how: raw.event._attributes.how || '',
213
+ time: raw.event._attributes.time,
214
+ start: raw.event._attributes.start,
215
+ stale: raw.event._attributes.stale,
216
+ },
217
+ geometry: {
218
+ type: 'Point',
219
+ coordinates: [ Number(raw.event.point._attributes.lon), Number(raw.event.point._attributes.lat), Number(raw.event.point._attributes.hae) ]
220
+ }
221
+ };
222
+
223
+ const contact = JSON.parse(JSON.stringify(raw.event.detail.contact._attributes));
224
+ delete contact.callsign;
225
+ if (Object.keys(contact).length) {
226
+ feat.properties.contact = contact;
227
+ }
228
+
229
+ if (cot.creator()) {
230
+ feat.properties.creator = cot.creator();
231
+ }
232
+
233
+ if (raw.event.detail.remarks && raw.event.detail.remarks._text) {
234
+ feat.properties.remarks = raw.event.detail.remarks._text;
235
+ }
236
+
237
+ if (raw.event.detail.fileshare) {
238
+ feat.properties.fileshare = raw.event.detail.fileshare._attributes;
239
+ if (feat.properties.fileshare && typeof feat.properties.fileshare.sizeInBytes === 'string') {
240
+ feat.properties.fileshare.sizeInBytes = parseInt(feat.properties.fileshare.sizeInBytes)
241
+ }
242
+ }
243
+
244
+ if (raw.event.detail.__milsym) {
245
+ feat.properties.milsym = {
246
+ id: raw.event.detail.__milsym._attributes.id
247
+ }
248
+ }
249
+
250
+ if (raw.event.detail.sensor) {
251
+ feat.properties.sensor = raw.event.detail.sensor._attributes;
252
+ }
253
+
254
+ if (raw.event.detail.range) {
255
+ feat.properties.range = raw.event.detail.range._attributes.value;
256
+ }
257
+
258
+ if (raw.event.detail.bearing) {
259
+ feat.properties.bearing = raw.event.detail.bearing._attributes.value;
260
+ }
261
+
262
+ if (raw.event.detail.__video && raw.event.detail.__video._attributes) {
263
+ feat.properties.video = raw.event.detail.__video._attributes;
264
+
265
+ if (raw.event.detail.__video.ConnectionEntry) {
266
+ feat.properties.video.connection = raw.event.detail.__video.ConnectionEntry._attributes;
267
+ }
268
+ }
269
+
270
+ if (raw.event.detail.__geofence) {
271
+ feat.properties.geofence = raw.event.detail.__geofence._attributes;
272
+ }
273
+
274
+ if (raw.event.detail.ackrequest) {
275
+ feat.properties.ackrequest = raw.event.detail.ackrequest._attributes;
276
+ }
277
+
278
+ if (raw.event.detail.attachment_list) {
279
+ feat.properties.attachments = JSON.parse(raw.event.detail.attachment_list._attributes.hashes);
280
+ }
281
+
282
+ if (raw.event.detail.link) {
283
+ if (!Array.isArray(raw.event.detail.link)) raw.event.detail.link = [raw.event.detail.link];
284
+
285
+ feat.properties.links = raw.event.detail.link.filter((link: Static<typeof Link>) => {
286
+ return !!link._attributes.url
287
+ }).map((link: Static<typeof Link>): Static<typeof LinkAttributes> => {
288
+ return link._attributes;
289
+ });
290
+
291
+ if (!feat.properties.links || !feat.properties.links.length) delete feat.properties.links;
292
+ }
293
+
294
+ if (raw.event.detail.archive) {
295
+ feat.properties.archived = true;
296
+ }
297
+
298
+ if (raw.event.detail.__chat) {
299
+ feat.properties.chat = {
300
+ ...raw.event.detail.__chat._attributes,
301
+ chatgrp: raw.event.detail.__chat.chatgrp
302
+ }
303
+ }
304
+
305
+ if (raw.event.detail.track && raw.event.detail.track._attributes) {
306
+ if (raw.event.detail.track._attributes.course) feat.properties.course = Number(raw.event.detail.track._attributes.course);
307
+ if (raw.event.detail.track._attributes.slope) feat.properties.slope = Number(raw.event.detail.track._attributes.slope);
308
+ if (raw.event.detail.track._attributes.course) feat.properties.speed = Number(raw.event.detail.track._attributes.speed);
309
+ }
310
+
311
+ if (raw.event.detail.marti && raw.event.detail.marti.dest) {
312
+ if (!Array.isArray(raw.event.detail.marti.dest)) raw.event.detail.marti.dest = [raw.event.detail.marti.dest];
313
+
314
+ const dest: Array<Static<typeof MartiDestAttributes>> = raw.event.detail.marti.dest.map((d: Static<typeof MartiDest>) => {
315
+ return { ...d._attributes };
316
+ });
317
+
318
+ feat.properties.dest = dest.length === 1 ? dest[0] : dest
319
+ }
320
+
321
+ if (raw.event.detail.usericon && raw.event.detail.usericon._attributes && raw.event.detail.usericon._attributes.iconsetpath) {
322
+ feat.properties.icon = raw.event.detail.usericon._attributes.iconsetpath;
323
+ }
324
+
325
+
326
+ if (raw.event.detail.uid && raw.event.detail.uid._attributes && raw.event.detail.uid._attributes.Droid) {
327
+ feat.properties.droid = raw.event.detail.uid._attributes.Droid;
328
+ }
329
+
330
+ if (raw.event.detail.takv && raw.event.detail.takv._attributes) {
331
+ feat.properties.takv = raw.event.detail.takv._attributes;
332
+ }
333
+
334
+ if (raw.event.detail.__group && raw.event.detail.__group._attributes) {
335
+ feat.properties.group = raw.event.detail.__group._attributes;
336
+ }
337
+
338
+ if (raw.event.detail['_flow-tags_'] && raw.event.detail['_flow-tags_']._attributes) {
339
+ feat.properties.flow = raw.event.detail['_flow-tags_']._attributes;
340
+ }
341
+
342
+ if (raw.event.detail.status && raw.event.detail.status._attributes) {
343
+ feat.properties.status = raw.event.detail.status._attributes;
344
+ }
345
+
346
+ if (raw.event.detail.mission && raw.event.detail.mission._attributes) {
347
+ const mission: Static<typeof FeaturePropertyMission> = {
348
+ ...raw.event.detail.mission._attributes
349
+ };
350
+
351
+ if (raw.event.detail.mission && raw.event.detail.mission.MissionChanges) {
352
+ const changes =
353
+ Array.isArray(raw.event.detail.mission.MissionChanges)
354
+ ? raw.event.detail.mission.MissionChanges
355
+ : [ raw.event.detail.mission.MissionChanges ]
356
+
357
+ mission.missionChanges = []
358
+ for (const change of changes) {
359
+ mission.missionChanges.push({
360
+ contentUid: change.MissionChange.contentUid._text,
361
+ creatorUid: change.MissionChange.creatorUid._text,
362
+ isFederatedChange: change.MissionChange.isFederatedChange._text,
363
+ missionName: change.MissionChange.missionName._text,
364
+ timestamp: change.MissionChange.timestamp._text,
365
+ type: change.MissionChange.type._text,
366
+ details: {
367
+ ...change.MissionChange.details._attributes,
368
+ ...change.MissionChange.details.location
369
+ ? change.MissionChange.details.location._attributes
370
+ : {}
371
+ }
372
+ })
373
+ }
374
+ }
375
+
376
+
377
+ if (raw.event.detail.mission && raw.event.detail.mission.missionLayer) {
378
+ const missionLayer: Static<typeof FeaturePropertyMissionLayer> = {};
379
+
380
+ if (raw.event.detail.mission.missionLayer.name && raw.event.detail.mission.missionLayer.name._text) {
381
+ missionLayer.name = raw.event.detail.mission.missionLayer.name._text;
382
+ }
383
+ if (raw.event.detail.mission.missionLayer.parentUid && raw.event.detail.mission.missionLayer.parentUid._text) {
384
+ missionLayer.parentUid = raw.event.detail.mission.missionLayer.parentUid._text;
385
+ }
386
+ if (raw.event.detail.mission.missionLayer.type && raw.event.detail.mission.missionLayer.type._text) {
387
+ missionLayer.type = raw.event.detail.mission.missionLayer.type._text;
388
+ }
389
+ if (raw.event.detail.mission.missionLayer.uid && raw.event.detail.mission.missionLayer.uid._text) {
390
+ missionLayer.uid = raw.event.detail.mission.missionLayer.uid._text;
391
+ }
392
+
393
+ mission.missionLayer = missionLayer;
394
+ }
395
+
396
+ feat.properties.mission = mission;
397
+ }
398
+
399
+ if (raw.event.detail.precisionlocation && raw.event.detail.precisionlocation._attributes) {
400
+ feat.properties.precisionlocation = raw.event.detail.precisionlocation._attributes;
401
+ }
402
+
403
+ // Line or Polygon style types
404
+ if (['u-d-f', 'u-d-r', 'b-m-r', 'u-rb-a'].includes(raw.event._attributes.type) && Array.isArray(raw.event.detail.link)) {
405
+ const coordinates = [];
406
+
407
+ for (const l of raw.event.detail.link) {
408
+ if (!l._attributes.point) continue;
409
+ coordinates.push(l._attributes.point.split(',').map((p: string) => { return Number(p.trim()) }).splice(0, 2).reverse());
410
+ }
411
+
412
+ if (raw.event.detail.strokeColor && raw.event.detail.strokeColor._attributes && raw.event.detail.strokeColor._attributes.value) {
413
+ const stroke = new Color(Number(raw.event.detail.strokeColor._attributes.value));
414
+ feat.properties.stroke = stroke.as_hex();
415
+ feat.properties['stroke-opacity'] = stroke.as_opacity() / 255;
416
+ }
417
+
418
+ if (raw.event.detail.strokeWeight && raw.event.detail.strokeWeight._attributes && raw.event.detail.strokeWeight._attributes.value) {
419
+ feat.properties['stroke-width'] = Number(raw.event.detail.strokeWeight._attributes.value);
420
+ }
421
+
422
+ if (raw.event.detail.strokeStyle && raw.event.detail.strokeStyle._attributes && raw.event.detail.strokeStyle._attributes.value) {
423
+ feat.properties['stroke-style'] = raw.event.detail.strokeStyle._attributes.value;
424
+ }
425
+
426
+ // Range & Bearing Line
427
+ if (raw.event._attributes.type === 'u-rb-a') {
428
+ const detail = cot.detail();
429
+
430
+ if (!detail.range) throw new Error('Range value not provided')
431
+ if (!detail.bearing) throw new Error('Bearing value not provided')
432
+
433
+ // TODO Support inclination
434
+ const dest = destination(
435
+ cot.position(),
436
+ detail.range._attributes.value / 1000,
437
+ detail.bearing._attributes.value
438
+ ).geometry.coordinates;
439
+
440
+ feat.geometry = {
441
+ type: 'LineString',
442
+ coordinates: [cot.position(), dest]
443
+ };
444
+ } else if (raw.event._attributes.type === 'u-d-r' || (coordinates[0][0] === coordinates[coordinates.length -1][0] && coordinates[0][1] === coordinates[coordinates.length -1][1])) {
445
+ if (raw.event._attributes.type === 'u-d-r') {
446
+ // CoT rectangles are only 4 points - GeoJSON needs to be closed
447
+ coordinates.push(coordinates[0])
448
+ }
449
+
450
+ feat.geometry = {
451
+ type: 'Polygon',
452
+ coordinates: [coordinates]
453
+ }
454
+
455
+ if (raw.event.detail.fillColor && raw.event.detail.fillColor._attributes && raw.event.detail.fillColor._attributes.value) {
456
+ const fill = new Color(Number(raw.event.detail.fillColor._attributes.value));
457
+ feat.properties['fill-opacity'] = fill.as_opacity() / 255;
458
+ feat.properties['fill'] = fill.as_hex();
459
+ }
460
+ } else {
461
+ feat.geometry = {
462
+ type: 'LineString',
463
+ coordinates
464
+ }
465
+ }
466
+ } else if (raw.event._attributes.type.startsWith('u-d-c-c')) {
467
+ if (!raw.event.detail.shape) throw new Err(400, null, 'u-d-c-c (Circle) must define shape value')
468
+ if (
469
+ !raw.event.detail.shape.ellipse
470
+ || !raw.event.detail.shape.ellipse._attributes
471
+ ) throw new Err(400, null, 'u-d-c-c (Circle) must define ellipse shape value')
472
+
473
+ const ellipse = {
474
+ major: Number(raw.event.detail.shape.ellipse._attributes.major),
475
+ minor: Number(raw.event.detail.shape.ellipse._attributes.minor),
476
+ angle: Number(raw.event.detail.shape.ellipse._attributes.angle)
477
+ }
478
+
479
+ feat.geometry = Truncate(Ellipse(
480
+ feat.geometry.coordinates as number[],
481
+ Number(ellipse.major) / 1000,
482
+ Number(ellipse.minor) / 1000,
483
+ {
484
+ angle: ellipse.angle
485
+ }
486
+ ), {
487
+ precision: COORDINATE_PRECISION,
488
+ mutate: true
489
+ }).geometry as Static<typeof Polygon>;
490
+
491
+ feat.properties.shape = {};
492
+ feat.properties.shape.ellipse = ellipse;
493
+ } else if (raw.event._attributes.type.startsWith('b-m-p-s-p-i')) {
494
+ // TODO: Currently the "shape" tag is only parsed here - asking ARA for clarification if it is a general use tag
495
+ if (raw.event.detail.shape && raw.event.detail.shape.polyline && raw.event.detail.shape.polyline.vertex) {
496
+ const coordinates = [];
497
+
498
+ const vertices = Array.isArray(raw.event.detail.shape.polyline.vertex) ? raw.event.detail.shape.polyline.vertex : [raw.event.detail.shape.polyline.vertex];
499
+ for (const v of vertices) {
500
+ coordinates.push([Number(v._attributes.lon), Number(v._attributes.lat)]);
501
+ }
502
+
503
+ if (coordinates.length === 1) {
504
+ feat.geometry = { type: 'Point', coordinates: coordinates[0] }
505
+ } else if (raw.event.detail.shape.polyline._attributes && raw.event.detail.shape.polyline._attributes.closed === true) {
506
+ coordinates.push(coordinates[0]);
507
+ feat.geometry = { type: 'Polygon', coordinates: [coordinates] }
508
+ } else {
509
+ feat.geometry = { type: 'LineString', coordinates }
510
+ }
511
+ }
512
+
513
+ if (
514
+ raw.event.detail.shape
515
+ && raw.event.detail.shape.polyline
516
+ && raw.event.detail.shape.polyline._attributes
517
+ && raw.event.detail.shape.polyline._attributes
518
+ ) {
519
+ if (raw.event.detail.shape.polyline._attributes.fillColor) {
520
+ const fill = new Color(Number(raw.event.detail.shape.polyline._attributes.fillColor));
521
+ feat.properties['fill-opacity'] = fill.as_opacity() / 255;
522
+ feat.properties['fill'] = fill.as_hex();
523
+ }
524
+
525
+ if (raw.event.detail.shape.polyline._attributes.color) {
526
+ const stroke = new Color(Number(raw.event.detail.shape.polyline._attributes.color));
527
+ feat.properties.stroke = stroke.as_hex();
528
+ feat.properties['stroke-opacity'] = stroke.as_opacity() / 255;
529
+ }
530
+ }
531
+ }
532
+
533
+ if (raw.event.detail.color && raw.event.detail.color._attributes && raw.event.detail.color._attributes.argb) {
534
+ const color = new Color(Number(raw.event.detail.color._attributes.argb));
535
+ feat.properties['marker-color'] = color.as_hex();
536
+ feat.properties['marker-opacity'] = color.as_opacity() / 255;
537
+ }
538
+
539
+ feat.properties.metadata = cot.metadata;
540
+ feat.path = cot.path;
541
+
542
+ return feat;
543
+ }
544
+
545
+ /**
546
+ * Parse an ATAK compliant Protobuf to a JS Object
547
+ */
548
+ static from_proto(
549
+ raw: Uint8Array,
550
+ version = 1,
551
+ opts: CoTOptions = {}
552
+ ): CoT {
553
+ const ProtoMessage = RootMessage.lookupType(`atakmap.commoncommo.protobuf.v${version}.TakMessage`)
554
+
555
+ // TODO Type this
556
+ const msg: any = ProtoMessage.decode(raw);
557
+
558
+ if (!msg.cotEvent) throw new Err(400, null, 'No cotEvent Data');
559
+
560
+ const detail: Record<string, any> = {};
561
+ const metadata: Record<string, unknown> = {};
562
+ for (const key in msg.cotEvent.detail) {
563
+ if (key === 'xmlDetail') {
564
+ const parsed: any = xml2js(`<detail>${msg.cotEvent.detail.xmlDetail}</detail>`, { compact: true });
565
+ Object.assign(detail, parsed.detail);
566
+
567
+ if (detail.metadata) {
568
+ for (const key in detail.metadata) {
569
+ metadata[key] = detail.metadata[key]._text;
570
+ }
571
+ delete detail.metadata;
572
+ }
573
+ } else if (key === 'group') {
574
+ if (msg.cotEvent.detail[key]) {
575
+ detail.__group = { _attributes: msg.cotEvent.detail[key] };
576
+ }
577
+ } else if (['contact', 'precisionlocation', 'status', 'takv', 'track'].includes(key)) {
578
+ if (msg.cotEvent.detail[key]) {
579
+ detail[key] = { _attributes: msg.cotEvent.detail[key] };
580
+ }
581
+ }
582
+ }
583
+
584
+ const cot = new CoT({
585
+ event: {
586
+ _attributes: {
587
+ version: '2.0',
588
+ uid: msg.cotEvent.uid, type: msg.cotEvent.type, how: msg.cotEvent.how,
589
+ qos: msg.cotEvent.qos, opex: msg.cotEvent.opex, access: msg.cotEvent.access,
590
+ time: new Date(msg.cotEvent.sendTime.toNumber()).toISOString(),
591
+ start: new Date(msg.cotEvent.startTime.toNumber()).toISOString(),
592
+ stale: new Date(msg.cotEvent.staleTime.toNumber()).toISOString(),
593
+ },
594
+ detail,
595
+ point: {
596
+ _attributes: {
597
+ lat: msg.cotEvent.lat,
598
+ lon: msg.cotEvent.lon,
599
+ hae: msg.cotEvent.hae,
600
+ le: msg.cotEvent.le,
601
+ ce: msg.cotEvent.ce,
602
+ },
603
+ }
604
+ }
605
+ }, opts);
606
+
607
+ cot.metadata = metadata;
608
+
609
+ return this.validate(cot);
610
+ }
611
+
612
+ /**
613
+ * Return an CoT Message given a GeoJSON Feature
614
+ *
615
+ * @param {Object} feature GeoJSON Point Feature
616
+ *
617
+ * @return {CoT}
618
+ */
619
+ static from_geojson(
620
+ feature: Static<typeof InputFeature>,
621
+ opts: CoTOptions = {}
622
+ ): CoT {
623
+ checkFeat(feature);
624
+ if (checkFeat.errors) throw new Err(400, null, `${checkFeat.errors[0].message} (${checkFeat.errors[0].instancePath})`);
625
+
626
+ const cot: Static<typeof JSONCoT> = {
627
+ event: {
628
+ _attributes: Util.cot_event_attr(
629
+ feature.properties.type || 'a-f-G',
630
+ feature.properties.how || 'm-g',
631
+ feature.properties.time,
632
+ feature.properties.start,
633
+ feature.properties.stale
634
+ ),
635
+ point: Util.cot_point(),
636
+ detail: Util.cot_event_detail(feature.properties.callsign)
637
+ }
638
+ };
639
+
640
+ if (feature.id) cot.event._attributes.uid = String(feature.id);
641
+ if (feature.properties.callsign && !feature.id) cot.event._attributes.uid = feature.properties.callsign;
642
+ if (!cot.event.detail) cot.event.detail = {};
643
+
644
+ if (feature.properties.droid) {
645
+ cot.event.detail.uid = { _attributes: { Droid: feature.properties.droid } };
646
+ }
647
+
648
+ if (feature.properties.archived) {
649
+ cot.event.detail.archive = { _attributes: { } };
650
+ }
651
+
652
+ if (feature.properties.links) {
653
+ if (!cot.event.detail.link) cot.event.detail.link = [];
654
+ else if (!Array.isArray(cot.event.detail.link)) cot.event.detail.link = [cot.event.detail.link];
655
+
656
+ cot.event.detail.link.push(...feature.properties.links.map((link: Static<typeof LinkAttributes>) => {
657
+ return { _attributes: link };
658
+ }))
659
+ }
660
+
661
+ if (feature.properties.dest) {
662
+ const dest = !Array.isArray(feature.properties.dest) ? [ feature.properties.dest ] : feature.properties.dest;
663
+
664
+ cot.event.detail.marti = {
665
+ dest: dest.map((dest) => {
666
+ return { _attributes: { ...dest } };
667
+ })
668
+ }
669
+ }
670
+
671
+ if (feature.properties.takv) {
672
+ cot.event.detail.takv = { _attributes: { ...feature.properties.takv } };
673
+ }
674
+
675
+ if (feature.properties.creator) {
676
+ cot.event.detail.creator = { _attributes: { ...feature.properties.creator } };
677
+ }
678
+
679
+ if (feature.properties.range !== undefined) {
680
+ cot.event.detail.range = { _attributes: { value: feature.properties.range } }
681
+ }
682
+
683
+ if (feature.properties.bearing !== undefined) {
684
+ cot.event.detail.bearing = { _attributes: { value: feature.properties.bearing } }
685
+ }
686
+
687
+ if (feature.properties.geofence) {
688
+ cot.event.detail.__geofence = { _attributes: { ...feature.properties.geofence } };
689
+ }
690
+
691
+ if (feature.properties.milsym) {
692
+ cot.event.detail.__milsym = { _attributes: { id: feature.properties.milsym.id} };
693
+ }
694
+
695
+ if (feature.properties.sensor) {
696
+ cot.event.detail.sensor = { _attributes: { ...feature.properties.sensor } };
697
+ }
698
+
699
+ if (feature.properties.ackrequest) {
700
+ cot.event.detail.ackrequest = { _attributes: { ...feature.properties.ackrequest } };
701
+ }
702
+
703
+ if (feature.properties.video) {
704
+ if (feature.properties.video.connection) {
705
+ const video = JSON.parse(JSON.stringify(feature.properties.video));
706
+
707
+ const connection = video.connection;
708
+ delete video.connection;
709
+
710
+ cot.event.detail.__video = {
711
+ _attributes: { ...video },
712
+ ConnectionEntry: {
713
+ _attributes: connection
714
+ }
715
+ }
716
+ } else {
717
+ cot.event.detail.__video = { _attributes: { ...feature.properties.video } };
718
+ }
719
+ }
720
+
721
+ if (feature.properties.attachments) {
722
+ cot.event.detail.attachment_list = { _attributes: { hashes: JSON.stringify(feature.properties.attachments) } };
723
+ }
724
+
725
+ if (feature.properties.contact) {
726
+ cot.event.detail.contact = {
727
+ _attributes: {
728
+ ...feature.properties.contact,
729
+ callsign: feature.properties.callsign || 'UNKNOWN',
730
+ }
731
+ };
732
+ }
733
+
734
+ if (feature.properties.fileshare) {
735
+ cot.event.detail.fileshare = { _attributes: { ...feature.properties.fileshare } };
736
+ }
737
+
738
+ if (feature.properties.course !== undefined || feature.properties.speed !== undefined || feature.properties.slope !== undefined) {
739
+ cot.event.detail.track = {
740
+ _attributes: Util.cot_track_attr(feature.properties.course, feature.properties.speed, feature.properties.slope)
741
+ }
742
+ }
743
+
744
+ if (feature.properties.group) {
745
+ cot.event.detail.__group = { _attributes: { ...feature.properties.group } }
746
+ }
747
+
748
+ if (feature.properties.flow) {
749
+ cot.event.detail['_flow-tags_'] = { _attributes: { ...feature.properties.flow } }
750
+ }
751
+
752
+ if (feature.properties.status) {
753
+ cot.event.detail.status = { _attributes: { ...feature.properties.status } }
754
+ }
755
+
756
+ if (feature.properties.precisionlocation) {
757
+ cot.event.detail.precisionlocation = { _attributes: { ...feature.properties.precisionlocation } }
758
+ }
759
+
760
+ if (feature.properties.icon) {
761
+ cot.event.detail.usericon = { _attributes: { iconsetpath: feature.properties.icon } }
762
+ }
763
+
764
+ if (feature.properties.mission) {
765
+ cot.event.detail.mission = {
766
+ _attributes: {
767
+ type: feature.properties.mission.type,
768
+ guid: feature.properties.mission.guid,
769
+ tool: feature.properties.mission.tool,
770
+ name: feature.properties.mission.name,
771
+ authorUid: feature.properties.mission.authorUid,
772
+ }
773
+ }
774
+
775
+ if (feature.properties.mission.missionLayer) {
776
+ cot.event.detail.mission.missionLayer = {};
777
+
778
+ if (feature.properties.mission.missionLayer.name) {
779
+ cot.event.detail.mission.missionLayer.name = { _text: feature.properties.mission.missionLayer.name };
780
+ }
781
+
782
+ if (feature.properties.mission.missionLayer.parentUid) {
783
+ cot.event.detail.mission.missionLayer.parentUid = { _text: feature.properties.mission.missionLayer.parentUid };
784
+ }
785
+
786
+ if (feature.properties.mission.missionLayer.type) {
787
+ cot.event.detail.mission.missionLayer.type = { _text: feature.properties.mission.missionLayer.type };
788
+ }
789
+
790
+ if (feature.properties.mission.missionLayer.uid) {
791
+ cot.event.detail.mission.missionLayer.uid = { _text: feature.properties.mission.missionLayer.uid };
792
+ }
793
+ }
794
+ }
795
+
796
+ cot.event.detail.remarks = { _attributes: { }, _text: feature.properties.remarks || '' };
797
+
798
+ if (!feature.geometry) {
799
+ throw new Err(400, null, 'Must have Geometry');
800
+ } else if (!['Point', 'Polygon', 'LineString'].includes(feature.geometry.type)) {
801
+ throw new Err(400, null, 'Unsupported Geometry Type');
802
+ }
803
+
804
+ if (feature.geometry.type === 'Point') {
805
+ cot.event.point._attributes.lon = feature.geometry.coordinates[0];
806
+ cot.event.point._attributes.lat = feature.geometry.coordinates[1];
807
+ cot.event.point._attributes.hae = feature.geometry.coordinates[2] || 0.0;
808
+
809
+
810
+ if (feature.properties['marker-color']) {
811
+ const color = new Color(feature.properties['marker-color'] || -1761607936);
812
+ color.a = feature.properties['marker-opacity'] !== undefined ? feature.properties['marker-opacity'] * 255 : 128;
813
+ cot.event.detail.color = { _attributes: { argb: color.as_32bit() } };
814
+ }
815
+ } else if (feature.geometry.type === 'Polygon' && feature.properties.type === 'u-d-c-c') {
816
+ if (!feature.properties.shape || !feature.properties.shape.ellipse) {
817
+ throw new Err(400, null, 'u-d-c-c (Circle) must define a feature.properties.shape.ellipse property')
818
+ }
819
+ cot.event.detail.shape = { ellipse: { _attributes: feature.properties.shape.ellipse } }
820
+
821
+ if (feature.properties.center) {
822
+ cot.event.point._attributes.lon = feature.properties.center[0];
823
+ cot.event.point._attributes.lat = feature.properties.center[1];
824
+ } else {
825
+ const centre = PointOnFeature(feature as AllGeoJSON);
826
+ cot.event.point._attributes.lon = centre.geometry.coordinates[0];
827
+ cot.event.point._attributes.lat = centre.geometry.coordinates[1];
828
+ cot.event.point._attributes.hae = 0.0;
829
+ }
830
+ } else if (['Polygon', 'LineString'].includes(feature.geometry.type)) {
831
+ const stroke = new Color(feature.properties.stroke || -1761607936);
832
+ stroke.a = feature.properties['stroke-opacity'] !== undefined ? feature.properties['stroke-opacity'] * 255 : 128;
833
+ cot.event.detail.strokeColor = { _attributes: { value: stroke.as_32bit() } };
834
+
835
+ if (!feature.properties['stroke-width']) feature.properties['stroke-width'] = 3;
836
+ cot.event.detail.strokeWeight = { _attributes: {
837
+ value: feature.properties['stroke-width']
838
+ } };
839
+
840
+ if (!feature.properties['stroke-style']) feature.properties['stroke-style'] = 'solid';
841
+ cot.event.detail.strokeStyle = { _attributes: {
842
+ value: feature.properties['stroke-style']
843
+ } };
844
+
845
+ if (feature.geometry.type === 'LineString') {
846
+ cot.event._attributes.type = 'u-d-f';
847
+
848
+ if (!cot.event.detail.link) cot.event.detail.link = [];
849
+ else if (!Array.isArray(cot.event.detail.link)) cot.event.detail.link = [cot.event.detail.link]
850
+
851
+ for (const coord of feature.geometry.coordinates) {
852
+ cot.event.detail.link.push({
853
+ _attributes: { point: `${coord[1]},${coord[0]}` }
854
+ });
855
+ }
856
+ } else if (feature.geometry.type === 'Polygon') {
857
+ cot.event._attributes.type = 'u-d-f';
858
+
859
+ if (!cot.event.detail.link) cot.event.detail.link = [];
860
+ else if (!Array.isArray(cot.event.detail.link)) cot.event.detail.link = [cot.event.detail.link]
861
+
862
+ // Inner rings are not yet supported
863
+ for (const coord of feature.geometry.coordinates[0]) {
864
+ cot.event.detail.link.push({
865
+ _attributes: { point: `${coord[1]},${coord[0]}` }
866
+ });
867
+ }
868
+
869
+ const fill = new Color(feature.properties.fill || -1761607936);
870
+ fill.a = feature.properties['fill-opacity'] !== undefined ? feature.properties['fill-opacity'] * 255 : 128;
871
+ cot.event.detail.fillColor = { _attributes: { value: fill.as_32bit() } };
872
+ }
873
+
874
+ cot.event.detail.labels_on = { _attributes: { value: false } };
875
+ cot.event.detail.tog = { _attributes: { enabled: '0' } };
876
+
877
+ if (feature.properties.center && Array.isArray(feature.properties.center) && feature.properties.center.length >= 2) {
878
+ cot.event.point._attributes.lon = feature.properties.center[0];
879
+ cot.event.point._attributes.lat = feature.properties.center[1];
880
+
881
+ if (feature.properties.center.length >= 3) {
882
+ cot.event.point._attributes.hae = feature.properties.center[2] || 0.0;
883
+ } else {
884
+ cot.event.point._attributes.hae = 0.0;
885
+ }
886
+ } else {
887
+ const centre = PointOnFeature(feature as AllGeoJSON);
888
+ cot.event.point._attributes.lon = centre.geometry.coordinates[0];
889
+ cot.event.point._attributes.lat = centre.geometry.coordinates[1];
890
+ cot.event.point._attributes.hae = 0.0;
891
+ }
892
+ }
893
+
894
+ const newcot = new CoT(cot, opts);
895
+
896
+ if (feature.properties.metadata) {
897
+ newcot.metadata = feature.properties.metadata
898
+ }
899
+
900
+ if (feature.path) {
901
+ newcot.path = feature.path
902
+ }
903
+
904
+ return this.validate(newcot);
905
+ }
906
+ }