@3deye-toolkit/core 0.0.1-alpha.21

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/dist/core.d.ts ADDED
@@ -0,0 +1,955 @@
1
+ import { BehaviorSubject } from 'rxjs';
2
+ import crossfilter from 'crossfilter2';
3
+ import type { IReactionDisposer } from 'mobx';
4
+ import { Observable } from 'rxjs';
5
+ import { default as React_2 } from 'react';
6
+ import { Subject } from 'rxjs';
7
+ import { Subscription } from 'rxjs';
8
+
9
+ declare class AccountStore extends ApiStore {
10
+ private notification?;
11
+ user: User | null;
12
+ auth: Auth;
13
+ constructor(notification?: NotificationService | undefined);
14
+ get userDisplayName(): string | null;
15
+ protected afterInit(): void;
16
+ setUser(user: User | null): void;
17
+ setAuthStore(auth: Auth): void;
18
+ updateUserPassword(passwordData: {
19
+ previous: string;
20
+ new: string;
21
+ }): Promise<void>;
22
+ updateUserSettings({ firstName, lastName }: {
23
+ firstName: string;
24
+ lastName: string;
25
+ }): Observable<RawUser>;
26
+ updateCustomPreferences: (preferences: Record<string, any>) => Observable<RawUser>;
27
+ setDefaultGroup(groupId: number): Observable<RawUser> | undefined;
28
+ getPreference: (key: string) => any;
29
+ }
30
+
31
+ declare class Api<T> {
32
+ [key: string]: any;
33
+ static create<T extends PartialApi>(apiConfig: T | null, authStore: Auth, createConnection: (accessToken: string) => Connection): Api<T> & ExtractHubs<IApi, T>;
34
+ connectionShutdown$: Subject<null>;
35
+ connection$: BehaviorSubject<Connection | null>;
36
+ events: Subject<{
37
+ hub: keyof typeof events;
38
+ event: string;
39
+ data: any;
40
+ }>;
41
+ logging: boolean;
42
+ authStore: Auth;
43
+ createConnection: (accessToken: string) => Connection;
44
+ apiConfig: PartialApi;
45
+ constructor(apiConfig: T, authStore: Auth, createConnection: (accessToken: string) => Connection);
46
+ connect(token: Token): void;
47
+ shutdownConnection(): void;
48
+ private init;
49
+ private createHubMethod;
50
+ private subscribeToEvents;
51
+ }
52
+
53
+ declare type ApiPageResult<T> = {
54
+ success: true;
55
+ resultItems: T[];
56
+ pageInfo: PageInfo;
57
+ } | {
58
+ success: false;
59
+ error: {
60
+ code: number;
61
+ message: string;
62
+ };
63
+ };
64
+
65
+ declare type ApiResult<T> = {
66
+ success: true;
67
+ resultItems: T[];
68
+ } | {
69
+ success: false;
70
+ error: {
71
+ code: number;
72
+ message: string;
73
+ };
74
+ };
75
+
76
+ declare abstract class ApiStore {
77
+ api: Api<IApi> & IApi;
78
+ disposables: (IReactionDisposer | Subscription)[];
79
+ protected afterInit?(): void;
80
+ initWith(api: Api<IApi> & IApi): void;
81
+ dispose(): void;
82
+ }
83
+
84
+ /**
85
+ * @alpha
86
+ */
87
+ export declare const app: ToolkitApp;
88
+
89
+ export declare const AppContext: React_2.Context<ToolkitApp | null>;
90
+
91
+ declare class ArchiveChunk implements Chunk {
92
+ json?: string;
93
+ startTime: Date;
94
+ endTime: Date;
95
+ streamUrl: string;
96
+ duration?: number;
97
+ isLive: false;
98
+ cameraId: number;
99
+ id: number;
100
+ constructor(raw: any);
101
+ }
102
+
103
+ declare class ArchivesStore extends ApiStore {
104
+ data: crossfilter.Crossfilter<ArchiveChunk>;
105
+ chunksByCameraId: crossfilter.Dimension<ArchiveChunk, number>;
106
+ chunksByStart: crossfilter.Dimension<ArchiveChunk, number>;
107
+ chunksByEnd: crossfilter.Dimension<ArchiveChunk, number>;
108
+ chunksById: Map<number, ArchiveChunk>;
109
+ private pendingRequests;
110
+ private pendingRequestsByEnd;
111
+ private pendingRequestsByStart;
112
+ private pendingRequestsByCameraId;
113
+ knownIntervals: Map<number, [Date, Date]>;
114
+ updates: number;
115
+ constructor();
116
+ /**
117
+ * Fetches archive chunks for given camera and period
118
+ * @param cameraId - camera id
119
+ * @param startTime - start of the period
120
+ * @param endTime - end of the period
121
+ * TODO: add support for null endTime in order to remove requestedArchivesSince logic from player controller
122
+ */
123
+ fetch(cameraId: number, startTime: Date, endTime: Date): Observable<ArchiveChunk[]>;
124
+ extendKnownInterval(cameraId: number, chunks: ArchiveChunk[]): void;
125
+ add(chunks: ArchiveChunk[]): void;
126
+ getChunks({ cameraId, from, to }: ChunksQuery): ArchiveChunk[];
127
+ findClosestChunk({ cameraId, time }: {
128
+ cameraId: number;
129
+ time: Date;
130
+ }): ArchiveChunk;
131
+ protected afterInit(): void;
132
+ }
133
+
134
+ declare class Auth {
135
+ token: Token | null;
136
+ isAuthenticating: boolean;
137
+ storage: Storage_2;
138
+ tokenServiceUrl: string;
139
+ tokenStorageKey: string;
140
+ widgetTokenServiceUrl?: string;
141
+ deviceInfo: string | null;
142
+ clientId: string;
143
+ private pendingUpdateTokenRequest;
144
+ get isAuthenticated(): boolean;
145
+ constructor({ tokenServiceUrl, widgetTokenServiceUrl, storage, tokenStorageKey, deviceInfo, clientId }: AuthStoreOptions);
146
+ signOut: () => void;
147
+ signIn: ({ username, password, tokenToKick, agreedWithTerms }: {
148
+ username: string;
149
+ password: string;
150
+ tokenToKick?: string | undefined;
151
+ agreedWithTerms?: boolean | undefined;
152
+ }) => Promise<Token> | undefined;
153
+ invalidateToken: () => void;
154
+ getTokenFromStorage(): Promise<Token | null>;
155
+ private storeToken;
156
+ private getInitialToken;
157
+ private fetchTokenBy;
158
+ private updateToken;
159
+ private fetchWidgetToken;
160
+ }
161
+
162
+ declare interface AuthStoreOptions {
163
+ tokenServiceUrl: string;
164
+ widgetTokenServiceUrl?: string;
165
+ storage: Storage_2;
166
+ tokenStorageKey: string;
167
+ deviceInfo: any;
168
+ clientId: string;
169
+ }
170
+
171
+ declare interface Box {
172
+ Top: number;
173
+ Left: number;
174
+ Bottom: number;
175
+ Right: number;
176
+ }
177
+
178
+ declare class Camera {
179
+ id: number;
180
+ name: string;
181
+ imageUrl: string;
182
+ streamUrl: string;
183
+ dashStreamUrl: string;
184
+ address: {
185
+ Lat: number;
186
+ Lng: number;
187
+ } | null;
188
+ archiveDuration: number;
189
+ dvrWindowLength: number;
190
+ stateUpdatedAt: Date;
191
+ raw: RawCamera;
192
+ enabled: boolean;
193
+ isMicEnabled: boolean;
194
+ state: string;
195
+ pin: string;
196
+ webRtcUrl: string;
197
+ isPtz: boolean;
198
+ permissions: number;
199
+ get isOnline(): boolean;
200
+ get supportsWebRTC(): boolean;
201
+ constructor(raw: RawCamera);
202
+ update: (raw: RawCamera) => void;
203
+ }
204
+
205
+ declare class CameraEvent {
206
+ cameraId: number;
207
+ type: EventType;
208
+ raw: RawSensorEvent;
209
+ thumbnailUrl: string;
210
+ detectedObjects: DetectedObject[];
211
+ faces: Face[];
212
+ instant: boolean;
213
+ get id(): number;
214
+ get startTime(): Date;
215
+ get endTime(): Date;
216
+ get isLive(): boolean;
217
+ get acknowledged(): boolean;
218
+ constructor(raw: RawSensorEvent);
219
+ }
220
+
221
+ declare class CamerasStore extends ApiStore {
222
+ camerasById: Map<number, Camera>;
223
+ data: Camera[];
224
+ loading: boolean;
225
+ loaded: boolean;
226
+ constructor();
227
+ load: () => Observable<RawCamera[]> | undefined;
228
+ add: (cameras: RawCamera[]) => void;
229
+ sync: () => void;
230
+ fetchPermissions(): Promise<void>;
231
+ protected afterInit(): void;
232
+ dispose(): void;
233
+ }
234
+
235
+ declare interface CameraStatistics {
236
+ id: number;
237
+ month: number;
238
+ trafficOutMBytes: number;
239
+ archiveStorageMBytes: number;
240
+ clipStorageMBytes: number;
241
+ }
242
+
243
+ declare interface CamgroupItem {
244
+ id: number;
245
+ order: number;
246
+ }
247
+
248
+ declare interface Chunk {
249
+ json?: string;
250
+ startTime: Date;
251
+ endTime: Date;
252
+ streamUrl: string;
253
+ duration?: number;
254
+ }
255
+
256
+ declare interface ChunksQuery {
257
+ cameraId: number;
258
+ from: Date;
259
+ to: Date;
260
+ }
261
+
262
+ declare interface Connection {
263
+ state: CONNECTION_STATE;
264
+ stop: () => void;
265
+ start: () => Connection;
266
+ done: (callback: () => void) => Connection;
267
+ fail: (callback: (err: any) => void) => Connection;
268
+ error: (callback: (err: any) => void) => Connection;
269
+ disconnected: (callback: () => void) => Connection;
270
+ reconnecting: (callback: () => void) => Connection;
271
+ reconnected: (callback: () => void) => Connection;
272
+ proxies: {
273
+ [P in keyof typeof FULL_API_CONFIG]: {
274
+ on: (eventName: string, callback: (data: any) => void) => void;
275
+ invoke: any;
276
+ };
277
+ };
278
+ createHubProxy: (hubName: string) => void;
279
+ lastError: any;
280
+ qs: {
281
+ access_token: string;
282
+ };
283
+ }
284
+
285
+ declare enum CONNECTION_STATE {
286
+ CONNECTING = 0,
287
+ CONNECTED = 1,
288
+ RECONNECTING = 2,
289
+ DISCONNECTED = 3
290
+ }
291
+
292
+ declare type DeepPartial<T> = {
293
+ [K in keyof T]?: DeepPartial<T[K]>;
294
+ };
295
+
296
+ declare interface DetectedObject {
297
+ Type: string;
298
+ Box: {
299
+ Left: number;
300
+ Top: number;
301
+ Right: number;
302
+ Bottom: number;
303
+ };
304
+ Probability: number;
305
+ Colors: {
306
+ Color: string;
307
+ }[];
308
+ }
309
+
310
+ declare const events: {
311
+ [P in keyof PartialApi]: Array<{
312
+ name: string;
313
+ explicit?: boolean;
314
+ }>;
315
+ };
316
+
317
+ declare class EventSchemaStore extends ApiStore {
318
+ schemaDescription: SchemaDescriptionParameter[];
319
+ constructor();
320
+ get foundObjectTypes(): string[];
321
+ get foundObjectTypesForSelect(): {
322
+ id: EventType;
323
+ name: string;
324
+ color: string;
325
+ highlightColor: any;
326
+ isEventType: boolean;
327
+ }[];
328
+ get colorsByFoundObjectType(): Map<string, string>;
329
+ fetchAnalyticEventSchema: () => void;
330
+ protected afterInit(): void;
331
+ dispose(): void;
332
+ }
333
+
334
+ declare interface EventsQuery {
335
+ cameraIds?: number[];
336
+ eventTypes?: EventType[];
337
+ from: Date;
338
+ to: Date | null;
339
+ detectedObjectTypes?: string[];
340
+ colors?: Set<string>;
341
+ probability?: number;
342
+ }
343
+
344
+ declare class EventsStore extends ApiStore {
345
+ private camerasStore;
346
+ data: crossfilter.Crossfilter<CameraEvent>;
347
+ eventsByCameraId: crossfilter.Dimension<CameraEvent, number>;
348
+ eventsByStart: crossfilter.Dimension<CameraEvent, number>;
349
+ eventsByEnd: crossfilter.Dimension<CameraEvent, number>;
350
+ eventsByType: crossfilter.Dimension<CameraEvent, EventType>;
351
+ eventsByFoundObjects: crossfilter.Dimension<CameraEvent, string>;
352
+ eventsByColor: crossfilter.Dimension<CameraEvent, string>;
353
+ eventsByLiveliness: crossfilter.Dimension<CameraEvent, boolean>;
354
+ pendingRequests: crossfilter.Crossfilter<PendingRequest>;
355
+ pendingRequestsByEnd: crossfilter.Dimension<PendingRequest, number>;
356
+ pendingRequestsByStart: crossfilter.Dimension<PendingRequest, number>;
357
+ pendingRequestsByCameraId: crossfilter.Dimension<PendingRequest, number>;
358
+ knownIntervals: crossfilter.Crossfilter<Interval_2>;
359
+ knownIntervalsByCameraId: crossfilter.Dimension<Interval_2, number>;
360
+ knownIntervalsByStart: crossfilter.Dimension<Interval_2, number>;
361
+ knownIntervalsByEnd: crossfilter.Dimension<Interval_2, number>;
362
+ eventsById: Map<number, CameraEvent>;
363
+ updates: number;
364
+ /**
365
+ * Contains recent additions to the store as list of event ids
366
+ * NOTE: do not update several times in single action as we lose info about intermediate additions that way
367
+ */
368
+ recentAdditions: number[];
369
+ constructor(camerasStore: CamerasStore);
370
+ /**
371
+ * Populates store with the events for given camera and period
372
+ * @param cameraId - camera id or -1 to fetch all available events for given period
373
+ * @param startTime - start of the period
374
+ * @param endTime - end of the period
375
+ */
376
+ populateEvents(cameraId: number, startTime: Date, endTime: Date): void;
377
+ update: (data: CameraEvent[]) => void;
378
+ add: (data: CameraEvent[]) => void;
379
+ getEvents({ cameraIds, from, to, detectedObjectTypes, eventTypes, colors, probability }: EventsQuery): CameraEvent[];
380
+ getOverlappedEvents({ cameraId, from, to }: {
381
+ cameraId: number;
382
+ from: Date;
383
+ to: Date;
384
+ }): CameraEvent[];
385
+ getLastNonAnalyticEventBefore({ cameraId, date }: {
386
+ cameraId: number;
387
+ date: Date;
388
+ }): CameraEvent;
389
+ getLastObjectBefore({ cameraId, date, objectFilters }: {
390
+ cameraId: number;
391
+ date: Date;
392
+ objectFilters: {
393
+ people: boolean;
394
+ cars: boolean;
395
+ misc: boolean;
396
+ };
397
+ }): CameraEvent;
398
+ getFirstNonAnalyticEventAfter({ cameraId, date }: {
399
+ cameraId: number;
400
+ date: Date;
401
+ }): CameraEvent;
402
+ getFirstObjectAfter({ cameraId, date, objectFilters }: {
403
+ cameraId: number;
404
+ date: Date;
405
+ objectFilters: {
406
+ people: boolean;
407
+ cars: boolean;
408
+ misc: boolean;
409
+ };
410
+ }): CameraEvent;
411
+ protected afterInit(): void;
412
+ processNewEvents: ({ data }: {
413
+ data: RawSensorEvent[];
414
+ }) => void;
415
+ dispose(): void;
416
+ }
417
+
418
+ declare type EventType = 'Motion' | 'Tampering' | 'PanTiltZoom' | 'CrossLine' | 'Intrusion' | 'LicensePlate' | 'FaceDetection' | 'Audio' | 'Analytic' | 'SpeedDetection' | 'PeopleCounter' | 'Temperature' | 'PoS' | 'GPS' | 'DigitalInput' | 'Normal' | 'Suspicious' | 'Loitering' | 'Vandalism' | 'Trespass' | 'Emergency' | 'LifeInDanger' | 'ErroneousAlert' | 'Misidentification' | 'Fire' | 'MedicalDuress' | 'HoldUp' | 'CheckIn' | 'CheckOut' | 'ClockIn' | 'ClockOut' | 'ParkingStart' | 'ParkingEnd' | 'ParkingViolation' | 'GateAccess' | 'DoorAccess' | 'TemperatureCheck' | 'IDCheck' | 'PPECheck' | 'WelfareCheck' | 'Uncategorized' | 'Unknown';
419
+
420
+ declare type ExtractHubs<T, K> = {
421
+ [P in keyof ExtractMethods<T, K>]: ExtractMethods<T[P], K[P]>;
422
+ };
423
+
424
+ declare type ExtractMethods<T, K> = Pick<T, Extract<keyof T, keyof K>>;
425
+
426
+ declare interface Face {
427
+ PersonId: number;
428
+ Name: string;
429
+ Box: {
430
+ Left: number;
431
+ Top: number;
432
+ Right: number;
433
+ Bottom: number;
434
+ };
435
+ Probability: number;
436
+ }
437
+
438
+ declare const FULL_API_CONFIG: IApi;
439
+
440
+ declare interface GetThumbnailParams {
441
+ cameraId: number;
442
+ from: Date;
443
+ to: Date;
444
+ size?: {
445
+ width: number;
446
+ height: number;
447
+ };
448
+ }
449
+
450
+ declare interface IApi {
451
+ archives: {
452
+ PopulateArchive: (params: {
453
+ cameraId: number;
454
+ endTime: Date;
455
+ startTime: Date;
456
+ }) => Observable<any>;
457
+ GetArchives: (params: any) => Observable<any>;
458
+ GetClips: () => Observable<any>;
459
+ UpdateClip: (params: any) => Observable<any>;
460
+ DeleteClip: (params: any) => Observable<any>;
461
+ SaveClip: (params: any) => Observable<any>;
462
+ SaveTimelaps: (params: any) => Observable<any>;
463
+ SaveArchive: (params: any) => Observable<any>;
464
+ DeleteArchive: (params: any) => Observable<any>;
465
+ ShareClip: (sharedClip: RawSharedClip) => Observable<ApiResult<RawSharedClip>>;
466
+ GetSharedClips: (recordId: number | null) => Observable<ApiResult<RawSharedClip>>;
467
+ UpdateSharedClip: (sharedClip: RawSharedClip) => Observable<ApiResult<RawSharedClip>>;
468
+ DeleteSharedClip: (recordId: number) => Observable<ApiResult<RawSharedClip>>;
469
+ };
470
+ cameras: {
471
+ GetCameras: (camera: {
472
+ id?: number;
473
+ } | null, since: Date | null) => Observable<ApiResult<RawCamera>>;
474
+ /**
475
+ * @deprecated
476
+ */
477
+ GetMotionEvents: (params: {
478
+ cameraId: number;
479
+ endTime: Date | null;
480
+ startTime: Date;
481
+ }) => Observable<OBVIOUSLY_NEEDS_TO_BE_FIXED_EventsApiResult<RawEvent>>;
482
+ GetSensorDataSchema: (eventType: EventType) => Observable<any>;
483
+ GetSensorEvents: (params: SensorEventsParams, filter: string, box: Box) => Observable<ApiResult<RawSensorEvent>>;
484
+ GetSensorEventsPage: (request: SensorEventsRequest, filter: string | null, searchPolygons: string[]) => Observable<ApiPageResult<RawSensorEvent>>;
485
+ AddUserSensorEvent: (event: PartialExcept<RawSensorEvent, 'id' | 'eventType' | 'message'>) => Observable<ApiResult<RawSensorEvent>>;
486
+ AcknowledgeSensorEvent: (event: PartialExcept<RawSensorEvent, 'id' | 'ackEventType' | 'message'>) => Observable<ApiResult<RawSensorEvent>>;
487
+ MoveCamera: (camera: {
488
+ id: number;
489
+ }, x: number, y: number, zoom: number, moveSpeed: number, zoomSpeed: number) => Observable<any>;
490
+ MoveCameraContinuousStart: ({ id }: {
491
+ id: number;
492
+ }, x: number, y: number, zoom: number, timeout: number) => Observable<any>;
493
+ MoveCameraContinuousStop: ({ id }: {
494
+ id: number;
495
+ }) => Observable<any>;
496
+ GoHomePtzCamera: ({ id }: {
497
+ id: number;
498
+ }) => Observable<any>;
499
+ SetHomePtzCamera: ({ id }: {
500
+ id: number;
501
+ }) => Observable<any>;
502
+ };
503
+ camgroups: {
504
+ GetCamgroups: () => Observable<ApiResult<RawCamgroup>>;
505
+ DeleteCamgroup: (params: any) => Observable<ApiResult<RawCamgroup>>;
506
+ AddCamgroup: (params: any) => Observable<ApiResult<RawCamgroup>>;
507
+ UpdateCamgroup: (params: any) => Observable<ApiResult<RawCamgroup>>;
508
+ };
509
+ sound: {
510
+ GetPushSoundServiceUrl: (id: number) => Observable<any>;
511
+ };
512
+ thumbnails: {
513
+ GetThumbnailsInfo: (params: {
514
+ cameraId: number;
515
+ from: Date;
516
+ to: Date;
517
+ count: number;
518
+ }) => Observable<any>;
519
+ GetThumbnailInfo: (params: {
520
+ cameraId: number;
521
+ from: Date;
522
+ to: Date;
523
+ }) => Observable<any>;
524
+ GetHeatMapsInfo: (params: {
525
+ cameraId: number;
526
+ from: Date;
527
+ to: Date;
528
+ count: number;
529
+ }) => Observable<any>;
530
+ };
531
+ users: {
532
+ GetUser: () => Observable<ApiResult<RawUser>>;
533
+ UserUpdateProfile: (user: Partial<RawUser>) => Observable<ApiResult<RawUser>>;
534
+ };
535
+ }
536
+
537
+ declare interface InitParams {
538
+ token?: RawToken | {
539
+ widgetId: string;
540
+ widgetToken: string;
541
+ };
542
+ tokenStorage?: Storage_2;
543
+ tokenStorageKey?: string;
544
+ apiUrl?: string;
545
+ tokenServiceUrl?: string;
546
+ widgetTokenServiceUrl?: string;
547
+ }
548
+
549
+ declare interface Interval_2 {
550
+ cameraId: number;
551
+ from: Date;
552
+ to: Date;
553
+ }
554
+
555
+ declare type IntervalState = {
556
+ state: 'fullfilled';
557
+ data: Thumbnail;
558
+ } | {
559
+ state: 'pending';
560
+ request: Observable<any>;
561
+ };
562
+
563
+ declare interface NotificationOptions_2 {
564
+ autoClose: number | false | undefined;
565
+ }
566
+
567
+ declare class NotificationService implements Notifier {
568
+ private notifier;
569
+ constructor(notifier: Notifier);
570
+ error(message: string): void;
571
+ success(message: string, options?: NotificationOptions_2): void;
572
+ warn(message: string): void;
573
+ }
574
+
575
+ declare interface Notifier {
576
+ success: (message: string, options?: NotificationOptions_2) => void;
577
+ warn: (message: string) => void;
578
+ error: (message: string) => void;
579
+ }
580
+
581
+ declare type OBVIOUSLY_NEEDS_TO_BE_FIXED_EventsApiResult<T> = {
582
+ success: true;
583
+ motionEventItems: T[];
584
+ } | {
585
+ success: false;
586
+ error: {
587
+ code: number;
588
+ message: string;
589
+ };
590
+ };
591
+
592
+ declare interface PageInfo {
593
+ isDescending: boolean;
594
+ nextPageToken: number;
595
+ haveMore: boolean;
596
+ }
597
+
598
+ declare type PartialApi = DeepPartial<IApi>;
599
+
600
+ declare type PartialExcept<T, K extends keyof T> = Pick<T, K> & Partial<T>;
601
+
602
+ declare interface PendingRequest {
603
+ cameraId: number;
604
+ startTime: Date;
605
+ endTime: Date;
606
+ request: Observable<any>;
607
+ }
608
+
609
+ declare interface PendingRequest_2 {
610
+ cameraId: number;
611
+ from: Date;
612
+ to: Date;
613
+ count: number;
614
+ request: Observable<any>;
615
+ }
616
+
617
+ declare interface RawCamera {
618
+ id: number;
619
+ customerId: number;
620
+ name: string;
621
+ description: string;
622
+ cameraBrand: string;
623
+ cameraModel: string;
624
+ enabled: boolean;
625
+ cameraUserName: string;
626
+ cameraPassword: null;
627
+ serialNum: string;
628
+ isOnvif: boolean;
629
+ isP2P: boolean;
630
+ p2pRegistrationCode: null;
631
+ planId: null;
632
+ p2pState: string;
633
+ cameraVideoFormat: string;
634
+ cameraState: string;
635
+ cameraStateChangedTime: Date;
636
+ cameraError: null;
637
+ cameraAddress: string;
638
+ isMicEnabled: boolean;
639
+ imageQuality: number;
640
+ cameraSourceChannel: string;
641
+ pin: string;
642
+ streamUrl: string;
643
+ dashStreamUrl: string;
644
+ rtmpUrl: string;
645
+ webRtcStreamHost: string;
646
+ webRtcUrl: string;
647
+ cameraHttpSourceUrl: string;
648
+ cameraRtspSourceUrl: string;
649
+ supportedResolutions: string;
650
+ cameraType: string;
651
+ isCloud: boolean;
652
+ generateImageUrl: null;
653
+ imageUrl: string;
654
+ qualityProfile: string;
655
+ encodingProfile: null;
656
+ width: number;
657
+ height: number;
658
+ bitRate: number;
659
+ frameRate: number;
660
+ archiveDuration: number;
661
+ isArchiveByMotionEvent: boolean;
662
+ isAnalyticsEnabled: boolean;
663
+ isTimelapseAvailable: boolean;
664
+ motionEnabled: boolean;
665
+ isPTZ: boolean;
666
+ motionDuration: number;
667
+ dvrWindowLength: number;
668
+ jsonField: string;
669
+ dtUpdUtc: Date;
670
+ version: string;
671
+ statistics: CameraStatistics;
672
+ }
673
+
674
+ declare interface RawCamgroup {
675
+ id: number;
676
+ name: string | null;
677
+ text: null;
678
+ description: null;
679
+ iconUrl: null;
680
+ iconCls: null;
681
+ dynamic: boolean;
682
+ allowDuplicates: boolean;
683
+ allowDrop: boolean;
684
+ allowNodeDropInView: boolean;
685
+ visible: boolean;
686
+ layout_id: string;
687
+ contentFilter: null;
688
+ customerWideGroup: boolean;
689
+ cameras: CamgroupItem[];
690
+ camgroups: CamgroupItem[];
691
+ version: string;
692
+ order: number;
693
+ }
694
+
695
+ declare interface RawEvent {
696
+ id: number;
697
+ startTime: string;
698
+ endTime?: string;
699
+ cameraId: number;
700
+ data: string | null;
701
+ }
702
+
703
+ declare interface RawSensorEvent {
704
+ message: string;
705
+ data: string | null;
706
+ id: number;
707
+ customerId: number;
708
+ sensorId: number;
709
+ sensorType: 'CameraSensor' | 'MotionSensor' | 'IntrusionSensor' | 'AudioSensor' | 'TemperatureSensor' | 'SpeedSensor' | 'Unknown';
710
+ eventType: EventType;
711
+ ackEventType: string;
712
+ description?: any;
713
+ tags?: any;
714
+ customerData?: any;
715
+ startTime: string;
716
+ endTime: string;
717
+ userId: string;
718
+ }
719
+
720
+ declare interface RawSharedClip {
721
+ id: number;
722
+ recordId: number;
723
+ creatorUserId: number;
724
+ cameraId: number;
725
+ startTime: string | Date;
726
+ endTime: string | Date;
727
+ duration: number;
728
+ fileSize: number;
729
+ password: string;
730
+ name: string;
731
+ description: string;
732
+ url: string;
733
+ validTo: string | Date;
734
+ }
735
+
736
+ declare interface RawToken {
737
+ access_token: string;
738
+ accessToken: string;
739
+ access_token_expires: string;
740
+ accessTokenExpires: string;
741
+ access_token_issued: string;
742
+ accessTokenIssued: string;
743
+ client_id: string;
744
+ clientId: string;
745
+ expires_in: number;
746
+ expiresIn: number;
747
+ refresh_token: string;
748
+ refreshToken: string;
749
+ refresh_token_expires: string;
750
+ refreshTokenExpires: string;
751
+ refresh_token_issued: string;
752
+ refreshTokenIssued: string;
753
+ token_type: string;
754
+ tokenType: string;
755
+ userName: string;
756
+ widgetId?: string;
757
+ widgetToken?: string;
758
+ }
759
+
760
+ declare interface RawUser {
761
+ id: number;
762
+ customerId: number;
763
+ userName: string;
764
+ firstName?: string;
765
+ lastName?: string;
766
+ email: string;
767
+ languageCode: string;
768
+ layoutStartId: number | null;
769
+ layoutStartType: 'camera' | 'camgroup' | '';
770
+ timeZoneOffset: string;
771
+ connectionId: string;
772
+ ipAddress: string;
773
+ userRoles: string[];
774
+ lastLoginAt: Date;
775
+ createdAt: Date;
776
+ jsonField: string;
777
+ imageUrl: null;
778
+ permissions: number;
779
+ version: string;
780
+ }
781
+
782
+ declare interface SchemaDescriptionParameter {
783
+ schemaId: number;
784
+ eventType: string;
785
+ description: string;
786
+ fieldName: string;
787
+ parameterType: string;
788
+ possibleValues: string;
789
+ valueSet: string;
790
+ values?: string[];
791
+ }
792
+
793
+ declare interface SensorEventsParams {
794
+ sensorId: number;
795
+ sensorType: 'CameraSensor' | 'MotionSensor' | 'IntrusionSensor' | 'AudioSensor' | 'TemperatureSensor' | 'SpeedSensor' | 'Unknown';
796
+ startTime: Date;
797
+ endTime: Date;
798
+ eventType: EventType;
799
+ }
800
+
801
+ declare interface SensorEventsRequest {
802
+ sensorIds: number[];
803
+ sensorType: string;
804
+ sensorEventTypes: SensorEventType[];
805
+ startTime?: Date;
806
+ endTime?: Date;
807
+ isDescending: boolean;
808
+ rowsLimit: number;
809
+ pageToken?: number;
810
+ }
811
+
812
+ declare enum SensorEventType {
813
+ Motion = 0,
814
+ Tampering = 1,
815
+ PanTiltZoom = 2,
816
+ CrossLine = 3,
817
+ Intrusion = 4,
818
+ LicensePlate = 5,
819
+ FaceDetection = 6,
820
+ Audio = 7,
821
+ Analytic = 8,
822
+ SpeedDetection = 9,
823
+ PeopleCounter = 10,
824
+ Temperature = 11,
825
+ PoS = 12,
826
+ GPS = 13,
827
+ DigitalInput = 14,
828
+ Normal = 15,
829
+ Suspicious = 16,
830
+ Loitering = 17,
831
+ Vandalism = 18,
832
+ Trespass = 19,
833
+ Emergency = 20,
834
+ LifeInDanger = 21,
835
+ ErroneousAlert = 22,
836
+ Misidentification = 23,
837
+ Fire = 24,
838
+ MedicalDuress = 25,
839
+ HoldUp = 26,
840
+ CheckIn = 27,
841
+ CheckOut = 28,
842
+ ClockIn = 29,
843
+ ClockOut = 30,
844
+ ParkingStart = 31,
845
+ ParkingEnd = 32,
846
+ ParkingViolation = 33,
847
+ GateAccess = 34,
848
+ DoorAccess = 35,
849
+ TemperatureCheck = 36,
850
+ IDCheck = 37,
851
+ PPECheck = 38,
852
+ WelfareCheck = 39,
853
+ Uncategorized = 40,
854
+ Unknown = 999
855
+ }
856
+
857
+ declare interface Storage_2 {
858
+ setItem: (key: string, value: string) => void | Promise<undefined>;
859
+ getItem: (key: string) => (string | null) | Promise<string | null>;
860
+ removeItem: (key: string) => void | Promise<undefined>;
861
+ }
862
+
863
+ declare interface Thumbnail {
864
+ cameraId: number;
865
+ timestamp: Date;
866
+ realTimestamp: Date;
867
+ url: string;
868
+ width: number;
869
+ height: number;
870
+ }
871
+
872
+ declare class ThumbnailsStore extends ApiStore {
873
+ thumbnails: crossfilter.Crossfilter<Thumbnail>;
874
+ thumbnailsByCameraId: crossfilter.Dimension<Thumbnail, number>;
875
+ thumbnailsByDate: crossfilter.Dimension<Thumbnail, number>;
876
+ pendingRequests: crossfilter.Crossfilter<PendingRequest_2>;
877
+ pendingRequestsByEnd: crossfilter.Dimension<PendingRequest_2, number>;
878
+ pendingRequestsByStart: crossfilter.Dimension<PendingRequest_2, number>;
879
+ pendingRequestsByCameraId: crossfilter.Dimension<PendingRequest_2, number>;
880
+ pendingRequestsByCount: crossfilter.Dimension<PendingRequest_2, number>;
881
+ constructor();
882
+ /**
883
+ * Fetches thumbnails for given camera and period.
884
+ * Given period is evenly divided by number of smaller periods that equals to `count`.
885
+ * Server returns first available thumbnail in each period
886
+ * @param cameraId - camera id
887
+ * @param from - start of the period
888
+ * @param to - end of the period
889
+ * @param count - number of thumbnails
890
+ */
891
+ fetchThumbnails(cameraId: number, from: Date, to: Date, count: number): Observable<any>;
892
+ getIntervalState(cameraId: number, from: Date, to: Date): IntervalState | null;
893
+ fetchThumbnail(cameraId: number, from: Date, to: Date): Observable<Thumbnail>;
894
+ /**
895
+ * Returns first available thumbnail for given camera within period
896
+ */
897
+ getThumbnail({ cameraId, from, to }: GetThumbnailParams): Thumbnail;
898
+ /**
899
+ * Returns previously obtained thumbnails for given camera within period
900
+ */
901
+ getThumbnails({ cameraId, from, to }: GetThumbnailParams): Thumbnail[];
902
+ toThumbnail: (cameraId: number) => ({ realtimestamp, url, width, height }: {
903
+ realtimestamp: string;
904
+ url: string;
905
+ width: number;
906
+ height: number;
907
+ }) => Thumbnail;
908
+ }
909
+
910
+ declare class Token {
911
+ accessToken: string;
912
+ accessTokenExpires: Date;
913
+ accessTokenIssued: Date;
914
+ clientId: string;
915
+ expiresIn: number;
916
+ refreshToken: string;
917
+ refreshTokenExpires: Date;
918
+ refreshTokenIssued: Date;
919
+ tokenType: string;
920
+ userName: string;
921
+ invalid: boolean;
922
+ widgetId?: string;
923
+ widgetToken?: string;
924
+ json: RawToken;
925
+ constructor(raw: RawToken);
926
+ }
927
+
928
+ declare class ToolkitApp {
929
+ readonly name: string;
930
+ cameras: CamerasStore;
931
+ archives: ArchivesStore;
932
+ events: EventsStore;
933
+ eventSchema: EventSchemaStore;
934
+ thumbnails: ThumbnailsStore;
935
+ account: AccountStore;
936
+ notification: NotificationService;
937
+ auth: Auth;
938
+ api: Api<IApi> & IApi;
939
+ private disposables;
940
+ private tokenUpdateReactions;
941
+ constructor(name: string);
942
+ init({ token, tokenStorage: storage, tokenStorageKey, apiUrl, tokenServiceUrl, widgetTokenServiceUrl }: InitParams, name?: string): ToolkitApp;
943
+ dispose: () => void;
944
+ /**
945
+ * Adds a reaction to token changes
946
+ * If token passed to the callback is null, then the user is signed out
947
+ * and you should react accordingly
948
+ * @param cb
949
+ */
950
+ onTokenUpdate: (cb: (token: RawToken | null) => void) => () => void;
951
+ }
952
+
953
+ declare type User = RawUser;
954
+
955
+ export { }
package/dist/core.js ADDED
@@ -0,0 +1 @@
1
+ import{reaction as e,computed as t,runInAction as r,makeObservable as n,observable as i,action as s,when as a}from"mobx";import{Subject as o,BehaviorSubject as l,EMPTY as u,timer as c,throwError as d,Observable as h,of as f,Subscription as b}from"rxjs";import{filter as p,switchMap as v,delay as m,take as y,mergeMap as g,catchError as w,takeUntil as j,retryWhen as O,startWith as k,pairwise as I,concatMap as P,shareReplay as T,map as B,tap as S,share as C,skip as _,expand as A}from"rxjs/operators";import E from"jqueryless-signalr";import{StatusCodes as U}from"http-status-codes";import q from"crossfilter2";import R from"string-natural-compare";import D from"material-colors";import N from"react";function x(e){return null!=e}function F(){return e=>e.pipe(p(x))}const M={archives:{PopulateArchive:null,GetArchives:null,GetClips:null,UpdateClip:null,DeleteClip:null,SaveClip:null,SaveTimelaps:null,SaveArchive:null,DeleteArchive:null,ShareClip:null,GetSharedClips:null,UpdateSharedClip:null,DeleteSharedClip:null},cameras:{GetCameras:null,GetSensorDataSchema:null,GetMotionEvents:null,GetSensorEvents:null,GetSensorEventsPage:null,AddUserSensorEvent:null,AcknowledgeSensorEvent:null,MoveCamera:null,MoveCameraContinuousStart:null,MoveCameraContinuousStop:null,GoHomePtzCamera:null,SetHomePtzCamera:null},camgroups:{GetCamgroups:null,DeleteCamgroup:null,AddCamgroup:null,UpdateCamgroup:null},sound:{GetPushSoundServiceUrl:null},thumbnails:{GetThumbnailsInfo:null,GetThumbnailInfo:null,GetHeatMapsInfo:null},users:{GetUser:null,UserUpdateProfile:null}},z={cameras:[{name:"OnCameraMotionEvent",explicit:!0},{name:"OnCameraAdded"},{name:"OnCameraUpdated"},{name:"OnSystemCameraUpdated"},{name:"OnCameraDeleted"}],users:[{name:"OnUserUpdateProfile"}],camgroups:[{name:"OnAdd"},{name:"OnUpdate"},{name:"OnDelete"}],archives:[{name:"OnTimelapsAdded"},{name:"OnClipAdded"},{name:"OnClipUpdated"},{name:"OnClipDeleted"},{name:"OnArchiveAdded"},{name:"OnArchiveUpdated"},{name:"OnArchiveDeleted"},{name:"OnArchiveRecordCreated"}]};var $,G;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTED=3]="DISCONNECTED"}($||($={}));class L{constructor(t,r,n){Object.defineProperty(this,"connectionShutdown$",{enumerable:!0,configurable:!0,writable:!0,value:new o}),Object.defineProperty(this,"connection$",{enumerable:!0,configurable:!0,writable:!0,value:new l(null)}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:new o}),Object.defineProperty(this,"logging",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"authStore",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"createConnection",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.apiConfig=t,this.init(),this.createConnection=n,this.authStore=r,e((()=>r.token),(e=>{if(!e)return void this.shutdownConnection();if(e.invalid)return;if(!e.accessToken)return;const t=this.connection$.getValue();t&&t.state!==$.DISCONNECTED?t.qs.access_token=e.accessToken:this.connect(e)})),this.connection$.pipe(v((e=>null!==e||!r.isAuthenticated||r.token&&r.token.invalid?u:(this.logging&&console.warn("disconnected by some reason"),c(5e3)))),p((()=>r.isAuthenticated&&!!r.token&&!r.token.invalid))).subscribe((()=>{this.connect(r.token),this.logging&&console.warn("attempting to reconnect")})),this.connection$.pipe(F(),m(100)).subscribe(this.subscribeToEvents)}static create(e,t,r){return new L(null!==e?e:M,t,r)}connect(e){if(this.connection$.getValue()&&this.connection$.getValue().state===$.CONNECTED)return;const{accessToken:t}=e,r=this.createConnection(t);Object.keys(this.apiConfig).forEach((e=>r.createHubProxy(e))),Object.entries(z).forEach((([e,t])=>{t&&r.proxies[e]&&t.forEach((({name:t})=>{r.proxies[e].on(t,(r=>this.events.next({hub:e,event:t,data:r})))}))})),r.start().done((()=>{this.logging&&console.warn("connected"),this.connection$.next(r)})).fail((e=>{var t,r,n;401!==(null===(t=e.source)||void 0===t?void 0:t.status)&&403!==(null===(r=e.source)||void 0===r?void 0:r.status)&&409!==(null===(n=e.source)||void 0===n?void 0:n.status)||this.authStore.invalidateToken()})),r.error((e=>{if(e.source&&(401===e.source.status||403===e.source.status||409===e.source.status))return this.logging&&console.warn("authentication error, invalidating token"),this.authStore.invalidateToken()})),r.disconnected((()=>{this.connection$.getValue()?this.logging&&console.warn("disconnected",this.connection$.getValue().lastError):this.logging&&console.warn("disconnected. this connection is already null"),this.connection$.next(null)})),r.reconnecting((()=>console.log("reconnecting"))),r.reconnected((()=>{this.connection$.getValue()===r&&(this.logging&&console.warn("reconnected"),this.connection$.next(r))}))}shutdownConnection(){const e=this.connection$.getValue();e&&e.stop(),this.connectionShutdown$.next(null)}init(){Object.keys(this.apiConfig).forEach((e=>{this[e]={},Object.keys(this.apiConfig[e]).forEach((t=>{this[e][t]=this.createHubMethod(e,t)}))}))}createHubMethod(e,t){const r=this;return function n(...i){return r.connection$.pipe(F(),p((e=>e.state===$.CONNECTED)),y(1)).pipe(g((r=>new Promise(((n,s)=>{r.proxies[e].invoke(t,...i).done((e=>n(e))).fail((e=>s(e)))})))),w((e=>!e.message||"Connection started reconnecting before invocation result was received."!==e.message&&"Connection was disconnected before invocation result was received."!==e.message?e.message&&e.message.startsWith("Caller is not authorized to invoke the ")?(console.warn(e.message),r.connection$.getValue().stop(),r.authStore.invalidateToken(),n(...i)):d(e):(console.warn(e.message),n(...i)))),j(r.connectionShutdown$))}}subscribeToEvents(e){Object.entries(z).forEach((([t,r])=>{r&&e.proxies[t]&&e.state===$.CONNECTED&&r.filter((({explicit:e})=>e)).forEach((({name:r})=>{e.proxies[t].invoke("SubscribeToEvent",r)}))}))}}class W{constructor(e){Object.defineProperty(this,"accessToken",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"accessTokenExpires",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"accessTokenIssued",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"clientId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"expiresIn",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshToken",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTokenExpires",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTokenIssued",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokenType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"userName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"invalid",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"widgetId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"widgetToken",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"json",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.json=e,this.accessToken=e.access_token||e.accessToken,this.accessTokenExpires=new Date(e.access_token_expires||e.accessTokenExpires),this.accessTokenIssued=new Date(e.access_token_issued||e.accessTokenIssued),this.clientId=e.client_id||e.clientId,this.expiresIn=e.expires_in||e.expiresIn,this.refreshToken=e.refresh_token||e.refreshToken,this.refreshTokenExpires=new Date(e.refresh_token_expires||e.refreshTokenExpires),this.refreshTokenIssued=new Date(e.refresh_token_issued||e.refreshTokenIssued),this.tokenType=e.token_type||e.tokenType,this.userName=e.userName,this.widgetId=e.widgetId,this.widgetToken=e.widgetToken,this.invalid=!1}}function V(e,r=!1){const n=t(e);return new h((e=>{const t=n.observe_((({newValue:t})=>e.next(t)),r);return()=>t()}))}class K{constructor({tokenServiceUrl:e,widgetTokenServiceUrl:a,storage:o,tokenStorageKey:l,deviceInfo:h,clientId:b}){Object.defineProperty(this,"token",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"isAuthenticating",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"storage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokenServiceUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tokenStorageKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"widgetTokenServiceUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"deviceInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"clientId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingUpdateTokenRequest",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"signOut",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.isAuthenticating||r((()=>this.token=null))}}),Object.defineProperty(this,"signIn",{enumerable:!0,configurable:!0,writable:!0,value:({username:e,password:t,tokenToKick:n,agreedWithTerms:i})=>{if(this.isAuthenticating)return;r((()=>this.isAuthenticating=!0));const s={username:e,password:t};n&&(s.kick_refresh_token=n),i&&(s.agree_with_terms=!0);return this.fetchTokenBy("password",s).then((e=>(r((()=>{this.token=e,this.isAuthenticating=!1})),e))).catch((e=>{throw r((()=>{this.isAuthenticating=!1})),e}))}}),Object.defineProperty(this,"invalidateToken",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.token&&r((()=>{this.token=Object.assign(Object.assign({},this.token),{invalid:!0})}))}}),n(this,{token:i.ref,isAuthenticating:i,isAuthenticated:t,signOut:s,invalidateToken:s}),this.isAuthenticating=!0,this.storage=o,this.tokenServiceUrl=e,this.widgetTokenServiceUrl=a,this.tokenStorageKey=l,this.deviceInfo=h,this.clientId=b;const m=V((()=>this.token)),y=m.pipe(v((e=>{if(null===e)return u;const t=f(e).pipe(g((e=>e.widgetId?this.fetchWidgetToken(e):this.updateToken(e.refreshToken))),O((e=>e.pipe(g((e=>!e.status||401!==e.status&&403!==e.status&&409!==e.status?e.error&&"refresh_token_error"===e.error||"invalid_grant"===e.error?d(e):c(5e3):d(e)))))));if(!e.invalid){const r=Math.max(.75*(+e.accessTokenExpires-Date.now()),0);return c(r).pipe(g((()=>t)))}return t})),w((e=>(console.error(e),r((()=>this.token=null)),y))));y.subscribe((e=>{r((()=>this.token=e))})),m.pipe(k(null),I(),p((([e,t])=>!!(t||!t&&e))),P((([,e])=>this.storeToken(e)))).subscribe(),this.getInitialToken().then((e=>{r((()=>{this.token=e,this.isAuthenticating=!1}))}))}get isAuthenticated(){return Boolean(this.token&&!this.isAuthenticating)}async getTokenFromStorage(){const e=await this.storage.getItem(this.tokenStorageKey);return e?new W(JSON.parse(e)):null}async storeToken(e){return!e||e.invalid?this.storage.removeItem(this.tokenStorageKey):this.storage.setItem(this.tokenStorageKey,JSON.stringify(e.json))}async getInitialToken(){const e=await this.getTokenFromStorage();return e||null}async fetchTokenBy(e,t){const r=Object.assign({grant_type:e,client_id:this.clientId,device:this.deviceInfo},t),n=Object.keys(r).map((e=>`${e}=${encodeURIComponent(r[e])}`)).join("&"),i=new Headers;i.append("Content-Type","application/x-www-form-urlencoded"),i.append("accept","application/json");const s=await fetch(this.tokenServiceUrl,{method:"POST",headers:i,body:n});try{const e=await s.json();return 200!==s.status?Promise.reject({status:s.status,data:e}):new W(e)}catch(e){return Promise.reject(s)}}async updateToken(e){var t;try{return this.pendingUpdateTokenRequest&&this.pendingUpdateTokenRequest.refreshToken===e||(this.pendingUpdateTokenRequest={refreshToken:e,request:this.fetchTokenBy("refresh_token",{refresh_token:e})}),await this.pendingUpdateTokenRequest.request}finally{(null===(t=this.pendingUpdateTokenRequest)||void 0===t?void 0:t.refreshToken)===e&&(this.pendingUpdateTokenRequest=null)}}async fetchWidgetToken(e){const{widgetId:t,widgetToken:r}=e;if(!t||!r)throw new Error("token must contain widgetId and widgetToken");if(!this.widgetTokenServiceUrl)throw new Error("please set widgetTokenServiceUrl");const n={widgetId:t,userKey:r},i=new Headers;i.append("Content-Type","application/x-www-form-urlencoded"),i.append("accept","application/json");const s=Object.keys(n).map((e=>`${e}=${encodeURIComponent(n[e])}`)).join("&"),a=await fetch(this.widgetTokenServiceUrl,{method:"POST",headers:i,body:s});try{const e=await a.json();return 200!==a.status?Promise.reject({status:a.status,data:e}):new W(Object.assign({widgetId:t,widgetToken:r},e))}catch(e){return Promise.reject(a)}}}!function(e){e[e.Motion=0]="Motion",e[e.Tampering=1]="Tampering",e[e.PanTiltZoom=2]="PanTiltZoom",e[e.CrossLine=3]="CrossLine",e[e.Intrusion=4]="Intrusion",e[e.LicensePlate=5]="LicensePlate",e[e.FaceDetection=6]="FaceDetection",e[e.Audio=7]="Audio",e[e.Analytic=8]="Analytic",e[e.SpeedDetection=9]="SpeedDetection",e[e.PeopleCounter=10]="PeopleCounter",e[e.Temperature=11]="Temperature",e[e.PoS=12]="PoS",e[e.GPS=13]="GPS",e[e.DigitalInput=14]="DigitalInput",e[e.Normal=15]="Normal",e[e.Suspicious=16]="Suspicious",e[e.Loitering=17]="Loitering",e[e.Vandalism=18]="Vandalism",e[e.Trespass=19]="Trespass",e[e.Emergency=20]="Emergency",e[e.LifeInDanger=21]="LifeInDanger",e[e.ErroneousAlert=22]="ErroneousAlert",e[e.Misidentification=23]="Misidentification",e[e.Fire=24]="Fire",e[e.MedicalDuress=25]="MedicalDuress",e[e.HoldUp=26]="HoldUp",e[e.CheckIn=27]="CheckIn",e[e.CheckOut=28]="CheckOut",e[e.ClockIn=29]="ClockIn",e[e.ClockOut=30]="ClockOut",e[e.ParkingStart=31]="ParkingStart",e[e.ParkingEnd=32]="ParkingEnd",e[e.ParkingViolation=33]="ParkingViolation",e[e.GateAccess=34]="GateAccess",e[e.DoorAccess=35]="DoorAccess",e[e.TemperatureCheck=36]="TemperatureCheck",e[e.IDCheck=37]="IDCheck",e[e.PPECheck=38]="PPECheck",e[e.WelfareCheck=39]="WelfareCheck",e[e.Uncategorized=40]="Uncategorized",e[e.Unknown=999]="Unknown"}(G||(G={}));class H{constructor(){Object.defineProperty(this,"values",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}getItem(e){return this.values.get(e)||null}setItem(e,t){this.values.set(e,t)}removeItem(e){this.values.delete(e)}}let J=[];function Z(){return Array.isArray(J)?J[0]:J}class Q{constructor(){Object.defineProperty(this,"api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disposables",{enumerable:!0,configurable:!0,writable:!0,value:[]})}initWith(e){this.api=e,this.afterInit&&this.afterInit()}dispose(){this.disposables.forEach((e=>{e instanceof b?e.closed||e.unsubscribe():e()}))}}class X extends Q{constructor(e){super(),Object.defineProperty(this,"notification",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"user",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"auth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"updateCustomPreferences",{enumerable:!0,configurable:!0,writable:!0,value:e=>{if(!this.user)return d("user is not initialized");const t={id:this.user.id,jsonField:JSON.stringify({...JSON.parse(this.user.jsonField||"{}"),...e}),version:this.user.version},r=this.api.users.UserUpdateProfile(t).pipe(g((e=>e.success?f(e.resultItems[0]):d(e.error))),T());return r.subscribe((e=>{this.setUser(e)})),r}}),Object.defineProperty(this,"getPreference",{enumerable:!0,configurable:!0,writable:!0,value:e=>{var t;try{return JSON.parse((null===(t=this.user)||void 0===t?void 0:t.jsonField)||"{}")[e]}catch{return null}}}),n(this,{user:i.ref,setUser:s,userDisplayName:t})}get userDisplayName(){return this.user?this.user.firstName&&this.user.firstName.trim()||this.user.lastName&&this.user.lastName.trim()?[this.user.firstName,this.user.lastName].filter(Boolean).join(" ").trim():this.user.email:null}afterInit(){this.api.users.GetUser().pipe(g((e=>e.success?f(e.resultItems[0]):d(e.error)))).subscribe((e=>this.setUser(e)),(()=>console.error("Couldn't get user")))}setUser(e){this.user=e}setAuthStore(e){this.auth=e}async updateUserPassword(e){var t,r;const n=Z().changePasswordUrl,i=null===(r=null===(t=this.auth)||void 0===t?void 0:t.token)||void 0===r?void 0:r.accessToken,s=JSON.stringify({currentPassword:e.previous,newPassword:e.new}),a=new Headers;a.append("content-type","application/json"),a.append("accept","application/json"),a.append("authorization",`bearer ${i}`);const o=await fetch(n,{method:"PUT",headers:a,body:s}),{status:l}=o;if(l!==U.OK){const e=await o.json();throw new Error(e.errors[0].message)}}updateUserSettings({firstName:e,lastName:t}){if(!this.user)return d("user is not initialized");const r={id:this.user.id,firstName:e,lastName:t,version:this.user.version},n=this.api.users.UserUpdateProfile(r).pipe(g((e=>e.success?f(e.resultItems[0]):d(e.error))),T());return n.subscribe((e=>{this.setUser(e)})),n}setDefaultGroup(e){if(!this.user)return;const t={id:this.user.id,layoutStartId:e,layoutStartType:"camgroup",version:this.user.version},r=this.api.users.UserUpdateProfile(t).pipe(g((e=>e.success?f(e.resultItems[0]):d(e.error))),T());return r.subscribe((e=>{var t;this.setUser(e),null===(t=this.notification)||void 0===t||t.success("Successfully set default group")}),(e=>{var t;console.error(e),null===(t=this.notification)||void 0===t||t.error(e.message)})),r}}class Y{constructor(e){Object.defineProperty(this,"json",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"startTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"endTime",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"duration",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isLive",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"cameraId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.json=JSON.stringify(e,null,2),this.startTime=new Date(e.startTime),this.endTime=new Date(e.endTime),this.streamUrl=e.streamUrl,this.cameraId=e.cameraId,this.duration=e.duration,this.id=e.id}}window.ArchiveChunk=Y;class ee extends Q{constructor(){super(),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chunksByCameraId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chunksByStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chunksByEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"chunksById",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"pendingRequests",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRequestsByEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRequestsByStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRequestsByCameraId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"knownIntervals",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"updates",{enumerable:!0,configurable:!0,writable:!0,value:0}),n(this,{updates:i,add:s.bound}),this.data=q(),this.chunksByCameraId=this.data.dimension((e=>e.cameraId)),this.chunksByStart=this.data.dimension((e=>+e.startTime)),this.chunksByEnd=this.data.dimension((e=>+e.endTime)),this.pendingRequests=q(),this.pendingRequestsByStart=this.pendingRequests.dimension((e=>+e.startTime)),this.pendingRequestsByEnd=this.pendingRequests.dimension((e=>+e.endTime)),this.pendingRequestsByCameraId=this.pendingRequests.dimension((e=>e.cameraId))}fetch(e,t,r){this.pendingRequestsByCameraId.filter(e),this.pendingRequestsByStart.filter(t),this.pendingRequestsByEnd.filter(r);const n=this.pendingRequests.allFiltered()[0];if(this.pendingRequestsByCameraId.filterAll(),this.pendingRequestsByStart.filterAll(),this.pendingRequestsByEnd.filterAll(),n)return n.request;if(this.knownIntervals.has(e)){const[n,i]=this.knownIntervals.get(e);if(n<=t&&i>=r)return f(this.getChunks({cameraId:e,from:t,to:r}));n<=t&&i<r&&(t=i),n>t&&i>=r&&(r=n),r<n&&(r=n),t>i&&(t=i)}const i=this.api.archives.PopulateArchive({cameraId:e,startTime:t,endTime:r}).pipe(B((e=>e.resultItems[0].chunks.map((e=>new Y(e))))),S(this.add),S((t=>this.extendKnownInterval(e,t))),T());return this.pendingRequests.add([{cameraId:e,startTime:t,endTime:r,request:i}]),i.pipe(S((()=>this.pendingRequests.remove((e=>e.request===i))))).subscribe(),i}extendKnownInterval(e,t){const r=new Date(Math.min(...t.map((e=>+e.startTime)))),n=new Date(Math.max(...t.map((e=>+e.endTime))));if(this.knownIntervals.has(e)){const t=this.knownIntervals.get(e);r<t[0]&&(t[0]=r),n>t[1]&&(t[1]=n)}else this.knownIntervals.set(e,[r,n])}add(e){const t=e.filter((e=>!this.chunksById.has(e.id)));t.forEach((e=>this.chunksById.set(e.id,e))),this.data.add(t),t.length&&this.updates++}getChunks({cameraId:e,from:t,to:r}){this.chunksByStart.filter([-1/0,+r+5e-4]),this.chunksByEnd.filter([t,1/0]),e&&this.chunksByCameraId.filter(e);const n=this.chunksByStart.top(1/0);return e&&this.chunksByCameraId.filterAll(),this.chunksByStart.filterAll(),this.chunksByEnd.filterAll(),n}findClosestChunk({cameraId:e,time:t}){this.chunksByCameraId.filter(e),this.chunksByEnd.filter([t,1/0]);const r=this.chunksByStart.bottom(1);return this.chunksByCameraId.filterAll(),this.chunksByEnd.filterAll(),r[0]}afterInit(){this.api.events.pipe(p((({hub:e,event:t})=>"archives"===e&&"OnArchiveChunksCreated"===t))).subscribe((({data:e})=>{this.add(e.resultItems.map((e=>new Y(e))))}))}}class te{constructor(e){Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"imageUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"streamUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dashStreamUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"address",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"archiveDuration",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dvrWindowLength",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stateUpdatedAt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"enabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isMicEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pin",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webRtcUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"isPtz",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"permissions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"update",{enumerable:!0,configurable:!0,writable:!0,value:e=>{this.raw=e,this.id=e.id,this.name=e.name,this.isPtz=e.isPTZ,this.isMicEnabled=e.isMicEnabled,this.imageUrl=e.imageUrl,this.address=e.cameraAddress?JSON.parse(e.cameraAddress):null,this.streamUrl=e.streamUrl,this.dashStreamUrl=e.dashStreamUrl,this.enabled=e.enabled,this.state=this.raw.cameraState,this.dvrWindowLength=e.dvrWindowLength?1e3*e.dvrWindowLength:e.dvrWindowLength,this.archiveDuration=e.archiveDuration,this.pin=e.pin,this.webRtcUrl=e.webRtcUrl,this.permissions=e.permissions||0,this.stateUpdatedAt=new Date(e.cameraStateChangedTime)}}),n(this,{name:i,streamUrl:i,dashStreamUrl:i,enabled:i,isMicEnabled:i,state:i,pin:i,webRtcUrl:i,permissions:i,isOnline:t,update:s}),this.update(e)}get isOnline(){return this.enabled&&"Started"===this.state}get supportsWebRTC(){return!!this.webRtcUrl}}const re={View:1,SaveClip:2,Share:4,Ptz:8,EditSettings:16,Timelapse:32,Delete:64};class ne extends Q{constructor(){super(),Object.defineProperty(this,"camerasById",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"loading",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"loaded",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"load",{enumerable:!0,configurable:!0,writable:!0,value:()=>{if(this.loaded)return;r((()=>this.loading=!0));const e=this.api.cameras.GetCameras({},null).pipe(g((e=>e.success?f(e.resultItems):(console.error(e.error),d(e.error)))),C());return e.subscribe((e=>{r((()=>{this.add(e),this.loading=!1,this.loaded=!0}))})),e}}),Object.defineProperty(this,"add",{enumerable:!0,configurable:!0,writable:!0,value:e=>{e.forEach((e=>{this.camerasById.has(e.id)?this.camerasById.get(e.id).update(e):this.camerasById.set(e.id,new te(e))})),this.data=Array.from(this.camerasById.values()).sort(((e,t)=>R(e.name,t.name,{caseInsensitive:!0})))}}),Object.defineProperty(this,"sync",{enumerable:!0,configurable:!0,writable:!0,value:()=>{const e=this.data.reduce(((e,t)=>Math.max(e,+t.stateUpdatedAt)),0);e&&this.api.cameras.GetCameras({},new Date(1e3*(Math.floor(e/1e3)+1))).pipe(g((e=>e.success?f(e.resultItems):(console.error(e.error),d(e.error))))).subscribe((e=>this.add(e)))}}),n(this,{data:i.ref,loading:i,loaded:i,add:s}),this.disposables.push(a((()=>this.loaded),(()=>{this.api.connection$.pipe(_(1)).subscribe(this.sync)}))),this.disposables.push(V((()=>this.loaded),!0).pipe(p(Boolean),y(1),g((()=>this.fetchPermissions()))).subscribe())}async fetchPermissions(){var e;if(!Z())return;const t=Z().userPermissionsUrl;if(!t)return console.warn("user permissions URL is missing in config");if(!this.data.length)return;if(this.data.some((e=>e.permissions>0)))return;const n=null===(e=this.api.authStore.token)||void 0===e?void 0:e.accessToken,i=new Headers;i.append("content-type","application/json"),i.append("accept","application/json"),i.append("authorization",`bearer ${n}`);const s=await fetch(t,{headers:i}),{status:a}=s;if(a!==U.OK){const e=await s.json();throw new Error(e.errors[0].message)}(await s.json()).securables.forEach((e=>{if("camera"!==e.securableType)return;const t=e.permissions.map((e=>re[e])).reduce(((e,t)=>e+t)),n=this.camerasById.get(e.securableId);n&&r((()=>{n.permissions=t}))}))}afterInit(){this.disposables.push(this.api.events.pipe(p((({hub:e,event:t})=>"cameras"===e&&("OnCameraUpdated"===t||"OnSystemCameraUpdated"===t))),B((({data:e})=>e.resultItems?e.resultItems[0]:e))).subscribe((e=>{const t=this.camerasById.get(e.id);if(!t)return console.warn("got update for unknown camera:",e.id);t.update(e)})))}dispose(){super.dispose(),this.camerasById.clear(),this.data=[]}}const ie={Person:"red",Car:"green",Animal:"blue"},se=["green","red","blue","purple","teal","amber","pink","cyan","lightGreen","deepOrange","deepPurple","lime","indigo","orange","lightBlue"];class ae extends Q{constructor(){super(),Object.defineProperty(this,"schemaDescription",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"fetchAnalyticEventSchema",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.api.cameras.GetSensorDataSchema("Analytic").subscribe((e=>{e.success?this.schemaDescription=e.resultItems:console.error(e)}),console.error)}}),n(this,{schemaDescription:i.ref,foundObjectTypes:t,foundObjectTypesForSelect:t,colorsByFoundObjectType:t})}get foundObjectTypes(){if(!this.schemaDescription.length)return[];const e=this.schemaDescription.filter((e=>"filter"===e.parameterType&&"Type"===e.fieldName&&"Analytic"===e.eventType))[0];return e?e.valueSet.split(", "):[]}get foundObjectTypesForSelect(){const e=Object.entries(ie).filter((([e])=>this.foundObjectTypes.includes(e))).map((([,e])=>e)),t=se.filter((t=>!e.includes(t)));let r=0;return this.foundObjectTypes.map((e=>{const n=e in ie?ie[e]:t[r++],i=D[n];return{id:e,name:e.toLowerCase(),color:i[500],highlightColor:i.a400,isEventType:!0}}))}get colorsByFoundObjectType(){const e=new Map;return this.foundObjectTypesForSelect.forEach((t=>{e.set(t.id,t.highlightColor)})),e}afterInit(){this.fetchAnalyticEventSchema()}dispose(){super.dispose(),this.schemaDescription=[]}}var oe=function(e,t,r,n){for(var i=-1,s=null==e?0:e.length;++i<s;){var a=e[i];t(n,a,r(a),e)}return n};var le=function(e){return function(t,r,n){for(var i=-1,s=Object(t),a=n(t),o=a.length;o--;){var l=a[e?o:++i];if(!1===r(s[l],l,s))break}return t}}();var ue=function(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n},ce="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function de(e){var t={exports:{}};return e(t,t.exports),t.exports}var he="object"==typeof ce&&ce&&ce.Object===Object&&ce,fe="object"==typeof self&&self&&self.Object===Object&&self,be=he||fe||Function("return this")(),pe=be.Symbol,ve=Object.prototype,me=ve.hasOwnProperty,ye=ve.toString,ge=pe?pe.toStringTag:void 0;var we=function(e){var t=me.call(e,ge),r=e[ge];try{e[ge]=void 0;var n=!0}catch(e){}var i=ye.call(e);return n&&(t?e[ge]=r:delete e[ge]),i},je=Object.prototype.toString;var Oe=function(e){return je.call(e)},ke=pe?pe.toStringTag:void 0;var Ie=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":ke&&ke in Object(e)?we(e):Oe(e)};var Pe=function(e){return null!=e&&"object"==typeof e};var Te=function(e){return Pe(e)&&"[object Arguments]"==Ie(e)},Be=Object.prototype,Se=Be.hasOwnProperty,Ce=Be.propertyIsEnumerable,_e=Te(function(){return arguments}())?Te:function(e){return Pe(e)&&Se.call(e,"callee")&&!Ce.call(e,"callee")},Ae=Array.isArray;var Ee=function(){return!1},Ue=de((function(e,t){var r=t&&!t.nodeType&&t,n=r&&e&&!e.nodeType&&e,i=n&&n.exports===r?be.Buffer:void 0,s=(i?i.isBuffer:void 0)||Ee;e.exports=s})),qe=/^(?:0|[1-9]\d*)$/;var Re=function(e,t){var r=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==r||"symbol"!=r&&qe.test(e))&&e>-1&&e%1==0&&e<t};var De=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991},Ne={};Ne["[object Float32Array]"]=Ne["[object Float64Array]"]=Ne["[object Int8Array]"]=Ne["[object Int16Array]"]=Ne["[object Int32Array]"]=Ne["[object Uint8Array]"]=Ne["[object Uint8ClampedArray]"]=Ne["[object Uint16Array]"]=Ne["[object Uint32Array]"]=!0,Ne["[object Arguments]"]=Ne["[object Array]"]=Ne["[object ArrayBuffer]"]=Ne["[object Boolean]"]=Ne["[object DataView]"]=Ne["[object Date]"]=Ne["[object Error]"]=Ne["[object Function]"]=Ne["[object Map]"]=Ne["[object Number]"]=Ne["[object Object]"]=Ne["[object RegExp]"]=Ne["[object Set]"]=Ne["[object String]"]=Ne["[object WeakMap]"]=!1;var xe=function(e){return Pe(e)&&De(e.length)&&!!Ne[Ie(e)]};var Fe=function(e){return function(t){return e(t)}},Me=de((function(e,t){var r=t&&!t.nodeType&&t,n=r&&e&&!e.nodeType&&e,i=n&&n.exports===r&&he.process,s=function(){try{var e=n&&n.require&&n.require("util").types;return e||i&&i.binding&&i.binding("util")}catch(e){}}();e.exports=s})),ze=Me&&Me.isTypedArray,$e=ze?Fe(ze):xe,Ge=Object.prototype.hasOwnProperty;var Le=function(e,t){var r=Ae(e),n=!r&&_e(e),i=!r&&!n&&Ue(e),s=!r&&!n&&!i&&$e(e),a=r||n||i||s,o=a?ue(e.length,String):[],l=o.length;for(var u in e)!t&&!Ge.call(e,u)||a&&("length"==u||i&&("offset"==u||"parent"==u)||s&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||Re(u,l))||o.push(u);return o},We=Object.prototype;var Ve=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||We)};var Ke=function(e,t){return function(r){return e(t(r))}}(Object.keys,Object),He=Object.prototype.hasOwnProperty;var Je=function(e){if(!Ve(e))return Ke(e);var t=[];for(var r in Object(e))He.call(e,r)&&"constructor"!=r&&t.push(r);return t};var Ze=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)};var Qe=function(e){if(!Ze(e))return!1;var t=Ie(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t};var Xe=function(e){return null!=e&&De(e.length)&&!Qe(e)};var Ye=function(e){return Xe(e)?Le(e):Je(e)};var et=function(e,t){return function(r,n){if(null==r)return r;if(!Xe(r))return e(r,n);for(var i=r.length,s=t?i:-1,a=Object(r);(t?s--:++s<i)&&!1!==n(a[s],s,a););return r}}((function(e,t){return e&&le(e,t,Ye)}));var tt=function(e,t,r,n){return et(e,(function(e,i,s){t(n,e,r(e),s)})),n};var rt=function(){this.__data__=[],this.size=0};var nt=function(e,t){return e===t||e!=e&&t!=t};var it=function(e,t){for(var r=e.length;r--;)if(nt(e[r][0],t))return r;return-1},st=Array.prototype.splice;var at=function(e){var t=this.__data__,r=it(t,e);return!(r<0)&&(r==t.length-1?t.pop():st.call(t,r,1),--this.size,!0)};var ot=function(e){var t=this.__data__,r=it(t,e);return r<0?void 0:t[r][1]};var lt=function(e){return it(this.__data__,e)>-1};var ut=function(e,t){var r=this.__data__,n=it(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this};function ct(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}ct.prototype.clear=rt,ct.prototype.delete=at,ct.prototype.get=ot,ct.prototype.has=lt,ct.prototype.set=ut;var dt=ct;var ht=function(){this.__data__=new dt,this.size=0};var ft=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r};var bt=function(e){return this.__data__.get(e)};var pt,vt=function(e){return this.__data__.has(e)},mt=be["__core-js_shared__"],yt=(pt=/[^.]+$/.exec(mt&&mt.keys&&mt.keys.IE_PROTO||""))?"Symbol(src)_1."+pt:"";var gt=function(e){return!!yt&&yt in e},wt=Function.prototype.toString;var jt=function(e){if(null!=e){try{return wt.call(e)}catch(e){}try{return e+""}catch(e){}}return""},Ot=/^\[object .+?Constructor\]$/,kt=Function.prototype,It=Object.prototype,Pt=kt.toString,Tt=It.hasOwnProperty,Bt=RegExp("^"+Pt.call(Tt).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var St=function(e){return!(!Ze(e)||gt(e))&&(Qe(e)?Bt:Ot).test(jt(e))};var Ct=function(e,t){return null==e?void 0:e[t]};var _t=function(e,t){var r=Ct(e,t);return St(r)?r:void 0},At=_t(be,"Map"),Et=_t(Object,"create");var Ut=function(){this.__data__=Et?Et(null):{},this.size=0};var qt=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Rt=Object.prototype.hasOwnProperty;var Dt=function(e){var t=this.__data__;if(Et){var r=t[e];return"__lodash_hash_undefined__"===r?void 0:r}return Rt.call(t,e)?t[e]:void 0},Nt=Object.prototype.hasOwnProperty;var xt=function(e){var t=this.__data__;return Et?void 0!==t[e]:Nt.call(t,e)};var Ft=function(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Et&&void 0===t?"__lodash_hash_undefined__":t,this};function Mt(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Mt.prototype.clear=Ut,Mt.prototype.delete=qt,Mt.prototype.get=Dt,Mt.prototype.has=xt,Mt.prototype.set=Ft;var zt=Mt;var $t=function(){this.size=0,this.__data__={hash:new zt,map:new(At||dt),string:new zt}};var Gt=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e};var Lt=function(e,t){var r=e.__data__;return Gt(t)?r["string"==typeof t?"string":"hash"]:r.map};var Wt=function(e){var t=Lt(this,e).delete(e);return this.size-=t?1:0,t};var Vt=function(e){return Lt(this,e).get(e)};var Kt=function(e){return Lt(this,e).has(e)};var Ht=function(e,t){var r=Lt(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this};function Jt(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Jt.prototype.clear=$t,Jt.prototype.delete=Wt,Jt.prototype.get=Vt,Jt.prototype.has=Kt,Jt.prototype.set=Ht;var Zt=Jt;var Qt=function(e,t){var r=this.__data__;if(r instanceof dt){var n=r.__data__;if(!At||n.length<199)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new Zt(n)}return r.set(e,t),this.size=r.size,this};function Xt(e){var t=this.__data__=new dt(e);this.size=t.size}Xt.prototype.clear=ht,Xt.prototype.delete=ft,Xt.prototype.get=bt,Xt.prototype.has=vt,Xt.prototype.set=Qt;var Yt=Xt;var er=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this};var tr=function(e){return this.__data__.has(e)};function rr(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new Zt;++t<r;)this.add(e[t])}rr.prototype.add=rr.prototype.push=er,rr.prototype.has=tr;var nr=rr;var ir=function(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1};var sr=function(e,t){return e.has(t)};var ar=function(e,t,r,n,i,s){var a=1&r,o=e.length,l=t.length;if(o!=l&&!(a&&l>o))return!1;var u=s.get(e),c=s.get(t);if(u&&c)return u==t&&c==e;var d=-1,h=!0,f=2&r?new nr:void 0;for(s.set(e,t),s.set(t,e);++d<o;){var b=e[d],p=t[d];if(n)var v=a?n(p,b,d,t,e,s):n(b,p,d,e,t,s);if(void 0!==v){if(v)continue;h=!1;break}if(f){if(!ir(t,(function(e,t){if(!sr(f,t)&&(b===e||i(b,e,r,n,s)))return f.push(t)}))){h=!1;break}}else if(b!==p&&!i(b,p,r,n,s)){h=!1;break}}return s.delete(e),s.delete(t),h},or=be.Uint8Array;var lr=function(e){var t=-1,r=Array(e.size);return e.forEach((function(e,n){r[++t]=[n,e]})),r};var ur=function(e){var t=-1,r=Array(e.size);return e.forEach((function(e){r[++t]=e})),r},cr=pe?pe.prototype:void 0,dr=cr?cr.valueOf:void 0;var hr=function(e,t,r,n,i,s,a){switch(r){case"[object DataView]":if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case"[object ArrayBuffer]":return!(e.byteLength!=t.byteLength||!s(new or(e),new or(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return nt(+e,+t);case"[object Error]":return e.name==t.name&&e.message==t.message;case"[object RegExp]":case"[object String]":return e==t+"";case"[object Map]":var o=lr;case"[object Set]":var l=1&n;if(o||(o=ur),e.size!=t.size&&!l)return!1;var u=a.get(e);if(u)return u==t;n|=2,a.set(e,t);var c=ar(o(e),o(t),n,i,s,a);return a.delete(e),c;case"[object Symbol]":if(dr)return dr.call(e)==dr.call(t)}return!1};var fr=function(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e};var br=function(e,t,r){var n=t(e);return Ae(e)?n:fr(n,r(e))};var pr=function(e,t){for(var r=-1,n=null==e?0:e.length,i=0,s=[];++r<n;){var a=e[r];t(a,r,e)&&(s[i++]=a)}return s};var vr=function(){return[]},mr=Object.prototype.propertyIsEnumerable,yr=Object.getOwnPropertySymbols,gr=yr?function(e){return null==e?[]:(e=Object(e),pr(yr(e),(function(t){return mr.call(e,t)})))}:vr;var wr=function(e){return br(e,Ye,gr)},jr=Object.prototype.hasOwnProperty;var Or=function(e,t,r,n,i,s){var a=1&r,o=wr(e),l=o.length;if(l!=wr(t).length&&!a)return!1;for(var u=l;u--;){var c=o[u];if(!(a?c in t:jr.call(t,c)))return!1}var d=s.get(e),h=s.get(t);if(d&&h)return d==t&&h==e;var f=!0;s.set(e,t),s.set(t,e);for(var b=a;++u<l;){var p=e[c=o[u]],v=t[c];if(n)var m=a?n(v,p,c,t,e,s):n(p,v,c,e,t,s);if(!(void 0===m?p===v||i(p,v,r,n,s):m)){f=!1;break}b||(b="constructor"==c)}if(f&&!b){var y=e.constructor,g=t.constructor;y==g||!("constructor"in e)||!("constructor"in t)||"function"==typeof y&&y instanceof y&&"function"==typeof g&&g instanceof g||(f=!1)}return s.delete(e),s.delete(t),f},kr=_t(be,"DataView"),Ir=_t(be,"Promise"),Pr=_t(be,"Set"),Tr=_t(be,"WeakMap"),Br=jt(kr),Sr=jt(At),Cr=jt(Ir),_r=jt(Pr),Ar=jt(Tr),Er=Ie;(kr&&"[object DataView]"!=Er(new kr(new ArrayBuffer(1)))||At&&"[object Map]"!=Er(new At)||Ir&&"[object Promise]"!=Er(Ir.resolve())||Pr&&"[object Set]"!=Er(new Pr)||Tr&&"[object WeakMap]"!=Er(new Tr))&&(Er=function(e){var t=Ie(e),r="[object Object]"==t?e.constructor:void 0,n=r?jt(r):"";if(n)switch(n){case Br:return"[object DataView]";case Sr:return"[object Map]";case Cr:return"[object Promise]";case _r:return"[object Set]";case Ar:return"[object WeakMap]"}return t});var Ur=Er,qr="[object Object]",Rr=Object.prototype.hasOwnProperty;var Dr=function(e,t,r,n,i,s){var a=Ae(e),o=Ae(t),l=a?"[object Array]":Ur(e),u=o?"[object Array]":Ur(t),c=(l="[object Arguments]"==l?qr:l)==qr,d=(u="[object Arguments]"==u?qr:u)==qr,h=l==u;if(h&&Ue(e)){if(!Ue(t))return!1;a=!0,c=!1}if(h&&!c)return s||(s=new Yt),a||$e(e)?ar(e,t,r,n,i,s):hr(e,t,l,r,n,i,s);if(!(1&r)){var f=c&&Rr.call(e,"__wrapped__"),b=d&&Rr.call(t,"__wrapped__");if(f||b){var p=f?e.value():e,v=b?t.value():t;return s||(s=new Yt),i(p,v,r,n,s)}}return!!h&&(s||(s=new Yt),Or(e,t,r,n,i,s))};var Nr=function e(t,r,n,i,s){return t===r||(null==t||null==r||!Pe(t)&&!Pe(r)?t!=t&&r!=r:Dr(t,r,n,i,e,s))};var xr=function(e,t,r,n){var i=r.length,s=i,a=!n;if(null==e)return!s;for(e=Object(e);i--;){var o=r[i];if(a&&o[2]?o[1]!==e[o[0]]:!(o[0]in e))return!1}for(;++i<s;){var l=(o=r[i])[0],u=e[l],c=o[1];if(a&&o[2]){if(void 0===u&&!(l in e))return!1}else{var d=new Yt;if(n)var h=n(u,c,l,e,t,d);if(!(void 0===h?Nr(c,u,3,n,d):h))return!1}}return!0};var Fr=function(e){return e==e&&!Ze(e)};var Mr=function(e){for(var t=Ye(e),r=t.length;r--;){var n=t[r],i=e[n];t[r]=[n,i,Fr(i)]}return t};var zr=function(e,t){return function(r){return null!=r&&(r[e]===t&&(void 0!==t||e in Object(r)))}};var $r=function(e){var t=Mr(e);return 1==t.length&&t[0][2]?zr(t[0][0],t[0][1]):function(r){return r===e||xr(r,e,t)}};var Gr=function(e){return"symbol"==typeof e||Pe(e)&&"[object Symbol]"==Ie(e)},Lr=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Wr=/^\w*$/;var Vr=function(e,t){if(Ae(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!Gr(e))||(Wr.test(e)||!Lr.test(e)||null!=t&&e in Object(t))};function Kr(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError("Expected a function");var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],s=r.cache;if(s.has(i))return s.get(i);var a=e.apply(this,n);return r.cache=s.set(i,a)||s,a};return r.cache=new(Kr.Cache||Zt),r}Kr.Cache=Zt;var Hr=Kr;var Jr=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Zr=/\\(\\)?/g,Qr=function(e){var t=Hr(e,(function(e){return 500===r.size&&r.clear(),e})),r=t.cache;return t}((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(Jr,(function(e,r,n,i){t.push(n?i.replace(Zr,"$1"):r||e)})),t}));var Xr=function(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i},Yr=pe?pe.prototype:void 0,en=Yr?Yr.toString:void 0;var tn=function e(t){if("string"==typeof t)return t;if(Ae(t))return Xr(t,e)+"";if(Gr(t))return en?en.call(t):"";var r=t+"";return"0"==r&&1/t==-Infinity?"-0":r};var rn=function(e){return null==e?"":tn(e)};var nn=function(e,t){return Ae(e)?e:Vr(e,t)?[e]:Qr(rn(e))};var sn=function(e){if("string"==typeof e||Gr(e))return e;var t=e+"";return"0"==t&&1/e==-Infinity?"-0":t};var an=function(e,t){for(var r=0,n=(t=nn(t,e)).length;null!=e&&r<n;)e=e[sn(t[r++])];return r&&r==n?e:void 0};var on=function(e,t,r){var n=null==e?void 0:an(e,t);return void 0===n?r:n};var ln=function(e,t){return null!=e&&t in Object(e)};var un=function(e,t,r){for(var n=-1,i=(t=nn(t,e)).length,s=!1;++n<i;){var a=sn(t[n]);if(!(s=null!=e&&r(e,a)))break;e=e[a]}return s||++n!=i?s:!!(i=null==e?0:e.length)&&De(i)&&Re(a,i)&&(Ae(e)||_e(e))};var cn=function(e,t){return null!=e&&un(e,t,ln)};var dn=function(e,t){return Vr(e)&&Fr(t)?zr(sn(e),t):function(r){var n=on(r,e);return void 0===n&&n===t?cn(r,e):Nr(t,n,3)}};var hn=function(e){return e};var fn=function(e){return function(t){return null==t?void 0:t[e]}};var bn=function(e){return function(t){return an(t,e)}};var pn=function(e){return Vr(e)?fn(sn(e)):bn(e)};var vn=function(e){return"function"==typeof e?e:null==e?hn:"object"==typeof e?Ae(e)?dn(e[0],e[1]):$r(e):pn(e)};var mn=function(e,t){return function(r,n){var i=Ae(r)?oe:tt,s=t?t():{};return i(r,e,vn(n),s)}}((function(e,t,r){e[r?0:1].push(t)}),(function(){return[[],[]]}));var yn=function(e,t,r,n){for(var i=e.length,s=r+(n?1:-1);n?s--:++s<i;)if(t(e[s],s,e))return s;return-1};var gn=function(e){return e!=e};var wn=function(e,t,r){for(var n=r-1,i=e.length;++n<i;)if(e[n]===t)return n;return-1};var jn=function(e,t,r){return t==t?wn(e,t,r):yn(e,gn,r)};var On=function(e,t){return!!(null==e?0:e.length)&&jn(e,t,0)>-1};var kn=function(e,t,r){for(var n=-1,i=null==e?0:e.length;++n<i;)if(r(t,e[n]))return!0;return!1};var In=function(){},Pn=Pr&&1/ur(new Pr([,-0]))[1]==1/0?function(e){return new Pr(e)}:In;var Tn=function(e,t,r){var n=-1,i=On,s=e.length,a=!0,o=[],l=o;if(r)a=!1,i=kn;else if(s>=200){var u=t?null:Pn(e);if(u)return ur(u);a=!1,i=sr,l=new nr}else l=t?[]:o;e:for(;++n<s;){var c=e[n],d=t?t(c):c;if(c=r||0!==c?c:0,a&&d==d){for(var h=l.length;h--;)if(l[h]===d)continue e;t&&l.push(d),o.push(c)}else i(l,d,r)||(l!==o&&l.push(d),o.push(c))}return o};var Bn=function(e,t){return e&&e.length?Tn(e,vn(t)):[]};const Sn=new Set(["LicensePlate","FaceDetection","Analytic","SpeedDetection","Temperature","PoS","GPS","DigitalInput"]);class Cn{constructor(e){if(Object.defineProperty(this,"cameraId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"raw",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thumbnailUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"detectedObjects",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"faces",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"instant",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),n(this,{id:t,startTime:t,endTime:t,acknowledged:t,isLive:t,raw:i.ref}),this.raw=e,this.type=e.eventType,this.cameraId=e.sensorId,("Analytic"===this.type||"FaceDetection"===this.type)&&e.data)try{const t=JSON.parse(e.data);t.FoundObjects&&(this.type="Analytic",this.detectedObjects=t.FoundObjects),t.Faces&&(this.type="FaceDetection",this.faces=t.Faces),this.thumbnailUrl=t.ThumbnailUrl}catch{console.warn("invalid data",e.data),this.type="Motion"}this.instant=Sn.has(this.type),this.detectedObjects||(this.detectedObjects=[])}get id(){return this.raw.id}get startTime(){return new Date(this.raw.startTime)}get endTime(){return new Date(this.raw.endTime)}get isLive(){return!Sn.has(this.type)&&+this.startTime==+this.endTime}get acknowledged(){return"sensorId"in this.raw&&!!this.raw.ackEventType}}function _n(e){if(e.length<2)return e;const t=[e[0]];for(let r=1;r<e.length;r++){const n=t.length-1,i=t[n],s=e[r];s[0]>i[1]?t.push(s):t[n]=[i[0],new Date(Math.max(+i[1],+s[1]))]}return t}const An=()=>!0;class En extends Q{constructor(e){super(),Object.defineProperty(this,"camerasStore",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"data",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventsByCameraId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventsByStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventsByEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventsByType",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventsByFoundObjects",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventsByColor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventsByLiveliness",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRequests",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRequestsByEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRequestsByStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRequestsByCameraId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"knownIntervals",{enumerable:!0,configurable:!0,writable:!0,value:q()}),Object.defineProperty(this,"knownIntervalsByCameraId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"knownIntervalsByStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"knownIntervalsByEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"eventsById",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"updates",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"recentAdditions",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"update",{enumerable:!0,configurable:!0,writable:!0,value:e=>{e.forEach((e=>{const t=this.eventsById.get(e.id);t&&(t.raw=e.raw,this.data.remove((t=>t.id===e.id)),this.data.add([t]))}))}}),Object.defineProperty(this,"add",{enumerable:!0,configurable:!0,writable:!0,value:e=>{const t=e.filter((e=>!this.eventsById.has(e.id)));t.forEach((e=>this.eventsById.set(e.id,e))),this.data.add(t),t.length&&this.updates++}}),Object.defineProperty(this,"processNewEvents",{enumerable:!0,configurable:!0,writable:!0,value:({data:e})=>{const t=Bn(e.filter((e=>this.camerasStore.camerasById.has(e.sensorId))).reverse(),"id").map((e=>new Cn(e))),[r,n]=mn(t,(e=>this.eventsById.has(e.id)));this.update(r),this.add(n),n.length&&(this.recentAdditions=n.map((e=>e.id)))}}),n(this,{updates:i,recentAdditions:i.ref,processNewEvents:s,update:s,add:s,dispose:s}),this.data=q(),this.eventsByCameraId=this.data.dimension((e=>e.cameraId)),this.eventsByStart=this.data.dimension((e=>+e.startTime)),this.eventsByEnd=this.data.dimension((e=>+e.endTime)),this.eventsByType=this.data.dimension((e=>e.type)),this.eventsByFoundObjects=this.data.dimension((e=>e.detectedObjects.map((e=>e.Type))),!0),this.eventsByColor=this.data.dimension((e=>e.detectedObjects.reduce(((e,t)=>e.concat(...t.Colors.map((e=>e.Color)))),[])),!0),this.eventsByLiveliness=this.data.dimension((e=>e.isLive)),this.pendingRequests=q(),this.pendingRequestsByStart=this.pendingRequests.dimension((e=>+e.startTime)),this.pendingRequestsByEnd=this.pendingRequests.dimension((e=>+e.endTime)),this.pendingRequestsByCameraId=this.pendingRequests.dimension((e=>e.cameraId)),this.knownIntervalsByCameraId=this.knownIntervals.dimension((e=>e.cameraId)),this.knownIntervalsByStart=this.knownIntervals.dimension((e=>+e.from)),this.knownIntervalsByEnd=this.knownIntervals.dimension((e=>+e.to))}populateEvents(e,t,r){const n=null===r?new Date(Date.now()-6e5):r;-1===e?this.knownIntervalsByCameraId.filter(-1):this.knownIntervalsByCameraId.filter((t=>-1===t||t===e)),this.knownIntervalsByStart.filter([-1/0,n]),this.knownIntervalsByEnd.filter([t,1/0]);const i=this.knownIntervalsByStart.bottom(1/0),s=[];if(this.knownIntervalsByCameraId.filterAll(),this.knownIntervalsByStart.filterAll(),this.knownIntervalsByEnd.filterAll(),i.length){const a=_n(i.map((e=>[e.from,e.to])));a[0][0]>t&&s.push([t,a[0][0]]);for(let e=0;e<a.length-1;e++)s.push([a[e][1],a[e+1][0]]);a[_n.length-1][1]<n&&s.push([a[_n.length-1][1],n]),s.length&&(t=s[0][0],+s[s.length-1][1]<=+n&&(r=s[s.length-1][1]),this.knownIntervals.add([{cameraId:e,from:t,to:n}]))}else this.knownIntervals.add([{cameraId:e,from:t,to:n}]);this.pendingRequestsByCameraId.filter(e),this.pendingRequestsByStart.filter(t),this.pendingRequestsByEnd.filter(n);const a=this.pendingRequests.allFiltered()[0];if(this.pendingRequestsByCameraId.filterAll(),this.pendingRequestsByStart.filterAll(),this.pendingRequestsByEnd.filterAll(),a)return;if(i.length&&!s.length)return;const o=n=>this.api.cameras.GetSensorEventsPage({sensorIds:[e],sensorType:"camera",sensorEventTypes:[],startTime:t,endTime:r,rowsLimit:100,isDescending:!0,pageToken:n},null,[]).pipe(g((e=>e.success?f(e):(console.error(e.error),d(e.error))))),l=o().pipe(A((e=>e.pageInfo.haveMore?o(e.pageInfo.nextPageToken):u)),B((e=>e.resultItems.map((e=>new Cn(e))))),C());this.pendingRequests.add([{cameraId:e,startTime:t,endTime:r||new Date,request:l}]),l.subscribe({next:this.add,error:e=>{console.error(e),this.pendingRequests.remove((e=>e.request===l))},complete:()=>{this.pendingRequests.remove((e=>e.request===l))}})}getEvents({cameraIds:e,from:t,to:r,detectedObjectTypes:n,eventTypes:i,colors:s,probability:a}){this.eventsByStart.filter([+t,r?+r+5e-4:1/0]),(null==e?void 0:e.length)&&this.eventsByCameraId.filter((t=>e.includes(t))),(null==i?void 0:i.length)&&this.eventsByType.filter((e=>i.includes(e))),(null==n?void 0:n.length)&&this.eventsByFoundObjects.filter((e=>n.includes(e))),(null==s?void 0:s.size)&&this.eventsByColor.filter((e=>s.has(e)));let o=this.eventsByStart.top(1/0);return(null==i?void 0:i.length)&&this.eventsByType.filterAll(),(null==e?void 0:e.length)&&this.eventsByCameraId.filterAll(),(null==n?void 0:n.length)&&this.eventsByFoundObjects.filterAll(),(null==s?void 0:s.size)&&this.eventsByColor.filterAll(),this.eventsByStart.filterAll(),void 0!==a&&(null==n?void 0:n.length)&&(o=o.filter((e=>e.detectedObjects.some((e=>e.Probability>=a&&n.includes(e.Type)))))),o}getOverlappedEvents({cameraId:e,from:t,to:r}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([-1/0,+r+5e-4]),this.eventsByEnd.filter([+t,1/0]);const n=this.eventsByStart.top(1/0);return this.eventsByCameraId.filterAll(),this.eventsByStart.filterAll(),this.eventsByStart.filterAll(),n}getLastNonAnalyticEventBefore({cameraId:e,date:t}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([-1/0,+t]),this.eventsByType.filter((e=>"Analytic"!==e));const r=this.eventsByStart.top(1);return this.eventsByType.filterAll(),this.eventsByStart.filterAll(),this.eventsByCameraId.filterAll(),r[0]}getLastObjectBefore({cameraId:e,date:t,objectFilters:r}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([-1/0,+t]),this.eventsByType.filter((e=>"Analytic"===e));const{cars:n,people:i,misc:s}=r;i&&n&&s||this.eventsByFoundObjects.filter((e=>s?i||n?!(!i||!n)||(i?"Car"!==e:"Person"!==e):"Person"!==e&&"Car"!==e:i&&n?"Person"===e||"Car"===e:i?"Person"===e:"Car"===e));const a=this.eventsByStart.top(1);return this.eventsByFoundObjects.filterAll(),this.eventsByType.filterAll(),this.eventsByStart.filterAll(),this.eventsByCameraId.filterAll(),a[0]}getFirstNonAnalyticEventAfter({cameraId:e,date:t}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([+t+5e-4,1/0]),this.eventsByType.filter((e=>"Analytic"!==e));const r=this.eventsByEnd.bottom(1);return this.eventsByType.filterAll(),this.eventsByCameraId.filterAll(),this.eventsByStart.filterAll(),r[0]}getFirstObjectAfter({cameraId:e,date:t,objectFilters:r}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([+t+5e-4,1/0]),this.eventsByType.filter((e=>"Analytic"===e));const{cars:n,people:i,misc:s}=r;i&&n&&s||this.eventsByFoundObjects.filter((e=>s?i||n?!(!i||!n)||(i?"Car"!==e:"Person"!==e):"Person"!==e&&"Car"!==e:i&&n?"Person"===e||"Car"===e:i?"Person"===e:"Car"===e));const a=this.eventsByStart.bottom(1);return this.eventsByFoundObjects.filterAll(),this.eventsByType.filterAll(),this.eventsByStart.filterAll(),this.eventsByCameraId.filterAll(),a[0]}afterInit(){this.api.events.pipe(p((({hub:e,event:t})=>"cameras"===e&&"OnCameraMotionEvent"===t))).subscribe(this.processNewEvents)}dispose(){super.dispose(),this.data.remove(An),this.updates++}}class Un extends Q{constructor(){super(),Object.defineProperty(this,"thumbnails",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thumbnailsByCameraId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"thumbnailsByDate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRequests",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRequestsByEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRequestsByStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRequestsByCameraId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pendingRequestsByCount",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"toThumbnail",{enumerable:!0,configurable:!0,writable:!0,value:e=>({realtimestamp:t,url:r,width:n,height:i})=>({cameraId:e,url:r,width:n,height:i,timestamp:new Date(t)})}),this.thumbnails=q(),this.thumbnailsByCameraId=this.thumbnails.dimension((e=>e.cameraId)),this.thumbnailsByDate=this.thumbnails.dimension((e=>+e.timestamp)),this.pendingRequests=q(),this.pendingRequestsByStart=this.pendingRequests.dimension((e=>+e.from)),this.pendingRequestsByEnd=this.pendingRequests.dimension((e=>+e.to)),this.pendingRequestsByCameraId=this.pendingRequests.dimension((e=>e.cameraId)),this.pendingRequestsByCount=this.pendingRequests.dimension((e=>e.count))}fetchThumbnails(e,t,r,n){this.pendingRequestsByCameraId.filter(e),this.pendingRequestsByStart.filter(t),this.pendingRequestsByEnd.filter(r),this.pendingRequestsByCount.filter(n);const i=this.pendingRequests.allFiltered()[0];if(this.pendingRequestsByCameraId.filterAll(),this.pendingRequestsByStart.filterAll(),this.pendingRequestsByEnd.filterAll(),this.pendingRequestsByCount.filterAll(),i)return i.request;const s=this.api.thumbnails.GetThumbnailsInfo({cameraId:e,from:t,to:r,count:n}).pipe(B((t=>t.resultItems.filter((e=>e.url)).map(this.toThumbnail(e)))),T());return this.pendingRequests.add([{cameraId:e,from:t,to:r,count:n,request:s}]),s.subscribe((e=>{this.thumbnails.add(e),this.pendingRequests.remove((e=>e.request===s))})),s}getIntervalState(e,t,r){const n=this.getThumbnail({cameraId:e,from:t,to:r});if(n)return{state:"fullfilled",data:n};this.pendingRequestsByCameraId.filter(e),this.pendingRequestsByStart.filter([-1/0,+r+5e-4]),this.pendingRequestsByEnd.filter([t,1/0]);let i=this.pendingRequests.allFiltered();return this.pendingRequestsByCameraId.filterAll(),this.pendingRequestsByStart.filterAll(),this.pendingRequestsByEnd.filterAll(),i=i.filter((e=>1===e.count?+e.from==+t&&+e.to==+r:Math.abs((+e.to-+e.from)/e.count-(+r-+t))<=1)),i.length?{state:"pending",request:i[0].request}:null}fetchThumbnail(e,t,r){const n=this.getIntervalState(e,t,r);if(null!==n){if("fullfilled"===n.state)return f(n.data);if("pending"===n.state)return n.request.pipe(B((()=>this.getThumbnail({cameraId:e,from:t,to:r}))))}const i=this.api.thumbnails.GetThumbnailInfo({cameraId:e,from:t,to:r}).pipe(B((e=>e.resultItems)),T());return i.subscribe((t=>{const r=t.filter((e=>e.url)).map(this.toThumbnail(e));this.thumbnails.add(r),this.pendingRequests.remove((e=>e.request===i))})),this.pendingRequests.add([{cameraId:e,from:t,to:r,count:1,request:i}]),i.pipe(B((()=>this.getThumbnail({cameraId:e,from:t,to:r}))))}getThumbnail({cameraId:e,from:t,to:r}){this.thumbnailsByCameraId.filter(e),this.thumbnailsByDate.filter([+t,+r+(+t==+r?5e-4:0)]);const n=this.thumbnails.allFiltered()[0];return this.thumbnailsByDate.filterAll(),this.thumbnailsByCameraId.filterAll(),n}getThumbnails({cameraId:e,from:t,to:r}){this.thumbnailsByCameraId.filter(e),this.thumbnailsByDate.filter([+t,+r+5e-4]);const n=this.thumbnails.allFiltered();return this.thumbnailsByDate.filterAll(),this.thumbnailsByCameraId.filterAll(),n}}class qn{constructor(e){Object.defineProperty(this,"notifier",{enumerable:!0,configurable:!0,writable:!0,value:e})}error(e){this.notifier.error(e)}success(e,t){this.notifier.success(e,t)}warn(e){this.notifier.warn(e)}}const Rn=new Map;class Dn{constructor(t){Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"cameras",{enumerable:!0,configurable:!0,writable:!0,value:new ne}),Object.defineProperty(this,"archives",{enumerable:!0,configurable:!0,writable:!0,value:new ee}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:new En(this.cameras)}),Object.defineProperty(this,"eventSchema",{enumerable:!0,configurable:!0,writable:!0,value:new ae}),Object.defineProperty(this,"thumbnails",{enumerable:!0,configurable:!0,writable:!0,value:new Un}),Object.defineProperty(this,"account",{enumerable:!0,configurable:!0,writable:!0,value:new X}),Object.defineProperty(this,"notification",{enumerable:!0,configurable:!0,writable:!0,value:new qn({success:console.log,warn:console.warn,error:console.error})}),Object.defineProperty(this,"auth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"api",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"disposables",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tokenUpdateReactions",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"dispose",{enumerable:!0,configurable:!0,writable:!0,value:()=>{this.disposables.forEach((e=>{e instanceof b?e.closed||e.unsubscribe():e()})),this.tokenUpdateReactions.forEach((e=>e())),this.tokenUpdateReactions.clear(),this.auth.signOut(),this.cameras.dispose(),this.events.dispose(),this.thumbnails.dispose(),this.eventSchema.dispose(),this.account.dispose(),Rn.delete(this.name)}}),Object.defineProperty(this,"onTokenUpdate",{enumerable:!0,configurable:!0,writable:!0,value:t=>{if(!this.auth)throw new Error("app has to be inited first");const r=e((()=>this.auth.token),(e=>t((null==e?void 0:e.json)||null)));return this.tokenUpdateReactions.add(r),()=>{r(),this.tokenUpdateReactions.delete(r)}}}),this.disposables.push(a((()=>!!this.account.user),(()=>{this.cameras.load()})))}init({token:e,tokenStorage:t=new H,tokenStorageKey:r,apiUrl:n="https://services.3deye.me/reactiveapi",tokenServiceUrl:i="https://admin.3deye.me/token",widgetTokenServiceUrl:s="https://admin.3deye.me/widget/token"},a="default"){if(r||(r=`@3deye-toolkit/${a}/token`),Rn.has(a))return console.warn("Can`t init two apps with the same name"),Rn.get(a);if(this.auth&&a===this.name)return console.warn("Can`t init already inited app"),this;if(this.auth||"default"===this.name&&"default"!==a)return new Dn(a).init({token:e,tokenStorage:t,tokenStorageKey:r,apiUrl:n,tokenServiceUrl:i,widgetTokenServiceUrl:s},a);const o=e&&"clientId"in e?e.clientId:"WebApp";return e&&t.setItem(r,JSON.stringify(e)),this.auth=new K({widgetTokenServiceUrl:s,tokenServiceUrl:i,tokenStorageKey:r,storage:t,clientId:o,deviceInfo:null}),this.api=L.create(M,this.auth,(e=>E(n,{qs:{access_token:e}}))),this.cameras.initWith(this.api),this.archives.initWith(this.api),this.events.initWith(this.api),this.eventSchema.initWith(this.api),this.thumbnails.initWith(this.api),this.account.initWith(this.api),this.account.setAuthStore(this.auth),Rn.set(a,this),this}}const Nn=new Dn("default"),xn=N.createContext(null);export{xn as AppContext,Nn as app};
@@ -0,0 +1,11 @@
1
+ // This file is read by tools that parse documentation comments conforming to the TSDoc standard.
2
+ // It should be published with your NPM package. It should not be tracked by Git.
3
+ {
4
+ "tsdocVersion": "0.12",
5
+ "toolPackages": [
6
+ {
7
+ "packageName": "@microsoft/api-extractor",
8
+ "packageVersion": "7.18.14"
9
+ }
10
+ ]
11
+ }
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "@3deye-toolkit/core",
3
+ "version": "0.0.1-alpha.21",
4
+ "module": "dist/core.js",
5
+ "types": "dist/core.d.ts",
6
+ "files": [
7
+ "dist"
8
+ ],
9
+ "dependencies": {
10
+ "crossfilter2": "^1.5.4",
11
+ "http-status-codes": "^2.1.4",
12
+ "jqueryless-signalr": "1.0.0",
13
+ "lodash": "4.17.21",
14
+ "material-colors": "^1.2.6",
15
+ "mobx": "^6.3.2",
16
+ "rxjs": "^6.5.5",
17
+ "string-natural-compare": "^3.0.1"
18
+ },
19
+ "peerDependencies": {
20
+ "react": "^16.8.0 || ^17",
21
+ "react-dom": "^16.8.0 || ^17"
22
+ },
23
+ "sideEffects": false,
24
+ "license": "mit"
25
+ }