@3deye-toolkit/core 0.0.9 → 0.0.10

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
@@ -115,7 +115,7 @@ declare class ArchiveChunk implements Chunk {
115
115
  isLive: false;
116
116
  cameraId: number;
117
117
  id: number;
118
- constructor(raw: any);
118
+ constructor(raw: Pick<RawArchiveChunk, 'startTime' | 'endTime' | 'streamUrl' | 'cameraId' | 'id'> & Partial<Omit<RawArchiveChunk, 'startTime' | 'endTime' | 'streamUrl' | 'cameraId' | 'id'>>);
119
119
  }
120
120
 
121
121
  declare class ArchivesStore extends ApiStore {
@@ -129,7 +129,10 @@ declare class ArchivesStore extends ApiStore {
129
129
  private pendingRequestsByEnd;
130
130
  private pendingRequestsByStart;
131
131
  private pendingRequestsByCameraId;
132
- knownIntervals: Map<number, [Date, Date]>;
132
+ knownIntervals: crossfilter.Crossfilter<Interval>;
133
+ knownIntervalsByCameraId: crossfilter.Dimension<Interval, number>;
134
+ knownIntervalsByStart: crossfilter.Dimension<Interval, number>;
135
+ knownIntervalsByEnd: crossfilter.Dimension<Interval, number>;
133
136
  updates: number;
134
137
  constructor(camerasStore: CamerasStore);
135
138
  /**
@@ -141,7 +144,6 @@ declare class ArchivesStore extends ApiStore {
141
144
  * TODO: add error handling
142
145
  */
143
146
  fetch(cameraId: number, startTime: Date, endTime: Date): Observable<ArchiveChunk[]>;
144
- extendKnownInterval(cameraId: number, startTime: Date, chunks: ArchiveChunk[]): void;
145
147
  add(chunks: ArchiveChunk[]): void;
146
148
  getChunks({ cameraId, from, to }: ChunksQuery): ArchiveChunk[];
147
149
  /**
@@ -175,6 +177,25 @@ declare class ArchivesStore extends ApiStore {
175
177
  protected afterInit(): void;
176
178
  }
177
179
 
180
+ declare interface ArchiveWithChunks {
181
+ id: number | null;
182
+ isCurrent: boolean;
183
+ recordType: string | null;
184
+ name: string | null;
185
+ description: string | null;
186
+ tagName: string | null;
187
+ cameraId: number;
188
+ startTime: string;
189
+ endTime: string;
190
+ elapsedTimeSec: number | null;
191
+ thumbnailUrl: string | null;
192
+ validTo: string | null;
193
+ timeCreated: string | null;
194
+ timeUpdated: string | null;
195
+ version: string;
196
+ chunks: RawArchiveChunk[];
197
+ }
198
+
178
199
  declare class Auth {
179
200
  token: Token | null;
180
201
  isAuthenticating: boolean;
@@ -208,7 +229,7 @@ declare interface AuthStoreOptions {
208
229
  tokenServiceUrl: string;
209
230
  storage: Storage_2;
210
231
  tokenStorageKey: string;
211
- deviceInfo: any;
232
+ deviceInfo: string | null;
212
233
  clientId: string;
213
234
  }
214
235
 
@@ -277,6 +298,8 @@ declare class CameraEvent {
277
298
  get acknowledged(): boolean;
278
299
  update: (raw: RawSensorEvent) => void;
279
300
  constructor(raw: RawSensorEvent);
301
+ static fromWebhookEvent: (event: WebhookEvent) => CameraEvent;
302
+ toWebhookEvent: () => WebhookEvent;
280
303
  }
281
304
 
282
305
  declare const enum CameraPermissions {
@@ -320,6 +343,8 @@ declare interface CamgroupItem {
320
343
  declare interface Car {
321
344
  Type: 'Car';
322
345
  BodyType?: string;
346
+ Specialization?: string;
347
+ SpecialPurpose?: string;
323
348
  Box: BoundingBox;
324
349
  Probability: number;
325
350
  Colors?: {
@@ -376,7 +401,7 @@ declare type DeepPartial<T> = {
376
401
  };
377
402
 
378
403
  declare type DetectedObject = Car | LicensePlate | {
379
- Type: 'Person' | 'Animal' | 'Bicycle' | 'Luggage' | 'Boat' | 'HardHat' | 'NoHardHat' | 'Fire' | 'Smoke' | 'Face';
404
+ Type: 'Person' | 'Animal' | 'Bicycle' | 'Luggage' | 'Boat' | 'HardHat' | 'NoHardHat' | 'Vest' | 'NoVest' | 'Gun' | 'Fire' | 'Smoke' | 'Face';
380
405
  Box: BoundingBox;
381
406
  Probability: number;
382
407
  Colors?: {
@@ -432,10 +457,10 @@ declare class EventsStore extends ApiStore {
432
457
  pendingRequestsByEnd: crossfilter.Dimension<PendingRequest, number>;
433
458
  pendingRequestsByStart: crossfilter.Dimension<PendingRequest, number>;
434
459
  pendingRequestsByCameraId: crossfilter.Dimension<PendingRequest, number>;
435
- knownIntervals: crossfilter.Crossfilter<Interval>;
436
- knownIntervalsByCameraId: crossfilter.Dimension<Interval, number>;
437
- knownIntervalsByStart: crossfilter.Dimension<Interval, number>;
438
- knownIntervalsByEnd: crossfilter.Dimension<Interval, number>;
460
+ knownIntervals: crossfilter.Crossfilter<Interval_2>;
461
+ knownIntervalsByCameraId: crossfilter.Dimension<Interval_2, number>;
462
+ knownIntervalsByStart: crossfilter.Dimension<Interval_2, number>;
463
+ knownIntervalsByEnd: crossfilter.Dimension<Interval_2, number>;
439
464
  eventsById: Map<number, CameraEvent>;
440
465
  updates: number;
441
466
  updatesByCameraId: Map<number, number>;
@@ -452,8 +477,10 @@ declare class EventsStore extends ApiStore {
452
477
  * @param endTime - end of the period
453
478
  */
454
479
  populateEvents(cameraId: number, startTime: Date, endTime: Date): void;
455
- update: (data: CameraEvent[]) => void;
456
480
  add: (data: CameraEvent[]) => void;
481
+ processNewEvents: ({ data }: {
482
+ data: RawSensorEvent[];
483
+ }) => void;
457
484
  getEvents({ cameraIds, from, to, detectedObjectTypes, eventTypes, colors, probability }: EventsQuery): CameraEvent[];
458
485
  getOverlappedEvents({ cameraId, from, to }: {
459
486
  cameraId: number;
@@ -488,9 +515,6 @@ declare class EventsStore extends ApiStore {
488
515
  };
489
516
  }): CameraEvent;
490
517
  protected afterInit(): void;
491
- processNewEvents: ({ data }: {
492
- data: RawSensorEvent[];
493
- }) => void;
494
518
  dispose(): void;
495
519
  }
496
520
 
@@ -532,7 +556,7 @@ declare interface IApi {
532
556
  cameraId: number;
533
557
  endTime: Date;
534
558
  startTime: Date;
535
- }) => Observable<any>;
559
+ }) => Observable<ApiResult<ArchiveWithChunks>>;
536
560
  GetArchives: (params: Record<string, never>) => Observable<ApiResult<RawClip>>;
537
561
  GetClips: () => Observable<any>;
538
562
  UpdateClip: (params: any) => Observable<any>;
@@ -587,6 +611,8 @@ declare interface IApi {
587
611
  };
588
612
  sound: {
589
613
  GetPushSoundServiceUrl: (id: number) => Observable<ApiResult<string>>;
614
+ GenerateSpeech: (text: string) => Observable<ApiResult<string>>;
615
+ SendText: (cameras: number[], text: string) => Observable<ApiResult<string>>;
590
616
  };
591
617
  thumbnails: {
592
618
  GetThumbnailsInfo: (params: {
@@ -631,6 +657,12 @@ declare interface Interval {
631
657
  to: Date;
632
658
  }
633
659
 
660
+ declare interface Interval_2 {
661
+ cameraId: number;
662
+ from: Date;
663
+ to: Date;
664
+ }
665
+
634
666
  declare type IntervalState = {
635
667
  state: 'fulfilled';
636
668
  data: Thumbnail;
@@ -873,6 +905,20 @@ declare const preferencesSchema: z.ZodObject<{
873
905
  startOfWeek?: "monday" | "sunday" | undefined;
874
906
  }>;
875
907
 
908
+ declare interface RawArchiveChunk {
909
+ id: number;
910
+ tagName: string | null;
911
+ description: string;
912
+ cameraId: number;
913
+ startTime: string;
914
+ endTime: string;
915
+ elapsedTime: number;
916
+ streamUrl: string;
917
+ isDvr: boolean;
918
+ thumbnailUrl: string;
919
+ duration?: number;
920
+ }
921
+
876
922
  declare interface RawCamera {
877
923
  id: number;
878
924
  customerId: number;
@@ -1090,6 +1136,7 @@ declare interface SensorEventsRequest {
1090
1136
  sensorIds: number[];
1091
1137
  sensorType: string;
1092
1138
  sensorEventTypes: SensorEventType[];
1139
+ acknowledged?: boolean | null;
1093
1140
  startTime?: Date;
1094
1141
  endTime?: Date;
1095
1142
  isDescending: boolean;
@@ -1242,4 +1289,62 @@ declare class ToolkitApp implements App {
1242
1289
 
1243
1290
  declare type User = RawUser;
1244
1291
 
1292
+ declare type WebhookEvent = {
1293
+ id: number;
1294
+ deviceId: number;
1295
+ ackType?: string;
1296
+ ackData?: {
1297
+ timestampUtc: string;
1298
+ message: string;
1299
+ translatedMessage?: string;
1300
+ editedMessage?: string;
1301
+ userId: string;
1302
+ };
1303
+ } & ({
1304
+ type: Exclude<EventType, 'LicensePlate' | 'Analytic'>;
1305
+ data: {
1306
+ thumbnailUrl: string;
1307
+ sharedVideoUrl?: string;
1308
+ } & ({
1309
+ timestampUtc: string;
1310
+ } | {
1311
+ startTimeUtc: string;
1312
+ endTimeUtc: string;
1313
+ });
1314
+ } | {
1315
+ type: 'Analytic';
1316
+ data: {
1317
+ objectsFound: {
1318
+ type: string;
1319
+ box: {
1320
+ left: number;
1321
+ top: number;
1322
+ right: number;
1323
+ bottom: number;
1324
+ };
1325
+ probability: number;
1326
+ }[];
1327
+ thumbnailUrl: string;
1328
+ sharedVideoUrl?: string;
1329
+ timestampUtc: string;
1330
+ };
1331
+ } | {
1332
+ type: 'LicensePlateRecognition';
1333
+ data: {
1334
+ platesFound: {
1335
+ box: {
1336
+ left: number;
1337
+ top: number;
1338
+ right: number;
1339
+ bottom: number;
1340
+ };
1341
+ probability: number;
1342
+ plateNumber: string;
1343
+ }[];
1344
+ thumbnailUrl: string;
1345
+ sharedVideoUrl?: string;
1346
+ timestampUtc: string;
1347
+ };
1348
+ });
1349
+
1245
1350
  export { }
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- import e from"jqueryless-signalr";import{makeObservable as t,observable as n,action as s,computed as r,reaction as i,when as a,runInAction as o,observe as u}from"mobx";import{Subscription as c,filter as l,map as h,mergeMap as d,of as p,throwError as f,tap as m,shareReplay as v,retry as y,expand as g,EMPTY as b,last as I,Subject as w,skip as T,exhaustMap as k,takeUntil as S,share as _,BehaviorSubject as C,switchMap as B,timer as O,take as A,catchError as E,Observable as j,startWith as R,pairwise as N,concatMap as U}from"rxjs";import q from"string-natural-compare";import D from"crossfilter2";import{z as P}from"zod";import x from"react";var F="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function M(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var z="object"==typeof F&&F&&F.Object===Object&&F,W=z,L="object"==typeof self&&self&&self.Object===Object&&self,G=W||L||Function("return this")(),V=G.Symbol,$=V,H=Object.prototype,Y=H.hasOwnProperty,K=H.toString,J=$?$.toStringTag:void 0;var Z=function(e){var t=Y.call(e,J),n=e[J];try{e[J]=void 0;var s=!0}catch(e){}var r=K.call(e);return s&&(t?e[J]=n:delete e[J]),r},Q=Object.prototype.toString;var X=Z,ee=function(e){return Q.call(e)},te=V?V.toStringTag:void 0;var ne=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":te&&te in Object(e)?X(e):ee(e)};var se=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},re=ne,ie=se;var ae,oe=function(e){if(!ie(e))return!1;var t=re(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t},ue=G["__core-js_shared__"],ce=(ae=/[^.]+$/.exec(ue&&ue.keys&&ue.keys.IE_PROTO||""))?"Symbol(src)_1."+ae:"";var le=function(e){return!!ce&&ce in e},he=Function.prototype.toString;var de=function(e){if(null!=e){try{return he.call(e)}catch(e){}try{return e+""}catch(e){}}return""},pe=oe,fe=le,me=se,ve=de,ye=/^\[object .+?Constructor\]$/,ge=Function.prototype,be=Object.prototype,Ie=ge.toString,we=be.hasOwnProperty,Te=RegExp("^"+Ie.call(we).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var ke=function(e){return!(!me(e)||fe(e))&&(pe(e)?Te:ye).test(ve(e))},Se=function(e,t){return null==e?void 0:e[t]};var _e=function(e,t){var n=Se(e,t);return ke(n)?n:void 0},Ce=_e(Object,"create"),Be=Ce;var Oe=function(){this.__data__=Be?Be(null):{},this.size=0};var Ae=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Ee=Ce,je=Object.prototype.hasOwnProperty;var Re=function(e){var t=this.__data__;if(Ee){var n=t[e];return"__lodash_hash_undefined__"===n?void 0:n}return je.call(t,e)?t[e]:void 0},Ne=Ce,Ue=Object.prototype.hasOwnProperty;var qe=Ce;var De=Oe,Pe=Ae,xe=Re,Fe=function(e){var t=this.__data__;return Ne?void 0!==t[e]:Ue.call(t,e)},Me=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=qe&&void 0===t?"__lodash_hash_undefined__":t,this};function ze(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])}}ze.prototype.clear=De,ze.prototype.delete=Pe,ze.prototype.get=xe,ze.prototype.has=Fe,ze.prototype.set=Me;var We=ze;var Le=function(){this.__data__=[],this.size=0};var Ge=function(e,t){return e===t||e!=e&&t!=t},Ve=Ge;var $e=function(e,t){for(var n=e.length;n--;)if(Ve(e[n][0],t))return n;return-1},He=$e,Ye=Array.prototype.splice;var Ke=$e;var Je=$e;var Ze=$e;var Qe=Le,Xe=function(e){var t=this.__data__,n=He(t,e);return!(n<0)&&(n==t.length-1?t.pop():Ye.call(t,n,1),--this.size,!0)},et=function(e){var t=this.__data__,n=Ke(t,e);return n<0?void 0:t[n][1]},tt=function(e){return Je(this.__data__,e)>-1},nt=function(e,t){var n=this.__data__,s=Ze(n,e);return s<0?(++this.size,n.push([e,t])):n[s][1]=t,this};function st(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])}}st.prototype.clear=Qe,st.prototype.delete=Xe,st.prototype.get=et,st.prototype.has=tt,st.prototype.set=nt;var rt=st,it=_e(G,"Map"),at=We,ot=rt,ut=it;var ct=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 n=e.__data__;return ct(t)?n["string"==typeof t?"string":"hash"]:n.map},ht=lt;var dt=lt;var pt=lt;var ft=lt;var mt=function(){this.size=0,this.__data__={hash:new at,map:new(ut||ot),string:new at}},vt=function(e){var t=ht(this,e).delete(e);return this.size-=t?1:0,t},yt=function(e){return dt(this,e).get(e)},gt=function(e){return pt(this,e).has(e)},bt=function(e,t){var n=ft(this,e),s=n.size;return n.set(e,t),this.size+=n.size==s?0:1,this};function It(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])}}It.prototype.clear=mt,It.prototype.delete=vt,It.prototype.get=yt,It.prototype.has=gt,It.prototype.set=bt;var wt=It,Tt=wt;function kt(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 a=e.apply(this,s);return n.cache=i.set(r,a)||i,a};return n.cache=new(kt.Cache||Tt),n}kt.Cache=Tt;var St=kt;class _t{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)}}function Ct(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 Bt=()=>!0;class Ot{api;disposables=[];initWith(e){this.api=e,this.afterInit&&this.afterInit()}dispose(){for(const e of this.disposables)e instanceof c?e.closed||e.unsubscribe():e()}}var At;!function(e){e.DEFAULT_VIDEO_RESIZE_MODE="defaultVideoResizeMode",e.RESIZE_MODE_PER_CAMERA="camerasResizeMode",e.FISHEYE_CAMERAS="fisheyeCameras",e.UTC="utc",e.HOUR12="hour12",e.START_OF_WEEK="startOfWeek"}(At||(At={}));const Et=P.enum(["fill","contain"]),jt=P.object({lat:P.number(),lon:P.number(),fov:P.number()}),Rt=P.object({params:P.object({x:P.number(),y:P.number(),r:P.number(),s:P.number()}),positions:P.tuple([jt,jt,jt]).optional()}),Nt=P.tuple([P.number(),P.number(),P.number()]),Ut=P.object({[At.DEFAULT_VIDEO_RESIZE_MODE]:Et.optional(),[At.RESIZE_MODE_PER_CAMERA]:P.array(P.tuple([P.number(),Et])).optional(),[At.FISHEYE_CAMERAS]:P.array(P.tuple([P.number(),P.union([Nt,Rt,P.null()])])).optional(),[At.UTC]:P.boolean().default(!1),[At.HOUR12]:P.boolean().default(!1),[At.START_OF_WEEK]:P.enum(["monday","sunday"]).default("monday")});class qt extends Ot{notification;user=null;auth;constructor(e){super(),this.notification=e,t(this,{user:n.ref,setUser:s,userDisplayName:r,preferences:r,isSharingUserAccount:r})}get isSharingUserAccount(){return this.user?.email.endsWith("@share.share")||!1}get userDisplayName(){return this.user?this.user.firstName?.trim()||this.user.lastName?.trim()?[this.user.firstName,this.user.lastName].filter(Boolean).join(" ").trim():this.user.email:null}afterInit(){this.disposables.push(this.api.events.pipe(l((({hub:e,event:t})=>"users"===e&&"OnUserUpdateProfile"===t)),h((({data:e})=>e.resultItems[0]))).subscribe(this.setUser))}loadUser$(){return this.api.users.GetUser().pipe(d((e=>e.success?p(e.resultItems[0]):f((()=>e.error)))),m(this.setUser),v(1))}setUser=e=>{this.user=e};setAuthStore(e){this.auth=e,this.disposables.push(i((()=>this.auth.isAuthenticated),(()=>{this.auth.isAuthenticated&&this.loadUser$().subscribe()})))}async updateUserPassword(e){const t=function(){throw new Error("Config not initialized")}().changePasswordUrl,n=this.auth?.token?.accessToken,s=JSON.stringify({currentPassword:e.previous,newPassword:e.new}),r=new Headers;r.append("content-type","application/json"),r.append("accept","application/json"),r.append("authorization",`bearer ${n}`);const i=await fetch(t,{method:"PUT",headers:r,body:s}),{status:a}=i;if(200!==a){const e=await i.json();throw new Error(e.errors[0].message)}}updateUserSettings({firstName:e,lastName:t}){const n=p(null).pipe(d((()=>{if(!this.user)throw new Error("user is not initialized");return this.api.users.UserUpdateProfile({id:this.user.id,firstName:e,lastName:t,version:this.user.version})})),d((e=>e.success?p(e.resultItems[0]):f((()=>e.error)))),this.retryOnVersionMismatch(),v());return n.subscribe((e=>{this.setUser(e)})),n}updateUserLanguage(e){const t=p(null).pipe(d((()=>{if(!this.user)throw new Error("user is not initialized");return this.api.users.UserUpdateProfile({id:this.user.id,languageCode:e,version:this.user.version})})),d((e=>e.success?p(e.resultItems[0]):f((()=>e.error)))),this.retryOnVersionMismatch(),v());return t.subscribe((e=>{this.setUser(e)})),t}updateCustomPreferences=e=>{const t=p(null).pipe(d((()=>{if(!this.user)return f((()=>"user is not initialized"));const t={id:this.user.id,jsonField:JSON.stringify({...JSON.parse(this.user.jsonField||"{}"),...e}),version:this.user.version};return this.api.users.UserUpdateProfile(t)})),d((e=>e.success?p(e.resultItems[0]):f((()=>e.error)))),this.retryOnVersionMismatch(),v());return t.subscribe((e=>{this.setUser(e)})),t};setDefaultGroup(e){const t=p(null).pipe(d((()=>{if(!this.user)return f((()=>"user is not initialized"));const t={id:this.user.id,layoutStartId:e,layoutStartType:"camgroup",version:this.user.version};return this.api.users.UserUpdateProfile(t)})),d((e=>e.success?p(e.resultItems[0]):f((()=>e.error)))),this.retryOnVersionMismatch(),v());return t.subscribe({next:e=>{this.setUser(e),this.notification?.success("Successfully set default group")},error:e=>{console.error(e),this.notification?.error(e.message)}}),t}get preferences(){try{return Ut.parse(JSON.parse(this.user?.jsonField||"{}"))}catch(e){console.error(e)}return{[At.DEFAULT_VIDEO_RESIZE_MODE]:void 0,[At.RESIZE_MODE_PER_CAMERA]:void 0,[At.FISHEYE_CAMERAS]:void 0,[At.UTC]:!1,[At.HOUR12]:!1,[At.START_OF_WEEK]:"monday"}}getPreference=e=>this.preferences[e];retryOnVersionMismatch=()=>y({delay:(e,t)=>t>1?f((()=>e)):-4===e?.code?this.loadUser$():f((()=>e))})}class Dt{json;startTime;endTime;streamUrl;duration;isLive=!1;cameraId;id;constructor(e){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}}class Pt{id;name;imageUrl;streamUrl;dashStreamUrl;address;archiveDuration;dvrWindowLength;stateUpdatedAt;raw;enabled;isMicEnabled;state;pin;webRtcUrl;isPtz;permissions;get isOnline(){return this.enabled&&"Started"===this.state}get supportsWebRTC(){return!!this.webRtcUrl}constructor(e){t(this,{name:n,streamUrl:n,dashStreamUrl:n,enabled:n,isMicEnabled:n,state:n,pin:n,webRtcUrl:n,permissions:n,isOnline:r,update:s}),this.update(e)}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.permissions=e.permissions||0,this.stateUpdatedAt=new Date(e.cameraStateChangedTime)};can=e=>!!(this.permissions&e)}var xt;!function(e){e[e.View=1]="View",e[e.SaveClip=2]="SaveClip",e[e.Share=4]="Share",e[e.Ptz=8]="Ptz",e[e.EditSettings=16]="EditSettings",e[e.Timelapse=32]="Timelapse",e[e.Delete=64]="Delete"}(xt||(xt={}));const Ft=new Set(["LicensePlate","FaceDetection","Analytic","SpeedDetection","Temperature","PoS","GPS","DigitalInput","Loitering"]);class Mt{id;cameraId;type;raw;thumbnailUrl;thumbnailWidth=0;thumbnailHeight=0;detectedObjects;faces;instant;get startTime(){return new Date(this.raw.startTime)}get endTime(){return new Date(this.raw.endTime)}get isLive(){return!Ft.has(this.type)&&+this.startTime==+this.endTime}get acknowledged(){return"sensorId"in this.raw&&!!this.raw.ackEventType}update=e=>{this.raw=e};constructor(e){if(t(this,{startTime:r,endTime:r,acknowledged:r,isLive:r,raw:n.ref,update:s}),this.raw=e,this.id=e.id,this.type=e.eventType,this.cameraId=e.sensorId,("Analytic"===this.type||"FaceDetection"===this.type||"Loitering"===this.type)&&e.data)try{const t=JSON.parse(e.data);t.FoundObjects&&(this.detectedObjects=t.FoundObjects),t.Faces&&(this.type="FaceDetection",this.faces=t.Faces),t.ThumbnailSize&&(this.thumbnailWidth=t.ThumbnailSize.Width,this.thumbnailHeight=t.ThumbnailSize.Height),this.thumbnailUrl=t.ThumbnailUrl}catch{console.warn("invalid data",e.data),this.type="Motion"}this.instant=Ft.has(this.type),this.detectedObjects||(this.detectedObjects=[])}}const zt=5e-4;class Wt extends Ot{camerasStore;data;chunksByCameraId;chunksByStart;chunksByEnd;chunksById=new Map;pendingRequests;pendingRequestsByEnd;pendingRequestsByStart;pendingRequestsByCameraId;knownIntervals=new Map;updates=0;constructor(e){super(),this.camerasStore=e,t(this,{updates:n,add:s.bound}),this.data=D(),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=D(),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 p(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(h((e=>e.resultItems[0].chunks.map((e=>new Dt(e))))),m(this.add),m((n=>this.extendKnownInterval(e,t,n))),v());return this.pendingRequests.add([{cameraId:e,startTime:t,endTime:n,request:r}]),r.pipe(m((()=>this.pendingRequests.remove((e=>e.request===r))))).subscribe(),r}extendKnownInterval(e,t,n){t=new Date(Math.min(+t,...n.map((e=>+e.startTime))));const s=new Date(Math.max(...n.map((e=>+e.endTime))));if(this.knownIntervals.has(e)){const n=this.knownIntervals.get(e);t<n[0]&&(n[0]=t),s>n[1]&&(n[1]=s)}else this.knownIntervals.set(e,[t,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+zt]),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}getClosestChunkRight=({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]};getClosestChunkLeft=({cameraId:e,time:t})=>{this.chunksByCameraId.filter(e),this.chunksByStart.filter([-1/0,+t+zt]);const n=this.chunksByStart.top(1);return this.chunksByCameraId.filterAll(),this.chunksByEnd.filterAll(),n[0]};fetchNextChunk=({cameraId:e,time:t})=>{if(this.knownIntervals.has(e)){const[n,s]=this.knownIntervals.get(e);if(n<=t&&s>=t){const n=this.getClosestChunkRight({cameraId:e,time:t});if(n)return p(n)}}return p({result:[],time:t}).pipe(g((({result:t,time:n})=>{if(t.length||n>=new Date)return b;const s=new Date(+n+36e5);return this.fetch(e,n,s).pipe(h((e=>({result:e,time:s}))))})),I(),h((()=>this.getClosestChunkRight({cameraId:e,time:t}))))};fetchPrevChunk=({cameraId:e,time:t})=>{if(this.knownIntervals.has(e)){const[n,s]=this.knownIntervals.get(e);if(n<=t&&s>=t){const n=this.getClosestChunkLeft({cameraId:e,time:t});if(n)return p(n)}}const n=this.camerasStore.camerasById.get(e);if(!n)return p(void 0);const s=new Date(Date.now()-3600*n.archiveDuration*1e3);return this.knownIntervals.get(e)&&this.knownIntervals.get(e)[0]<=s?p(void 0):p({result:[],time:t}).pipe(g((({result:t,time:n})=>{if(t.length||n<=s)return b;const r=new Date(Math.max(+n-36e5,+s));return this.fetch(e,r,n).pipe(h((e=>({result:e,time:r}))))})),I(),h((()=>this.getClosestChunkRight({cameraId:e,time:t}))))};afterInit(){this.api.events.pipe(l((({hub:e,event:t})=>"archives"===e&&"OnArchiveChunksCreated"===t))).subscribe((({data:e})=>{this.add(e.resultItems.map((e=>new Dt(e))))}))}}class Lt extends Ot{camerasById=new Map;data=[];loading=!1;loaded=!1;pendingLoadRequest;requestsCanceler=new w;constructor(){super(),t(this,{data:n.ref,loading:n,loaded:n,add:s}),this.disposables.push(a((()=>this.loaded),(()=>{this.api.connection$.pipe(T(1),k((()=>this.sync()))).subscribe()})))}load=()=>{if(this.loaded)return p([]);if(this.pendingLoadRequest)return this.pendingLoadRequest;o((()=>{this.loading=!0})),this.pendingLoadRequest=this.api.cameras.GetCameras({},null).pipe(d((e=>e.success?p(e.resultItems):(console.error(e.error),f((()=>e.error))))),v(1),S(this.requestsCanceler));const e=this.pendingLoadRequest;return e.subscribe((e=>{this.pendingLoadRequest=void 0,o((()=>{this.add(e),this.loading=!1,this.loaded=!0}))})),e};add=e=>{for(const t of e)this.camerasById.has(t.id)?this.camerasById.get(t.id)?.update(t):this.camerasById.set(t.id,new Pt(t));this.data=Array.from(this.camerasById.values()).sort(((e,t)=>q(e.name,t.name,{caseInsensitive:!0})))};sync=()=>{const e=this.data.reduce(((e,t)=>Math.max(e,+t.stateUpdatedAt)),0);if(!e)return b;const t=this.api.cameras.GetCameras({},new Date(1e3*(Math.floor(e/1e3)+1))).pipe(d((e=>e.success?p(e.resultItems):(console.error(e.error),f((()=>e.error))))),v(1),S(this.requestsCanceler));return t.subscribe((e=>this.add(e))),t};afterInit(){this.disposables.push(this.api.events.pipe(l((({hub:e,event:t})=>"cameras"===e&&("OnCameraUpdated"===t||"OnSystemCameraUpdated"===t))),h((({data:e,event:t})=>"resultItems"in e?{data:e.resultItems[0],event:t}:{data:e,event:t}))).subscribe((({data:e,event:t})=>{const n=this.camerasById.get(e.id);if(!n)return console.warn("got update for unknown camera:",e.id);if("OnSystemCameraUpdated"===t){const t=n.raw;for(const[n,s]of Object.entries(e))null===s&&(e[n]=t[n])}n.update(e)})))}dispose(){this.requestsCanceler.next(),this.camerasById.clear(),this.data=[],this.loading=!1,this.loaded=!1,super.dispose()}}var Gt=function(e,t,n,s){for(var r=-1,i=null==e?0:e.length;++r<i;){var a=e[r];t(s,a,n(a),e)}return s};var Vt=function(e){return function(t,n,s){for(var r=-1,i=Object(t),a=s(t),o=a.length;o--;){var u=a[e?o:++r];if(!1===n(i[u],u,i))break}return t}}();var $t=function(e,t){for(var n=-1,s=Array(e);++n<e;)s[n]=t(n);return s};var Ht=function(e){return null!=e&&"object"==typeof e},Yt=ne,Kt=Ht;var Jt=function(e){return Kt(e)&&"[object Arguments]"==Yt(e)},Zt=Ht,Qt=Object.prototype,Xt=Qt.hasOwnProperty,en=Qt.propertyIsEnumerable,tn=Jt(function(){return arguments}())?Jt:function(e){return Zt(e)&&Xt.call(e,"callee")&&!en.call(e,"callee")},nn=Array.isArray,sn={exports:{}};var rn=function(){return!1};!function(e,t){var n=G,s=rn,r=t&&!t.nodeType&&t,i=r&&e&&!e.nodeType&&e,a=i&&i.exports===r?n.Buffer:void 0,o=(a?a.isBuffer:void 0)||s;e.exports=o}(sn,sn.exports);var an=sn.exports,on=/^(?:0|[1-9]\d*)$/;var un=function(e,t){var n=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==n||"symbol"!=n&&on.test(e))&&e>-1&&e%1==0&&e<t};var cn=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991},ln=ne,hn=cn,dn=Ht,pn={};pn["[object Float32Array]"]=pn["[object Float64Array]"]=pn["[object Int8Array]"]=pn["[object Int16Array]"]=pn["[object Int32Array]"]=pn["[object Uint8Array]"]=pn["[object Uint8ClampedArray]"]=pn["[object Uint16Array]"]=pn["[object Uint32Array]"]=!0,pn["[object Arguments]"]=pn["[object Array]"]=pn["[object ArrayBuffer]"]=pn["[object Boolean]"]=pn["[object DataView]"]=pn["[object Date]"]=pn["[object Error]"]=pn["[object Function]"]=pn["[object Map]"]=pn["[object Number]"]=pn["[object Object]"]=pn["[object RegExp]"]=pn["[object Set]"]=pn["[object String]"]=pn["[object WeakMap]"]=!1;var fn=function(e){return dn(e)&&hn(e.length)&&!!pn[ln(e)]};var mn=function(e){return function(t){return e(t)}},vn={exports:{}};!function(e,t){var n=z,s=t&&!t.nodeType&&t,r=s&&e&&!e.nodeType&&e,i=r&&r.exports===s&&n.process,a=function(){try{var e=r&&r.require&&r.require("util").types;return e||i&&i.binding&&i.binding("util")}catch(e){}}();e.exports=a}(vn,vn.exports);var yn=vn.exports,gn=fn,bn=mn,In=yn&&yn.isTypedArray,wn=In?bn(In):gn,Tn=$t,kn=tn,Sn=nn,_n=an,Cn=un,Bn=wn,On=Object.prototype.hasOwnProperty;var An=function(e,t){var n=Sn(e),s=!n&&kn(e),r=!n&&!s&&_n(e),i=!n&&!s&&!r&&Bn(e),a=n||s||r||i,o=a?Tn(e.length,String):[],u=o.length;for(var c in e)!t&&!On.call(e,c)||a&&("length"==c||r&&("offset"==c||"parent"==c)||i&&("buffer"==c||"byteLength"==c||"byteOffset"==c)||Cn(c,u))||o.push(c);return o},En=Object.prototype;var jn=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||En)};var Rn=function(e,t){return function(n){return e(t(n))}}(Object.keys,Object),Nn=jn,Un=Rn,qn=Object.prototype.hasOwnProperty;var Dn=oe,Pn=cn;var xn=function(e){return null!=e&&Pn(e.length)&&!Dn(e)},Fn=An,Mn=function(e){if(!Nn(e))return Un(e);var t=[];for(var n in Object(e))qn.call(e,n)&&"constructor"!=n&&t.push(n);return t},zn=xn;var Wn=function(e){return zn(e)?Fn(e):Mn(e)},Ln=Vt,Gn=Wn;var Vn=xn;var $n=function(e,t){return function(n,s){if(null==n)return n;if(!Vn(n))return e(n,s);for(var r=n.length,i=t?r:-1,a=Object(n);(t?i--:++i<r)&&!1!==s(a[i],i,a););return n}}((function(e,t){return e&&Ln(e,t,Gn)}));var Hn=function(e,t,n,s){return $n(e,(function(e,r,i){t(s,e,n(e),i)})),s},Yn=rt;var Kn=rt,Jn=it,Zn=wt;var Qn=rt,Xn=function(){this.__data__=new Yn,this.size=0},es=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n},ts=function(e){return this.__data__.get(e)},ns=function(e){return this.__data__.has(e)},ss=function(e,t){var n=this.__data__;if(n instanceof Kn){var s=n.__data__;if(!Jn||s.length<199)return s.push([e,t]),this.size=++n.size,this;n=this.__data__=new Zn(s)}return n.set(e,t),this.size=n.size,this};function rs(e){var t=this.__data__=new Qn(e);this.size=t.size}rs.prototype.clear=Xn,rs.prototype.delete=es,rs.prototype.get=ts,rs.prototype.has=ns,rs.prototype.set=ss;var is=rs;var as=wt,os=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this},us=function(e){return this.__data__.has(e)};function cs(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new as;++t<n;)this.add(e[t])}cs.prototype.add=cs.prototype.push=os,cs.prototype.has=us;var ls=cs;var hs=function(e,t){return e.has(t)},ds=ls,ps=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},fs=hs;var ms=function(e,t,n,s,r,i){var a=1&n,o=e.length,u=t.length;if(o!=u&&!(a&&u>o))return!1;var c=i.get(e),l=i.get(t);if(c&&l)return c==t&&l==e;var h=-1,d=!0,p=2&n?new ds:void 0;for(i.set(e,t),i.set(t,e);++h<o;){var f=e[h],m=t[h];if(s)var v=a?s(m,f,h,t,e,i):s(f,m,h,e,t,i);if(void 0!==v){if(v)continue;d=!1;break}if(p){if(!ps(t,(function(e,t){if(!fs(p,t)&&(f===e||r(f,e,n,s,i)))return p.push(t)}))){d=!1;break}}else if(f!==m&&!r(f,m,n,s,i)){d=!1;break}}return i.delete(e),i.delete(t),d};var vs=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e,s){n[++t]=[s,e]})),n};var ys=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n},gs=G.Uint8Array,bs=Ge,Is=ms,ws=vs,Ts=ys,ks=V?V.prototype:void 0,Ss=ks?ks.valueOf:void 0;var _s=function(e,t,n,s,r,i,a){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 gs(e),new gs(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return bs(+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=ws;case"[object Set]":var u=1&s;if(o||(o=Ts),e.size!=t.size&&!u)return!1;var c=a.get(e);if(c)return c==t;s|=2,a.set(e,t);var l=Is(o(e),o(t),s,r,i,a);return a.delete(e),l;case"[object Symbol]":if(Ss)return Ss.call(e)==Ss.call(t)}return!1};var Cs=function(e,t){for(var n=-1,s=t.length,r=e.length;++n<s;)e[r+n]=t[n];return e},Bs=nn;var Os=function(e,t,n){var s=t(e);return Bs(e)?s:Cs(s,n(e))};var As=function(e,t){for(var n=-1,s=null==e?0:e.length,r=0,i=[];++n<s;){var a=e[n];t(a,n,e)&&(i[r++]=a)}return i},Es=function(){return[]},js=Object.prototype.propertyIsEnumerable,Rs=Object.getOwnPropertySymbols,Ns=Os,Us=Rs?function(e){return null==e?[]:(e=Object(e),As(Rs(e),(function(t){return js.call(e,t)})))}:Es,qs=Wn;var Ds=function(e){return Ns(e,qs,Us)},Ps=Object.prototype.hasOwnProperty;var xs=function(e,t,n,s,r,i){var a=1&n,o=Ds(e),u=o.length;if(u!=Ds(t).length&&!a)return!1;for(var c=u;c--;){var l=o[c];if(!(a?l in t:Ps.call(t,l)))return!1}var h=i.get(e),d=i.get(t);if(h&&d)return h==t&&d==e;var p=!0;i.set(e,t),i.set(t,e);for(var f=a;++c<u;){var m=e[l=o[c]],v=t[l];if(s)var y=a?s(v,m,l,t,e,i):s(m,v,l,e,t,i);if(!(void 0===y?m===v||r(m,v,n,s,i):y)){p=!1;break}f||(f="constructor"==l)}if(p&&!f){var g=e.constructor,b=t.constructor;g==b||!("constructor"in e)||!("constructor"in t)||"function"==typeof g&&g instanceof g&&"function"==typeof b&&b instanceof b||(p=!1)}return i.delete(e),i.delete(t),p},Fs=_e(G,"DataView"),Ms=_e(G,"Promise"),zs=_e(G,"Set"),Ws=Fs,Ls=it,Gs=Ms,Vs=zs,$s=_e(G,"WeakMap"),Hs=ne,Ys=de,Ks="[object Map]",Js="[object Promise]",Zs="[object Set]",Qs="[object WeakMap]",Xs="[object DataView]",er=Ys(Ws),tr=Ys(Ls),nr=Ys(Gs),sr=Ys(Vs),rr=Ys($s),ir=Hs;(Ws&&ir(new Ws(new ArrayBuffer(1)))!=Xs||Ls&&ir(new Ls)!=Ks||Gs&&ir(Gs.resolve())!=Js||Vs&&ir(new Vs)!=Zs||$s&&ir(new $s)!=Qs)&&(ir=function(e){var t=Hs(e),n="[object Object]"==t?e.constructor:void 0,s=n?Ys(n):"";if(s)switch(s){case er:return Xs;case tr:return Ks;case nr:return Js;case sr:return Zs;case rr:return Qs}return t});var ar=is,or=ms,ur=_s,cr=xs,lr=ir,hr=nn,dr=an,pr=wn,fr="[object Arguments]",mr="[object Array]",vr="[object Object]",yr=Object.prototype.hasOwnProperty;var gr=function(e,t,n,s,r,i){var a=hr(e),o=hr(t),u=a?mr:lr(e),c=o?mr:lr(t),l=(u=u==fr?vr:u)==vr,h=(c=c==fr?vr:c)==vr,d=u==c;if(d&&dr(e)){if(!dr(t))return!1;a=!0,l=!1}if(d&&!l)return i||(i=new ar),a||pr(e)?or(e,t,n,s,r,i):ur(e,t,u,n,s,r,i);if(!(1&n)){var p=l&&yr.call(e,"__wrapped__"),f=h&&yr.call(t,"__wrapped__");if(p||f){var m=p?e.value():e,v=f?t.value():t;return i||(i=new ar),r(m,v,n,s,i)}}return!!d&&(i||(i=new ar),cr(e,t,n,s,r,i))},br=Ht;var Ir=function e(t,n,s,r,i){return t===n||(null==t||null==n||!br(t)&&!br(n)?t!=t&&n!=n:gr(t,n,s,r,e,i))},wr=is,Tr=Ir;var kr=se;var Sr=function(e){return e==e&&!kr(e)},_r=Sr,Cr=Wn;var Br=function(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in Object(n)))}},Or=function(e,t,n,s){var r=n.length,i=r,a=!s;if(null==e)return!i;for(e=Object(e);r--;){var o=n[r];if(a&&o[2]?o[1]!==e[o[0]]:!(o[0]in e))return!1}for(;++r<i;){var u=(o=n[r])[0],c=e[u],l=o[1];if(a&&o[2]){if(void 0===c&&!(u in e))return!1}else{var h=new wr;if(s)var d=s(c,l,u,e,t,h);if(!(void 0===d?Tr(l,c,3,s,h):d))return!1}}return!0},Ar=function(e){for(var t=Cr(e),n=t.length;n--;){var s=t[n],r=e[s];t[n]=[s,r,_r(r)]}return t},Er=Br;var jr=function(e){var t=Ar(e);return 1==t.length&&t[0][2]?Er(t[0][0],t[0][1]):function(n){return n===e||Or(n,e,t)}},Rr=ne,Nr=Ht;var Ur=function(e){return"symbol"==typeof e||Nr(e)&&"[object Symbol]"==Rr(e)},qr=nn,Dr=Ur,Pr=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,xr=/^\w*$/;var Fr=function(e,t){if(qr(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!Dr(e))||(xr.test(e)||!Pr.test(e)||null!=t&&e in Object(t))},Mr=St;var zr=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Wr=/\\(\\)?/g,Lr=function(e){var t=Mr(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(zr,(function(e,n,s,r){t.push(s?r.replace(Wr,"$1"):n||e)})),t}));var Gr=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},Vr=nn,$r=Ur,Hr=V?V.prototype:void 0,Yr=Hr?Hr.toString:void 0;var Kr=function e(t){if("string"==typeof t)return t;if(Vr(t))return Gr(t,e)+"";if($r(t))return Yr?Yr.call(t):"";var n=t+"";return"0"==n&&1/t==-1/0?"-0":n},Jr=Kr;var Zr=nn,Qr=Fr,Xr=Lr,ei=function(e){return null==e?"":Jr(e)};var ti=function(e,t){return Zr(e)?e:Qr(e,t)?[e]:Xr(ei(e))},ni=Ur;var si=function(e){if("string"==typeof e||ni(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t},ri=ti,ii=si;var ai=function(e,t){for(var n=0,s=(t=ri(t,e)).length;null!=e&&n<s;)e=e[ii(t[n++])];return n&&n==s?e:void 0},oi=ai;var ui=ti,ci=tn,li=nn,hi=un,di=cn,pi=si;var fi=function(e,t){return null!=e&&t in Object(e)},mi=function(e,t,n){for(var s=-1,r=(t=ui(t,e)).length,i=!1;++s<r;){var a=pi(t[s]);if(!(i=null!=e&&n(e,a)))break;e=e[a]}return i||++s!=r?i:!!(r=null==e?0:e.length)&&di(r)&&hi(a,r)&&(li(e)||ci(e))};var vi=Ir,yi=function(e,t,n){var s=null==e?void 0:oi(e,t);return void 0===s?n:s},gi=function(e,t){return null!=e&&mi(e,t,fi)},bi=Fr,Ii=Sr,wi=Br,Ti=si;var ki=ai;var Si=function(e){return function(t){return null==t?void 0:t[e]}},_i=function(e){return function(t){return ki(t,e)}},Ci=Fr,Bi=si;var Oi=jr,Ai=function(e,t){return bi(e)&&Ii(t)?wi(Ti(e),t):function(n){var s=yi(n,e);return void 0===s&&s===t?gi(n,e):vi(t,s,3)}},Ei=function(e){return e},ji=nn,Ri=function(e){return Ci(e)?Si(Bi(e)):_i(e)};var Ni=function(e){return"function"==typeof e?e:null==e?Ei:"object"==typeof e?ji(e)?Ai(e[0],e[1]):Oi(e):Ri(e)},Ui=Gt,qi=Hn,Di=Ni,Pi=nn;var xi=M(function(e,t){return function(n,s){var r=Pi(n)?Ui:qi,i=t?t():{};return r(n,e,Di(s),i)}}((function(e,t,n){e[n?0:1].push(t)}),(function(){return[[],[]]})));var Fi=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},Mi=function(e){return e!=e},zi=function(e,t,n){for(var s=n-1,r=e.length;++s<r;)if(e[s]===t)return s;return-1};var Wi=function(e,t,n){return t==t?zi(e,t,n):Fi(e,Mi,n)};var Li=function(e,t){return!!(null==e?0:e.length)&&Wi(e,t,0)>-1};var Gi=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 Vi=zs,$i=function(){},Hi=Vi&&1/ys(new Vi([,-0]))[1]==1/0?function(e){return new Vi(e)}:$i,Yi=ls,Ki=Li,Ji=Gi,Zi=hs,Qi=Hi,Xi=ys;var ea=function(e,t,n){var s=-1,r=Ki,i=e.length,a=!0,o=[],u=o;if(n)a=!1,r=Ji;else if(i>=200){var c=t?null:Qi(e);if(c)return Xi(c);a=!1,r=Zi,u=new Yi}else u=t?[]:o;e:for(;++s<i;){var l=e[s],h=t?t(l):l;if(l=n||0!==l?l:0,a&&h==h){for(var d=u.length;d--;)if(u[d]===h)continue e;t&&u.push(h),o.push(l)}else r(u,h,n)||(u!==o&&u.push(h),o.push(l))}return o},ta=Ni,na=ea;var sa=M((function(e,t){return e&&e.length?na(e,ta(t)):[]}));const ra={Person:"red",Car:"green",Animal:"blue",LicensePlate:"cyan",Fire:"deepOrange",Smoke:"deepPurple"},ia={red:["#f44336","#ff1744"],green:["#4caf50","#00e676"],blue:["#2196f3","#2979ff"],purple:["#9c27b0","#d500f9"],teal:["#009688","#1de9b6"],amber:["#ff8f00","#ffc400"],pink:["#e91e63","#f50057"],cyan:["#00bcd4","#00e5ff"],lightGreen:["#9ccc65","#76ff03"],deepOrange:["#ff5722","#ff3d00"],deepPurple:["#7e57c2","#651fff"],lime:["#cddc39","#c6ff00"],indigo:["#3f51b5","#3d5afe"],lightBlue:["#03a9f4","#00b0ff"]};class aa extends Ot{schemaDescription=[];constructor(){super(),t(this,{schemaDescription:n.ref,foundObjectTypes:r,foundObjectTypesForSelect:r,colorsByFoundObjectType:r})}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.includes("LicensePlate")?e.valueSet.split(", "):e.valueSet.split(", ").concat(["LicensePlate"]):[]}get foundObjectTypesForSelect(){const e=Object.entries(ra).filter((([e])=>this.foundObjectTypes.includes(e))).map((([,e])=>e)),t=Object.keys(ia).filter((t=>!e.includes(t)));let n=0;return this.foundObjectTypes.map((e=>{const s=e in ra?ra[e]:t[n++],r=ia[s];return{value:e,label:e.toLowerCase(),color:r?.[0],highlightColor:r?.[1],type:"detectedObject"}}))}get colorsByFoundObjectType(){const e=new Map;for(const{value:t,highlightColor:n}of this.foundObjectTypesForSelect)e.set(t,n);return e}fetchAnalyticEventSchema=()=>{this.api.cameras.GetSensorDataSchema("Analytic").subscribe({next:e=>{e.success?o((()=>{this.schemaDescription=e.resultItems})):console.error(e)},error:console.error})};afterInit(){this.fetchAnalyticEventSchema()}dispose(){super.dispose(),this.schemaDescription=[]}}const oa=5e-4;class ua extends Ot{camerasStore;data;eventsByCameraId;eventsByStart;eventsByEnd;eventsByType;eventsByFoundObjects;eventsByColor;pendingRequests;pendingRequestsByEnd;pendingRequestsByStart;pendingRequestsByCameraId;knownIntervals=D();knownIntervalsByCameraId;knownIntervalsByStart;knownIntervalsByEnd;eventsById=new Map;updates=0;updatesByCameraId=new Map;recentAdditions=[];constructor(e){super(),this.camerasStore=e,t(this,{updates:n,recentAdditions:n.ref,processNewEvents:s,update:s,add:s,dispose:s}),this.data=D(),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(..."Colors"in t?t.Colors?.map((e=>e.Color))??[]:[])),[])),!0),this.pendingRequests=D(),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,n){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([Number.NEGATIVE_INFINITY,s]),this.knownIntervalsByEnd.filter([t,Number.POSITIVE_INFINITY]);const r=this.knownIntervalsByStart.bottom(Number.POSITIVE_INFINITY),i=[];if(this.knownIntervalsByCameraId.filterAll(),this.knownIntervalsByStart.filterAll(),this.knownIntervalsByEnd.filterAll(),r.length){const a=Ct(r.map((e=>[e.from,e.to])));a[0][0]>t&&i.push([t,a[0][0]]);for(let e=0;e<a.length-1;e++)i.push([a[e][1],a[e+1][0]]);a[Ct.length-1][1]<s&&i.push([a[Ct.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 a=this.pendingRequests.allFiltered()[0];if(this.pendingRequestsByCameraId.filterAll(),this.pendingRequestsByStart.filterAll(),this.pendingRequestsByEnd.filterAll(),a)return;if(r.length&&!i.length)return;const o=s=>this.api.cameras.GetSensorEventsPage({sensorIds:[e],sensorType:"camera",sensorEventTypes:[],startTime:t,endTime:n,rowsLimit:100,isDescending:!0,pageToken:s},null,[]).pipe(d((e=>e.success?p(e):(console.error(e.error),f((()=>e.error)))))),u=o().pipe(g((e=>e.pageInfo.haveMore?o(e.pageInfo.nextPageToken):b)),h((e=>e.resultItems.map((e=>new Mt(e))))),_());this.pendingRequests.add([{cameraId:e,startTime:t,endTime:n||new Date,request:u}]),u.subscribe({next:this.add,error:e=>{console.error(e),this.pendingRequests.remove((e=>e.request===u))},complete:()=>{this.pendingRequests.remove((e=>e.request===u))}})}update=e=>{for(const t of e){const e=this.eventsById.get(t.id);if(!e)return;e.update(t.raw),this.data.remove((e=>e.id===t.id)),this.data.add([e])}};add=e=>{const t=e.filter((e=>!this.eventsById.has(e.id)));for(const e of t)this.eventsById.set(e.id,e);if(this.data.add(t),t.length){const e=new Set(t.map((e=>e.cameraId)));for(const t of e)this.updatesByCameraId.set(t,(this.updatesByCameraId.get(t)??0)+1);this.updates++}};getEvents({cameraIds:e,from:t,to:n,detectedObjectTypes:s,eventTypes:r,colors:i,probability:a}){this.eventsByStart.filter([+t,n?+n+oa:Number.POSITIVE_INFINITY]),e?.length&&this.eventsByCameraId.filter((t=>e.includes(t))),r?.length&&this.eventsByType.filter((e=>r.includes(e))),s?.length&&this.eventsByFoundObjects.filter((e=>s.includes(e))),i?.size&&this.eventsByColor.filter((e=>i.has(e)));let o=this.eventsByStart.top(Number.POSITIVE_INFINITY);return r?.length&&this.eventsByType.filterAll(),e?.length&&this.eventsByCameraId.filterAll(),s?.length&&this.eventsByFoundObjects.filterAll(),i?.size&&this.eventsByColor.filterAll(),this.eventsByStart.filterAll(),void 0!==a&&s?.length&&(o=o.filter((e=>e.detectedObjects.some((e=>e.Probability>=a&&s.includes(e.Type)))))),o}getOverlappedEvents({cameraId:e,from:t,to:n}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([Number.NEGATIVE_INFINITY,+n+oa]),this.eventsByEnd.filter([+t,Number.POSITIVE_INFINITY]);const s=this.eventsByStart.bottom(Number.POSITIVE_INFINITY);return this.eventsByCameraId.filterAll(),this.eventsByStart.filterAll(),this.eventsByEnd.filterAll(),s}getLastNonAnalyticEventBefore({cameraId:e,date:t}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([Number.NEGATIVE_INFINITY,+t]),this.eventsByType.filter((e=>"Analytic"!==e));const n=this.eventsByStart.top(1);return this.eventsByType.filterAll(),this.eventsByStart.filterAll(),this.eventsByCameraId.filterAll(),n[0]}getLastObjectBefore({cameraId:e,date:t,objectFilters:n}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([Number.NEGATIVE_INFINITY,+t]),this.eventsByType.filter((e=>"Analytic"===e));const{cars:s,people:r,misc:i}=n;r&&s&&i||this.eventsByFoundObjects.filter((e=>i?r||s?!(!r||!s)||(r?"Car"!==e:"Person"!==e):"Person"!==e&&"Car"!==e:r&&s?"Person"===e||"Car"===e:r?"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]}getRunningEvent(e){this.eventsByCameraId.filter(e);const[t]=this.eventsByStart.top(1);if(this.eventsByCameraId.filterAll(),t?.isLive)return t}getFirstNonAnalyticEventAfter({cameraId:e,date:t}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([+t+oa,Number.POSITIVE_INFINITY]),this.eventsByType.filter((e=>"Analytic"!==e));const n=this.eventsByEnd.bottom(1);return this.eventsByType.filterAll(),this.eventsByCameraId.filterAll(),this.eventsByStart.filterAll(),n[0]}getFirstObjectAfter({cameraId:e,date:t,objectFilters:n}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([+t+oa,Number.POSITIVE_INFINITY]),this.eventsByType.filter((e=>"Analytic"===e));const{cars:s,people:r,misc:i}=n;r&&s&&i||this.eventsByFoundObjects.filter((e=>i?r||s?!(!r||!s)||(r?"Car"!==e:"Person"!==e):"Person"!==e&&"Car"!==e:r&&s?"Person"===e||"Car"===e:r?"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(l((({hub:e,event:t})=>"cameras"===e&&"OnCameraMotionEvent"===t))).subscribe(this.processNewEvents)}processNewEvents=({data:e})=>{const t=sa(e.filter((e=>"PeopleCounter"!==e.eventType&&this.camerasStore.camerasById.has(e.sensorId))).reverse(),"id").map((e=>new Mt(e))),[n,s]=xi(t,(e=>this.eventsById.has(e.id)));this.update(n),this.add(s),s.length&&(this.recentAdditions=s.map((e=>e.id)))};dispose(){super.dispose(),this.data.remove(Bt),this.updates++}}const ca=5e-4;class la extends Ot{thumbnails;thumbnailsByCameraId;thumbnailsByDate;pendingRequests;pendingRequestsByEnd;pendingRequestsByStart;pendingRequestsByCameraId;pendingRequestsByCount;constructor(){super(),this.thumbnails=D(),this.thumbnailsByCameraId=this.thumbnails.dimension((e=>e.cameraId)),this.thumbnailsByDate=this.thumbnails.dimension((e=>+e.timestamp)),this.pendingRequests=D(),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(d((e=>e.success?p(e.resultItems):f((()=>e.error)))),h((t=>t.filter((e=>e.url)).map(this.toThumbnail(e)))),v());return this.pendingRequests.add([{cameraId:e,from:t,to:n,count:s,request:i}]),i.subscribe((e=>{this.thumbnails.add(e),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:"fulfilled",data:s};this.pendingRequestsByCameraId.filter(e),this.pendingRequestsByStart.filter([Number.NEGATIVE_INFINITY,+n+ca]),this.pendingRequestsByEnd.filter([t,Number.POSITIVE_INFINITY]);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("fulfilled"===s.state)return p(s.data);if("pending"===s.state)return s.request.pipe(h((()=>this.getThumbnail({cameraId:e,from:t,to:n}))))}const r=this.api.thumbnails.GetThumbnailInfo({cameraId:e,from:t,to:n}).pipe(d((e=>e.success?p(e.resultItems):f((()=>e.error)))),h((t=>t.filter((e=>e.url)).map(this.toThumbnail(e)))),v());return r.subscribe((e=>{this.thumbnails.add(e),this.pendingRequests.remove((e=>e.request===r))})),this.pendingRequests.add([{cameraId:e,from:t,to:n,count:1,request:r}]),r.pipe(h((()=>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?ca: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+ca]);const s=this.thumbnails.allFiltered();return this.thumbnailsByDate.filterAll(),this.thumbnailsByCameraId.filterAll(),s}toThumbnail=e=>({realtimestamp:t,url:n})=>({cameraId:e,url:n,timestamp:new Date(t)})}const ha={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,UpdateCamera:null,GetSensorDataSchema:null,GetSensorEvents:null,GetSensorEventsPage:null,GetLicensePlateLookUp:null,GetSensorEventsLprPage:null,GetPeopleCountingData: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}};var da,pa,fa={cameras:[{name:"OnCameraAdded"},{name:"OnCameraUpdated"},{name:"OnSystemCameraUpdated"},{name:"OnCameraDeleted"},{name:"OnCameraMotionEvent"}],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"}]};!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTED=3]="DISCONNECTED"}(da||(da={})),function(e){e[e.INFO=0]="INFO",e[e.WARN=1]="WARN",e[e.ERROR=2]="ERROR"}(pa||(pa={}));class ma{static create(e,t,n){return new ma(null!==e?e:ha,t,n)}connectionShutdown$=new w;connection$=new C(null);events=new w;logLevel=pa.ERROR;authStore;createConnection;apiConfig;constructor(e,t,n){this.apiConfig=e,this.init(),this.createConnection=n,this.authStore=t,i((()=>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!==da.DISCONNECTED?t.qs.access_token=e.accessToken:this.connect(e)})),this.connection$.pipe(B((e=>null!==e||!t.isAuthenticated||t.token?.invalid?b:(this.log(pa.WARN,"disconnected by some reason"),O(5e3)))),l((()=>t.isAuthenticated&&!!t.token&&!t.token.invalid))).subscribe((()=>{this.connect(t.token),this.log(pa.WARN,"attempting to reconnect")}))}log=(e,...t)=>{if(e<this.logLevel)return;console[["log","warn","error"][e]](...t)};connect(e){if(this.connection$.getValue()?.state===da.CONNECTED)return;const{accessToken:t}=e,n=this.createConnection(t);for(const e of Object.keys(this.apiConfig))n.createHubProxy(e);for(const[e,t]of Object.entries(fa)){if(!t||!n.proxies[e])return;for(const{name:s}of t)n.proxies[e].on(s,(t=>this.events.next({hub:e,event:s,data:t})))}n.start().done((()=>{this.log(pa.INFO,"connected"),this.connection$.next(n)})).fail((e=>{!e.source||401!==e.source?.status&&403!==e.source?.status&&409!==e.source?.status||this.authStore.invalidateToken(),this.log(pa.ERROR,"connection failed",e)})),n.error((e=>{if(e.source&&(401===e.source.status||403===e.source.status||409===e.source.status))return this.log(pa.WARN,"authentication error, invalidating token"),this.authStore.invalidateToken();this.log(pa.ERROR,"connection error",e)})),n.disconnected((()=>{const e=this.connection$.getValue();e?this.log(pa.WARN,"disconnected",e.lastError):this.log(pa.WARN,"disconnected. this connection is already null"),this.connection$.next(null)})),n.reconnecting((()=>this.log(pa.WARN,"reconnecting"))),n.reconnected((()=>{this.connection$.getValue()===n&&(this.log(pa.WARN,"reconnected"),this.connection$.next(n))}))}shutdownConnection(){const e=this.connection$.getValue();e&&e.stop(),this.connectionShutdown$.next(null)}init(){for(const[e,t]of Object.entries(this.apiConfig)){this[e]={};for(const n of Object.keys(t))this[e][n]=this.createHubMethod(e,n)}}createHubMethod=(e,t)=>{const n=(...s)=>this.connection$.pipe(l(Boolean),l((e=>e.state===da.CONNECTED)),A(1)).pipe(d((n=>new Promise(((r,i)=>{n.proxies[e].invoke(t,...s).done((e=>r(e))).fail((e=>i(e)))})))),E((e=>e instanceof Error&&e.message&&("Connection started reconnecting before invocation result was received."===e.message||"Connection was disconnected before invocation result was received."===e.message)?(this.log(pa.WARN,e.message),n(...s)):e instanceof Error&&e.message&&e.message.startsWith("Caller is not authorized to invoke the ")?(this.log(pa.WARN,e.message),this.connection$.getValue()?.stop(),this.authStore.invalidateToken(),n(...s)):f((()=>e)))),S(this.connectionShutdown$));return n}}class va{accessToken;accessTokenIssued;clientId;expiresIn;refreshToken;refreshTokenExpires;refreshTokenIssued;tokenType;userName;invalid;widgetId;widgetToken;json;constructor(e){this.json=e,this.accessToken=e.access_token||e.accessToken,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}_exp=null;get accessTokenExpires(){if(this._exp)return this._exp;if(this.accessToken){try{const e=(new TextDecoder).decode(Uint8Array.from(atob(this.accessToken.split(".")[1]),(e=>e.charCodeAt(0))));this._exp=new Date(1e3*JSON.parse(e).exp)}catch(e){console.error("failed to parse token",e)}return this._exp||(this._exp=this._exp=new Date(this.json.access_token_expires||this.json.accessTokenExpires)),this._exp}}}class ya{token=null;isAuthenticating=!1;storage;tokenServiceUrl;tokenStorageKey;deviceInfo;clientId;pendingUpdateTokenRequest=null;get isAuthenticated(){return Boolean(this.token&&!this.isAuthenticating)}constructor({tokenServiceUrl:e,storage:i,tokenStorageKey:a,deviceInfo:c,clientId:h}){t(this,{token:n.ref,isAuthenticating:n,isAuthenticated:r,signOut:s,invalidateToken:s}),this.isAuthenticating=!0,this.storage=i,this.tokenServiceUrl=e,this.tokenStorageKey=a,this.deviceInfo=c,this.clientId=h;const m=function(e,t=!1){const n=r(e);return new j((e=>{const s=u(n,(({newValue:t})=>e.next(t)),t);return()=>s()}))}((()=>this.token)),v=m.pipe(B((e=>{if(null===e)return b;const t=p(e).pipe(d((e=>e.widgetId?this.fetchWidgetToken(e):this.updateToken(e.refreshToken))),y({delay:(e,t)=>e.status&&![500,502,503,504].includes(e.status)?f((()=>e)):O(2**Math.min(t+1,6)*1e3)}));if(!e.invalid&&e.accessTokenExpires){const n=Math.max(.75*(+e.accessTokenExpires-Date.now()),0);return O(n).pipe(d((()=>t)))}return t})),E((e=>(console.error(e),o((()=>this.token=null)),v))));v.subscribe((e=>{o((()=>this.token=e))})),m.pipe(R(null),N(),l((([e,t])=>!!(t||!t&&e))),U((([,e])=>this.storeToken(e)))).subscribe(),this.getInitialToken().then((e=>{o((()=>{this.token=e,this.isAuthenticating=!1}))}))}signOut=()=>{this.isAuthenticating||o((()=>this.token=null))};signIn=e=>{if(this.isAuthenticating)return;o((()=>this.isAuthenticating=!0)),!1===e.agreedWithTerms&&(e={...e,agreedWithTerms:void 0});return this.fetchToken(e).then((e=>(o((()=>{this.token=e,this.isAuthenticating=!1})),e))).catch((e=>{throw o((()=>{this.isAuthenticating=!1})),e}))};signInWithToken=e=>{this.isAuthenticating?console.warn("Attempt to sign in with token while authenticating"):o((()=>{this.token=new va(e)}))};invalidateToken=()=>{this.token&&o((()=>{this.token={...this.token,invalid:!0}}))};async getTokenFromStorage(){const e=await this.storage.getItem(this.tokenStorageKey);return e?new va(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 fetchToken(e){const t={clientId:this.clientId,client_id:this.clientId,device:this.deviceInfo,...e},n=new Headers;n.append("Content-Type","application/x-www-form-urlencoded"),n.append("accept","application/json");const s=await fetch(this.tokenServiceUrl,{method:"POST",headers:n,body:new URLSearchParams(t)});try{const e=await s.json();return 200!==s.status?Promise.reject({status:s.status,data:e}):new va(e)}catch(e){return Promise.reject(s)}}async updateToken(e){try{return this.pendingUpdateTokenRequest&&this.pendingUpdateTokenRequest.refreshToken===e||(this.pendingUpdateTokenRequest={refreshToken:e,request:this.fetchToken({refreshToken:e,refresh_token:e,grant_type:"refresh_token"})}),await this.pendingUpdateTokenRequest.request}finally{this.pendingUpdateTokenRequest?.refreshToken===e&&(this.pendingUpdateTokenRequest=null)}}async fetchWidgetToken(e){const{widgetId:t,widgetToken:n}=e;if(!t||!n)throw new Error("token must contain widgetId and widgetToken");const s={widgetId:t,widgetToken:n},r=new Headers;r.append("Content-Type","application/json"),r.append("accept","application/json");const i=await fetch(this.tokenServiceUrl,{method:"POST",headers:r,body:JSON.stringify(s)});try{const e=await i.json();return 200!==i.status?Promise.reject({status:i.status,data:e}):new va({widgetId:t,widgetToken:n,...e})}catch(e){return Promise.reject(i)}}}class ga{notifier;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 ba="default",Ia=new Map;class wa{name;initialized=!1;cameras=new Lt;archives=new Wt(this.cameras);_events=null;get events(){return this._events||(this._events=new ua(this.cameras),this.initialized&&this._events.initWith(this.api)),this._events}eventSchema=new aa;thumbnails=new la;account=new qt;notification=new ga({success:console.log,warn:console.warn,error:console.error});disposables=[];tokenUpdateReactions=new Set;constructor(e){this.name=e,t(this,{initialized:n}),this.disposables.push(a((()=>!!this.account.user),(()=>{this.cameras.load()})))}init({clientId:t="WebApp",token:n,tokenStorage:s=new _t,tokenStorageKey:r,apiUrl:i="https://services.3deye.me/reactiveapi",tokenServiceUrl:a="https://admin.3deye.me/webapi/v3/auth/token"},u=ba){return r||(r=`@3deye-toolkit/${u}/token`),Ia.has(u)?(console.warn("Can`t init two apps with the same name"),Ia.get(u)):this.auth&&u===this.name?(console.warn("Can`t init already inited app"),this):this.auth||this.name===ba&&u!==ba?new wa(u).init({clientId:t,token:n,tokenStorage:s,tokenStorageKey:r,apiUrl:i,tokenServiceUrl:a},u):(t=n&&"clientId"in n?n.clientId:t,n&&s.setItem(r,JSON.stringify(n)),this.auth=new ya({tokenServiceUrl:a,tokenStorageKey:r,storage:s,clientId:t,deviceInfo:null}),this.api=ma.create(ha,this.auth,(t=>e(i,{qs:{access_token:t}}))),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),o((()=>{this.initialized=!0})),Ia.set(u,this),this)}dispose=()=>{for(const e of this.disposables)e instanceof c?e.closed||e.unsubscribe():e();for(const e of this.tokenUpdateReactions)e();this.tokenUpdateReactions.clear(),this.auth.signOut(),this.cameras.dispose(),this._events?.dispose(),this.thumbnails.dispose(),this.eventSchema.dispose(),this.account.dispose(),Ia.delete(this.name)};onTokenUpdate=e=>{if(!this.auth)throw new Error("app has to be inited first");const t=i((()=>this.auth.token),(t=>e(t?.json||null)));return this.tokenUpdateReactions.add(t),()=>{t(),this.tokenUpdateReactions.delete(t)}}}var Ta=new wa(ba);var ka=x.createContext(null);export{ka as AppContext,Ta as app};
1
+ import e from"jqueryless-signalr";import{makeObservable as t,observable as n,action as s,computed as r,reaction as i,when as a,runInAction as o,observe as c}from"mobx";import{Subscription as u,filter as l,map as h,mergeMap as d,of as p,throwError as f,tap as m,shareReplay as v,retry as y,expand as g,EMPTY as b,last as I,Subject as T,skip as w,exhaustMap as k,takeUntil as S,share as B,BehaviorSubject as _,switchMap as E,timer as C,take as O,catchError as A,Observable as j,startWith as R,pairwise as N,concatMap as U}from"rxjs";import q from"string-natural-compare";import P from"crossfilter2";import{z as D}from"zod";import x from"react";var F="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function M(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var z="object"==typeof F&&F&&F.Object===Object&&F,L=z,V="object"==typeof self&&self&&self.Object===Object&&self,W=L||V||Function("return this")(),G=W.Symbol,$=G,Y=Object.prototype,H=Y.hasOwnProperty,J=Y.toString,K=$?$.toStringTag:void 0;var Z=function(e){var t=H.call(e,K),n=e[K];try{e[K]=void 0;var s=!0}catch(e){}var r=J.call(e);return s&&(t?e[K]=n:delete e[K]),r},Q=Object.prototype.toString;var X=Z,ee=function(e){return Q.call(e)},te=G?G.toStringTag:void 0;var ne=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":te&&te in Object(e)?X(e):ee(e)};var se=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},re=ne,ie=se;var ae,oe=function(e){if(!ie(e))return!1;var t=re(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t},ce=W["__core-js_shared__"],ue=(ae=/[^.]+$/.exec(ce&&ce.keys&&ce.keys.IE_PROTO||""))?"Symbol(src)_1."+ae:"";var le=function(e){return!!ue&&ue in e},he=Function.prototype.toString;var de=function(e){if(null!=e){try{return he.call(e)}catch(e){}try{return e+""}catch(e){}}return""},pe=oe,fe=le,me=se,ve=de,ye=/^\[object .+?Constructor\]$/,ge=Function.prototype,be=Object.prototype,Ie=ge.toString,Te=be.hasOwnProperty,we=RegExp("^"+Ie.call(Te).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var ke=function(e){return!(!me(e)||fe(e))&&(pe(e)?we:ye).test(ve(e))},Se=function(e,t){return null==e?void 0:e[t]};var Be=function(e,t){var n=Se(e,t);return ke(n)?n:void 0},_e=Be(Object,"create"),Ee=_e;var Ce=function(){this.__data__=Ee?Ee(null):{},this.size=0};var Oe=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Ae=_e,je=Object.prototype.hasOwnProperty;var Re=function(e){var t=this.__data__;if(Ae){var n=t[e];return"__lodash_hash_undefined__"===n?void 0:n}return je.call(t,e)?t[e]:void 0},Ne=_e,Ue=Object.prototype.hasOwnProperty;var qe=_e;var Pe=Ce,De=Oe,xe=Re,Fe=function(e){var t=this.__data__;return Ne?void 0!==t[e]:Ue.call(t,e)},Me=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=qe&&void 0===t?"__lodash_hash_undefined__":t,this};function ze(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])}}ze.prototype.clear=Pe,ze.prototype.delete=De,ze.prototype.get=xe,ze.prototype.has=Fe,ze.prototype.set=Me;var Le=ze;var Ve=function(){this.__data__=[],this.size=0};var We=function(e,t){return e===t||e!=e&&t!=t},Ge=We;var $e=function(e,t){for(var n=e.length;n--;)if(Ge(e[n][0],t))return n;return-1},Ye=$e,He=Array.prototype.splice;var Je=$e;var Ke=$e;var Ze=$e;var Qe=Ve,Xe=function(e){var t=this.__data__,n=Ye(t,e);return!(n<0)&&(n==t.length-1?t.pop():He.call(t,n,1),--this.size,!0)},et=function(e){var t=this.__data__,n=Je(t,e);return n<0?void 0:t[n][1]},tt=function(e){return Ke(this.__data__,e)>-1},nt=function(e,t){var n=this.__data__,s=Ze(n,e);return s<0?(++this.size,n.push([e,t])):n[s][1]=t,this};function st(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])}}st.prototype.clear=Qe,st.prototype.delete=Xe,st.prototype.get=et,st.prototype.has=tt,st.prototype.set=nt;var rt=st,it=Be(W,"Map"),at=Le,ot=rt,ct=it;var ut=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 n=e.__data__;return ut(t)?n["string"==typeof t?"string":"hash"]:n.map},ht=lt;var dt=lt;var pt=lt;var ft=lt;var mt=function(){this.size=0,this.__data__={hash:new at,map:new(ct||ot),string:new at}},vt=function(e){var t=ht(this,e).delete(e);return this.size-=t?1:0,t},yt=function(e){return dt(this,e).get(e)},gt=function(e){return pt(this,e).has(e)},bt=function(e,t){var n=ft(this,e),s=n.size;return n.set(e,t),this.size+=n.size==s?0:1,this};function It(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])}}It.prototype.clear=mt,It.prototype.delete=vt,It.prototype.get=yt,It.prototype.has=gt,It.prototype.set=bt;var Tt=It,wt=Tt;function kt(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 a=e.apply(this,s);return n.cache=i.set(r,a)||i,a};return n.cache=new(kt.Cache||wt),n}kt.Cache=wt;var St=kt;class Bt{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)}}function _t(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 Et=()=>!0;class Ct{api;disposables=[];initWith(e){this.api=e,this.afterInit&&this.afterInit()}dispose(){for(const e of this.disposables)e instanceof u?e.closed||e.unsubscribe():e()}}var Ot;!function(e){e.DEFAULT_VIDEO_RESIZE_MODE="defaultVideoResizeMode",e.RESIZE_MODE_PER_CAMERA="camerasResizeMode",e.FISHEYE_CAMERAS="fisheyeCameras",e.UTC="utc",e.HOUR12="hour12",e.START_OF_WEEK="startOfWeek"}(Ot||(Ot={}));const At=D.enum(["fill","contain"]),jt=D.object({lat:D.number(),lon:D.number(),fov:D.number()}),Rt=D.object({params:D.object({x:D.number(),y:D.number(),r:D.number(),s:D.number()}),positions:D.tuple([jt,jt,jt]).optional()}),Nt=D.tuple([D.number(),D.number(),D.number()]),Ut=D.object({[Ot.DEFAULT_VIDEO_RESIZE_MODE]:At.optional(),[Ot.RESIZE_MODE_PER_CAMERA]:D.array(D.tuple([D.number(),At])).optional(),[Ot.FISHEYE_CAMERAS]:D.array(D.tuple([D.number(),D.union([Nt,Rt,D.null()])])).optional(),[Ot.UTC]:D.boolean().default(!1),[Ot.HOUR12]:D.boolean().default(!1),[Ot.START_OF_WEEK]:D.enum(["monday","sunday"]).default("monday")});class qt extends Ct{notification;user=null;auth;constructor(e){super(),this.notification=e,t(this,{user:n.ref,setUser:s,userDisplayName:r,preferences:r,isSharingUserAccount:r})}get isSharingUserAccount(){return this.user?.email.endsWith("@share.share")||!1}get userDisplayName(){return this.user?this.user.firstName?.trim()||this.user.lastName?.trim()?[this.user.firstName,this.user.lastName].filter(Boolean).join(" ").trim():this.user.email:null}afterInit(){this.disposables.push(this.api.events.pipe(l((({hub:e,event:t})=>"users"===e&&"OnUserUpdateProfile"===t)),h((({data:e})=>e.resultItems[0]))).subscribe(this.setUser))}loadUser$(){return this.api.users.GetUser().pipe(d((e=>e.success?p(e.resultItems[0]):f((()=>e.error)))),m(this.setUser),v(1))}setUser=e=>{this.user=e};setAuthStore(e){this.auth=e,this.disposables.push(i((()=>this.auth.isAuthenticated),(()=>{this.auth.isAuthenticated&&this.loadUser$().subscribe()})))}async updateUserPassword(e){const t=function(){throw new Error("Config not initialized")}().changePasswordUrl,n=this.auth?.token?.accessToken,s=JSON.stringify({currentPassword:e.previous,newPassword:e.new}),r=new Headers;r.append("content-type","application/json"),r.append("accept","application/json"),r.append("authorization",`bearer ${n}`);const i=await fetch(t,{method:"PUT",headers:r,body:s}),{status:a}=i;if(200!==a){const e=await i.json();throw new Error(e.errors[0].message)}}updateUserSettings({firstName:e,lastName:t}){const n=p(null).pipe(d((()=>{if(!this.user)throw new Error("user is not initialized");return this.api.users.UserUpdateProfile({id:this.user.id,firstName:e,lastName:t,version:this.user.version})})),d((e=>e.success?p(e.resultItems[0]):f((()=>e.error)))),this.retryOnVersionMismatch(),v());return n.subscribe((e=>{this.setUser(e)})),n}updateUserLanguage(e){const t=p(null).pipe(d((()=>{if(!this.user)throw new Error("user is not initialized");return this.api.users.UserUpdateProfile({id:this.user.id,languageCode:e,version:this.user.version})})),d((e=>e.success?p(e.resultItems[0]):f((()=>e.error)))),this.retryOnVersionMismatch(),v());return t.subscribe((e=>{this.setUser(e)})),t}updateCustomPreferences=e=>{const t=p(null).pipe(d((()=>{if(!this.user)return f((()=>"user is not initialized"));const t={id:this.user.id,jsonField:JSON.stringify({...JSON.parse(this.user.jsonField||"{}"),...e}),version:this.user.version};return this.api.users.UserUpdateProfile(t)})),d((e=>e.success?p(e.resultItems[0]):f((()=>e.error)))),this.retryOnVersionMismatch(),v());return t.subscribe((e=>{this.setUser(e)})),t};setDefaultGroup(e){const t=p(null).pipe(d((()=>{if(!this.user)return f((()=>"user is not initialized"));const t={id:this.user.id,layoutStartId:e,layoutStartType:"camgroup",version:this.user.version};return this.api.users.UserUpdateProfile(t)})),d((e=>e.success?p(e.resultItems[0]):f((()=>e.error)))),this.retryOnVersionMismatch(),v());return t.subscribe({next:e=>{this.setUser(e),this.notification?.success("Successfully set default group")},error:e=>{console.error(e),this.notification?.error(e.message)}}),t}get preferences(){try{return Ut.parse(JSON.parse(this.user?.jsonField||"{}"))}catch(e){console.error(e)}return{[Ot.DEFAULT_VIDEO_RESIZE_MODE]:void 0,[Ot.RESIZE_MODE_PER_CAMERA]:void 0,[Ot.FISHEYE_CAMERAS]:void 0,[Ot.UTC]:!1,[Ot.HOUR12]:!1,[Ot.START_OF_WEEK]:"monday"}}getPreference=e=>this.preferences[e];retryOnVersionMismatch=()=>y({delay:(e,t)=>t>1?f((()=>e)):-4===e?.code?this.loadUser$():f((()=>e))})}class Pt{json;startTime;endTime;streamUrl;duration;isLive=!1;cameraId;id;constructor(e){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?e.duration:e.endTime?(new Date(e.endTime).getTime()-new Date(e.startTime).getTime())/1e3:void 0,this.id=e.id}}class Dt{id;name;imageUrl;streamUrl;dashStreamUrl;address;archiveDuration;dvrWindowLength;stateUpdatedAt;raw;enabled;isMicEnabled;state;pin;webRtcUrl;isPtz;permissions;get isOnline(){return this.enabled&&"Started"===this.state}get supportsWebRTC(){return!!this.webRtcUrl}constructor(e){t(this,{name:n,streamUrl:n,dashStreamUrl:n,enabled:n,isMicEnabled:n,state:n,pin:n,webRtcUrl:n,permissions:n,isOnline:r,update:s}),this.update(e)}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.permissions=e.permissions||0,this.stateUpdatedAt=new Date(e.cameraStateChangedTime)};can=e=>!!(this.permissions&e)}var xt;!function(e){e[e.View=1]="View",e[e.SaveClip=2]="SaveClip",e[e.Share=4]="Share",e[e.Ptz=8]="Ptz",e[e.EditSettings=16]="EditSettings",e[e.Timelapse=32]="Timelapse",e[e.Delete=64]="Delete"}(xt||(xt={}));const Ft=new Set(["LicensePlate","FaceDetection","Analytic","SpeedDetection","Temperature","PoS","GPS","DigitalInput","Loitering"]);class Mt{id;cameraId;type;raw;thumbnailUrl;thumbnailWidth=0;thumbnailHeight=0;detectedObjects;faces;instant;get startTime(){return new Date(this.raw.startTime)}get endTime(){return new Date(this.raw.endTime)}get isLive(){return!Ft.has(this.type)&&+this.startTime==+this.endTime}get acknowledged(){return"sensorId"in this.raw&&!!this.raw.ackEventType}update=e=>{const t=e.startTime??this.raw.startTime,n=e.endTime??this.raw.endTime,s=e.ackEventType??this.raw.ackEventType;this.raw={...this.raw,...e,startTime:t,endTime:n,ackEventType:s}};constructor(e){if(t(this,{startTime:r,endTime:r,acknowledged:r,isLive:r,raw:n.ref,update:s}),this.raw=e,this.id=e.id,this.type=e.eventType,this.cameraId=e.sensorId,("Analytic"===this.type||"FaceDetection"===this.type||"Loitering"===this.type)&&e.data)try{const t=JSON.parse(e.data);t.FoundObjects&&(this.detectedObjects=t.FoundObjects),t.Faces&&(this.type="FaceDetection",this.faces=t.Faces),t.ThumbnailSize&&(this.thumbnailWidth=t.ThumbnailSize.Width,this.thumbnailHeight=t.ThumbnailSize.Height),this.thumbnailUrl=t.ThumbnailUrl}catch{console.warn("invalid data",e.data),this.type="Motion"}this.instant=Ft.has(this.type),this.detectedObjects||(this.detectedObjects=[])}static fromWebhookEvent=e=>{const t="LicensePlateRecognition"===e.type?"LicensePlate":e.type,n="timestampUtc"in e.data?e.data.timestampUtc:e.data.startTimeUtc,s="timestampUtc"in e.data?e.data.timestampUtc:e.data.endTimeUtc,r={message:"",data:null,id:e.id,customerId:0,sensorId:e.deviceId,sensorType:"CameraSensor",eventType:t,ackEventType:e.ackType??"",startTime:n,endTime:s,userId:""},i=new Mt(r);return i.thumbnailUrl=e.data.thumbnailUrl,i.detectedObjects="objectsFound"in e.data?e.data.objectsFound.map((e=>({Type:e.type,Box:{Left:e.box.left,Top:e.box.top,Right:e.box.right,Bottom:e.box.bottom},Probability:e.probability}))):[],i.raw.data=JSON.stringify({ThumbnailUrl:e.data.thumbnailUrl,FoundObjects:i.detectedObjects}),i};toWebhookEvent=()=>{const e=this.raw.ackEventType?{timestampUtc:(new Date).toISOString(),message:this.raw.message,userId:this.raw.userId}:void 0;return"Analytic"===this.type?{id:this.id,deviceId:this.cameraId,type:this.type,ackType:this.raw.ackEventType,data:{objectsFound:this.detectedObjects.map((({Type:e,Box:t,Probability:n})=>({type:e,box:{left:t.Left,top:t.Top,right:t.Right,bottom:t.Bottom},probability:n}))),thumbnailUrl:this.thumbnailUrl,timestampUtc:this.startTime.toISOString()},ackData:e}:"LicensePlate"===this.type?{id:this.id,deviceId:this.cameraId,type:"LicensePlateRecognition",ackType:this.raw.ackEventType,data:{platesFound:this.detectedObjects.filter((e=>"LicensePlate"===e.Type)).map((({Value:e,Box:t,Probability:n})=>({plateNumber:e,box:{left:t.Left,top:t.Top,right:t.Right,bottom:t.Bottom},probability:n}))),thumbnailUrl:this.thumbnailUrl,timestampUtc:this.startTime.toISOString()},ackData:e}:this.instant?{id:this.id,deviceId:this.cameraId,type:this.type,ackType:this.raw.ackEventType,data:{thumbnailUrl:this.thumbnailUrl,timestampUtc:this.startTime.toISOString()},ackData:e}:{id:this.id,deviceId:this.cameraId,type:this.type,ackType:this.raw.ackEventType,data:{thumbnailUrl:this.thumbnailUrl,startTimeUtc:this.startTime.toISOString(),endTimeUtc:this.endTime.toISOString()},ackData:e}}}const zt=5e-4;class Lt extends Ct{camerasStore;data;chunksByCameraId;chunksByStart;chunksByEnd;chunksById=new Map;pendingRequests;pendingRequestsByEnd;pendingRequestsByStart;pendingRequestsByCameraId;knownIntervals=P();knownIntervalsByCameraId;knownIntervalsByStart;knownIntervalsByEnd;updates=0;constructor(e){super(),this.camerasStore=e,t(this,{updates:n,add:s.bound}),this.data=P(),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=P(),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))}fetch(e,t,n){this.knownIntervalsByCameraId.filter(e),this.knownIntervalsByStart.filter([Number.NEGATIVE_INFINITY,+n]),this.knownIntervalsByEnd.filter([+t,Number.POSITIVE_INFINITY]);const s=this.knownIntervalsByStart.bottom(Number.POSITIVE_INFINITY);this.knownIntervalsByCameraId.filterAll(),this.knownIntervalsByStart.filterAll(),this.knownIntervalsByEnd.filterAll();let r=t,i=n,a=!0;if(s.length){const o=_t(s.map((e=>[e.from,e.to])));if(o.some((([e,s])=>e<=t&&s>=n)))return p(this.getChunks({cameraId:e,from:t,to:n}));if(o[0][0]>t)r=t,i=n;else{let e=!1;for(let s=0;s<o.length;s++){const[a,c]=o[s];if(a<=t&&c>=t){if(c<n){r=c,i=n,e=!0;break}}else if(a>t&&a<n){r=t,i=n,e=!0;break}}if(!e){const e=o[o.length-1];e[1]<n?(r=e[1],i=n):a=!1}}}if(!a)return p(this.getChunks({cameraId:e,from:t,to:n}));this.pendingRequestsByCameraId.filter(e),this.pendingRequestsByStart.filter([Number.NEGATIVE_INFINITY,+r]),this.pendingRequestsByEnd.filter([+i,Number.POSITIVE_INFINITY]);const o=this.pendingRequests.allFiltered()[0];if(this.pendingRequestsByCameraId.filterAll(),this.pendingRequestsByStart.filterAll(),this.pendingRequestsByEnd.filterAll(),o)return o.request.pipe(h((()=>this.getChunks({cameraId:e,from:t,to:n}))));const c=this.api.archives.PopulateArchive({cameraId:e,startTime:r,endTime:i}).pipe(d((e=>e.success?p(e.resultItems[0].chunks.map((e=>new Pt(e)))):f((()=>new Error(e.error.message||"Failed to fetch archives"))))),m((t=>{this.add(t);let n=i;const s=t.at(-1);if(s&&s?.endTime>=i)n=s.endTime;else{this.chunksByCameraId.filter(e);const t=this.chunksByEnd.top(1)[0];if(this.chunksByCameraId.filterAll(),s&&(!t||t.endTime<n)&&(n=s.endTime),!s&&(!t||t.endTime<n))return}this.knownIntervals.add([{cameraId:e,from:r,to:n}])})),h((()=>this.getChunks({cameraId:e,from:t,to:n}))),v());return this.pendingRequests.add([{cameraId:e,startTime:r,endTime:i,request:c}]),c.pipe(m((()=>this.pendingRequests.remove((e=>e.request===c))))).subscribe(),c}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([Number.NEGATIVE_INFINITY,+n+zt]),this.chunksByEnd.filter([t,Number.POSITIVE_INFINITY]),e&&this.chunksByCameraId.filter(e);const s=this.chunksByStart.top(Number.POSITIVE_INFINITY);return e&&this.chunksByCameraId.filterAll(),this.chunksByStart.filterAll(),this.chunksByEnd.filterAll(),s}getClosestChunkRight=({cameraId:e,time:t})=>{this.chunksByCameraId.filter(e),this.chunksByEnd.filter([t,Number.POSITIVE_INFINITY]);const n=this.chunksByStart.bottom(1);return this.chunksByCameraId.filterAll(),this.chunksByEnd.filterAll(),n[0]};getClosestChunkLeft=({cameraId:e,time:t})=>{this.chunksByCameraId.filter(e),this.chunksByStart.filter([Number.NEGATIVE_INFINITY,+t+zt]);const n=this.chunksByStart.top(1);return this.chunksByCameraId.filterAll(),this.chunksByEnd.filterAll(),n[0]};fetchNextChunk=({cameraId:e,time:t})=>p({result:[],time:t}).pipe(g((({result:t,time:n})=>{if(t.length||n>=new Date)return b;const s=new Date(+n+36e5);return this.fetch(e,n,s).pipe(h((e=>({result:e,time:s}))))})),I(),h((()=>this.getClosestChunkRight({cameraId:e,time:t}))));fetchPrevChunk=({cameraId:e,time:t})=>{const n=this.camerasStore.camerasById.get(e);if(!n)return p(void 0);const s=new Date(Date.now()-3600*n.archiveDuration*1e3);return p({result:[],time:t}).pipe(g((({result:t,time:n})=>{if(t.length||n<=s)return b;const r=new Date(Math.max(+n-36e5,+s));return this.fetch(e,r,n).pipe(h((e=>({result:e,time:r}))))})),I(),h((()=>this.getClosestChunkRight({cameraId:e,time:t}))))};afterInit(){this.api.events.pipe(l((({hub:e,event:t})=>"archives"===e&&"OnArchiveChunksCreated"===t))).subscribe((({data:e})=>{this.add(e.resultItems.map((e=>new Pt(e))))}))}}class Vt extends Ct{camerasById=new Map;data=[];loading=!1;loaded=!1;pendingLoadRequest;requestsCanceler=new T;constructor(){super(),t(this,{data:n.ref,loading:n,loaded:n,add:s}),this.disposables.push(a((()=>this.loaded),(()=>{this.api.connection$.pipe(w(1),k((()=>this.sync()))).subscribe()})))}load=()=>{if(this.loaded)return p([]);if(this.pendingLoadRequest)return this.pendingLoadRequest;o((()=>{this.loading=!0})),this.pendingLoadRequest=this.api.cameras.GetCameras({},null).pipe(d((e=>e.success?p(e.resultItems):(console.error(e.error),f((()=>e.error))))),v(1),S(this.requestsCanceler));const e=this.pendingLoadRequest;return e.subscribe((e=>{this.pendingLoadRequest=void 0,o((()=>{this.add(e),this.loading=!1,this.loaded=!0}))})),e};add=e=>{for(const t of e)this.camerasById.has(t.id)?this.camerasById.get(t.id)?.update(t):this.camerasById.set(t.id,new Dt(t));this.data=Array.from(this.camerasById.values()).sort(((e,t)=>q(e.name,t.name,{caseInsensitive:!0})))};sync=()=>{const e=this.data.reduce(((e,t)=>Math.max(e,+t.stateUpdatedAt)),0);if(!e)return b;const t=this.api.cameras.GetCameras({},new Date(1e3*(Math.floor(e/1e3)+1))).pipe(d((e=>e.success?p(e.resultItems):(console.error(e.error),f((()=>e.error))))),v(1),S(this.requestsCanceler));return t.subscribe((e=>this.add(e))),t};afterInit(){this.disposables.push(this.api.events.pipe(l((({hub:e,event:t})=>"cameras"===e&&("OnCameraUpdated"===t||"OnSystemCameraUpdated"===t))),h((({data:e,event:t})=>"resultItems"in e?{data:e.resultItems[0],event:t}:{data:e,event:t}))).subscribe((({data:e,event:t})=>{const n=this.camerasById.get(e.id);if(!n)return console.warn("got update for unknown camera:",e.id);if("OnSystemCameraUpdated"===t){const t=n.raw;for(const[n,s]of Object.entries(e))null===s&&(e[n]=t[n])}n.update(e)})))}dispose(){this.requestsCanceler.next(),this.camerasById.clear(),this.data=[],this.loading=!1,this.loaded=!1,super.dispose()}}var Wt=function(e,t,n,s){for(var r=-1,i=null==e?0:e.length;++r<i;){var a=e[r];t(s,a,n(a),e)}return s};var Gt=function(e){return function(t,n,s){for(var r=-1,i=Object(t),a=s(t),o=a.length;o--;){var c=a[e?o:++r];if(!1===n(i[c],c,i))break}return t}}();var $t=function(e,t){for(var n=-1,s=Array(e);++n<e;)s[n]=t(n);return s};var Yt=function(e){return null!=e&&"object"==typeof e},Ht=ne,Jt=Yt;var Kt=function(e){return Jt(e)&&"[object Arguments]"==Ht(e)},Zt=Yt,Qt=Object.prototype,Xt=Qt.hasOwnProperty,en=Qt.propertyIsEnumerable,tn=Kt(function(){return arguments}())?Kt:function(e){return Zt(e)&&Xt.call(e,"callee")&&!en.call(e,"callee")},nn=Array.isArray,sn={exports:{}};var rn=function(){return!1};!function(e,t){var n=W,s=rn,r=t&&!t.nodeType&&t,i=r&&e&&!e.nodeType&&e,a=i&&i.exports===r?n.Buffer:void 0,o=(a?a.isBuffer:void 0)||s;e.exports=o}(sn,sn.exports);var an=sn.exports,on=/^(?:0|[1-9]\d*)$/;var cn=function(e,t){var n=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==n||"symbol"!=n&&on.test(e))&&e>-1&&e%1==0&&e<t};var un=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991},ln=ne,hn=un,dn=Yt,pn={};pn["[object Float32Array]"]=pn["[object Float64Array]"]=pn["[object Int8Array]"]=pn["[object Int16Array]"]=pn["[object Int32Array]"]=pn["[object Uint8Array]"]=pn["[object Uint8ClampedArray]"]=pn["[object Uint16Array]"]=pn["[object Uint32Array]"]=!0,pn["[object Arguments]"]=pn["[object Array]"]=pn["[object ArrayBuffer]"]=pn["[object Boolean]"]=pn["[object DataView]"]=pn["[object Date]"]=pn["[object Error]"]=pn["[object Function]"]=pn["[object Map]"]=pn["[object Number]"]=pn["[object Object]"]=pn["[object RegExp]"]=pn["[object Set]"]=pn["[object String]"]=pn["[object WeakMap]"]=!1;var fn=function(e){return dn(e)&&hn(e.length)&&!!pn[ln(e)]};var mn=function(e){return function(t){return e(t)}},vn={exports:{}};!function(e,t){var n=z,s=t&&!t.nodeType&&t,r=s&&e&&!e.nodeType&&e,i=r&&r.exports===s&&n.process,a=function(){try{var e=r&&r.require&&r.require("util").types;return e||i&&i.binding&&i.binding("util")}catch(e){}}();e.exports=a}(vn,vn.exports);var yn=vn.exports,gn=fn,bn=mn,In=yn&&yn.isTypedArray,Tn=In?bn(In):gn,wn=$t,kn=tn,Sn=nn,Bn=an,_n=cn,En=Tn,Cn=Object.prototype.hasOwnProperty;var On=function(e,t){var n=Sn(e),s=!n&&kn(e),r=!n&&!s&&Bn(e),i=!n&&!s&&!r&&En(e),a=n||s||r||i,o=a?wn(e.length,String):[],c=o.length;for(var u in e)!t&&!Cn.call(e,u)||a&&("length"==u||r&&("offset"==u||"parent"==u)||i&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||_n(u,c))||o.push(u);return o},An=Object.prototype;var jn=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||An)};var Rn=function(e,t){return function(n){return e(t(n))}}(Object.keys,Object),Nn=jn,Un=Rn,qn=Object.prototype.hasOwnProperty;var Pn=oe,Dn=un;var xn=function(e){return null!=e&&Dn(e.length)&&!Pn(e)},Fn=On,Mn=function(e){if(!Nn(e))return Un(e);var t=[];for(var n in Object(e))qn.call(e,n)&&"constructor"!=n&&t.push(n);return t},zn=xn;var Ln=function(e){return zn(e)?Fn(e):Mn(e)},Vn=Gt,Wn=Ln;var Gn=xn;var $n=function(e,t){return function(n,s){if(null==n)return n;if(!Gn(n))return e(n,s);for(var r=n.length,i=t?r:-1,a=Object(n);(t?i--:++i<r)&&!1!==s(a[i],i,a););return n}}((function(e,t){return e&&Vn(e,t,Wn)}));var Yn=function(e,t,n,s){return $n(e,(function(e,r,i){t(s,e,n(e),i)})),s},Hn=rt;var Jn=rt,Kn=it,Zn=Tt;var Qn=rt,Xn=function(){this.__data__=new Hn,this.size=0},es=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n},ts=function(e){return this.__data__.get(e)},ns=function(e){return this.__data__.has(e)},ss=function(e,t){var n=this.__data__;if(n instanceof Jn){var s=n.__data__;if(!Kn||s.length<199)return s.push([e,t]),this.size=++n.size,this;n=this.__data__=new Zn(s)}return n.set(e,t),this.size=n.size,this};function rs(e){var t=this.__data__=new Qn(e);this.size=t.size}rs.prototype.clear=Xn,rs.prototype.delete=es,rs.prototype.get=ts,rs.prototype.has=ns,rs.prototype.set=ss;var is=rs;var as=Tt,os=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this},cs=function(e){return this.__data__.has(e)};function us(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new as;++t<n;)this.add(e[t])}us.prototype.add=us.prototype.push=os,us.prototype.has=cs;var ls=us;var hs=function(e,t){return e.has(t)},ds=ls,ps=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},fs=hs;var ms=function(e,t,n,s,r,i){var a=1&n,o=e.length,c=t.length;if(o!=c&&!(a&&c>o))return!1;var u=i.get(e),l=i.get(t);if(u&&l)return u==t&&l==e;var h=-1,d=!0,p=2&n?new ds:void 0;for(i.set(e,t),i.set(t,e);++h<o;){var f=e[h],m=t[h];if(s)var v=a?s(m,f,h,t,e,i):s(f,m,h,e,t,i);if(void 0!==v){if(v)continue;d=!1;break}if(p){if(!ps(t,(function(e,t){if(!fs(p,t)&&(f===e||r(f,e,n,s,i)))return p.push(t)}))){d=!1;break}}else if(f!==m&&!r(f,m,n,s,i)){d=!1;break}}return i.delete(e),i.delete(t),d};var vs=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e,s){n[++t]=[s,e]})),n};var ys=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n},gs=W.Uint8Array,bs=We,Is=ms,Ts=vs,ws=ys,ks=G?G.prototype:void 0,Ss=ks?ks.valueOf:void 0;var Bs=function(e,t,n,s,r,i,a){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 gs(e),new gs(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return bs(+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=Ts;case"[object Set]":var c=1&s;if(o||(o=ws),e.size!=t.size&&!c)return!1;var u=a.get(e);if(u)return u==t;s|=2,a.set(e,t);var l=Is(o(e),o(t),s,r,i,a);return a.delete(e),l;case"[object Symbol]":if(Ss)return Ss.call(e)==Ss.call(t)}return!1};var _s=function(e,t){for(var n=-1,s=t.length,r=e.length;++n<s;)e[r+n]=t[n];return e},Es=nn;var Cs=function(e,t,n){var s=t(e);return Es(e)?s:_s(s,n(e))};var Os=function(e,t){for(var n=-1,s=null==e?0:e.length,r=0,i=[];++n<s;){var a=e[n];t(a,n,e)&&(i[r++]=a)}return i},As=function(){return[]},js=Object.prototype.propertyIsEnumerable,Rs=Object.getOwnPropertySymbols,Ns=Cs,Us=Rs?function(e){return null==e?[]:(e=Object(e),Os(Rs(e),(function(t){return js.call(e,t)})))}:As,qs=Ln;var Ps=function(e){return Ns(e,qs,Us)},Ds=Object.prototype.hasOwnProperty;var xs=function(e,t,n,s,r,i){var a=1&n,o=Ps(e),c=o.length;if(c!=Ps(t).length&&!a)return!1;for(var u=c;u--;){var l=o[u];if(!(a?l in t:Ds.call(t,l)))return!1}var h=i.get(e),d=i.get(t);if(h&&d)return h==t&&d==e;var p=!0;i.set(e,t),i.set(t,e);for(var f=a;++u<c;){var m=e[l=o[u]],v=t[l];if(s)var y=a?s(v,m,l,t,e,i):s(m,v,l,e,t,i);if(!(void 0===y?m===v||r(m,v,n,s,i):y)){p=!1;break}f||(f="constructor"==l)}if(p&&!f){var g=e.constructor,b=t.constructor;g==b||!("constructor"in e)||!("constructor"in t)||"function"==typeof g&&g instanceof g&&"function"==typeof b&&b instanceof b||(p=!1)}return i.delete(e),i.delete(t),p},Fs=Be(W,"DataView"),Ms=Be(W,"Promise"),zs=Be(W,"Set"),Ls=Fs,Vs=it,Ws=Ms,Gs=zs,$s=Be(W,"WeakMap"),Ys=ne,Hs=de,Js="[object Map]",Ks="[object Promise]",Zs="[object Set]",Qs="[object WeakMap]",Xs="[object DataView]",er=Hs(Ls),tr=Hs(Vs),nr=Hs(Ws),sr=Hs(Gs),rr=Hs($s),ir=Ys;(Ls&&ir(new Ls(new ArrayBuffer(1)))!=Xs||Vs&&ir(new Vs)!=Js||Ws&&ir(Ws.resolve())!=Ks||Gs&&ir(new Gs)!=Zs||$s&&ir(new $s)!=Qs)&&(ir=function(e){var t=Ys(e),n="[object Object]"==t?e.constructor:void 0,s=n?Hs(n):"";if(s)switch(s){case er:return Xs;case tr:return Js;case nr:return Ks;case sr:return Zs;case rr:return Qs}return t});var ar=is,or=ms,cr=Bs,ur=xs,lr=ir,hr=nn,dr=an,pr=Tn,fr="[object Arguments]",mr="[object Array]",vr="[object Object]",yr=Object.prototype.hasOwnProperty;var gr=function(e,t,n,s,r,i){var a=hr(e),o=hr(t),c=a?mr:lr(e),u=o?mr:lr(t),l=(c=c==fr?vr:c)==vr,h=(u=u==fr?vr:u)==vr,d=c==u;if(d&&dr(e)){if(!dr(t))return!1;a=!0,l=!1}if(d&&!l)return i||(i=new ar),a||pr(e)?or(e,t,n,s,r,i):cr(e,t,c,n,s,r,i);if(!(1&n)){var p=l&&yr.call(e,"__wrapped__"),f=h&&yr.call(t,"__wrapped__");if(p||f){var m=p?e.value():e,v=f?t.value():t;return i||(i=new ar),r(m,v,n,s,i)}}return!!d&&(i||(i=new ar),ur(e,t,n,s,r,i))},br=Yt;var Ir=function e(t,n,s,r,i){return t===n||(null==t||null==n||!br(t)&&!br(n)?t!=t&&n!=n:gr(t,n,s,r,e,i))},Tr=is,wr=Ir;var kr=se;var Sr=function(e){return e==e&&!kr(e)},Br=Sr,_r=Ln;var Er=function(e,t){return function(n){return null!=n&&(n[e]===t&&(void 0!==t||e in Object(n)))}},Cr=function(e,t,n,s){var r=n.length,i=r,a=!s;if(null==e)return!i;for(e=Object(e);r--;){var o=n[r];if(a&&o[2]?o[1]!==e[o[0]]:!(o[0]in e))return!1}for(;++r<i;){var c=(o=n[r])[0],u=e[c],l=o[1];if(a&&o[2]){if(void 0===u&&!(c in e))return!1}else{var h=new Tr;if(s)var d=s(u,l,c,e,t,h);if(!(void 0===d?wr(l,u,3,s,h):d))return!1}}return!0},Or=function(e){for(var t=_r(e),n=t.length;n--;){var s=t[n],r=e[s];t[n]=[s,r,Br(r)]}return t},Ar=Er;var jr=function(e){var t=Or(e);return 1==t.length&&t[0][2]?Ar(t[0][0],t[0][1]):function(n){return n===e||Cr(n,e,t)}},Rr=ne,Nr=Yt;var Ur=function(e){return"symbol"==typeof e||Nr(e)&&"[object Symbol]"==Rr(e)},qr=nn,Pr=Ur,Dr=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,xr=/^\w*$/;var Fr=function(e,t){if(qr(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!Pr(e))||(xr.test(e)||!Dr.test(e)||null!=t&&e in Object(t))},Mr=St;var zr=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Lr=/\\(\\)?/g,Vr=function(e){var t=Mr(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(zr,(function(e,n,s,r){t.push(s?r.replace(Lr,"$1"):n||e)})),t}));var Wr=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},Gr=nn,$r=Ur,Yr=G?G.prototype:void 0,Hr=Yr?Yr.toString:void 0;var Jr=function e(t){if("string"==typeof t)return t;if(Gr(t))return Wr(t,e)+"";if($r(t))return Hr?Hr.call(t):"";var n=t+"";return"0"==n&&1/t==-1/0?"-0":n},Kr=Jr;var Zr=nn,Qr=Fr,Xr=Vr,ei=function(e){return null==e?"":Kr(e)};var ti=function(e,t){return Zr(e)?e:Qr(e,t)?[e]:Xr(ei(e))},ni=Ur;var si=function(e){if("string"==typeof e||ni(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t},ri=ti,ii=si;var ai=function(e,t){for(var n=0,s=(t=ri(t,e)).length;null!=e&&n<s;)e=e[ii(t[n++])];return n&&n==s?e:void 0},oi=ai;var ci=ti,ui=tn,li=nn,hi=cn,di=un,pi=si;var fi=function(e,t){return null!=e&&t in Object(e)},mi=function(e,t,n){for(var s=-1,r=(t=ci(t,e)).length,i=!1;++s<r;){var a=pi(t[s]);if(!(i=null!=e&&n(e,a)))break;e=e[a]}return i||++s!=r?i:!!(r=null==e?0:e.length)&&di(r)&&hi(a,r)&&(li(e)||ui(e))};var vi=Ir,yi=function(e,t,n){var s=null==e?void 0:oi(e,t);return void 0===s?n:s},gi=function(e,t){return null!=e&&mi(e,t,fi)},bi=Fr,Ii=Sr,Ti=Er,wi=si;var ki=ai;var Si=function(e){return function(t){return null==t?void 0:t[e]}},Bi=function(e){return function(t){return ki(t,e)}},_i=Fr,Ei=si;var Ci=jr,Oi=function(e,t){return bi(e)&&Ii(t)?Ti(wi(e),t):function(n){var s=yi(n,e);return void 0===s&&s===t?gi(n,e):vi(t,s,3)}},Ai=function(e){return e},ji=nn,Ri=function(e){return _i(e)?Si(Ei(e)):Bi(e)};var Ni=function(e){return"function"==typeof e?e:null==e?Ai:"object"==typeof e?ji(e)?Oi(e[0],e[1]):Ci(e):Ri(e)},Ui=Wt,qi=Yn,Pi=Ni,Di=nn;var xi=M(function(e,t){return function(n,s){var r=Di(n)?Ui:qi,i=t?t():{};return r(n,e,Pi(s),i)}}((function(e,t,n){e[n?0:1].push(t)}),(function(){return[[],[]]})));var Fi=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},Mi=function(e){return e!=e},zi=function(e,t,n){for(var s=n-1,r=e.length;++s<r;)if(e[s]===t)return s;return-1};var Li=function(e,t,n){return t==t?zi(e,t,n):Fi(e,Mi,n)};var Vi=function(e,t){return!!(null==e?0:e.length)&&Li(e,t,0)>-1};var Wi=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 Gi=zs,$i=function(){},Yi=Gi&&1/ys(new Gi([,-0]))[1]==1/0?function(e){return new Gi(e)}:$i,Hi=ls,Ji=Vi,Ki=Wi,Zi=hs,Qi=Yi,Xi=ys;var ea=function(e,t,n){var s=-1,r=Ji,i=e.length,a=!0,o=[],c=o;if(n)a=!1,r=Ki;else if(i>=200){var u=t?null:Qi(e);if(u)return Xi(u);a=!1,r=Zi,c=new Hi}else c=t?[]:o;e:for(;++s<i;){var l=e[s],h=t?t(l):l;if(l=n||0!==l?l:0,a&&h==h){for(var d=c.length;d--;)if(c[d]===h)continue e;t&&c.push(h),o.push(l)}else r(c,h,n)||(c!==o&&c.push(h),o.push(l))}return o},ta=Ni,na=ea;var sa=M((function(e,t){return e&&e.length?na(e,ta(t)):[]}));const ra={Person:"red",Car:"green",Animal:"blue",HardHat:"yellow",Vest:"amber",LicensePlate:"cyan",Fire:"deepOrange",Smoke:"deepPurple"},ia={red:["#f44336","#ff1744"],green:["#4caf50","#00e676"],blue:["#2196f3","#2979ff"],purple:["#9c27b0","#d500f9"],teal:["#009688","#1de9b6"],amber:["#ff8f00","#ffc400"],pink:["#e91e63","#f50057"],cyan:["#00bcd4","#00e5ff"],lightGreen:["#65a30d","#76ff03"],yellow:["#f59e0b","#ffd600"],deepOrange:["#ff5722","#ff3d00"],deepPurple:["#7e57c2","#651fff"],lime:["#22c55e","#c6ff00"],indigo:["#3f51b5","#3d5afe"],lightBlue:["#03a9f4","#00b0ff"]};class aa extends Ct{schemaDescription=[];constructor(){super(),t(this,{schemaDescription:n.ref,foundObjectTypes:r,foundObjectTypesForSelect:r,colorsByFoundObjectType:r})}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.includes("LicensePlate")?e.valueSet.split(", "):e.valueSet.split(", ").concat(["LicensePlate"]):[]}get foundObjectTypesForSelect(){const e=Object.entries(ra).filter((([e])=>this.foundObjectTypes.includes(e))).map((([,e])=>e)),t=Object.keys(ia).filter((t=>!e.includes(t)));let n=0;return this.foundObjectTypes.map((e=>{const s=e in ra?ra[e]:t[n++],r=ia[s];return{value:e,label:e,color:r?.[0],highlightColor:r?.[1],type:"detectedObject"}}))}get colorsByFoundObjectType(){const e=new Map;for(const{value:t,highlightColor:n}of this.foundObjectTypesForSelect)e.set(t,n);return e}fetchAnalyticEventSchema=()=>{this.api.cameras.GetSensorDataSchema("Analytic").subscribe({next:e=>{e.success?o((()=>{this.schemaDescription=e.resultItems})):console.error(e)},error:console.error})};afterInit(){this.fetchAnalyticEventSchema()}dispose(){super.dispose(),this.schemaDescription=[]}}const oa=5e-4;class ca extends Ct{camerasStore;data;eventsByCameraId;eventsByStart;eventsByEnd;eventsByType;eventsByFoundObjects;eventsByColor;pendingRequests;pendingRequestsByEnd;pendingRequestsByStart;pendingRequestsByCameraId;knownIntervals=P();knownIntervalsByCameraId;knownIntervalsByStart;knownIntervalsByEnd;eventsById=new Map;updates=0;updatesByCameraId=new Map;recentAdditions=[];constructor(e){super(),this.camerasStore=e,t(this,{updates:n,recentAdditions:n.ref,processNewEvents:s,add:s,dispose:s}),this.data=P(),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(..."Colors"in t?t.Colors?.map((e=>e.Color))??[]:[])),[])),!0),this.pendingRequests=P(),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,n){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([Number.NEGATIVE_INFINITY,s]),this.knownIntervalsByEnd.filter([t,Number.POSITIVE_INFINITY]);const r=this.knownIntervalsByStart.bottom(Number.POSITIVE_INFINITY),i=[];if(this.knownIntervalsByCameraId.filterAll(),this.knownIntervalsByStart.filterAll(),this.knownIntervalsByEnd.filterAll(),r.length){const a=_t(r.map((e=>[e.from,e.to])));a[0][0]>t&&i.push([t,a[0][0]]);for(let e=0;e<a.length-1;e++)i.push([a[e][1],a[e+1][0]]);a[_t.length-1][1]<s&&i.push([a[_t.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 a=this.pendingRequests.allFiltered()[0];if(this.pendingRequestsByCameraId.filterAll(),this.pendingRequestsByStart.filterAll(),this.pendingRequestsByEnd.filterAll(),a)return;if(r.length&&!i.length)return;const o=s=>this.api.cameras.GetSensorEventsPage({sensorIds:[e],sensorType:"camera",sensorEventTypes:[],startTime:t,endTime:n,rowsLimit:100,isDescending:!0,pageToken:s},null,[]).pipe(d((e=>e.success?s===e.pageInfo.nextPageToken?(console.error("API returned the same page token for the next page. This may lead to infinite loading loop."),f((()=>new Error("API returned the same page token for the next page. This may lead to infinite loading loop.")))):p(e):(console.error(e.error),f((()=>e.error)))))),c=o().pipe(g((e=>e.pageInfo.haveMore?o(e.pageInfo.nextPageToken):b)),h((e=>e.resultItems.map((e=>new Mt(e))))),B());this.pendingRequests.add([{cameraId:e,startTime:t,endTime:n||new Date,request:c}]),c.subscribe({next:this.add,error:e=>{console.error(e),this.pendingRequests.remove((e=>e.request===c))},complete:()=>{this.pendingRequests.remove((e=>e.request===c))}})}add=e=>{const[t,n]=xi(e,(e=>this.eventsById.has(e.id)));for(const e of n)this.eventsById.set(e.id,e);if(this.data.add(n),n.length){const e=new Set(n.map((e=>e.cameraId)));for(const t of e)this.updatesByCameraId.set(t,(this.updatesByCameraId.get(t)??0)+1);this.updates++}for(const e of t){const t=this.eventsById.get(e.id);if(!t)return;t.update(e.raw),this.data.remove((t=>t.id===e.id)),this.data.add([t])}};processNewEvents=({data:e})=>{const t=sa(e.filter((e=>"PeopleCounter"!==e.eventType&&this.camerasStore.camerasById.has(e.sensorId))).reverse(),"id").map((e=>new Mt(e))),n=t.filter((e=>!this.eventsById.has(e.id)));this.add(t),n.length&&(this.recentAdditions=n.map((e=>e.id)))};getEvents({cameraIds:e,from:t,to:n,detectedObjectTypes:s,eventTypes:r,colors:i,probability:a}){this.eventsByStart.filter([+t,n?+n+oa:Number.POSITIVE_INFINITY]),e?.length&&this.eventsByCameraId.filter((t=>e.includes(t))),r?.length&&this.eventsByType.filter((e=>r.includes(e))),s?.length&&this.eventsByFoundObjects.filter((e=>s.includes(e))),i?.size&&this.eventsByColor.filter((e=>i.has(e)));let o=this.eventsByStart.top(Number.POSITIVE_INFINITY);return r?.length&&this.eventsByType.filterAll(),e?.length&&this.eventsByCameraId.filterAll(),s?.length&&this.eventsByFoundObjects.filterAll(),i?.size&&this.eventsByColor.filterAll(),this.eventsByStart.filterAll(),void 0!==a&&s?.length&&(o=o.filter((e=>e.detectedObjects.some((e=>e.Probability>=a&&s.includes(e.Type)))))),o}getOverlappedEvents({cameraId:e,from:t,to:n}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([Number.NEGATIVE_INFINITY,+n+oa]),this.eventsByEnd.filter([+t,Number.POSITIVE_INFINITY]);const s=this.eventsByStart.bottom(Number.POSITIVE_INFINITY);return this.eventsByCameraId.filterAll(),this.eventsByStart.filterAll(),this.eventsByEnd.filterAll(),s}getLastNonAnalyticEventBefore({cameraId:e,date:t}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([Number.NEGATIVE_INFINITY,+t]),this.eventsByType.filter((e=>"Analytic"!==e));const n=this.eventsByStart.top(1);return this.eventsByType.filterAll(),this.eventsByStart.filterAll(),this.eventsByCameraId.filterAll(),n[0]}getLastObjectBefore({cameraId:e,date:t,objectFilters:n}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([Number.NEGATIVE_INFINITY,+t]),this.eventsByType.filter((e=>"Analytic"===e));const{cars:s,people:r,misc:i}=n;r&&s&&i||this.eventsByFoundObjects.filter((e=>i?r||s?!(!r||!s)||(r?"Car"!==e:"Person"!==e):"Person"!==e&&"Car"!==e:r&&s?"Person"===e||"Car"===e:r?"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]}getRunningEvent(e){this.eventsByCameraId.filter(e);const[t]=this.eventsByStart.top(1);if(this.eventsByCameraId.filterAll(),t?.isLive)return t}getFirstNonAnalyticEventAfter({cameraId:e,date:t}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([+t+oa,Number.POSITIVE_INFINITY]),this.eventsByType.filter((e=>"Analytic"!==e));const n=this.eventsByEnd.bottom(1);return this.eventsByType.filterAll(),this.eventsByCameraId.filterAll(),this.eventsByStart.filterAll(),n[0]}getFirstObjectAfter({cameraId:e,date:t,objectFilters:n}){this.eventsByCameraId.filter(e),this.eventsByStart.filter([+t+oa,Number.POSITIVE_INFINITY]),this.eventsByType.filter((e=>"Analytic"===e));const{cars:s,people:r,misc:i}=n;r&&s&&i||this.eventsByFoundObjects.filter((e=>i?r||s?!(!r||!s)||(r?"Car"!==e:"Person"!==e):"Person"!==e&&"Car"!==e:r&&s?"Person"===e||"Car"===e:r?"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(l((({hub:e,event:t})=>"cameras"===e&&"OnCameraMotionEvent"===t))).subscribe(this.processNewEvents)}dispose(){super.dispose(),this.data.remove(Et),this.updates++}}const ua=5e-4;class la extends Ct{thumbnails;thumbnailsByCameraId;thumbnailsByDate;pendingRequests;pendingRequestsByEnd;pendingRequestsByStart;pendingRequestsByCameraId;pendingRequestsByCount;constructor(){super(),this.thumbnails=P(),this.thumbnailsByCameraId=this.thumbnails.dimension((e=>e.cameraId)),this.thumbnailsByDate=this.thumbnails.dimension((e=>+e.timestamp)),this.pendingRequests=P(),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(d((e=>e.success?p(e.resultItems):f((()=>e.error)))),h((t=>t.filter((e=>e.url)).map(this.toThumbnail(e)))),v());return this.pendingRequests.add([{cameraId:e,from:t,to:n,count:s,request:i}]),i.subscribe((e=>{this.thumbnails.add(e),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:"fulfilled",data:s};this.pendingRequestsByCameraId.filter(e),this.pendingRequestsByStart.filter([Number.NEGATIVE_INFINITY,+n+ua]),this.pendingRequestsByEnd.filter([t,Number.POSITIVE_INFINITY]);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("fulfilled"===s.state)return p(s.data);if("pending"===s.state)return s.request.pipe(h((()=>this.getThumbnail({cameraId:e,from:t,to:n}))))}const r=this.api.thumbnails.GetThumbnailInfo({cameraId:e,from:t,to:n}).pipe(d((e=>e.success?p(e.resultItems):f((()=>e.error)))),h((t=>t.filter((e=>e.url)).map(this.toThumbnail(e)))),v());return r.subscribe((e=>{this.thumbnails.add(e),this.pendingRequests.remove((e=>e.request===r))})),this.pendingRequests.add([{cameraId:e,from:t,to:n,count:1,request:r}]),r.pipe(h((()=>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?ua: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+ua]);const s=this.thumbnails.allFiltered();return this.thumbnailsByDate.filterAll(),this.thumbnailsByCameraId.filterAll(),s}toThumbnail=e=>({realtimestamp:t,url:n})=>({cameraId:e,url:n,timestamp:new Date(t)})}const ha={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,UpdateCamera:null,GetSensorDataSchema:null,GetSensorEvents:null,GetSensorEventsPage:null,GetLicensePlateLookUp:null,GetSensorEventsLprPage:null,GetPeopleCountingData: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,GenerateSpeech:null,SendText:null},thumbnails:{GetThumbnailsInfo:null,GetThumbnailInfo:null,GetHeatMapsInfo:null},users:{GetUser:null,UserUpdateProfile:null}};var da,pa,fa={cameras:[{name:"OnCameraAdded"},{name:"OnCameraUpdated"},{name:"OnSystemCameraUpdated"},{name:"OnCameraDeleted"},{name:"OnCameraMotionEvent"}],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"}]};!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTED=3]="DISCONNECTED"}(da||(da={})),function(e){e[e.INFO=0]="INFO",e[e.WARN=1]="WARN",e[e.ERROR=2]="ERROR"}(pa||(pa={}));class ma{static create(e,t,n){return new ma(null!==e?e:ha,t,n)}connectionShutdown$=new T;connection$=new _(null);events=new T;logLevel=pa.ERROR;authStore;createConnection;apiConfig;constructor(e,t,n){this.apiConfig=e,this.init(),this.createConnection=n,this.authStore=t,i((()=>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!==da.DISCONNECTED?t.qs.access_token=e.accessToken:this.connect(e)})),this.connection$.pipe(E((e=>null!==e||!t.isAuthenticated||t.token?.invalid?b:(this.log(pa.WARN,"disconnected by some reason"),C(5e3)))),l((()=>t.isAuthenticated&&!!t.token&&!t.token.invalid))).subscribe((()=>{this.connect(t.token),this.log(pa.WARN,"attempting to reconnect")}))}log=(e,...t)=>{if(e<this.logLevel)return;console[["log","warn","error"][e]](...t)};connect(e){if(this.connection$.getValue()?.state===da.CONNECTED)return;const{accessToken:t}=e,n=this.createConnection(t);for(const e of Object.keys(this.apiConfig))n.createHubProxy(e);for(const[e,t]of Object.entries(fa)){if(!t||!n.proxies[e])return;for(const{name:s}of t)n.proxies[e].on(s,(t=>this.events.next({hub:e,event:s,data:t})))}n.start().done((()=>{this.log(pa.INFO,"connected"),this.connection$.next(n)})).fail((e=>{!e.source||401!==e.source?.status&&403!==e.source?.status&&409!==e.source?.status||this.authStore.invalidateToken(),this.log(pa.ERROR,"connection failed",e)})),n.error((e=>{if(e.source&&(401===e.source.status||403===e.source.status||409===e.source.status))return this.log(pa.WARN,"authentication error, invalidating token"),this.authStore.invalidateToken();this.log(pa.ERROR,"connection error",e)})),n.disconnected((()=>{const e=this.connection$.getValue();e?this.log(pa.WARN,"disconnected",e.lastError):this.log(pa.WARN,"disconnected. this connection is already null"),this.connection$.next(null)})),n.reconnecting((()=>this.log(pa.WARN,"reconnecting"))),n.reconnected((()=>{this.connection$.getValue()===n&&(this.log(pa.WARN,"reconnected"),this.connection$.next(n))}))}shutdownConnection(){const e=this.connection$.getValue();e&&e.stop(),this.connectionShutdown$.next(null)}init(){for(const[e,t]of Object.entries(this.apiConfig)){this[e]={};for(const n of Object.keys(t))this[e][n]=this.createHubMethod(e,n)}}createHubMethod=(e,t)=>{const n=(...s)=>this.connection$.pipe(l(Boolean),l((e=>e.state===da.CONNECTED)),O(1)).pipe(d((n=>new Promise(((r,i)=>{n.proxies[e].invoke(t,...s).done((e=>r(e))).fail((e=>i(e)))})))),A((e=>e instanceof Error&&e.message&&("Connection started reconnecting before invocation result was received."===e.message||"Connection was disconnected before invocation result was received."===e.message)?(this.log(pa.WARN,e.message),n(...s)):e instanceof Error&&e.message&&e.message.startsWith("Caller is not authorized to invoke the ")?(this.log(pa.WARN,e.message),this.connection$.getValue()?.stop(),this.authStore.invalidateToken(),n(...s)):f((()=>e)))),S(this.connectionShutdown$));return n}}class va{accessToken;accessTokenIssued;clientId;expiresIn;refreshToken;refreshTokenExpires;refreshTokenIssued;tokenType;userName;invalid;widgetId;widgetToken;json;constructor(e){this.json=e,this.accessToken=e.access_token||e.accessToken,this.accessTokenIssued=new Date(e.access_token_issued||e.accessTokenIssued),this.clientId=e.client_id||e.clientId,this.expiresIn=e.expires_in??e.expiresIn??Math.floor(((this.accessTokenExpires?.getTime()??Date.now())-Date.now())/1e3),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}_exp=null;get accessTokenExpires(){if(this._exp)return this._exp;if(this.accessToken){try{const t=this.accessToken.split(".")[1],n=(e=function(e){let t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw new Error("Invalid base64")}return t}(t),(new TextDecoder).decode(Uint8Array.from(atob(e),(e=>e.charCodeAt(0))))),s=JSON.parse(n);this._exp=new Date(1e3*s.exp)}catch(e){console.error("failed to parse token",e)}var e;return this._exp||(this._exp=new Date(this.json.access_token_expires||this.json.accessTokenExpires)),this._exp}}}class ya{notifier;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)}}class ga{token=null;isAuthenticating=!1;storage;tokenServiceUrl;tokenStorageKey;deviceInfo;clientId;pendingUpdateTokenRequest=null;get isAuthenticated(){return Boolean(this.token&&!this.isAuthenticating)}constructor({tokenServiceUrl:e,storage:i,tokenStorageKey:a,deviceInfo:u,clientId:h}){t(this,{token:n.ref,isAuthenticating:n,isAuthenticated:r,signOut:s,invalidateToken:s}),this.isAuthenticating=!0,this.storage=i,this.tokenServiceUrl=e,this.tokenStorageKey=a,this.deviceInfo=u,this.clientId=h;const m=function(e,t=!1){const n=r(e);return new j((e=>{const s=c(n,(({newValue:t})=>e.next(t)),t);return()=>s()}))}((()=>this.token)),v=m.pipe(E((e=>{if(null===e)return b;const t=p(e).pipe(d((e=>e.widgetId?this.fetchWidgetToken(e):this.updateToken(e.refreshToken))),y({delay:(e,t)=>e.status&&![500,502,503,504].includes(e.status)?f((()=>e)):C(2**Math.min(t+1,6)*1e3)}));if(!e.invalid&&e.expiresIn){const n=750*e.expiresIn;return C(n).pipe(d((()=>t)))}return t})),A((e=>(console.error(e),o((()=>{this.token=null})),v))));v.subscribe((e=>{o((()=>{this.token=e}))})),m.pipe(R(null),N(),l((([e,t])=>!!(t||!t&&e))),U((([,e])=>this.storeToken(e)))).subscribe(),this.getInitialToken().then((e=>{o((()=>{this.token=e,this.isAuthenticating=!1}))}))}signOut=()=>{this.isAuthenticating||o((()=>{this.token=null}))};signIn=e=>{if(this.isAuthenticating)return;o((()=>{this.isAuthenticating=!0})),!1===e.agreedWithTerms&&(e={...e,agreedWithTerms:void 0});return this.fetchToken(e).then((e=>(o((()=>{this.token=e,this.isAuthenticating=!1})),e))).catch((e=>{throw o((()=>{this.isAuthenticating=!1})),e}))};signInWithToken=e=>{this.isAuthenticating?console.warn("Attempt to sign in with token while authenticating"):o((()=>{this.token=new va(e)}))};invalidateToken=()=>{this.token&&o((()=>{this.token={...this.token,invalid:!0}}))};async getTokenFromStorage(){const e=await this.storage.getItem(this.tokenStorageKey);return e?new va(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?(e.accessTokenExpires&&(e.expiresIn=Math.max(0,Math.floor((+e.accessTokenExpires-Date.now())/1e3))),e):null}async fetchToken(e){const t={clientId:this.clientId,client_id:this.clientId,device:this.deviceInfo,...e},n=new Headers;n.append("Content-Type","application/x-www-form-urlencoded"),n.append("accept","application/json");const s=await fetch(this.tokenServiceUrl,{method:"POST",headers:n,body:new URLSearchParams(t)});try{const e=await s.json();return 200!==s.status?Promise.reject({status:s.status,data:e}):new va(e)}catch(e){return Promise.reject(s)}}async updateToken(e){try{return this.pendingUpdateTokenRequest&&this.pendingUpdateTokenRequest.refreshToken===e||(this.pendingUpdateTokenRequest={refreshToken:e,request:this.fetchToken({refreshToken:e,refresh_token:e,grant_type:"refresh_token"})}),await this.pendingUpdateTokenRequest.request}finally{this.pendingUpdateTokenRequest?.refreshToken===e&&(this.pendingUpdateTokenRequest=null)}}async fetchWidgetToken(e){const{widgetId:t,widgetToken:n}=e;if(!t||!n)throw new Error("token must contain widgetId and widgetToken");const s={widgetId:t,widgetToken:n},r=new Headers;r.append("Content-Type","application/json"),r.append("accept","application/json");const i=await fetch(this.tokenServiceUrl,{method:"POST",headers:r,body:JSON.stringify(s)});try{const e=await i.json();return 200!==i.status?Promise.reject({status:i.status,data:e}):new va({widgetId:t,widgetToken:n,...e})}catch(e){return Promise.reject(i)}}}const ba="default",Ia=new Map;class Ta{name;initialized=!1;cameras=new Vt;archives=new Lt(this.cameras);_events=null;get events(){return this._events||(this._events=new ca(this.cameras),this.initialized&&this._events.initWith(this.api)),this._events}eventSchema=new aa;thumbnails=new la;account=new qt;notification=new ya({success:console.log,warn:console.warn,error:console.error});disposables=[];tokenUpdateReactions=new Set;constructor(e){this.name=e,t(this,{initialized:n}),this.disposables.push(a((()=>!!this.account.user),(()=>{this.cameras.load()})))}init({clientId:t="WebApp",token:n,tokenStorage:s=new Bt,tokenStorageKey:r,apiUrl:i="https://services.3deye.me/reactiveapi",tokenServiceUrl:a="https://admin.3deye.me/webapi/v3/auth/token"},c=ba){return r||(r=`@3deye-toolkit/${c}/token`),Ia.has(c)?(console.warn("Can`t init two apps with the same name"),Ia.get(c)):this.auth&&c===this.name?(console.warn("Can`t init already inited app"),this):this.auth||this.name===ba&&c!==ba?new Ta(c).init({clientId:t,token:n,tokenStorage:s,tokenStorageKey:r,apiUrl:i,tokenServiceUrl:a},c):(t=n&&"clientId"in n?n.clientId:t,n&&s.setItem(r,JSON.stringify(n)),this.auth=new ga({tokenServiceUrl:a,tokenStorageKey:r,storage:s,clientId:t,deviceInfo:null}),this.api=ma.create(ha,this.auth,(t=>e(i,{qs:{access_token:t}}))),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),o((()=>{this.initialized=!0})),Ia.set(c,this),this)}dispose=()=>{for(const e of this.disposables)e instanceof u?e.closed||e.unsubscribe():e();for(const e of this.tokenUpdateReactions)e();this.tokenUpdateReactions.clear(),this.auth.signOut(),this.cameras.dispose(),this._events?.dispose(),this.thumbnails.dispose(),this.eventSchema.dispose(),this.account.dispose(),Ia.delete(this.name)};onTokenUpdate=e=>{if(!this.auth)throw new Error("app has to be inited first");const t=i((()=>this.auth.token),(t=>e(t?.json||null)));return this.tokenUpdateReactions.add(t),()=>{t(),this.tokenUpdateReactions.delete(t)}}}var wa=new Ta(ba);var ka=x.createContext(null);export{ka as AppContext,wa as app};
@@ -5,7 +5,7 @@
5
5
  "toolPackages": [
6
6
  {
7
7
  "packageName": "@microsoft/api-extractor",
8
- "packageVersion": "7.47.4"
8
+ "packageVersion": "7.52.10"
9
9
  }
10
10
  ]
11
11
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@3deye-toolkit/core",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
4
4
  "module": "dist/core.js",
5
5
  "types": "dist/core.d.ts",
6
6
  "files": [
@@ -10,14 +10,14 @@
10
10
  "crossfilter2": "^1.5.4",
11
11
  "jqueryless-signalr": "1.0.0",
12
12
  "lodash": "4.17.21",
13
- "mobx": "^6.10.2",
14
- "rxjs": "^7.8.1",
13
+ "mobx": "6",
14
+ "rxjs": "7",
15
15
  "string-natural-compare": "^3.0.1",
16
16
  "zod": "^3.22.2"
17
17
  },
18
18
  "peerDependencies": {
19
- "react": "^16.8.0 || ^17 || ^18",
20
- "react-dom": "^16.8.0 || ^17 || ^18"
19
+ "react": "^16.8.0 || ^17 || ^18 || ^19",
20
+ "react-dom": "^16.8.0 || ^17 || ^18 || ^19"
21
21
  },
22
22
  "publishConfig": {
23
23
  "access": "public",