-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask.ts
More file actions
319 lines (292 loc) · 13.7 KB
/
task.ts
File metadata and controls
319 lines (292 loc) · 13.7 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
import { Feature } from '@tak-ps/node-cot'
import { Static, Type, TSchema } from '@sinclair/typebox';
import type { Event } from '@tak-ps/etl';
import ETL, { SchemaType, handler as internal, local, DataFlowType, InvocationType } from '@tak-ps/etl';
import { fetch } from '@tak-ps/etl';
const InputSchema = Type.Object({
AgencyName: Type.String({
description: 'Account Name used to login to evidence.com'
}),
AgencyAcronym: Type.Optional(Type.String({
description: 'Used to prefix the Callsign'
})),
DataTimeout: Type.Integer({
description: 'Get locations updated within the last provided number of minutes',
default: 5
}),
PartnerID: Type.String({
description: 'Generated as part of API Access Flow'
}),
ClientID: Type.String({
description: 'Generated as part of API Access Flow'
}),
ClientSecret: Type.String({
description: 'Generated as part of API Access Flow'
}),
DEBUG: Type.Boolean({
default: false,
description: 'Print results in logs'
})
});
const OutputSchema = Type.Object({
partnerName: Type.String(),
axonDeviceId: Type.String(),
deviceModel: Type.String(),
deviceUpdateTimestamp: Type.Integer(),
deviceSerial: Type.String(),
location_accuracy: Type.Number(),
location_latitude: Type.Number(),
location_longitude: Type.Number(),
location_locationUpdateTimestamp: Type.Integer(),
status: Type.String(),
stream_isStreamable: Type.Boolean(),
signalStrength: Type.Optional(Type.String()),
battery: Type.Optional(Type.Integer()),
primary_assignee_firstName: Type.Optional(Type.String()),
primary_assignee_lastName: Type.Optional(Type.String()),
primary_assignee_badgeNumber: Type.Optional(Type.String()),
primary_assignee_userId: Type.Optional(Type.String()),
vehicle_vehicleId: Type.Optional(Type.String()),
vehicle_assigneeType: Type.Optional(Type.String()),
vehicle_vehicleName: Type.Optional(Type.String()),
});
export default class Task extends ETL {
static name = 'etl-axon'
static flow = [ DataFlowType.Incoming ];
static invocation = [ InvocationType.Schedule ];
async schema(
type: SchemaType = SchemaType.Input,
flow: DataFlowType = DataFlowType.Incoming
): Promise<TSchema> {
if (flow === DataFlowType.Incoming) {
if (type === SchemaType.Input) {
return InputSchema;
} else {
return OutputSchema;
}
} else {
return Type.Object({});
}
}
async control(): Promise<void> {
const layer = await this.fetchLayer();
const env = await this.env(InputSchema);
let access_token;
if (
!layer.incoming.ephemeral.access_token
|| !layer.incoming.ephemeral.access_token_expires
// If Token is going to expire within 1 minute, request a new token
|| (Number(layer.incoming.ephemeral.access_token_expires) + 60000) < +new Date()
) {
console.log('ok - Requesting New Token');
const oauthReq = await fetch(`https://${env.AgencyName}.evidence.com/api/oauth2/token`, {
method: 'POST',
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
grant_type: 'client_credentials',
partner_id: env.PartnerID,
client_id: env.ClientID,
client_secret: env.ClientSecret
})
})
const oauthRes = await oauthReq.typed(Type.Object({
access_token: Type.String(),
token_type: Type.String(),
expires_in: Type.Integer(),
expires_on: Type.Integer(),
not_before: Type.Integer(),
version: Type.String(),
entity: Type.Object({
type: Type.String(),
id: Type.String(),
partner_id: Type.String()
})
}));
await this.setEphemeral({
access_token: oauthRes.access_token,
access_token_expires: String(oauthRes.expires_on)
})
access_token = oauthRes.access_token;
} else {
access_token = layer.incoming.ephemeral.access_token;
}
console.log('ok - requesting devices');
let from = 0;
let total = Infinity;
do {
const devicesReq = await fetch(`https://${env.AgencyName}.evidence.com/respond/api/v1/devices/states/search`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Client-Type': 'EXTERNAL',
Authorization: `Bearer ${access_token}`
},
body: JSON.stringify({
from: 0,
size: 2000
})
});
const devicesRes = await devicesReq.typed(Type.Object({
meta: Type.Object({
correlationId: Type.String(),
serverTimestamp: Type.Integer(),
totalHits: Type.Optional(Type.Integer()),
count: Type.Optional(Type.Integer())
}),
data: Type.Optional(Type.Array(Type.Object({
partnerId: Type.String(),
partnerName: Type.String(),
axonDeviceId: Type.String(),
deviceModel: Type.String(),
deviceUpdateTimestamp: Type.Integer(),
attributes: Type.Object({
deviceSerial: Type.String(),
location: Type.Optional(Type.Object({
accuracy: Type.Number(),
latitude: Type.Number(),
longitude: Type.Number(),
locationUpdateTimestamp: Type.Integer()
})),
status: Type.String(),
stream: Type.Object({
isStreamable: Type.Boolean(),
reason: Type.Optional(Type.String())
}),
links: Type.Optional(Type.Object({
view: Type.String()
})),
signalStrengths: Type.Optional(Type.Array(Type.Object({
signalStrength: Type.String()
}))),
batteries: Type.Optional(Type.Array(Type.Object({
batteryPercentage: Type.Integer()
}))),
connectedDevices: Type.Optional(Type.Array(Type.Object({
axonDeviceId: Type.String()
}))),
vehicle: Type.Optional(Type.Object({
assigneeType: Type.String(),
vehicleName: Type.String(),
vehicleId: Type.String()
})),
assignees: Type.Optional(Type.Array(Type.Object({
assigneeType: Type.String(),
firstName: Type.String(),
lastName: Type.String(),
badgeNumber: Type.String(),
userId: Type.String(),
primary: Type.Boolean()
})))
})
})))
}), {
verbose: true
});
const features: Static<typeof Feature.InputFeature>[] = [];
if (devicesRes.data === undefined) {
console.log('not ok - No Devices Data Returned - Is the API Token Scoped Correctly?');
return;
}
for (const device of devicesRes.data || []) {
const primary = (device.attributes.assignees || []).filter((user) => {
return user.primary
})
if (device.attributes.status === 'DOCKED') {
// We don't care about charging devices
continue;
} else if (
// If the device has no location, we can't use it
!device.attributes.location
// We cut off devices if we haveh't seen them for 30 minutes
|| new Date(device.attributes.location.locationUpdateTimestamp).getTime() < new Date().getTime() - (env.DataTimeout * 60 * 1000)
) {
continue;
}
const metadata = {
partnerName: device.partnerName,
axonDeviceId: device.axonDeviceId,
deviceModel: device.deviceModel,
deviceUpdateTimestamp: device.deviceUpdateTimestamp,
deviceSerial: device.attributes.deviceSerial,
location_accuracy: device.attributes.location.accuracy,
location_latitude: device.attributes.location.latitude,
location_longitude: device.attributes.location.longitude,
location_locationUpdateTimestamp: device.attributes.location.locationUpdateTimestamp,
status: device.attributes.status,
stream_isStreamable: device.attributes.stream ? device.attributes.stream.isStreamable : false,
signalStrength: device.attributes.signalStrengths ? device.attributes.signalStrengths[0].signalStrength : undefined,
battery: device.attributes.batteries ? device.attributes.batteries[0].batteryPercentage : undefined,
primary_assignee_firstName: primary.length ? primary[0].firstName : undefined,
primary_assignee_lastName: primary.length ? primary[0].lastName : undefined,
primary_assignee_badgeNumber: primary.length ? primary[0].badgeNumber : undefined,
primary_assignee_userId: primary.length ? primary[0].userId : undefined,
vehicle_vehicleId: device.attributes.vehicle ? device.attributes.vehicle.vehicleId : undefined,
vehicle_assigneeType: device.attributes.vehicle ? device.attributes.vehicle.assigneeType : undefined,
vehicle_vehicleName: device.attributes.vehicle ? device.attributes.vehicle.vehicleName : undefined
}
if (primary.length) {
features.push({
id: device.axonDeviceId,
type: 'Feature',
properties: {
type: 'a-f-G-U-U-L',
how: 'm-g',
callsign: (primary.length ? `${env.AgencyAcronym || ''} ${primary[0].firstName.slice(0, 1)}. ${primary[0].lastName}` : 'Unknown User').trim(),
time: new Date().toISOString(),
start: new Date(device.attributes.location.locationUpdateTimestamp).toISOString(),
status: device.attributes.batteries ? {
battery: String(device.attributes.batteries[0].batteryPercentage)
} : undefined,
remarks: [
'Type: Officer',
`Agency: ${device.partnerName}`,
`Name: ${primary.length ? primary[0].firstName + " " + primary[0].lastName: "Unknown"}`
].join('\n'),
metadata: metadata
},
geometry: {
type: 'Point',
coordinates: [ device.attributes.location.longitude, device.attributes.location.latitude ]
}
});
} else if (device.attributes.vehicle) {
features.push({
id: device.axonDeviceId,
type: 'Feature',
properties: {
type: 'a-f-G-E-V',
how: 'm-g',
callsign: device.attributes.vehicle.vehicleName,
time: new Date().toISOString(),
start: new Date(device.attributes.location.locationUpdateTimestamp).toISOString(),
remarks: [
'Type: Vehicle',
`Agency: ${device.partnerName}`,
`Name: ${device.attributes.vehicle.vehicleName}`
].join('\n'),
metadata: metadata
},
geometry: {
type: 'Point',
coordinates: [ device.attributes.location.longitude, device.attributes.location.latitude ]
}
});
}
}
const fc: Static<typeof Feature.InputFeatureCollection> = {
type: 'FeatureCollection',
features: features
}
await this.submit(fc);
total = devicesRes.meta.totalHits || 0;
from = from + 2000;
} while (total > from)
}
}
await local(await Task.init(import.meta.url), import.meta.url);
export async function handler(event: Event = {}) {
return await internal(await Task.init(import.meta.url), event);
}