@3deye-toolkit/core 0.0.1-alpha.18 → 0.0.1-alpha.22

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  import { BehaviorSubject } from 'rxjs';
2
2
  import crossfilter from 'crossfilter2';
3
- import { IReactionDisposer } from 'mobx';
3
+ import type { IReactionDisposer } from 'mobx';
4
4
  import { Observable } from 'rxjs';
5
5
  import { default as React_2 } from 'react';
6
6
  import { Subject } from 'rxjs';
@@ -9,17 +9,16 @@ import { Subscription } from 'rxjs';
9
9
  declare class AccountStore extends ApiStore {
10
10
  private notification?;
11
11
  user: User | null;
12
- camerasPermissions: Map<number, string[]>;
13
12
  auth: Auth;
14
13
  constructor(notification?: NotificationService | undefined);
15
14
  get userDisplayName(): string | null;
16
15
  protected afterInit(): void;
16
+ setUser(user: User | null): void;
17
17
  setAuthStore(auth: Auth): void;
18
18
  updateUserPassword(passwordData: {
19
19
  previous: string;
20
20
  new: string;
21
21
  }): Promise<void>;
22
- fetchPermissions(): Promise<void>;
23
22
  updateUserSettings({ firstName, lastName }: {
24
23
  firstName: string;
25
24
  lastName: string;
@@ -51,6 +50,18 @@ declare class Api<T> {
51
50
  private subscribeToEvents;
52
51
  }
53
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
+
54
65
  declare type ApiResult<T> = {
55
66
  success: true;
56
67
  resultItems: T[];
@@ -129,6 +140,7 @@ declare class Auth {
129
140
  widgetTokenServiceUrl?: string;
130
141
  deviceInfo: string | null;
131
142
  clientId: string;
143
+ private pendingUpdateTokenRequest;
132
144
  get isAuthenticated(): boolean;
133
145
  constructor({ tokenServiceUrl, widgetTokenServiceUrl, storage, tokenStorageKey, deviceInfo, clientId }: AuthStoreOptions);
134
146
  signOut: () => void;
@@ -140,12 +152,11 @@ declare class Auth {
140
152
  }) => Promise<Token> | undefined;
141
153
  invalidateToken: () => void;
142
154
  getTokenFromStorage(): Promise<Token | null>;
143
- storeToken(token: Token | null): Promise<void | undefined>;
144
- getInitialToken(): Promise<Token | null>;
145
- fetchTokenBy(grantType: string, params: {
146
- [key: string]: string | boolean;
147
- }): Promise<Token>;
148
- fetchWidgetToken(token: Token): Promise<Token>;
155
+ private storeToken;
156
+ private getInitialToken;
157
+ private fetchTokenBy;
158
+ private updateToken;
159
+ private fetchWidgetToken;
149
160
  }
150
161
 
151
162
  declare interface AuthStoreOptions {
@@ -184,6 +195,7 @@ declare class Camera {
184
195
  pin: string;
185
196
  webRtcUrl: string;
186
197
  isPtz: boolean;
198
+ permissions: number;
187
199
  get isOnline(): boolean;
188
200
  get supportsWebRTC(): boolean;
189
201
  constructor(raw: RawCamera);
@@ -191,17 +203,19 @@ declare class Camera {
191
203
  }
192
204
 
193
205
  declare class CameraEvent {
194
- id: number;
195
- startTime: Date;
196
- endTime: Date;
197
206
  cameraId: number;
198
- type: EventType_2;
207
+ type: EventType;
208
+ raw: RawSensorEvent;
199
209
  thumbnailUrl: string;
200
- raw: RawEvent;
201
- foundObjects: FoundObject[];
210
+ detectedObjects: DetectedObject[];
202
211
  faces: Face[];
212
+ instant: boolean;
213
+ get id(): number;
214
+ get startTime(): Date;
215
+ get endTime(): Date;
203
216
  get isLive(): boolean;
204
- constructor(raw: RawEvent);
217
+ get acknowledged(): boolean;
218
+ constructor(raw: RawSensorEvent);
205
219
  }
206
220
 
207
221
  declare class CamerasStore extends ApiStore {
@@ -210,9 +224,10 @@ declare class CamerasStore extends ApiStore {
210
224
  loading: boolean;
211
225
  loaded: boolean;
212
226
  constructor();
213
- fetch(): Observable<RawCamera[]>;
227
+ load: () => Observable<RawCamera[]> | undefined;
214
228
  add: (cameras: RawCamera[]) => void;
215
229
  sync: () => void;
230
+ fetchPermissions(): Promise<void>;
216
231
  protected afterInit(): void;
217
232
  dispose(): void;
218
233
  }
@@ -278,47 +293,18 @@ declare type DeepPartial<T> = {
278
293
  [K in keyof T]?: DeepPartial<T[K]>;
279
294
  };
280
295
 
281
- declare class EventListlStore {
282
- private eventsStore;
283
- data: CameraEvent[];
284
- cameraFilters: Camera[];
285
- objectFilters: EventOption[];
286
- to: Date | null;
287
- from: Date;
288
- loading: boolean;
289
- probabilityThreshold: number;
290
- facesProbabilityThreshold: number;
291
- onlyFaces: boolean;
292
- totalCount: number;
293
- facesCount: number;
294
- title: string;
295
- pendingData: CameraEvent[];
296
- paused: boolean;
297
- updates: number;
298
- colors: Set<string>;
299
- get someAnalyticsFilterSelected(): boolean;
300
- get filters(): (Camera | EventOption)[];
301
- constructor(eventsStore: EventsStore);
302
- flushUpdates: () => void;
303
- isAboveThreshold: (e: CameraEvent) => boolean;
304
- hasFacesAboveThreshold: (e: CameraEvent) => boolean;
305
- toggleFaces(): void;
306
- load(): void;
307
- setFilters(filters: (Camera | EventOption)[] | null): void;
308
- getProbabilityTreshold: () => number;
309
- setProbabilityTreshold: (value: number) => void;
310
- getFacesProbabilityTreshold: () => number;
311
- setFacesProbabilityTreshold: (value: number) => void;
312
- toggleColor(color: string): void;
313
- clearColors(): void;
314
- }
315
-
316
- declare interface EventOption {
317
- id: string;
318
- name: string;
319
- color: string;
320
- highlightColor: string;
321
- isEventType: boolean;
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
+ }[];
322
308
  }
323
309
 
324
310
  declare const events: {
@@ -329,8 +315,8 @@ declare const events: {
329
315
  };
330
316
 
331
317
  declare class EventSchemaStore extends ApiStore {
332
- api: Api<IApi> & IApi;
333
318
  schemaDescription: SchemaDescriptionParameter[];
319
+ constructor();
334
320
  get foundObjectTypes(): string[];
335
321
  get foundObjectTypesForSelect(): {
336
322
  id: EventType;
@@ -347,10 +333,12 @@ declare class EventSchemaStore extends ApiStore {
347
333
 
348
334
  declare interface EventsQuery {
349
335
  cameraIds?: number[];
336
+ eventTypes?: EventType[];
350
337
  from: Date;
351
338
  to: Date | null;
352
- objectType?: string[];
339
+ detectedObjectTypes?: string[];
353
340
  colors?: Set<string>;
341
+ probability?: number;
354
342
  }
355
343
 
356
344
  declare class EventsStore extends ApiStore {
@@ -359,7 +347,7 @@ declare class EventsStore extends ApiStore {
359
347
  eventsByCameraId: crossfilter.Dimension<CameraEvent, number>;
360
348
  eventsByStart: crossfilter.Dimension<CameraEvent, number>;
361
349
  eventsByEnd: crossfilter.Dimension<CameraEvent, number>;
362
- eventsByType: crossfilter.Dimension<CameraEvent, EventType_2>;
350
+ eventsByType: crossfilter.Dimension<CameraEvent, EventType>;
363
351
  eventsByFoundObjects: crossfilter.Dimension<CameraEvent, string>;
364
352
  eventsByColor: crossfilter.Dimension<CameraEvent, string>;
365
353
  eventsByLiveliness: crossfilter.Dimension<CameraEvent, boolean>;
@@ -380,52 +368,54 @@ declare class EventsStore extends ApiStore {
380
368
  recentAdditions: number[];
381
369
  constructor(camerasStore: CamerasStore);
382
370
  /**
383
- * Fetches events for given camera and period
371
+ * Populates store with the events for given camera and period
384
372
  * @param cameraId - camera id or -1 to fetch all available events for given period
385
373
  * @param startTime - start of the period
386
374
  * @param endTime - end of the period
387
375
  */
388
- fetchEvents(cameraId: number, startTime: Date, endTime: Date | null): Observable<CameraEvent[]>;
376
+ populateEvents(cameraId: number, startTime: Date, endTime: Date): void;
389
377
  update: (data: CameraEvent[]) => void;
390
378
  add: (data: CameraEvent[]) => void;
391
- getEvents({ cameraIds, from, to, objectType, colors }: EventsQuery): CameraEvent[];
379
+ getEvents({ cameraIds, from, to, detectedObjectTypes, eventTypes, colors, probability }: EventsQuery): CameraEvent[];
392
380
  getOverlappedEvents({ cameraId, from, to }: {
393
381
  cameraId: number;
394
382
  from: Date;
395
383
  to: Date;
396
384
  }): CameraEvent[];
397
- getLastBefore({ cameraId, date }: {
385
+ getLastNonAnalyticEventBefore({ cameraId, date }: {
398
386
  cameraId: number;
399
387
  date: Date;
400
388
  }): CameraEvent;
401
- getFirstAfter({ cameraId, date }: {
389
+ getLastObjectBefore({ cameraId, date, objectFilters }: {
402
390
  cameraId: number;
403
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
+ };
404
410
  }): CameraEvent;
405
411
  protected afterInit(): void;
406
412
  processNewEvents: ({ data }: {
407
- data: RawEvent[];
413
+ data: RawSensorEvent[];
408
414
  }) => void;
409
415
  dispose(): void;
410
416
  }
411
417
 
412
- declare enum EventType {
413
- Motion = "Motion",
414
- Tampering = "Tampering",
415
- PanTiltZoom = "PanTiltZoom",
416
- CrossLine = "CrossLine",
417
- Start = "Start",
418
- Stop = "Stop",
419
- Restart = "Restart",
420
- Audio = "Audio",
421
- Analytic = "Analytic",
422
- Unknown = "Unknown"
423
- }
424
-
425
- declare enum EventType_2 {
426
- Default = "Default",
427
- Analytic = "Analytic"
428
- }
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';
429
419
 
430
420
  declare type ExtractHubs<T, K> = {
431
421
  [P in keyof ExtractMethods<T, K>]: ExtractMethods<T[P], K[P]>;
@@ -445,20 +435,6 @@ declare interface Face {
445
435
  Probability: number;
446
436
  }
447
437
 
448
- declare interface FoundObject {
449
- Type: string;
450
- Box: {
451
- Left: number;
452
- Top: number;
453
- Right: number;
454
- Bottom: number;
455
- };
456
- Probability: number;
457
- Colors: {
458
- Color: string;
459
- }[];
460
- }
461
-
462
438
  declare const FULL_API_CONFIG: IApi;
463
439
 
464
440
  declare interface GetThumbnailParams {
@@ -495,6 +471,9 @@ declare interface IApi {
495
471
  GetCameras: (camera: {
496
472
  id?: number;
497
473
  } | null, since: Date | null) => Observable<ApiResult<RawCamera>>;
474
+ /**
475
+ * @deprecated
476
+ */
498
477
  GetMotionEvents: (params: {
499
478
  cameraId: number;
500
479
  endTime: Date | null;
@@ -502,9 +481,18 @@ declare interface IApi {
502
481
  }) => Observable<OBVIOUSLY_NEEDS_TO_BE_FIXED_EventsApiResult<RawEvent>>;
503
482
  GetSensorDataSchema: (eventType: EventType) => Observable<any>;
504
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>>;
505
487
  MoveCamera: (camera: {
506
488
  id: number;
507
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>;
508
496
  GoHomePtzCamera: ({ id }: {
509
497
  id: number;
510
498
  }) => Observable<any>;
@@ -601,8 +589,16 @@ declare type OBVIOUSLY_NEEDS_TO_BE_FIXED_EventsApiResult<T> = {
601
589
  };
602
590
  };
603
591
 
592
+ declare interface PageInfo {
593
+ isDescending: boolean;
594
+ nextPageToken: number;
595
+ haveMore: boolean;
596
+ }
597
+
604
598
  declare type PartialApi = DeepPartial<IApi>;
605
599
 
600
+ declare type PartialExcept<T, K extends keyof T> = Pick<T, K> & Partial<T>;
601
+
606
602
  declare interface PendingRequest {
607
603
  cameraId: number;
608
604
  startTime: Date;
@@ -701,24 +697,24 @@ declare interface RawEvent {
701
697
  startTime: string;
702
698
  endTime?: string;
703
699
  cameraId: number;
704
- thumbnailUrl: string;
705
- data: string;
700
+ data: string | null;
706
701
  }
707
702
 
708
703
  declare interface RawSensorEvent {
709
704
  message: string;
710
- data: string;
711
- minEventDuration: number;
705
+ data: string | null;
712
706
  id: number;
713
707
  customerId: number;
714
708
  sensorId: number;
715
709
  sensorType: 'CameraSensor' | 'MotionSensor' | 'IntrusionSensor' | 'AudioSensor' | 'TemperatureSensor' | 'SpeedSensor' | 'Unknown';
716
- eventType: 'Motion' | 'Tampering' | 'PanTiltZoom' | 'CrossLine' | 'Start' | 'Stop' | 'Restart' | 'Audio' | 'Analytic' | 'Unknown';
710
+ eventType: EventType;
711
+ ackEventType: string;
717
712
  description?: any;
718
713
  tags?: any;
719
714
  customerData?: any;
720
715
  startTime: string;
721
716
  endTime: string;
717
+ userId: string;
722
718
  }
723
719
 
724
720
  declare interface RawSharedClip {
@@ -802,6 +798,62 @@ declare interface SensorEventsParams {
802
798
  eventType: EventType;
803
799
  }
804
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
+
805
857
  declare interface Storage_2 {
806
858
  setItem: (key: string, value: string) => void | Promise<undefined>;
807
859
  getItem: (key: string) => (string | null) | Promise<string | null>;
@@ -881,7 +933,6 @@ declare class ToolkitApp {
881
933
  eventSchema: EventSchemaStore;
882
934
  thumbnails: ThumbnailsStore;
883
935
  account: AccountStore;
884
- eventList: EventListlStore;
885
936
  notification: NotificationService;
886
937
  auth: Auth;
887
938
  api: Api<IApi> & IApi;
package/dist/core.js CHANGED
@@ -1,29 +1 @@
1
- import{observable as e,computed as t,action as n,runInAction as s,reaction as r,when as i}from"mobx";import{Observable as o,empty as a,of as c,throwError as l,timer as h,Subject as u,BehaviorSubject as d,Subscription as p}from"rxjs";import{switchMap as f,flatMap as v,retryWhen as m,catchError as y,startWith as g,pairwise as b,filter as w,concatMap as T,delay as k,take as I,takeUntil as j,shareReplay as _,map as S,tap as B,skip as C,share as O}from"rxjs/operators";import A from"jqueryless-signalr";import E from"http-status-codes";import R from"crossfilter2";import D from"string-natural-compare";import U from"material-colors";import q from"react";function P(e){return null!=e}function F(){return e=>e.pipe(w(P))}const x={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,GetMotionEvents:null,MoveCamera:null,GoHomePtzCamera:null,SetHomePtzCamera:null,GetSensorDataSchema:null,GetSensorEvents: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}},N={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 M,z;!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTED=3]="DISCONNECTED"}(M||(M={}));class ${constructor(e,t,n){this.connectionShutdown$=new u,this.connection$=new d(null),this.events=new u,this.logging=!1,this.apiConfig=e,this.init(),this.createConnection=n,this.authStore=t,r(()=>t.token,e=>{if(!e)return void this.shutdownConnection();if(e.invalid)return;if(!e.accessToken)return;const t=this.connection$.getValue();t&&t.state!==M.DISCONNECTED?t.qs.access_token=e.accessToken:this.connect(e)}),this.connection$.pipe(f(e=>null!==e||!t.isAuthenticated||t.token&&t.token.invalid?a():(this.logging&&console.warn("disconnected by some reason"),h(5e3))),w(()=>t.isAuthenticated&&!!t.token&&!t.token.invalid)).subscribe(()=>{this.connect(t.token),this.logging&&console.warn("attempting to reconnect")}),this.connection$.pipe(F(),k(100)).subscribe(this.subscribeToEvents)}static create(e,t,n){return new $(null!==e?e:x,t,n)}connect(e){if(this.connection$.getValue()&&this.connection$.getValue().state===M.CONNECTED)return;const{accessToken:t}=e,n=this.createConnection(t);Object.keys(this.apiConfig).forEach(e=>n.createHubProxy(e)),Object.entries(N).forEach(([e,t])=>{t&&n.proxies[e]&&t.forEach(({name:t})=>{n.proxies[e].on(t,n=>this.events.next({hub:e,event:t,data:n}))})}),n.start().done(()=>{this.logging&&console.warn("connected"),this.connection$.next(n)}).fail(e=>{if(401===e.source.status||403===e.source.status||409===e.source.status)return this.authStore.invalidateToken()}),n.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()}),n.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)}),n.reconnecting(()=>console.log("reconnecting")),n.reconnected(()=>{this.connection$.getValue()===n&&(this.logging&&console.warn("reconnected"),this.connection$.next(n))})}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 n=this;return function s(...r){return n.connection$.pipe(F(),w(e=>e.state===M.CONNECTED),I(1)).pipe(v(n=>new Promise((s,i)=>{n.proxies[e].invoke(t,...r).done(e=>s(e)).fail(e=>i(e))})),y(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),n.connection$.getValue().stop(),n.authStore.invalidateToken(),s(...r)):l(e):(console.warn(e.message),s(...r))),j(n.connectionShutdown$))}}subscribeToEvents(e){Object.entries(N).forEach(([t,n])=>{n&&e.proxies[t]&&n.filter(({explicit:e})=>e).forEach(({name:n})=>{e.proxies[t].invoke("SubscribeToEvent",n)})})}}
2
- /*! *****************************************************************************
3
- Copyright (c) Microsoft Corporation. All rights reserved.
4
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
5
- this file except in compliance with the License. You may obtain a copy of the
6
- License at http://www.apache.org/licenses/LICENSE-2.0
7
-
8
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
9
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
10
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
11
- MERCHANTABLITY OR NON-INFRINGEMENT.
12
-
13
- See the Apache Version 2.0 License for specific language governing permissions
14
- and limitations under the License.
15
- ***************************************************************************** */function G(e,t,n,s){var r,i=arguments.length,o=i<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(i<3?r(o):i>3?r(t,n,o):r(t,n))||o);return i>3&&o&&Object.defineProperty(t,n,o),o}function L(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)}class W{constructor(e){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 K(e,n=!1){const s=t(e);return o.create(e=>s.observe(({newValue:t})=>e.next(t),n))}class V{constructor({tokenServiceUrl:e,widgetTokenServiceUrl:t,storage:n,tokenStorageKey:r,deviceInfo:i,clientId:o}){this.token=null,this.isAuthenticating=!1,this.signOut=()=>{this.isAuthenticating||(this.token=null)},this.signIn=({username:e,password:t,tokenToKick:n,agreedWithTerms:r})=>{if(this.isAuthenticating)return;s(()=>this.isAuthenticating=!0);const i={username:e,password:t};return n&&(i.kick_refresh_token=n),r&&(i.agree_with_terms=!0),this.fetchTokenBy("password",i).then(e=>(s(()=>{this.token=e,this.isAuthenticating=!1}),e)).catch(e=>{throw s(()=>{this.isAuthenticating=!1}),e})},this.invalidateToken=()=>{this.token&&(this.token=Object.assign(Object.assign({},this.token),{invalid:!0}))},this.isAuthenticating=!0,this.storage=n,this.tokenServiceUrl=e,this.widgetTokenServiceUrl=t,this.tokenStorageKey=r,this.deviceInfo=i,this.clientId=o,this.getInitialToken().then(e=>{this.token=e,this.isAuthenticating=!1});const u=K(()=>this.token),d=u.pipe(f(e=>{if(null===e)return a();const t=c(e).pipe(v(e=>e.widgetId?this.fetchWidgetToken(e):this.fetchTokenBy("refresh_token",{refresh_token:e.refreshToken})),m(e=>e.pipe(v(e=>!e.status||401!==e.status&&403!==e.status&&409!==e.status?e.error&&"refresh_token_error"===e.error||"invalid_grant"===e.error?l(e):h(5e3):l(e)))));if(!e.invalid){const n=Math.max(.75*(+e.accessTokenExpires-Date.now()),0);return h(n).pipe(v(()=>t))}return t}),y(e=>(console.error(e),this.token=null,d)));d.subscribe(e=>{this.token=e,console.warn("token updated")}),u.pipe(g(null),b(),w(([e,t])=>!!(t||!t&&e)),T(([,e])=>this.storeToken(e))).subscribe()}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();if(!e)return null;if(+e.accessTokenExpires>Date.now())return e;if(e.widgetId&&e.widgetToken)return e;if(+e.refreshTokenExpires>Date.now())try{const{refreshToken:t}=e;return await this.fetchTokenBy("refresh_token",{refresh_token:t})}catch(e){this.token=null,this.storeToken(null),console.error("refresh token error",e)}return null}async fetchTokenBy(e,t){const n=Object.assign({grant_type:e,client_id:this.clientId,device:this.deviceInfo},t),s=Object.keys(n).map(e=>`${e}=${encodeURIComponent(n[e])}`).join("&"),r=new Headers;r.append("Content-Type","application/x-www-form-urlencoded"),r.append("accept","application/json");const i=await fetch(this.tokenServiceUrl,{method:"POST",headers:r,body:s});try{const e=await i.json();return 200!==i.status?Promise.reject({status:i.status,data:e}):new W(e)}catch(e){return Promise.reject(i)}}async fetchWidgetToken(e){const{widgetId:t,widgetToken:n}=e;if(!t||!n)throw new Error("token must contain widgetId and widgetToken");if(!this.widgetTokenServiceUrl)throw new Error("please set widgetTokenServiceUrl");const s={widgetId:t,userKey:n},r=new Headers;r.append("Content-Type","application/x-www-form-urlencoded"),r.append("accept","application/json");const i=Object.keys(s).map(e=>`${e}=${encodeURIComponent(s[e])}`).join("&"),o=await fetch(this.widgetTokenServiceUrl,{method:"POST",headers:r,body:i});try{const e=await o.json();return 200!==o.status?Promise.reject({status:o.status,data:e}):new W(Object.assign({widgetId:t,widgetToken:n},e))}catch(e){return Promise.reject(o)}}}G([e,L("design:type",Object)],V.prototype,"token",void 0),G([e,L("design:type",Boolean)],V.prototype,"isAuthenticating",void 0),G([t,L("design:type",Boolean),L("design:paramtypes",[])],V.prototype,"isAuthenticated",null),G([n,L("design:type",Object)],V.prototype,"signOut",void 0),G([n,L("design:type",Object)],V.prototype,"invalidateToken",void 0),function(e){e.Motion="Motion",e.Tampering="Tampering",e.PanTiltZoom="PanTiltZoom",e.CrossLine="CrossLine",e.Start="Start",e.Stop="Stop",e.Restart="Restart",e.Audio="Audio",e.Analytic="Analytic",e.Unknown="Unknown"}(z||(z={}));class H{constructor(){this.values=new Map}getItem(e){return this.values.get(e)||null}setItem(e,t){this.values.set(e,t)}removeItem(e){this.values.delete(e)}}
16
- /*! *****************************************************************************
17
- Copyright (c) Microsoft Corporation. All rights reserved.
18
- Licensed under the Apache License, Version 2.0 (the "License"); you may not use
19
- this file except in compliance with the License. You may obtain a copy of the
20
- License at http://www.apache.org/licenses/LICENSE-2.0
21
-
22
- THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
23
- KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
24
- WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
25
- MERCHANTABLITY OR NON-INFRINGEMENT.
26
-
27
- See the Apache Version 2.0 License for specific language governing permissions
28
- and limitations under the License.
29
- ***************************************************************************** */function J(e,t,n,s){var r,i=arguments.length,o=i<3?t:null===s?s=Object.getOwnPropertyDescriptor(t,n):s;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,s);else for(var a=e.length-1;a>=0;a--)(r=e[a])&&(o=(i<3?r(o):i>3?r(t,n,o):r(t,n))||o);return i>3&&o&&Object.defineProperty(t,n,o),o}let Z=[];function Q(){return Array.isArray(Z)?Z[0]:Z}class X{constructor(){this.disposables=[]}initWith(e){this.api=e,this.afterInit&&this.afterInit()}dispose(){this.disposables.forEach(e=>{e instanceof p?e.closed||e.unsubscribe():e()})}}class Y extends X{constructor(e){super(),this.notification=e,this.user=null,this.camerasPermissions=new Map,this.updateCustomPreferences=e=>{if(!this.user)return l("user is not initialized");const t={id:this.user.id,jsonField:JSON.stringify({...JSON.parse(this.user.jsonField||"{}"),...e}),version:this.user.version},n=this.api.users.UserUpdateProfile(t).pipe(v(e=>e.success?c(e.resultItems[0]):l(e.error)),_());return n.subscribe(e=>{this.user=e}),n},this.getPreference=e=>{var t;try{return JSON.parse((null===(t=this.user)||void 0===t?void 0:t.jsonField)||"{}")[e]}catch{return null}},i(()=>!!this.user,()=>{this.fetchPermissions()})}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(v(e=>e.success?c(e.resultItems[0]):l(e.error))).subscribe(e=>this.user=e,()=>console.error("Couldn't get user"))}setAuthStore(e){this.auth=e}async updateUserPassword(e){var t,n;const s=Q().changePasswordUrl,r=null===(n=null===(t=this.auth)||void 0===t?void 0:t.token)||void 0===n?void 0:n.accessToken,i=JSON.stringify({currentPassword:e.previous,newPassword:e.new}),o=new Headers;o.append("content-type","application/json"),o.append("accept","application/json"),o.append("authorization",`bearer ${r}`);const a=await fetch(s,{method:"PUT",headers:o,body:i}),{status:c}=a;if(c!==E.OK){const e=await a.json();throw new Error(e.errors[0].message)}}async fetchPermissions(){var e,t;if(!Q())return;const n=Q().userPermissionsUrl;if(!n)return console.warn("user permissions URL is missing in config");const s=null===(t=null===(e=this.auth)||void 0===e?void 0:e.token)||void 0===t?void 0:t.accessToken,r=new Headers;r.append("content-type","application/json"),r.append("accept","application/json"),r.append("authorization",`bearer ${s}`);const i=await fetch(n,{headers:r}),{status:o}=i;if(o!==E.OK){const e=await i.json();throw new Error(e.errors[0].message)}(await i.json()).securables.forEach(e=>{"camera"===e.securableType&&this.camerasPermissions.set(e.securableId,e.permissions)})}updateUserSettings({firstName:e,lastName:t}){if(!this.user)return l("user is not initialized");const n={id:this.user.id,firstName:e,lastName:t,version:this.user.version},s=this.api.users.UserUpdateProfile(n).pipe(v(e=>e.success?c(e.resultItems[0]):l(e.error)),_());return s.subscribe(e=>{this.user=e}),s}setDefaultGroup(e){if(!this.user)return;const t={id:this.user.id,layoutStartId:e,layoutStartType:"camgroup",version:this.user.version},n=this.api.users.UserUpdateProfile(t).pipe(v(e=>e.success?c(e.resultItems[0]):l(e.error)),_());return n.subscribe(e=>{var t;this.user=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)}),n}}J([e.ref],Y.prototype,"user",void 0),J([e],Y.prototype,"camerasPermissions",void 0),J([t],Y.prototype,"userDisplayName",null);class ee{constructor(e){this.isLive=!1,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=ee;class te extends X{constructor(){super(),this.chunksById=new Map,this.knownIntervals=new Map,this.updates=0,this.data=R(),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=R(),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,n){this.pendingRequestsByCameraId.filter(e),this.pendingRequestsByStart.filter(t),this.pendingRequestsByEnd.filter(n);const s=this.pendingRequests.allFiltered()[0];if(this.pendingRequestsByCameraId.filterAll(),this.pendingRequestsByStart.filterAll(),this.pendingRequestsByEnd.filterAll(),s)return s.request;if(this.knownIntervals.has(e)){const[s,r]=this.knownIntervals.get(e);if(s<=t&&r>=n)return c(this.getChunks({cameraId:e,from:t,to:n}));s<=t&&r<n&&(t=r),s>t&&r>=n&&(n=s),n<s&&(n=s),t>r&&(t=r)}const r=this.api.archives.PopulateArchive({cameraId:e,startTime:t,endTime:n}).pipe(S(e=>e.resultItems[0].chunks.map(e=>new ee(e))),B(this.add),B(t=>this.extendKnownInterval(e,t)),_());return this.pendingRequests.add([{cameraId:e,startTime:t,endTime:n,request:r}]),r.pipe(B(()=>this.pendingRequests.remove(e=>e.request===r))).subscribe(),r}extendKnownInterval(e,t){const n=new Date(Math.min(...t.map(e=>+e.startTime))),s=new Date(Math.max(...t.map(e=>+e.endTime)));if(this.knownIntervals.has(e)){const t=this.knownIntervals.get(e);n<t[0]&&(t[0]=n),s>t[1]&&(t[1]=s)}else this.knownIntervals.set(e,[n,s])}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:n}){this.chunksByStart.filter([-1/0,+n+5e-4]),this.chunksByEnd.filter([t,1/0]),e&&this.chunksByCameraId.filter(e);const s=this.chunksByStart.top(1/0);return e&&this.chunksByCameraId.filterAll(),this.chunksByStart.filterAll(),this.chunksByEnd.filterAll(),s}findClosestChunk({cameraId:e,time:t}){this.chunksByCameraId.filter(e),this.chunksByEnd.filter([t,1/0]);const n=this.chunksByStart.bottom(1);return this.chunksByCameraId.filterAll(),this.chunksByEnd.filterAll(),n[0]}afterInit(){this.api.events.pipe(w(({hub:e,event:t})=>"archives"===e&&"OnArchiveChunksCreated"===t)).subscribe(({data:e})=>{this.add(e.resultItems.map(e=>new ee(e)))})}}J([e],te.prototype,"updates",void 0),J([n.bound],te.prototype,"add",null);class ne{constructor(e){this.update=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.stateUpdatedAt=new Date(e.cameraStateChangedTime)},this.update(e)}get isOnline(){return this.enabled&&"Started"===this.state}get supportsWebRTC(){return!!this.webRtcUrl}}J([e],ne.prototype,"name",void 0),J([e],ne.prototype,"streamUrl",void 0),J([e],ne.prototype,"dashStreamUrl",void 0),J([e],ne.prototype,"enabled",void 0),J([e],ne.prototype,"isMicEnabled",void 0),J([e],ne.prototype,"state",void 0),J([e],ne.prototype,"pin",void 0),J([e],ne.prototype,"webRtcUrl",void 0),J([t],ne.prototype,"isOnline",null),J([n],ne.prototype,"update",void 0);class se extends X{constructor(){super(),this.camerasById=new Map,this.data=[],this.loading=!1,this.loaded=!1,this.add=e=>{e.forEach(e=>{this.camerasById.has(e.id)?this.camerasById.get(e.id).update(e):this.camerasById.set(e.id,new ne(e))}),this.data=Array.from(this.camerasById.values()).sort((e,t)=>D.caseInsensitive(e.name,t.name))},this.sync=()=>{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(v(e=>e.success?c(e.resultItems):(console.error(e.error),l(e.error)))).subscribe(e=>this.add(e))},this.disposables.push(i(()=>this.loaded,()=>{this.api.connection$.pipe(C(1)).subscribe(this.sync)}))}fetch(){this.loading=!0;const e=this.api.cameras.GetCameras({},null).pipe(v(e=>e.success?c(e.resultItems):(console.error(e.error),l(e.error))),O());return e.subscribe(e=>{s(()=>{this.add(e),this.loading=!1,this.loaded=!0})}),e}afterInit(){this.disposables.push(this.api.events.pipe(w(({hub:e,event:t})=>"cameras"===e&&("OnCameraUpdated"===t||"OnSystemCameraUpdated"===t)),S(({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=[]}}var re;J([e.ref],se.prototype,"data",void 0),J([e],se.prototype,"loading",void 0),J([e],se.prototype,"loaded",void 0),J([n],se.prototype,"add",void 0),function(e){e.Default="Default",e.Analytic="Analytic"}(re||(re={}));class ie{constructor(e){if(this.raw=e,this.id=e.id,this.startTime=new Date(e.startTime),e.endTime&&(this.endTime=new Date(e.endTime)),this.cameraId=e.cameraId,e.data.startsWith("{"))try{const t=JSON.parse(e.data);t.FoundObjects&&(this.type=re.Analytic,this.foundObjects=t.FoundObjects),t.Faces&&(this.type=re.Analytic,this.faces=t.Faces),this.thumbnailUrl=t.ThumbnailUrl}catch{console.warn("invalid data",e.data),this.type=re.Default}else this.type=re.Default;this.type===re.Default&&+this.endTime-+this.startTime==0&&Date.now()-+this.startTime>6e5&&(this.endTime=new Date(+this.startTime+12e4)),this.foundObjects||(this.foundObjects=[])}get isLive(){return this.type===re.Default&&+this.startTime==+this.endTime}}J([e],ie.prototype,"endTime",void 0);class oe{constructor(e){this.eventsStore=e,this.data=[],this.cameraFilters=[],this.objectFilters=[],this.loading=!1,this.probabilityThreshold=.5,this.facesProbabilityThreshold=.7,this.onlyFaces=!1,this.totalCount=0,this.facesCount=0,this.title="menu.events",this.pendingData=[],this.paused=!1,this.updates=0,this.colors=new Set,this.flushUpdates=()=>{this.pendingData=[],this.updates++},this.isAboveThreshold=e=>{if(e.type!==re.Analytic)return!0;if(!this.objectFilters.length)return!0;const t=this.objectFilters.map(e=>e.id);return!(!e.faces||!e.faces.some(e=>e.Probability>=this.probabilityThreshold))||e.foundObjects.some(e=>{const n=t.includes(e.Type)&&e.Probability>=this.probabilityThreshold;return this.colors.size?n&&e.Colors.some(e=>this.colors.has(e.Color)):n})},this.hasFacesAboveThreshold=e=>!(!e.faces||!e.faces.length)&&e.faces.some(e=>e.Probability>=this.facesProbabilityThreshold),this.getProbabilityTreshold=()=>this.probabilityThreshold,this.setProbabilityTreshold=e=>{this.probabilityThreshold=e},this.getFacesProbabilityTreshold=()=>this.facesProbabilityThreshold,this.setFacesProbabilityTreshold=e=>{this.facesProbabilityThreshold=e},K(()=>this.paused,!0).pipe(f(t=>K(t?()=>({updates:this.updates,from:this.from,to:this.to,filters:this.filters,onlyFaces:this.onlyFaces,probabilityThreshold:this.probabilityThreshold,facesProbabilityThreshold:this.facesProbabilityThreshold,colors:this.colors}):()=>({updates:e.updates,from:this.from,to:this.to,filters:this.filters,onlyFaces:this.onlyFaces,probabilityThreshold:this.probabilityThreshold,facesProbabilityThreshold:this.facesProbabilityThreshold,colors:this.colors})))).subscribe(({from:t,to:n,onlyFaces:r,colors:i})=>{const o=this.cameraFilters.map(e=>e.id),a=this.objectFilters.map(e=>e.id),c={from:t,to:n};o.length&&(c.cameraIds=o);const l={};a.length&&(l.objectType=a,i.size&&(l.colors=i)),s(()=>{if(r){const t=e.getEvents({...c,...l}).filter(this.isAboveThreshold);this.totalCount=t.length,this.data=e.getEvents(c).filter(e=>e.faces&&e.faces.length).filter(this.hasFacesAboveThreshold),this.facesCount=this.data.length}else this.data=e.getEvents({...c,...l}).filter(this.isAboveThreshold),this.totalCount=this.data.length,this.facesCount=e.getEvents(c).filter(this.hasFacesAboveThreshold).length})}),K(()=>this.paused,!0).pipe(f(t=>t?K(()=>e.recentAdditions):a())).subscribe(t=>{const n=t.map(t=>e.eventsById.get(t)).filter(Boolean),{from:s,to:r,onlyFaces:i}=this,o=this.cameraFilters.map(e=>e.id);let a=n;o&&(a=a.filter(e=>o.includes(e.cameraId))),s&&(a=a.filter(e=>e.startTime>=s)),r&&(a=a.filter(e=>e.endTime<=r)),i?a=a.filter(this.hasFacesAboveThreshold):this.objectFilters.length&&(a=a.filter(this.isAboveThreshold),this.colors.size&&a.filter(e=>e.foundObjects.some(e=>e.Colors.some(e=>this.colors.has(e.Color))))),a.length&&(this.pendingData=this.pendingData.concat(a))}),K(()=>({from:this.from,to:this.to})).pipe(f(({from:e,to:t})=>(this.loading=!0,this.eventsStore.fetchEvents(-1,e,t)))).subscribe(()=>{this.loading=!1})}get someAnalyticsFilterSelected(){return!!this.objectFilters.length}get filters(){return this.onlyFaces?this.cameraFilters:this.objectFilters.concat(this.cameraFilters)}toggleFaces(){this.onlyFaces=!this.onlyFaces}load(){this.from=new Date(Date.now()-864e5),this.to=null,this.loading=!1}setFilters(e){this.cameraFilters=e?e.filter(e=>!("isEventType"in e)):[],this.onlyFaces||(this.objectFilters=e?e.filter(e=>"isEventType"in e):[])}toggleColor(e){const t=new Set(this.colors);this.colors.has(e)?t.delete(e):t.add(e),this.colors=t}clearColors(){this.colors=new Set}}J([e.ref],oe.prototype,"data",void 0),J([e.ref],oe.prototype,"cameraFilters",void 0),J([e.ref],oe.prototype,"objectFilters",void 0),J([e],oe.prototype,"to",void 0),J([e],oe.prototype,"from",void 0),J([e],oe.prototype,"loading",void 0),J([e],oe.prototype,"probabilityThreshold",void 0),J([e],oe.prototype,"facesProbabilityThreshold",void 0),J([e],oe.prototype,"onlyFaces",void 0),J([e],oe.prototype,"totalCount",void 0),J([e],oe.prototype,"facesCount",void 0),J([e.ref],oe.prototype,"pendingData",void 0),J([e],oe.prototype,"paused",void 0),J([e],oe.prototype,"updates",void 0),J([e.ref],oe.prototype,"colors",void 0),J([t],oe.prototype,"someAnalyticsFilterSelected",null),J([t],oe.prototype,"filters",null),J([n],oe.prototype,"flushUpdates",void 0),J([n.bound],oe.prototype,"toggleFaces",null),J([n],oe.prototype,"load",null),J([n.bound],oe.prototype,"toggleColor",null),J([n.bound],oe.prototype,"clearColors",null);const ae={Person:"red",Car:"green",Animal:"blue"},ce=["green","red","blue","purple","teal","amber","pink","cyan","lightGreen","deepOrange","deepPurple","lime","indigo","orange","lightBlue"];class le extends X{constructor(){super(...arguments),this.schemaDescription=[],this.fetchAnalyticEventSchema=()=>{this.api.cameras.GetSensorDataSchema(z.Analytic).subscribe(e=>{e.success?this.schemaDescription=e.resultItems:console.error(e)},console.error)}}get foundObjectTypes(){if(!this.schemaDescription.length)return[];const e=this.schemaDescription.filter(e=>"filter"===e.parameterType&&"Type"===e.fieldName&&e.eventType===z.Analytic)[0];return e?e.valueSet.split(", "):[]}get foundObjectTypesForSelect(){const e=Object.entries(ae).filter(([e])=>this.foundObjectTypes.includes(e)).map(([,e])=>e),t=ce.filter(t=>!e.includes(t));let n=0;return this.foundObjectTypes.map(e=>{const s=e in ae?ae[e]:t[n++],r=U[s];return{id:e,name:e.toLowerCase(),color:r[500],highlightColor:r.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=[]}}J([e.ref],le.prototype,"schemaDescription",void 0),J([t],le.prototype,"foundObjectTypes",null),J([t],le.prototype,"foundObjectTypesForSelect",null),J([t],le.prototype,"colorsByFoundObjectType",null);var he=function(e,t,n,s){for(var r=-1,i=null==e?0:e.length;++r<i;){var o=e[r];t(s,o,n(o),e)}return s};var ue=function(e){return function(t,n,s){for(var r=-1,i=Object(t),o=s(t),a=o.length;a--;){var c=o[e?a:++r];if(!1===n(i[c],c,i))break}return t}}();var de=function(e,t){for(var n=-1,s=Array(e);++n<e;)s[n]=t(n);return s},pe="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function fe(e,t){return e(t={exports:{}},t.exports),t.exports}var ve="object"==typeof pe&&pe&&pe.Object===Object&&pe,me="object"==typeof self&&self&&self.Object===Object&&self,ye=ve||me||Function("return this")(),ge=ye.Symbol,be=Object.prototype,we=be.hasOwnProperty,Te=be.toString,ke=ge?ge.toStringTag:void 0;var Ie=function(e){var t=we.call(e,ke),n=e[ke];try{e[ke]=void 0;var s=!0}catch(e){}var r=Te.call(e);return s&&(t?e[ke]=n:delete e[ke]),r},je=Object.prototype.toString;var _e=function(e){return je.call(e)},Se=ge?ge.toStringTag:void 0;var Be=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":Se&&Se in Object(e)?Ie(e):_e(e)};var Ce=function(e){return null!=e&&"object"==typeof e};var Oe=function(e){return Ce(e)&&"[object Arguments]"==Be(e)},Ae=Object.prototype,Ee=Ae.hasOwnProperty,Re=Ae.propertyIsEnumerable,De=Oe(function(){return arguments}())?Oe:function(e){return Ce(e)&&Ee.call(e,"callee")&&!Re.call(e,"callee")},Ue=Array.isArray;var qe=function(){return!1},Pe=fe((function(e,t){var n=t&&!t.nodeType&&t,s=n&&e&&!e.nodeType&&e,r=s&&s.exports===n?ye.Buffer:void 0,i=(r?r.isBuffer:void 0)||qe;e.exports=i})),Fe=/^(?:0|[1-9]\d*)$/;var xe=function(e,t){var n=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==n||"symbol"!=n&&Fe.test(e))&&e>-1&&e%1==0&&e<t};var Ne=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991},Me={};Me["[object Float32Array]"]=Me["[object Float64Array]"]=Me["[object Int8Array]"]=Me["[object Int16Array]"]=Me["[object Int32Array]"]=Me["[object Uint8Array]"]=Me["[object Uint8ClampedArray]"]=Me["[object Uint16Array]"]=Me["[object Uint32Array]"]=!0,Me["[object Arguments]"]=Me["[object Array]"]=Me["[object ArrayBuffer]"]=Me["[object Boolean]"]=Me["[object DataView]"]=Me["[object Date]"]=Me["[object Error]"]=Me["[object Function]"]=Me["[object Map]"]=Me["[object Number]"]=Me["[object Object]"]=Me["[object RegExp]"]=Me["[object Set]"]=Me["[object String]"]=Me["[object WeakMap]"]=!1;var ze=function(e){return Ce(e)&&Ne(e.length)&&!!Me[Be(e)]};var $e=function(e){return function(t){return e(t)}},Ge=fe((function(e,t){var n=t&&!t.nodeType&&t,s=n&&e&&!e.nodeType&&e,r=s&&s.exports===n&&ve.process,i=function(){try{var e=s&&s.require&&s.require("util").types;return e||r&&r.binding&&r.binding("util")}catch(e){}}();e.exports=i})),Le=Ge&&Ge.isTypedArray,We=Le?$e(Le):ze,Ke=Object.prototype.hasOwnProperty;var Ve=function(e,t){var n=Ue(e),s=!n&&De(e),r=!n&&!s&&Pe(e),i=!n&&!s&&!r&&We(e),o=n||s||r||i,a=o?de(e.length,String):[],c=a.length;for(var l in e)!t&&!Ke.call(e,l)||o&&("length"==l||r&&("offset"==l||"parent"==l)||i&&("buffer"==l||"byteLength"==l||"byteOffset"==l)||xe(l,c))||a.push(l);return a},He=Object.prototype;var Je=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||He)};var Ze=function(e,t){return function(n){return e(t(n))}}(Object.keys,Object),Qe=Object.prototype.hasOwnProperty;var Xe=function(e){if(!Je(e))return Ze(e);var t=[];for(var n in Object(e))Qe.call(e,n)&&"constructor"!=n&&t.push(n);return t};var Ye=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)};var et=function(e){if(!Ye(e))return!1;var t=Be(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t};var tt=function(e){return null!=e&&Ne(e.length)&&!et(e)};var nt=function(e){return tt(e)?Ve(e):Xe(e)};var st=function(e,t){return function(n,s){if(null==n)return n;if(!tt(n))return e(n,s);for(var r=n.length,i=t?r:-1,o=Object(n);(t?i--:++i<r)&&!1!==s(o[i],i,o););return n}}((function(e,t){return e&&ue(e,t,nt)}));var rt=function(e,t,n,s){return st(e,(function(e,r,i){t(s,e,n(e),i)})),s};var it=function(){this.__data__=[],this.size=0};var ot=function(e,t){return e===t||e!=e&&t!=t};var at=function(e,t){for(var n=e.length;n--;)if(ot(e[n][0],t))return n;return-1},ct=Array.prototype.splice;var lt=function(e){var t=this.__data__,n=at(t,e);return!(n<0)&&(n==t.length-1?t.pop():ct.call(t,n,1),--this.size,!0)};var ht=function(e){var t=this.__data__,n=at(t,e);return n<0?void 0:t[n][1]};var ut=function(e){return at(this.__data__,e)>-1};var dt=function(e,t){var n=this.__data__,s=at(n,e);return s<0?(++this.size,n.push([e,t])):n[s][1]=t,this};function pt(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var s=e[t];this.set(s[0],s[1])}}pt.prototype.clear=it,pt.prototype.delete=lt,pt.prototype.get=ht,pt.prototype.has=ut,pt.prototype.set=dt;var ft=pt;var vt=function(){this.__data__=new ft,this.size=0};var mt=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n};var yt=function(e){return this.__data__.get(e)};var gt,bt=function(e){return this.__data__.has(e)},wt=ye["__core-js_shared__"],Tt=(gt=/[^.]+$/.exec(wt&&wt.keys&&wt.keys.IE_PROTO||""))?"Symbol(src)_1."+gt:"";var kt=function(e){return!!Tt&&Tt in e},It=Function.prototype.toString;var jt=function(e){if(null!=e){try{return It.call(e)}catch(e){}try{return e+""}catch(e){}}return""},_t=/^\[object .+?Constructor\]$/,St=Function.prototype,Bt=Object.prototype,Ct=St.toString,Ot=Bt.hasOwnProperty,At=RegExp("^"+Ct.call(Ot).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var Et=function(e){return!(!Ye(e)||kt(e))&&(et(e)?At:_t).test(jt(e))};var Rt=function(e,t){return null==e?void 0:e[t]};var Dt=function(e,t){var n=Rt(e,t);return Et(n)?n:void 0},Ut=Dt(ye,"Map"),qt=Dt(Object,"create");var Pt=function(){this.__data__=qt?qt(null):{},this.size=0};var Ft=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},xt=Object.prototype.hasOwnProperty;var Nt=function(e){var t=this.__data__;if(qt){var n=t[e];return"__lodash_hash_undefined__"===n?void 0:n}return xt.call(t,e)?t[e]:void 0},Mt=Object.prototype.hasOwnProperty;var zt=function(e){var t=this.__data__;return qt?void 0!==t[e]:Mt.call(t,e)};var $t=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=qt&&void 0===t?"__lodash_hash_undefined__":t,this};function Gt(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var s=e[t];this.set(s[0],s[1])}}Gt.prototype.clear=Pt,Gt.prototype.delete=Ft,Gt.prototype.get=Nt,Gt.prototype.has=zt,Gt.prototype.set=$t;var Lt=Gt;var Wt=function(){this.size=0,this.__data__={hash:new Lt,map:new(Ut||ft),string:new Lt}};var Kt=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e};var Vt=function(e,t){var n=e.__data__;return Kt(t)?n["string"==typeof t?"string":"hash"]:n.map};var Ht=function(e){var t=Vt(this,e).delete(e);return this.size-=t?1:0,t};var Jt=function(e){return Vt(this,e).get(e)};var Zt=function(e){return Vt(this,e).has(e)};var Qt=function(e,t){var n=Vt(this,e),s=n.size;return n.set(e,t),this.size+=n.size==s?0:1,this};function Xt(e){var t=-1,n=null==e?0:e.length;for(this.clear();++t<n;){var s=e[t];this.set(s[0],s[1])}}Xt.prototype.clear=Wt,Xt.prototype.delete=Ht,Xt.prototype.get=Jt,Xt.prototype.has=Zt,Xt.prototype.set=Qt;var Yt=Xt;var en=function(e,t){var n=this.__data__;if(n instanceof ft){var s=n.__data__;if(!Ut||s.length<199)return s.push([e,t]),this.size=++n.size,this;n=this.__data__=new Yt(s)}return n.set(e,t),this.size=n.size,this};function tn(e){var t=this.__data__=new ft(e);this.size=t.size}tn.prototype.clear=vt,tn.prototype.delete=mt,tn.prototype.get=yt,tn.prototype.has=bt,tn.prototype.set=en;var nn=tn;var sn=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this};var rn=function(e){return this.__data__.has(e)};function on(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new Yt;++t<n;)this.add(e[t])}on.prototype.add=on.prototype.push=sn,on.prototype.has=rn;var an=on;var cn=function(e,t){for(var n=-1,s=null==e?0:e.length;++n<s;)if(t(e[n],n,e))return!0;return!1};var ln=function(e,t){return e.has(t)};var hn=function(e,t,n,s,r,i){var o=1&n,a=e.length,c=t.length;if(a!=c&&!(o&&c>a))return!1;var l=i.get(e);if(l&&i.get(t))return l==t;var h=-1,u=!0,d=2&n?new an:void 0;for(i.set(e,t),i.set(t,e);++h<a;){var p=e[h],f=t[h];if(s)var v=o?s(f,p,h,t,e,i):s(p,f,h,e,t,i);if(void 0!==v){if(v)continue;u=!1;break}if(d){if(!cn(t,(function(e,t){if(!ln(d,t)&&(p===e||r(p,e,n,s,i)))return d.push(t)}))){u=!1;break}}else if(p!==f&&!r(p,f,n,s,i)){u=!1;break}}return i.delete(e),i.delete(t),u},un=ye.Uint8Array;var dn=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e,s){n[++t]=[s,e]})),n};var pn=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n},fn=ge?ge.prototype:void 0,vn=fn?fn.valueOf:void 0;var mn=function(e,t,n,s,r,i,o){switch(n){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||!i(new un(e),new un(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return ot(+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 a=dn;case"[object Set]":var c=1&s;if(a||(a=pn),e.size!=t.size&&!c)return!1;var l=o.get(e);if(l)return l==t;s|=2,o.set(e,t);var h=hn(a(e),a(t),s,r,i,o);return o.delete(e),h;case"[object Symbol]":if(vn)return vn.call(e)==vn.call(t)}return!1};var yn=function(e,t){for(var n=-1,s=t.length,r=e.length;++n<s;)e[r+n]=t[n];return e};var gn=function(e,t,n){var s=t(e);return Ue(e)?s:yn(s,n(e))};var bn=function(e,t){for(var n=-1,s=null==e?0:e.length,r=0,i=[];++n<s;){var o=e[n];t(o,n,e)&&(i[r++]=o)}return i};var wn=function(){return[]},Tn=Object.prototype.propertyIsEnumerable,kn=Object.getOwnPropertySymbols,In=kn?function(e){return null==e?[]:(e=Object(e),bn(kn(e),(function(t){return Tn.call(e,t)})))}:wn;var jn=function(e){return gn(e,nt,In)},_n=Object.prototype.hasOwnProperty;var Sn=function(e,t,n,s,r,i){var o=1&n,a=jn(e),c=a.length;if(c!=jn(t).length&&!o)return!1;for(var l=c;l--;){var h=a[l];if(!(o?h in t:_n.call(t,h)))return!1}var u=i.get(e);if(u&&i.get(t))return u==t;var d=!0;i.set(e,t),i.set(t,e);for(var p=o;++l<c;){var f=e[h=a[l]],v=t[h];if(s)var m=o?s(v,f,h,t,e,i):s(f,v,h,e,t,i);if(!(void 0===m?f===v||r(f,v,n,s,i):m)){d=!1;break}p||(p="constructor"==h)}if(d&&!p){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||(d=!1)}return i.delete(e),i.delete(t),d},Bn=Dt(ye,"DataView"),Cn=Dt(ye,"Promise"),On=Dt(ye,"Set"),An=Dt(ye,"WeakMap"),En=jt(Bn),Rn=jt(Ut),Dn=jt(Cn),Un=jt(On),qn=jt(An),Pn=Be;(Bn&&"[object DataView]"!=Pn(new Bn(new ArrayBuffer(1)))||Ut&&"[object Map]"!=Pn(new Ut)||Cn&&"[object Promise]"!=Pn(Cn.resolve())||On&&"[object Set]"!=Pn(new On)||An&&"[object WeakMap]"!=Pn(new An))&&(Pn=function(e){var t=Be(e),n="[object Object]"==t?e.constructor:void 0,s=n?jt(n):"";if(s)switch(s){case En:return"[object DataView]";case Rn:return"[object Map]";case Dn:return"[object Promise]";case Un:return"[object Set]";case qn:return"[object WeakMap]"}return t});var Fn=Pn,xn=Object.prototype.hasOwnProperty;var Nn=function(e,t,n,s,r,i){var o=Ue(e),a=Ue(t),c=o?"[object Array]":Fn(e),l=a?"[object Array]":Fn(t),h="[object Object]"==(c="[object Arguments]"==c?"[object Object]":c),u="[object Object]"==(l="[object Arguments]"==l?"[object Object]":l),d=c==l;if(d&&Pe(e)){if(!Pe(t))return!1;o=!0,h=!1}if(d&&!h)return i||(i=new nn),o||We(e)?hn(e,t,n,s,r,i):mn(e,t,c,n,s,r,i);if(!(1&n)){var p=h&&xn.call(e,"__wrapped__"),f=u&&xn.call(t,"__wrapped__");if(p||f){var v=p?e.value():e,m=f?t.value():t;return i||(i=new nn),r(v,m,n,s,i)}}return!!d&&(i||(i=new nn),Sn(e,t,n,s,r,i))};var Mn=function e(t,n,s,r,i){return t===n||(null==t||null==n||!Ce(t)&&!Ce(n)?t!=t&&n!=n:Nn(t,n,s,r,e,i))};var zn=function(e,t,n,s){var r=n.length,i=r,o=!s;if(null==e)return!i;for(e=Object(e);r--;){var a=n[r];if(o&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}for(;++r<i;){var c=(a=n[r])[0],l=e[c],h=a[1];if(o&&a[2]){if(void 0===l&&!(c in e))return!1}else{var u=new nn;if(s)var d=s(l,h,c,e,t,u);if(!(void 0===d?Mn(h,l,3,s,u):d))return!1}}return!0};var $n=function(e){return e==e&&!Ye(e)};var Gn=function(e){for(var t=nt(e),n=t.length;n--;){var s=t[n],r=e[s];t[n]=[s,r,$n(r)]}return t};var Ln=function(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in Object(n)))}};var Wn=function(e){var t=Gn(e);return 1==t.length&&t[0][2]?Ln(t[0][0],t[0][1]):function(n){return n===e||zn(n,e,t)}};var Kn=function(e){return"symbol"==typeof e||Ce(e)&&"[object Symbol]"==Be(e)},Vn=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Hn=/^\w*$/;var Jn=function(e,t){if(Ue(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!Kn(e))||(Hn.test(e)||!Vn.test(e)||null!=t&&e in Object(t))};function Zn(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError("Expected a function");var n=function(){var s=arguments,r=t?t.apply(this,s):s[0],i=n.cache;if(i.has(r))return i.get(r);var o=e.apply(this,s);return n.cache=i.set(r,o)||i,o};return n.cache=new(Zn.Cache||Yt),n}Zn.Cache=Yt;var Qn=Zn;var Xn=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Yn=/\\(\\)?/g,es=function(e){var t=Qn(e,(function(e){return 500===n.size&&n.clear(),e})),n=t.cache;return t}((function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(Xn,(function(e,n,s,r){t.push(s?r.replace(Yn,"$1"):n||e)})),t}));var ts=function(e,t){for(var n=-1,s=null==e?0:e.length,r=Array(s);++n<s;)r[n]=t(e[n],n,e);return r},ns=ge?ge.prototype:void 0,ss=ns?ns.toString:void 0;var rs=function e(t){if("string"==typeof t)return t;if(Ue(t))return ts(t,e)+"";if(Kn(t))return ss?ss.call(t):"";var n=t+"";return"0"==n&&1/t==-1/0?"-0":n};var is=function(e){return null==e?"":rs(e)};var os=function(e,t){return Ue(e)?e:Jn(e,t)?[e]:es(is(e))};var as=function(e){if("string"==typeof e||Kn(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t};var cs=function(e,t){for(var n=0,s=(t=os(t,e)).length;null!=e&&n<s;)e=e[as(t[n++])];return n&&n==s?e:void 0};var ls=function(e,t,n){var s=null==e?void 0:cs(e,t);return void 0===s?n:s};var hs=function(e,t){return null!=e&&t in Object(e)};var us=function(e,t,n){for(var s=-1,r=(t=os(t,e)).length,i=!1;++s<r;){var o=as(t[s]);if(!(i=null!=e&&n(e,o)))break;e=e[o]}return i||++s!=r?i:!!(r=null==e?0:e.length)&&Ne(r)&&xe(o,r)&&(Ue(e)||De(e))};var ds=function(e,t){return null!=e&&us(e,t,hs)};var ps=function(e,t){return Jn(e)&&$n(t)?Ln(as(e),t):function(n){var s=ls(n,e);return void 0===s&&s===t?ds(n,e):Mn(t,s,3)}};var fs=function(e){return e};var vs=function(e){return function(t){return null==t?void 0:t[e]}};var ms=function(e){return function(t){return cs(t,e)}};var ys=function(e){return Jn(e)?vs(as(e)):ms(e)};var gs=function(e){return"function"==typeof e?e:null==e?fs:"object"==typeof e?Ue(e)?ps(e[0],e[1]):Wn(e):ys(e)};var bs=function(e,t){return function(n,s){var r=Ue(n)?he:rt,i=t?t():{};return r(n,e,gs(s),i)}}((function(e,t,n){e[n?0:1].push(t)}),(function(){return[[],[]]}));var ws=function(e,t,n,s){for(var r=e.length,i=n+(s?1:-1);s?i--:++i<r;)if(t(e[i],i,e))return i;return-1};var Ts=function(e){return e!=e};var ks=function(e,t,n){for(var s=n-1,r=e.length;++s<r;)if(e[s]===t)return s;return-1};var Is=function(e,t,n){return t==t?ks(e,t,n):ws(e,Ts,n)};var js=function(e,t){return!!(null==e?0:e.length)&&Is(e,t,0)>-1};var _s=function(e,t,n){for(var s=-1,r=null==e?0:e.length;++s<r;)if(n(t,e[s]))return!0;return!1};var Ss=function(){},Bs=On&&1/pn(new On([,-0]))[1]==1/0?function(e){return new On(e)}:Ss;var Cs=function(e,t,n){var s=-1,r=js,i=e.length,o=!0,a=[],c=a;if(n)o=!1,r=_s;else if(i>=200){var l=t?null:Bs(e);if(l)return pn(l);o=!1,r=ln,c=new an}else c=t?[]:a;e:for(;++s<i;){var h=e[s],u=t?t(h):h;if(h=n||0!==h?h:0,o&&u==u){for(var d=c.length;d--;)if(c[d]===u)continue e;t&&c.push(u),a.push(h)}else r(c,u,n)||(c!==a&&c.push(u),a.push(h))}return a};var Os=function(e,t){return e&&e.length?Cs(e,gs(t)):[]};function As(e){if(e.length<2)return e;const t=[e[0]];for(let n=1;n<e.length;n++){const s=t.length-1,r=t[s],i=e[n];i[0]>r[1]?t.push(i):t[s]=[r[0],new Date(Math.max(+r[1],+i[1]))]}return t}const Es=()=>!0;class Rs extends X{constructor(e){super(),this.camerasStore=e,this.knownIntervals=R(),this.eventsById=new Map,this.updates=0,this.recentAdditions=[],this.update=e=>{e.forEach(e=>{const t=this.eventsById.get(e.id);t&&(t.endTime=e.endTime,this.data.remove(t=>t.id===e.id),this.data.add([t]))})},this.add=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++},this.processNewEvents=({data:e})=>{const t=Os(e.filter(e=>this.camerasStore.camerasById.has(e.cameraId)).reverse(),"id").map(e=>new ie(e)),[n,s]=bs(t,e=>this.eventsById.has(e.id));this.update(n),this.add(s),s.length&&(this.recentAdditions=s.map(e=>e.id))},this.data=R(),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.foundObjects.map(e=>e.Type),!0),this.eventsByColor=this.data.dimension(e=>e.foundObjects.reduce((e,t)=>e.concat(...t.Colors.map(e=>e.Color)),[]),!0),this.eventsByLiveliness=this.data.dimension(e=>e.isLive),this.pendingRequests=R(),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)}fetchEvents(e,t,n){n&&n>new Date&&(n=null);const s=null===n?new Date(Date.now()-6e5):n;-1===e?this.knownIntervalsByCameraId.filter(-1):this.knownIntervalsByCameraId.filter(t=>-1===t||t===e),this.knownIntervalsByStart.filter([-1/0,s]),this.knownIntervalsByEnd.filter([t,1/0]);const r=this.knownIntervalsByStart.bottom(1/0),i=[];if(this.knownIntervalsByCameraId.filterAll(),this.knownIntervalsByStart.filterAll(),this.knownIntervalsByEnd.filterAll(),r.length){const o=As(r.map(e=>[e.from,e.to]));o[0][0]>t&&i.push([t,o[0][0]]);for(let e=0;e<o.length-1;e++)i.push([o[e][1],o[e+1][0]]);o[As.length-1][1]<s&&i.push([o[As.length-1][1],s]),i.length&&(t=i[0][0],+i[i.length-1][1]<=+s&&(n=i[i.length-1][1]),this.knownIntervals.add([{cameraId:e,from:t,to:s}]))}else this.knownIntervals.add([{cameraId:e,from:t,to:s}]);this.pendingRequestsByCameraId.filter(e),this.pendingRequestsByStart.filter(t),this.pendingRequestsByEnd.filter(s);const o=this.pendingRequests.allFiltered()[0];if(this.pendingRequestsByCameraId.filterAll(),this.pendingRequestsByStart.filterAll(),this.pendingRequestsByEnd.filterAll(),o)return o.request;if(r.length&&!i.length)return c([]);const a=this.api.cameras.GetMotionEvents({cameraId:e,startTime:t,endTime:n}).pipe(v(e=>e.success?c(e.motionEventItems.map(e=>new ie(e))):(console.error(e.error),l(e.error))),O());return this.pendingRequests.add([{cameraId:e,startTime:t,endTime:n||new Date,request:a}]),a.pipe(B(()=>this.pendingRequests.remove(e=>e.request===a))).subscribe(this.add),a}getEvents({cameraIds:e,from:t,to:n,objectType:s,colors:r}){this.eventsByStart.filter([+t,n?+n+5e-4:1/0]),s&&this.eventsByFoundObjects.filter(e=>s.includes(e)),e&&this.eventsByCameraId.filter(t=>e.includes(t)),r&&this.eventsByColor.filter(e=>r.has(e));const i=this.eventsByStart.top(1/0);return e&&this.eventsByCameraId.filterAll(),s&&this.eventsByFoundObjects.filterAll(),r&&this.eventsByColor.filterAll(),this.eventsByStart.filterAll(),i}getOverlappedEvents({cameraId:e,from:t,to:n}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([-1/0,+n+5e-4]),this.eventsByLiveliness.filterExact(!0);const s=this.eventsByStart.top(1/0);this.eventsByLiveliness.filterAll(),this.eventsByEnd.filter([+t,1/0]);const r=this.eventsByStart.top(1/0);return this.eventsByCameraId.filterAll(),this.eventsByStart.filterAll(),this.eventsByStart.filterAll(),r.concat(s)}getLastBefore({cameraId:e,date:t}){this.eventsByCameraId.filter(e),this.eventsByEnd.filter([-1/0,+t]),this.eventsByLiveliness.filter(!1),this.eventsByType.filter(re.Default);const n=this.eventsByEnd.top(1);return this.eventsByCameraId.filterAll(),this.eventsByEnd.filterAll(),this.eventsByLiveliness.filterAll(),this.eventsByType.filterAll(),n[0]}getFirstAfter({cameraId:e,date:t}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([+t+5e-4,1/0]),this.eventsByType.filter(re.Default);const n=this.eventsByEnd.bottom(1);return this.eventsByCameraId.filterAll(),this.eventsByStart.filterAll(),this.eventsByType.filterAll(),n[0]}afterInit(){this.api.events.pipe(w(({hub:e,event:t})=>"cameras"===e&&"OnCameraMotionEvent"===t)).subscribe(this.processNewEvents)}dispose(){super.dispose(),this.data.remove(Es),this.updates++}}J([e],Rs.prototype,"updates",void 0),J([e.ref],Rs.prototype,"recentAdditions",void 0),J([n],Rs.prototype,"update",void 0),J([n],Rs.prototype,"add",void 0);class Ds extends X{constructor(){super(),this.toThumbnail=e=>({realtimestamp:t,url:n,width:s,height:r})=>({cameraId:e,url:n,width:s,height:r,timestamp:new Date(t)}),this.thumbnails=R(),this.thumbnailsByCameraId=this.thumbnails.dimension(e=>e.cameraId),this.thumbnailsByDate=this.thumbnails.dimension(e=>+e.timestamp),this.pendingRequests=R(),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,n,s){this.pendingRequestsByCameraId.filter(e),this.pendingRequestsByStart.filter(t),this.pendingRequestsByEnd.filter(n),this.pendingRequestsByCount.filter(s);const r=this.pendingRequests.allFiltered()[0];if(this.pendingRequestsByCameraId.filterAll(),this.pendingRequestsByStart.filterAll(),this.pendingRequestsByEnd.filterAll(),this.pendingRequestsByCount.filterAll(),r)return r.request;const i=this.api.thumbnails.GetThumbnailsInfo({cameraId:e,from:t,to:n,count:s}).pipe(S(e=>e.resultItems),_());return this.pendingRequests.add([{cameraId:e,from:t,to:n,count:s,request:i}]),i.subscribe(t=>{const n=t.filter(e=>e.url).map(this.toThumbnail(e));this.thumbnails.add(n),this.pendingRequests.remove(e=>e.request===i)}),i}getIntervalState(e,t,n){const s=this.getThumbnail({cameraId:e,from:t,to:n});if(s)return{state:"fullfilled",data:s};this.pendingRequestsByCameraId.filter(e),this.pendingRequestsByStart.filter([-1/0,+n+5e-4]),this.pendingRequestsByEnd.filter([t,1/0]);let r=this.pendingRequests.allFiltered();return this.pendingRequestsByCameraId.filterAll(),this.pendingRequestsByStart.filterAll(),this.pendingRequestsByEnd.filterAll(),r=r.filter(e=>1===e.count?+e.from==+t&&+e.to==+n:Math.abs((+e.to-+e.from)/e.count-(+n-+t))<=1),r.length?{state:"pending",request:r[0].request}:null}fetchThumbnail(e,t,n){const s=this.getIntervalState(e,t,n);if(null!==s){if("fullfilled"===s.state)return c(s.data);if("pending"===s.state)return s.request.pipe(S(()=>this.getThumbnail({cameraId:e,from:t,to:n})))}const r=this.api.thumbnails.GetThumbnailInfo({cameraId:e,from:t,to:n}).pipe(S(e=>e.resultItems),_());return r.subscribe(t=>{const n=t.filter(e=>e.url).map(this.toThumbnail(e));this.thumbnails.add(n),this.pendingRequests.remove(e=>e.request===r)}),this.pendingRequests.add([{cameraId:e,from:t,to:n,count:1,request:r}]),r.pipe(S(()=>this.getThumbnail({cameraId:e,from:t,to:n})))}getThumbnail({cameraId:e,from:t,to:n}){this.thumbnailsByCameraId.filter(e),this.thumbnailsByDate.filter([+t,+n+(+t==+n?5e-4:0)]);const s=this.thumbnails.allFiltered()[0];return this.thumbnailsByDate.filterAll(),this.thumbnailsByCameraId.filterAll(),s}getThumbnails({cameraId:e,from:t,to:n}){this.thumbnailsByCameraId.filter(e),this.thumbnailsByDate.filter([+t,+n+5e-4]);const s=this.thumbnails.allFiltered();return this.thumbnailsByDate.filterAll(),this.thumbnailsByCameraId.filterAll(),s}}class Us{constructor(e){this.notifier=e}error(e){this.notifier.error(e)}success(e,t){this.notifier.success(e,t)}warn(e){this.notifier.warn(e)}}const qs=new Map;class Ps{constructor(e){this.name=e,this.cameras=new se,this.archives=new te,this.events=new Rs(this.cameras),this.eventSchema=new le,this.thumbnails=new Ds,this.account=new Y,this.eventList=new oe(this.events),this.notification=new Us({success:console.log,warn:console.warn,error:console.error}),this.disposables=[],this.tokenUpdateReactions=new Set,this.dispose=()=>{this.disposables.forEach(e=>{e instanceof p?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(),qs.delete(this.name)},this.onTokenUpdate=e=>{if(!this.auth)throw new Error("app has to be inited first");const t=r(()=>this.auth.token,t=>e((null==t?void 0:t.json)||null));return this.tokenUpdateReactions.add(t),()=>{t(),this.tokenUpdateReactions.delete(t)}},this.disposables.push(i(()=>!!this.account.user,()=>{this.cameras.fetch()}),i(()=>this.cameras.loaded,()=>{this.eventList.load()}))}init({token:e,tokenStorage:t=new H,tokenStorageKey:n,apiUrl:s="https://services.3deye.me/reactiveapi",tokenServiceUrl:r="https://admin.3deye.me/token",widgetTokenServiceUrl:i="https://admin.3deye.me/widget/token"},o="default"){if(n||(n=`@3deye-toolkit/${o}/token`),qs.has(o))return console.warn("Can`t init two apps with the same name"),qs.get(o);if(this.auth&&o===this.name)return console.warn("Can`t init already inited app"),this;if(this.auth||"default"===this.name&&"default"!==o)return new Ps(o).init({token:e,tokenStorage:t,tokenStorageKey:n,apiUrl:s,tokenServiceUrl:r,widgetTokenServiceUrl:i},o);const a=e&&"clientId"in e?e.clientId:"WebApp";return e&&t.setItem(n,JSON.stringify(e)),this.auth=new V({widgetTokenServiceUrl:i,tokenServiceUrl:r,tokenStorageKey:n,storage:t,clientId:a,deviceInfo:null}),this.api=$.create(x,this.auth,e=>A(s,{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),qs.set(o,this),this}}const Fs=new Ps("default"),xs=q.createContext(null);export{xs as AppContext,Fs as app};
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,Update: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};
@@ -5,7 +5,7 @@
5
5
  "toolPackages": [
6
6
  {
7
7
  "packageName": "@microsoft/api-extractor",
8
- "packageVersion": "7.9.13"
8
+ "packageVersion": "7.18.14"
9
9
  }
10
10
  ]
11
11
  }
package/package.json CHANGED
@@ -1,24 +1,24 @@
1
1
  {
2
2
  "name": "@3deye-toolkit/core",
3
- "version": "0.0.1-alpha.18",
3
+ "version": "0.0.1-alpha.22",
4
4
  "module": "dist/core.js",
5
5
  "types": "dist/core.d.ts",
6
6
  "files": [
7
7
  "dist"
8
8
  ],
9
9
  "dependencies": {
10
- "crossfilter2": "^1.5.2",
11
- "http-status-codes": "^1.3.0",
10
+ "crossfilter2": "^1.5.4",
11
+ "http-status-codes": "^2.1.4",
12
12
  "jqueryless-signalr": "1.0.0",
13
- "lodash": "4.17.19",
14
- "material-colors": "^1.2.5",
15
- "mobx": "^5.15.4",
13
+ "lodash": "4.17.21",
14
+ "material-colors": "^1.2.6",
15
+ "mobx": "^6.3.2",
16
16
  "rxjs": "^6.5.5",
17
- "string-natural-compare": "^2.0.2"
17
+ "string-natural-compare": "^3.0.1"
18
18
  },
19
19
  "peerDependencies": {
20
- "react": "^16.12.x",
21
- "react-dom": "^16.12.x"
20
+ "react": "^16.8.0 || ^17",
21
+ "react-dom": "^16.8.0 || ^17"
22
22
  },
23
23
  "sideEffects": false,
24
24
  "license": "mit"