@3deye-toolkit/core 0.0.5 → 0.0.6

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
@@ -1198,7 +1198,6 @@ declare class ThumbnailsStore extends ApiStore {
1198
1198
 
1199
1199
  declare class Token {
1200
1200
  accessToken: string;
1201
- accessTokenExpires: Date;
1202
1201
  accessTokenIssued: Date;
1203
1202
  clientId: string;
1204
1203
  expiresIn: number;
@@ -1212,6 +1211,8 @@ declare class Token {
1212
1211
  widgetToken?: string;
1213
1212
  json: RawToken;
1214
1213
  constructor(raw: RawToken);
1214
+ private _exp;
1215
+ get accessTokenExpires(): Date;
1215
1216
  }
1216
1217
 
1217
1218
  declare class ToolkitApp implements App {
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 C,BehaviorSubject as B,switchMap as _,timer as E,delay as O,take as A,catchError as R,Observable as j,startWith as N,pairwise as q,concatMap as U}from"rxjs";import D from"string-natural-compare";import P from"crossfilter2";import{z as F}from"zod";import x from"react";var M="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function z(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var L="object"==typeof M&&M&&M.Object===Object&&M,W=L,V="object"==typeof self&&self&&self.Object===Object&&self,G=W||V||Function("return this")(),$=G.Symbol,H=$,Y=Object.prototype,K=Y.hasOwnProperty,J=Y.toString,Z=H?H.toStringTag:void 0;var Q=function(e){var t=K.call(e,Z),n=e[Z];try{e[Z]=void 0;var s=!0}catch(e){}var r=J.call(e);return s&&(t?e[Z]=n:delete e[Z]),r},X=Object.prototype.toString;var ee=Q,te=function(e){return X.call(e)},ne=$?$.toStringTag:void 0;var se=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":ne&&ne in Object(e)?ee(e):te(e)};var re=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},ie=se,ae=re;var oe,ue=function(e){if(!ae(e))return!1;var t=ie(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t},ce=G["__core-js_shared__"],le=(oe=/[^.]+$/.exec(ce&&ce.keys&&ce.keys.IE_PROTO||""))?"Symbol(src)_1."+oe:"";var he=function(e){return!!le&&le in e},de=Function.prototype.toString;var pe=function(e){if(null!=e){try{return de.call(e)}catch(e){}try{return e+""}catch(e){}}return""},fe=ue,me=he,ve=re,ye=pe,ge=/^\[object .+?Constructor\]$/,be=Function.prototype,Ie=Object.prototype,we=be.toString,Te=Ie.hasOwnProperty,ke=RegExp("^"+we.call(Te).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var Se=function(e){return!(!ve(e)||me(e))&&(fe(e)?ke:ge).test(ye(e))},Ce=function(e,t){return null==e?void 0:e[t]};var Be=function(e,t){var n=Ce(e,t);return Se(n)?n:void 0},_e=Be(Object,"create"),Ee=_e;var Oe=function(){this.__data__=Ee?Ee(null):{},this.size=0};var Ae=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},Re=_e,je=Object.prototype.hasOwnProperty;var Ne=function(e){var t=this.__data__;if(Re){var n=t[e];return"__lodash_hash_undefined__"===n?void 0:n}return je.call(t,e)?t[e]:void 0},qe=_e,Ue=Object.prototype.hasOwnProperty;var De=_e;var Pe=Oe,Fe=Ae,xe=Ne,Me=function(e){var t=this.__data__;return qe?void 0!==t[e]:Ue.call(t,e)},ze=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=De&&void 0===t?"__lodash_hash_undefined__":t,this};function Le(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])}}Le.prototype.clear=Pe,Le.prototype.delete=Fe,Le.prototype.get=xe,Le.prototype.has=Me,Le.prototype.set=ze;var We=Le;var Ve=function(){this.__data__=[],this.size=0};var Ge=function(e,t){return e===t||e!=e&&t!=t},$e=Ge;var He=function(e,t){for(var n=e.length;n--;)if($e(e[n][0],t))return n;return-1},Ye=He,Ke=Array.prototype.splice;var Je=He;var Ze=He;var Qe=He;var Xe=Ve,et=function(e){var t=this.__data__,n=Ye(t,e);return!(n<0)&&(n==t.length-1?t.pop():Ke.call(t,n,1),--this.size,!0)},tt=function(e){var t=this.__data__,n=Je(t,e);return n<0?void 0:t[n][1]},nt=function(e){return Ze(this.__data__,e)>-1},st=function(e,t){var n=this.__data__,s=Qe(n,e);return s<0?(++this.size,n.push([e,t])):n[s][1]=t,this};function rt(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])}}rt.prototype.clear=Xe,rt.prototype.delete=et,rt.prototype.get=tt,rt.prototype.has=nt,rt.prototype.set=st;var it=rt,at=Be(G,"Map"),ot=We,ut=it,ct=at;var lt=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e};var ht=function(e,t){var n=e.__data__;return lt(t)?n["string"==typeof t?"string":"hash"]:n.map},dt=ht;var pt=ht;var ft=ht;var mt=ht;var vt=function(){this.size=0,this.__data__={hash:new ot,map:new(ct||ut),string:new ot}},yt=function(e){var t=dt(this,e).delete(e);return this.size-=t?1:0,t},gt=function(e){return pt(this,e).get(e)},bt=function(e){return ft(this,e).has(e)},It=function(e,t){var n=mt(this,e),s=n.size;return n.set(e,t),this.size+=n.size==s?0:1,this};function wt(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])}}wt.prototype.clear=vt,wt.prototype.delete=yt,wt.prototype.get=gt,wt.prototype.has=bt,wt.prototype.set=It;var Tt=wt,kt=Tt;function St(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(St.Cache||kt),n}St.Cache=kt;var Ct=St;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 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 Rt=F.enum(["fill","contain"]),jt=F.object({lat:F.number(),lon:F.number(),fov:F.number()}),Nt=F.object({params:F.object({x:F.number(),y:F.number(),r:F.number(),s:F.number()}),positions:F.tuple([jt,jt,jt]).optional()}),qt=F.tuple([F.number(),F.number(),F.number()]),Ut=F.object({[At.DEFAULT_VIDEO_RESIZE_MODE]:Rt.optional(),[At.RESIZE_MODE_PER_CAMERA]:F.array(F.tuple([F.number(),Rt])).optional(),[At.FISHEYE_CAMERAS]:F.array(F.tuple([F.number(),F.union([qt,Nt,F.null()])])).optional(),[At.UTC]:F.boolean().default(!1),[At.HOUR12]:F.boolean().default(!1),[At.START_OF_WEEK]:F.enum(["monday","sunday"]).default("monday")});class Dt 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 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,this.id=e.id}}class Ft{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 Mt=new Set(["LicensePlate","FaceDetection","Analytic","SpeedDetection","Temperature","PoS","GPS","DigitalInput","Loitering"]);class zt{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!Mt.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=Mt.has(this.type),this.detectedObjects||(this.detectedObjects=[])}}const Lt=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=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))}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 Pt(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+Lt]),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+Lt]);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 Pt(e))))}))}}class Vt 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 Ft(t));this.data=Array.from(this.camerasById.values()).sort(((e,t)=>D(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 $t=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 Ht=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},Kt=se,Jt=Yt;var Zt=function(e){return Jt(e)&&"[object Arguments]"==Kt(e)},Qt=Yt,Xt=Object.prototype,en=Xt.hasOwnProperty,tn=Xt.propertyIsEnumerable,nn=Zt(function(){return arguments}())?Zt:function(e){return Qt(e)&&en.call(e,"callee")&&!tn.call(e,"callee")},sn=Array.isArray,rn={exports:{}};var an=function(){return!1};!function(e,t){var n=G,s=an,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}(rn,rn.exports);var on=rn.exports,un=/^(?:0|[1-9]\d*)$/;var cn=function(e,t){var n=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==n||"symbol"!=n&&un.test(e))&&e>-1&&e%1==0&&e<t};var ln=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991},hn=se,dn=ln,pn=Yt,fn={};fn["[object Float32Array]"]=fn["[object Float64Array]"]=fn["[object Int8Array]"]=fn["[object Int16Array]"]=fn["[object Int32Array]"]=fn["[object Uint8Array]"]=fn["[object Uint8ClampedArray]"]=fn["[object Uint16Array]"]=fn["[object Uint32Array]"]=!0,fn["[object Arguments]"]=fn["[object Array]"]=fn["[object ArrayBuffer]"]=fn["[object Boolean]"]=fn["[object DataView]"]=fn["[object Date]"]=fn["[object Error]"]=fn["[object Function]"]=fn["[object Map]"]=fn["[object Number]"]=fn["[object Object]"]=fn["[object RegExp]"]=fn["[object Set]"]=fn["[object String]"]=fn["[object WeakMap]"]=!1;var mn=function(e){return pn(e)&&dn(e.length)&&!!fn[hn(e)]};var vn=function(e){return function(t){return e(t)}},yn={exports:{}};!function(e,t){var n=L,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}(yn,yn.exports);var gn=yn.exports,bn=mn,In=vn,wn=gn&&gn.isTypedArray,Tn=wn?In(wn):bn,kn=Ht,Sn=nn,Cn=sn,Bn=on,_n=cn,En=Tn,On=Object.prototype.hasOwnProperty;var An=function(e,t){var n=Cn(e),s=!n&&Sn(e),r=!n&&!s&&Bn(e),i=!n&&!s&&!r&&En(e),a=n||s||r||i,o=a?kn(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)||_n(c,u))||o.push(c);return o},Rn=Object.prototype;var jn=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||Rn)};var Nn=function(e,t){return function(n){return e(t(n))}}(Object.keys,Object),qn=jn,Un=Nn,Dn=Object.prototype.hasOwnProperty;var Pn=ue,Fn=ln;var xn=function(e){return null!=e&&Fn(e.length)&&!Pn(e)},Mn=An,zn=function(e){if(!qn(e))return Un(e);var t=[];for(var n in Object(e))Dn.call(e,n)&&"constructor"!=n&&t.push(n);return t},Ln=xn;var Wn=function(e){return Ln(e)?Mn(e):zn(e)},Vn=$t,Gn=Wn;var $n=xn;var Hn=function(e,t){return function(n,s){if(null==n)return n;if(!$n(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,Gn)}));var Yn=function(e,t,n,s){return Hn(e,(function(e,r,i){t(s,e,n(e),i)})),s},Kn=it;var Jn=it,Zn=at,Qn=Tt;var Xn=it,es=function(){this.__data__=new Kn,this.size=0},ts=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n},ns=function(e){return this.__data__.get(e)},ss=function(e){return this.__data__.has(e)},rs=function(e,t){var n=this.__data__;if(n instanceof Jn){var s=n.__data__;if(!Zn||s.length<199)return s.push([e,t]),this.size=++n.size,this;n=this.__data__=new Qn(s)}return n.set(e,t),this.size=n.size,this};function is(e){var t=this.__data__=new Xn(e);this.size=t.size}is.prototype.clear=es,is.prototype.delete=ts,is.prototype.get=ns,is.prototype.has=ss,is.prototype.set=rs;var as=is;var os=Tt,us=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this},cs=function(e){return this.__data__.has(e)};function ls(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new os;++t<n;)this.add(e[t])}ls.prototype.add=ls.prototype.push=us,ls.prototype.has=cs;var hs=ls;var ds=function(e,t){return e.has(t)},ps=hs,fs=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},ms=ds;var vs=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 ps: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(!fs(t,(function(e,t){if(!ms(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 ys=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e,s){n[++t]=[s,e]})),n};var gs=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n},bs=G.Uint8Array,Is=Ge,ws=vs,Ts=ys,ks=gs,Ss=$?$.prototype:void 0,Cs=Ss?Ss.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 bs(e),new bs(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return Is(+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 u=1&s;if(o||(o=ks),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=ws(o(e),o(t),s,r,i,a);return a.delete(e),l;case"[object Symbol]":if(Cs)return Cs.call(e)==Cs.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=sn;var Os=function(e,t,n){var s=t(e);return Es(e)?s:_s(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},Rs=function(){return[]},js=Object.prototype.propertyIsEnumerable,Ns=Object.getOwnPropertySymbols,qs=Os,Us=Ns?function(e){return null==e?[]:(e=Object(e),As(Ns(e),(function(t){return js.call(e,t)})))}:Rs,Ds=Wn;var Ps=function(e){return qs(e,Ds,Us)},Fs=Object.prototype.hasOwnProperty;var xs=function(e,t,n,s,r,i){var a=1&n,o=Ps(e),u=o.length;if(u!=Ps(t).length&&!a)return!1;for(var c=u;c--;){var l=o[c];if(!(a?l in t:Fs.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},Ms=Be(G,"DataView"),zs=Be(G,"Promise"),Ls=Be(G,"Set"),Ws=Ms,Vs=at,Gs=zs,$s=Ls,Hs=Be(G,"WeakMap"),Ys=se,Ks=pe,Js="[object Map]",Zs="[object Promise]",Qs="[object Set]",Xs="[object WeakMap]",er="[object DataView]",tr=Ks(Ws),nr=Ks(Vs),sr=Ks(Gs),rr=Ks($s),ir=Ks(Hs),ar=Ys;(Ws&&ar(new Ws(new ArrayBuffer(1)))!=er||Vs&&ar(new Vs)!=Js||Gs&&ar(Gs.resolve())!=Zs||$s&&ar(new $s)!=Qs||Hs&&ar(new Hs)!=Xs)&&(ar=function(e){var t=Ys(e),n="[object Object]"==t?e.constructor:void 0,s=n?Ks(n):"";if(s)switch(s){case tr:return er;case nr:return Js;case sr:return Zs;case rr:return Qs;case ir:return Xs}return t});var or=as,ur=vs,cr=Bs,lr=xs,hr=ar,dr=sn,pr=on,fr=Tn,mr="[object Arguments]",vr="[object Array]",yr="[object Object]",gr=Object.prototype.hasOwnProperty;var br=function(e,t,n,s,r,i){var a=dr(e),o=dr(t),u=a?vr:hr(e),c=o?vr:hr(t),l=(u=u==mr?yr:u)==yr,h=(c=c==mr?yr:c)==yr,d=u==c;if(d&&pr(e)){if(!pr(t))return!1;a=!0,l=!1}if(d&&!l)return i||(i=new or),a||fr(e)?ur(e,t,n,s,r,i):cr(e,t,u,n,s,r,i);if(!(1&n)){var p=l&&gr.call(e,"__wrapped__"),f=h&&gr.call(t,"__wrapped__");if(p||f){var m=p?e.value():e,v=f?t.value():t;return i||(i=new or),r(m,v,n,s,i)}}return!!d&&(i||(i=new or),lr(e,t,n,s,r,i))},Ir=Yt;var wr=function e(t,n,s,r,i){return t===n||(null==t||null==n||!Ir(t)&&!Ir(n)?t!=t&&n!=n:br(t,n,s,r,e,i))},Tr=as,kr=wr;var Sr=re;var Cr=function(e){return e==e&&!Sr(e)},Br=Cr,_r=Wn;var Er=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 Tr;if(s)var d=s(c,l,u,e,t,h);if(!(void 0===d?kr(l,c,3,s,h):d))return!1}}return!0},Ar=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},Rr=Er;var jr=function(e){var t=Ar(e);return 1==t.length&&t[0][2]?Rr(t[0][0],t[0][1]):function(n){return n===e||Or(n,e,t)}},Nr=se,qr=Yt;var Ur=function(e){return"symbol"==typeof e||qr(e)&&"[object Symbol]"==Nr(e)},Dr=sn,Pr=Ur,Fr=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,xr=/^\w*$/;var Mr=function(e,t){if(Dr(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!Pr(e))||(xr.test(e)||!Fr.test(e)||null!=t&&e in Object(t))},zr=Ct;var Lr=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Wr=/\\(\\)?/g,Vr=function(e){var t=zr(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(Lr,(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},$r=sn,Hr=Ur,Yr=$?$.prototype:void 0,Kr=Yr?Yr.toString:void 0;var Jr=function e(t){if("string"==typeof t)return t;if($r(t))return Gr(t,e)+"";if(Hr(t))return Kr?Kr.call(t):"";var n=t+"";return"0"==n&&1/t==-1/0?"-0":n},Zr=Jr;var Qr=sn,Xr=Mr,ei=Vr,ti=function(e){return null==e?"":Zr(e)};var ni=function(e,t){return Qr(e)?e:Xr(e,t)?[e]:ei(ti(e))},si=Ur;var ri=function(e){if("string"==typeof e||si(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t},ii=ni,ai=ri;var oi=function(e,t){for(var n=0,s=(t=ii(t,e)).length;null!=e&&n<s;)e=e[ai(t[n++])];return n&&n==s?e:void 0},ui=oi;var ci=ni,li=nn,hi=sn,di=cn,pi=ln,fi=ri;var mi=function(e,t){return null!=e&&t in Object(e)},vi=function(e,t,n){for(var s=-1,r=(t=ci(t,e)).length,i=!1;++s<r;){var a=fi(t[s]);if(!(i=null!=e&&n(e,a)))break;e=e[a]}return i||++s!=r?i:!!(r=null==e?0:e.length)&&pi(r)&&di(a,r)&&(hi(e)||li(e))};var yi=wr,gi=function(e,t,n){var s=null==e?void 0:ui(e,t);return void 0===s?n:s},bi=function(e,t){return null!=e&&vi(e,t,mi)},Ii=Mr,wi=Cr,Ti=Er,ki=ri;var Si=oi;var Ci=function(e){return function(t){return null==t?void 0:t[e]}},Bi=function(e){return function(t){return Si(t,e)}},_i=Mr,Ei=ri;var Oi=jr,Ai=function(e,t){return Ii(e)&&wi(t)?Ti(ki(e),t):function(n){var s=gi(n,e);return void 0===s&&s===t?bi(n,e):yi(t,s,3)}},Ri=function(e){return e},ji=sn,Ni=function(e){return _i(e)?Ci(Ei(e)):Bi(e)};var qi=function(e){return"function"==typeof e?e:null==e?Ri:"object"==typeof e?ji(e)?Ai(e[0],e[1]):Oi(e):Ni(e)},Ui=Gt,Di=Yn,Pi=qi,Fi=sn;var xi=z(function(e,t){return function(n,s){var r=Fi(n)?Ui:Di,i=t?t():{};return r(n,e,Pi(s),i)}}((function(e,t,n){e[n?0:1].push(t)}),(function(){return[[],[]]})));var Mi=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},zi=function(e){return e!=e},Li=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?Li(e,t,n):Mi(e,zi,n)};var Vi=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 $i=Ls,Hi=function(){},Yi=$i&&1/gs(new $i([,-0]))[1]==1/0?function(e){return new $i(e)}:Hi,Ki=hs,Ji=Vi,Zi=Gi,Qi=ds,Xi=Yi,ea=gs;var ta=function(e,t,n){var s=-1,r=Ji,i=e.length,a=!0,o=[],u=o;if(n)a=!1,r=Zi;else if(i>=200){var c=t?null:Xi(e);if(c)return ea(c);a=!1,r=Qi,u=new Ki}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},na=qi,sa=ta;var ra=z((function(e,t){return e&&e.length?sa(e,na(t)):[]}));const ia={Person:"red",Car:"green",Animal:"blue",LicensePlate:"cyan",Fire:"deepOrange",Smoke:"deepPurple"},aa={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 oa 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(ia).filter((([e])=>this.foundObjectTypes.includes(e))).map((([,e])=>e)),t=Object.keys(aa).filter((t=>!e.includes(t)));let n=0;return this.foundObjectTypes.map((e=>{const s=e in ia?ia[e]:t[n++],r=aa[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 ua=5e-4;class ca extends Ot{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,update: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?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 zt(e))))),C());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+ua: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+ua]),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+ua,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+ua,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=ra(e.filter((e=>"PeopleCounter"!==e.eventType&&this.camerasStore.camerasById.has(e.sensorId))).reverse(),"id").map((e=>new zt(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(Et),this.updates++}}const la=5e-4;class ha extends Ot{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+la]),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?la: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+la]);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 da={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 pa,fa,ma={cameras:[{name:"OnCameraMotionEvent",explicit:!0},{name:"OnCameraAdded"},{name:"OnCameraUpdated"},{name:"OnSystemCameraUpdated"},{name:"OnCameraDeleted"}],users:[{name:"OnUserUpdateProfile"}],camgroups:[{name:"OnAdd"},{name:"OnUpdate"},{name:"OnDelete"}],archives:[{name:"OnTimelapsAdded"},{name:"OnClipAdded"},{name:"OnClipUpdated"},{name:"OnClipDeleted"},{name:"OnArchiveAdded"},{name:"OnArchiveUpdated"},{name:"OnArchiveDeleted"},{name:"OnArchiveRecordCreated"}]};!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTED=3]="DISCONNECTED"}(pa||(pa={})),function(e){e[e.INFO=0]="INFO",e[e.WARN=1]="WARN",e[e.ERROR=2]="ERROR"}(fa||(fa={}));class va{static create(e,t,n){return new va(null!==e?e:da,t,n)}connectionShutdown$=new w;connection$=new B(null);events=new w;logLevel=fa.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!==pa.DISCONNECTED?t.qs.access_token=e.accessToken:this.connect(e)})),this.connection$.pipe(_((e=>null!==e||!t.isAuthenticated||t.token&&t.token.invalid?b:(this.log(fa.WARN,"disconnected by some reason"),E(5e3)))),l((()=>t.isAuthenticated&&!!t.token&&!t.token.invalid))).subscribe((()=>{this.connect(t.token),this.log(fa.WARN,"attempting to reconnect")})),this.connection$.pipe(l(Boolean),O(100)).subscribe(this.subscribeToEvents)}log=(e,...t)=>{if(e<this.logLevel)return;console[["log","warn","error"][e]](...t)};connect(e){if(this.connection$.getValue()&&this.connection$.getValue().state===pa.CONNECTED)return;const{accessToken:t}=e,n=this.createConnection(t);Object.keys(this.apiConfig).forEach((e=>n.createHubProxy(e))),Object.entries(ma).forEach((([e,t])=>{t&&n.proxies[e]&&t.forEach((({name:t})=>{n.proxies[e].on(t,(n=>this.events.next({hub:e,event:t,data:n})))}))})),n.start().done((()=>{this.log(fa.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(fa.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(fa.WARN,"authentication error, invalidating token"),this.authStore.invalidateToken();this.log(fa.ERROR,"connection error",e)})),n.disconnected((()=>{this.connection$.getValue()?this.log(fa.WARN,"disconnected",this.connection$.getValue().lastError):this.log(fa.WARN,"disconnected. this connection is already null"),this.connection$.next(null)})),n.reconnecting((()=>this.log(fa.WARN,"reconnecting"))),n.reconnected((()=>{this.connection$.getValue()===n&&(this.log(fa.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===pa.CONNECTED)),A(1)).pipe(d((n=>new Promise(((r,i)=>{n.proxies[e].invoke(t,...s).done((e=>r(e))).fail((e=>i(e)))})))),R((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(fa.WARN,e.message),n(...s)):e instanceof Error&&e.message&&e.message.startsWith("Caller is not authorized to invoke the ")?(this.log(fa.WARN,e.message),this.connection$.getValue().stop(),this.authStore.invalidateToken(),n(...s)):f((()=>e)))),S(this.connectionShutdown$));return n};subscribeToEvents=e=>{Object.entries(ma).forEach((([t,n])=>{n&&e.proxies[t]&&e.state===pa.CONNECTED&&n.filter((({explicit:e})=>e)).forEach((({name:n})=>{e.proxies[t].invoke("SubscribeToEvent",n)}))}))}}class ya{accessToken;accessTokenExpires;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.accessTokenExpires=new Date(e.access_token_expires||e.accessTokenExpires||(this.accessToken?1e3*JSON.parse(atob(this.accessToken.split(".")[1])).exp:0)),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}}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: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(_((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)):E(2**Math.min(t+1,6)*1e3)}));if(!e.invalid){const n=Math.max(.75*(+e.accessTokenExpires-Date.now()),0);return E(n).pipe(d((()=>t)))}return t})),R((e=>(console.error(e),o((()=>this.token=null)),v))));v.subscribe((e=>{o((()=>this.token=e))})),m.pipe(N(null),q(),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 ya(e)}))};invalidateToken=()=>{this.token&&o((()=>{this.token={...this.token,invalid:!0}}))};async getTokenFromStorage(){const e=await this.storage.getItem(this.tokenStorageKey);return e?new ya(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 ya(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})}),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 ya({widgetId:t,widgetToken:n,...e})}catch(e){return Promise.reject(i)}}}class ba{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 Ia="default",wa=new Map;class Ta{name;initialized=!1;cameras=new Vt;archives=new Wt(this.cameras);events=new ca(this.cameras);eventSchema=new oa;thumbnails=new ha;account=new Dt;notification=new ba({success:console.log,warn:console.warn,error:console.error});auth;api;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"},u=Ia){return r||(r=`@3deye-toolkit/${u}/token`),wa.has(u)?(console.warn("Can`t init two apps with the same name"),wa.get(u)):this.auth&&u===this.name?(console.warn("Can`t init already inited app"),this):this.auth||this.name===Ia&&u!==Ia?new Ta(u).init({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 ga({tokenServiceUrl:a,tokenStorageKey:r,storage:s,clientId:t,deviceInfo:null}),this.api=va.create(da,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})),wa.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(),wa.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 ka=new Ta(Ia);var Sa=x.createContext(null);export{Sa as AppContext,ka 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 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 C,BehaviorSubject as _,switchMap as B,timer as E,delay as O,take as A,catchError as j,Observable as R,startWith as N,pairwise as U,concatMap as q}from"rxjs";import D from"string-natural-compare";import P from"crossfilter2";import{z as x}from"zod";import F from"react";var M="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function z(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var L="object"==typeof M&&M&&M.Object===Object&&M,W=L,V="object"==typeof self&&self&&self.Object===Object&&self,G=W||V||Function("return this")(),$=G.Symbol,H=$,Y=Object.prototype,K=Y.hasOwnProperty,J=Y.toString,Z=H?H.toStringTag:void 0;var Q=function(e){var t=K.call(e,Z),n=e[Z];try{e[Z]=void 0;var s=!0}catch(e){}var r=J.call(e);return s&&(t?e[Z]=n:delete e[Z]),r},X=Object.prototype.toString;var ee=Q,te=function(e){return X.call(e)},ne=$?$.toStringTag:void 0;var se=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":ne&&ne in Object(e)?ee(e):te(e)};var re=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},ie=se,ae=re;var oe,ue=function(e){if(!ae(e))return!1;var t=ie(e);return"[object Function]"==t||"[object GeneratorFunction]"==t||"[object AsyncFunction]"==t||"[object Proxy]"==t},ce=G["__core-js_shared__"],le=(oe=/[^.]+$/.exec(ce&&ce.keys&&ce.keys.IE_PROTO||""))?"Symbol(src)_1."+oe:"";var he=function(e){return!!le&&le in e},de=Function.prototype.toString;var pe=function(e){if(null!=e){try{return de.call(e)}catch(e){}try{return e+""}catch(e){}}return""},fe=ue,me=he,ve=re,ye=pe,ge=/^\[object .+?Constructor\]$/,be=Function.prototype,Ie=Object.prototype,we=be.toString,Te=Ie.hasOwnProperty,ke=RegExp("^"+we.call(Te).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var Se=function(e){return!(!ve(e)||me(e))&&(fe(e)?ke:ge).test(ye(e))},Ce=function(e,t){return null==e?void 0:e[t]};var _e=function(e,t){var n=Ce(e,t);return Se(n)?n:void 0},Be=_e(Object,"create"),Ee=Be;var Oe=function(){this.__data__=Ee?Ee(null):{},this.size=0};var Ae=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},je=Be,Re=Object.prototype.hasOwnProperty;var Ne=function(e){var t=this.__data__;if(je){var n=t[e];return"__lodash_hash_undefined__"===n?void 0:n}return Re.call(t,e)?t[e]:void 0},Ue=Be,qe=Object.prototype.hasOwnProperty;var De=Be;var Pe=Oe,xe=Ae,Fe=Ne,Me=function(e){var t=this.__data__;return Ue?void 0!==t[e]:qe.call(t,e)},ze=function(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=De&&void 0===t?"__lodash_hash_undefined__":t,this};function Le(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])}}Le.prototype.clear=Pe,Le.prototype.delete=xe,Le.prototype.get=Fe,Le.prototype.has=Me,Le.prototype.set=ze;var We=Le;var Ve=function(){this.__data__=[],this.size=0};var Ge=function(e,t){return e===t||e!=e&&t!=t},$e=Ge;var He=function(e,t){for(var n=e.length;n--;)if($e(e[n][0],t))return n;return-1},Ye=He,Ke=Array.prototype.splice;var Je=He;var Ze=He;var Qe=He;var Xe=Ve,et=function(e){var t=this.__data__,n=Ye(t,e);return!(n<0)&&(n==t.length-1?t.pop():Ke.call(t,n,1),--this.size,!0)},tt=function(e){var t=this.__data__,n=Je(t,e);return n<0?void 0:t[n][1]},nt=function(e){return Ze(this.__data__,e)>-1},st=function(e,t){var n=this.__data__,s=Qe(n,e);return s<0?(++this.size,n.push([e,t])):n[s][1]=t,this};function rt(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])}}rt.prototype.clear=Xe,rt.prototype.delete=et,rt.prototype.get=tt,rt.prototype.has=nt,rt.prototype.set=st;var it=rt,at=_e(G,"Map"),ot=We,ut=it,ct=at;var lt=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e};var ht=function(e,t){var n=e.__data__;return lt(t)?n["string"==typeof t?"string":"hash"]:n.map},dt=ht;var pt=ht;var ft=ht;var mt=ht;var vt=function(){this.size=0,this.__data__={hash:new ot,map:new(ct||ut),string:new ot}},yt=function(e){var t=dt(this,e).delete(e);return this.size-=t?1:0,t},gt=function(e){return pt(this,e).get(e)},bt=function(e){return ft(this,e).has(e)},It=function(e,t){var n=mt(this,e),s=n.size;return n.set(e,t),this.size+=n.size==s?0:1,this};function wt(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])}}wt.prototype.clear=vt,wt.prototype.delete=yt,wt.prototype.get=gt,wt.prototype.has=bt,wt.prototype.set=It;var Tt=wt,kt=Tt;function St(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(St.Cache||kt),n}St.Cache=kt;var Ct=St;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 Bt(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 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 jt=x.enum(["fill","contain"]),Rt=x.object({lat:x.number(),lon:x.number(),fov:x.number()}),Nt=x.object({params:x.object({x:x.number(),y:x.number(),r:x.number(),s:x.number()}),positions:x.tuple([Rt,Rt,Rt]).optional()}),Ut=x.tuple([x.number(),x.number(),x.number()]),qt=x.object({[At.DEFAULT_VIDEO_RESIZE_MODE]:jt.optional(),[At.RESIZE_MODE_PER_CAMERA]:x.array(x.tuple([x.number(),jt])).optional(),[At.FISHEYE_CAMERAS]:x.array(x.tuple([x.number(),x.union([Ut,Nt,x.null()])])).optional(),[At.UTC]:x.boolean().default(!1),[At.HOUR12]:x.boolean().default(!1),[At.START_OF_WEEK]:x.enum(["monday","sunday"]).default("monday")});class Dt 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 qt.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 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,this.id=e.id}}class xt{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 Ft;!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"}(Ft||(Ft={}));const Mt=new Set(["LicensePlate","FaceDetection","Analytic","SpeedDetection","Temperature","PoS","GPS","DigitalInput","Loitering"]);class zt{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!Mt.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=Mt.has(this.type),this.detectedObjects||(this.detectedObjects=[])}}const Lt=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=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))}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 Pt(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+Lt]),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+Lt]);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 Pt(e))))}))}}class Vt 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 xt(t));this.data=Array.from(this.camerasById.values()).sort(((e,t)=>D(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 $t=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 Ht=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},Kt=se,Jt=Yt;var Zt=function(e){return Jt(e)&&"[object Arguments]"==Kt(e)},Qt=Yt,Xt=Object.prototype,en=Xt.hasOwnProperty,tn=Xt.propertyIsEnumerable,nn=Zt(function(){return arguments}())?Zt:function(e){return Qt(e)&&en.call(e,"callee")&&!tn.call(e,"callee")},sn=Array.isArray,rn={exports:{}};var an=function(){return!1};!function(e,t){var n=G,s=an,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}(rn,rn.exports);var on=rn.exports,un=/^(?:0|[1-9]\d*)$/;var cn=function(e,t){var n=typeof e;return!!(t=null==t?9007199254740991:t)&&("number"==n||"symbol"!=n&&un.test(e))&&e>-1&&e%1==0&&e<t};var ln=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=9007199254740991},hn=se,dn=ln,pn=Yt,fn={};fn["[object Float32Array]"]=fn["[object Float64Array]"]=fn["[object Int8Array]"]=fn["[object Int16Array]"]=fn["[object Int32Array]"]=fn["[object Uint8Array]"]=fn["[object Uint8ClampedArray]"]=fn["[object Uint16Array]"]=fn["[object Uint32Array]"]=!0,fn["[object Arguments]"]=fn["[object Array]"]=fn["[object ArrayBuffer]"]=fn["[object Boolean]"]=fn["[object DataView]"]=fn["[object Date]"]=fn["[object Error]"]=fn["[object Function]"]=fn["[object Map]"]=fn["[object Number]"]=fn["[object Object]"]=fn["[object RegExp]"]=fn["[object Set]"]=fn["[object String]"]=fn["[object WeakMap]"]=!1;var mn=function(e){return pn(e)&&dn(e.length)&&!!fn[hn(e)]};var vn=function(e){return function(t){return e(t)}},yn={exports:{}};!function(e,t){var n=L,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}(yn,yn.exports);var gn=yn.exports,bn=mn,In=vn,wn=gn&&gn.isTypedArray,Tn=wn?In(wn):bn,kn=Ht,Sn=nn,Cn=sn,_n=on,Bn=cn,En=Tn,On=Object.prototype.hasOwnProperty;var An=function(e,t){var n=Cn(e),s=!n&&Sn(e),r=!n&&!s&&_n(e),i=!n&&!s&&!r&&En(e),a=n||s||r||i,o=a?kn(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)||Bn(c,u))||o.push(c);return o},jn=Object.prototype;var Rn=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||jn)};var Nn=function(e,t){return function(n){return e(t(n))}}(Object.keys,Object),Un=Rn,qn=Nn,Dn=Object.prototype.hasOwnProperty;var Pn=ue,xn=ln;var Fn=function(e){return null!=e&&xn(e.length)&&!Pn(e)},Mn=An,zn=function(e){if(!Un(e))return qn(e);var t=[];for(var n in Object(e))Dn.call(e,n)&&"constructor"!=n&&t.push(n);return t},Ln=Fn;var Wn=function(e){return Ln(e)?Mn(e):zn(e)},Vn=$t,Gn=Wn;var $n=Fn;var Hn=function(e,t){return function(n,s){if(null==n)return n;if(!$n(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,Gn)}));var Yn=function(e,t,n,s){return Hn(e,(function(e,r,i){t(s,e,n(e),i)})),s},Kn=it;var Jn=it,Zn=at,Qn=Tt;var Xn=it,es=function(){this.__data__=new Kn,this.size=0},ts=function(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n},ns=function(e){return this.__data__.get(e)},ss=function(e){return this.__data__.has(e)},rs=function(e,t){var n=this.__data__;if(n instanceof Jn){var s=n.__data__;if(!Zn||s.length<199)return s.push([e,t]),this.size=++n.size,this;n=this.__data__=new Qn(s)}return n.set(e,t),this.size=n.size,this};function is(e){var t=this.__data__=new Xn(e);this.size=t.size}is.prototype.clear=es,is.prototype.delete=ts,is.prototype.get=ns,is.prototype.has=ss,is.prototype.set=rs;var as=is;var os=Tt,us=function(e){return this.__data__.set(e,"__lodash_hash_undefined__"),this},cs=function(e){return this.__data__.has(e)};function ls(e){var t=-1,n=null==e?0:e.length;for(this.__data__=new os;++t<n;)this.add(e[t])}ls.prototype.add=ls.prototype.push=us,ls.prototype.has=cs;var hs=ls;var ds=function(e,t){return e.has(t)},ps=hs,fs=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},ms=ds;var vs=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 ps: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(!fs(t,(function(e,t){if(!ms(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 ys=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e,s){n[++t]=[s,e]})),n};var gs=function(e){var t=-1,n=Array(e.size);return e.forEach((function(e){n[++t]=e})),n},bs=G.Uint8Array,Is=Ge,ws=vs,Ts=ys,ks=gs,Ss=$?$.prototype:void 0,Cs=Ss?Ss.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 bs(e),new bs(t)));case"[object Boolean]":case"[object Date]":case"[object Number]":return Is(+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 u=1&s;if(o||(o=ks),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=ws(o(e),o(t),s,r,i,a);return a.delete(e),l;case"[object Symbol]":if(Cs)return Cs.call(e)==Cs.call(t)}return!1};var Bs=function(e,t){for(var n=-1,s=t.length,r=e.length;++n<s;)e[r+n]=t[n];return e},Es=sn;var Os=function(e,t,n){var s=t(e);return Es(e)?s:Bs(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},js=function(){return[]},Rs=Object.prototype.propertyIsEnumerable,Ns=Object.getOwnPropertySymbols,Us=Os,qs=Ns?function(e){return null==e?[]:(e=Object(e),As(Ns(e),(function(t){return Rs.call(e,t)})))}:js,Ds=Wn;var Ps=function(e){return Us(e,Ds,qs)},xs=Object.prototype.hasOwnProperty;var Fs=function(e,t,n,s,r,i){var a=1&n,o=Ps(e),u=o.length;if(u!=Ps(t).length&&!a)return!1;for(var c=u;c--;){var l=o[c];if(!(a?l in t:xs.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},Ms=_e(G,"DataView"),zs=_e(G,"Promise"),Ls=_e(G,"Set"),Ws=Ms,Vs=at,Gs=zs,$s=Ls,Hs=_e(G,"WeakMap"),Ys=se,Ks=pe,Js="[object Map]",Zs="[object Promise]",Qs="[object Set]",Xs="[object WeakMap]",er="[object DataView]",tr=Ks(Ws),nr=Ks(Vs),sr=Ks(Gs),rr=Ks($s),ir=Ks(Hs),ar=Ys;(Ws&&ar(new Ws(new ArrayBuffer(1)))!=er||Vs&&ar(new Vs)!=Js||Gs&&ar(Gs.resolve())!=Zs||$s&&ar(new $s)!=Qs||Hs&&ar(new Hs)!=Xs)&&(ar=function(e){var t=Ys(e),n="[object Object]"==t?e.constructor:void 0,s=n?Ks(n):"";if(s)switch(s){case tr:return er;case nr:return Js;case sr:return Zs;case rr:return Qs;case ir:return Xs}return t});var or=as,ur=vs,cr=_s,lr=Fs,hr=ar,dr=sn,pr=on,fr=Tn,mr="[object Arguments]",vr="[object Array]",yr="[object Object]",gr=Object.prototype.hasOwnProperty;var br=function(e,t,n,s,r,i){var a=dr(e),o=dr(t),u=a?vr:hr(e),c=o?vr:hr(t),l=(u=u==mr?yr:u)==yr,h=(c=c==mr?yr:c)==yr,d=u==c;if(d&&pr(e)){if(!pr(t))return!1;a=!0,l=!1}if(d&&!l)return i||(i=new or),a||fr(e)?ur(e,t,n,s,r,i):cr(e,t,u,n,s,r,i);if(!(1&n)){var p=l&&gr.call(e,"__wrapped__"),f=h&&gr.call(t,"__wrapped__");if(p||f){var m=p?e.value():e,v=f?t.value():t;return i||(i=new or),r(m,v,n,s,i)}}return!!d&&(i||(i=new or),lr(e,t,n,s,r,i))},Ir=Yt;var wr=function e(t,n,s,r,i){return t===n||(null==t||null==n||!Ir(t)&&!Ir(n)?t!=t&&n!=n:br(t,n,s,r,e,i))},Tr=as,kr=wr;var Sr=re;var Cr=function(e){return e==e&&!Sr(e)},_r=Cr,Br=Wn;var Er=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 Tr;if(s)var d=s(c,l,u,e,t,h);if(!(void 0===d?kr(l,c,3,s,h):d))return!1}}return!0},Ar=function(e){for(var t=Br(e),n=t.length;n--;){var s=t[n],r=e[s];t[n]=[s,r,_r(r)]}return t},jr=Er;var Rr=function(e){var t=Ar(e);return 1==t.length&&t[0][2]?jr(t[0][0],t[0][1]):function(n){return n===e||Or(n,e,t)}},Nr=se,Ur=Yt;var qr=function(e){return"symbol"==typeof e||Ur(e)&&"[object Symbol]"==Nr(e)},Dr=sn,Pr=qr,xr=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Fr=/^\w*$/;var Mr=function(e,t){if(Dr(e))return!1;var n=typeof e;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=e&&!Pr(e))||(Fr.test(e)||!xr.test(e)||null!=t&&e in Object(t))},zr=Ct;var Lr=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Wr=/\\(\\)?/g,Vr=function(e){var t=zr(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(Lr,(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},$r=sn,Hr=qr,Yr=$?$.prototype:void 0,Kr=Yr?Yr.toString:void 0;var Jr=function e(t){if("string"==typeof t)return t;if($r(t))return Gr(t,e)+"";if(Hr(t))return Kr?Kr.call(t):"";var n=t+"";return"0"==n&&1/t==-1/0?"-0":n},Zr=Jr;var Qr=sn,Xr=Mr,ei=Vr,ti=function(e){return null==e?"":Zr(e)};var ni=function(e,t){return Qr(e)?e:Xr(e,t)?[e]:ei(ti(e))},si=qr;var ri=function(e){if("string"==typeof e||si(e))return e;var t=e+"";return"0"==t&&1/e==-1/0?"-0":t},ii=ni,ai=ri;var oi=function(e,t){for(var n=0,s=(t=ii(t,e)).length;null!=e&&n<s;)e=e[ai(t[n++])];return n&&n==s?e:void 0},ui=oi;var ci=ni,li=nn,hi=sn,di=cn,pi=ln,fi=ri;var mi=function(e,t){return null!=e&&t in Object(e)},vi=function(e,t,n){for(var s=-1,r=(t=ci(t,e)).length,i=!1;++s<r;){var a=fi(t[s]);if(!(i=null!=e&&n(e,a)))break;e=e[a]}return i||++s!=r?i:!!(r=null==e?0:e.length)&&pi(r)&&di(a,r)&&(hi(e)||li(e))};var yi=wr,gi=function(e,t,n){var s=null==e?void 0:ui(e,t);return void 0===s?n:s},bi=function(e,t){return null!=e&&vi(e,t,mi)},Ii=Mr,wi=Cr,Ti=Er,ki=ri;var Si=oi;var Ci=function(e){return function(t){return null==t?void 0:t[e]}},_i=function(e){return function(t){return Si(t,e)}},Bi=Mr,Ei=ri;var Oi=Rr,Ai=function(e,t){return Ii(e)&&wi(t)?Ti(ki(e),t):function(n){var s=gi(n,e);return void 0===s&&s===t?bi(n,e):yi(t,s,3)}},ji=function(e){return e},Ri=sn,Ni=function(e){return Bi(e)?Ci(Ei(e)):_i(e)};var Ui=function(e){return"function"==typeof e?e:null==e?ji:"object"==typeof e?Ri(e)?Ai(e[0],e[1]):Oi(e):Ni(e)},qi=Gt,Di=Yn,Pi=Ui,xi=sn;var Fi=z(function(e,t){return function(n,s){var r=xi(n)?qi:Di,i=t?t():{};return r(n,e,Pi(s),i)}}((function(e,t,n){e[n?0:1].push(t)}),(function(){return[[],[]]})));var Mi=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},zi=function(e){return e!=e},Li=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?Li(e,t,n):Mi(e,zi,n)};var Vi=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 $i=Ls,Hi=function(){},Yi=$i&&1/gs(new $i([,-0]))[1]==1/0?function(e){return new $i(e)}:Hi,Ki=hs,Ji=Vi,Zi=Gi,Qi=ds,Xi=Yi,ea=gs;var ta=function(e,t,n){var s=-1,r=Ji,i=e.length,a=!0,o=[],u=o;if(n)a=!1,r=Zi;else if(i>=200){var c=t?null:Xi(e);if(c)return ea(c);a=!1,r=Qi,u=new Ki}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},na=Ui,sa=ta;var ra=z((function(e,t){return e&&e.length?sa(e,na(t)):[]}));const ia={Person:"red",Car:"green",Animal:"blue",LicensePlate:"cyan",Fire:"deepOrange",Smoke:"deepPurple"},aa={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 oa 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(ia).filter((([e])=>this.foundObjectTypes.includes(e))).map((([,e])=>e)),t=Object.keys(aa).filter((t=>!e.includes(t)));let n=0;return this.foundObjectTypes.map((e=>{const s=e in ia?ia[e]:t[n++],r=aa[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 ua=5e-4;class ca extends Ot{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,update: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=Bt(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[Bt.length-1][1]<s&&i.push([a[Bt.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 zt(e))))),C());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+ua: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+ua]),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+ua,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+ua,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=ra(e.filter((e=>"PeopleCounter"!==e.eventType&&this.camerasStore.camerasById.has(e.sensorId))).reverse(),"id").map((e=>new zt(e))),[n,s]=Fi(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(Et),this.updates++}}const la=5e-4;class ha extends Ot{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+la]),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?la: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+la]);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 da={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 pa,fa,ma={cameras:[{name:"OnCameraMotionEvent",explicit:!0},{name:"OnCameraAdded"},{name:"OnCameraUpdated"},{name:"OnSystemCameraUpdated"},{name:"OnCameraDeleted"}],users:[{name:"OnUserUpdateProfile"}],camgroups:[{name:"OnAdd"},{name:"OnUpdate"},{name:"OnDelete"}],archives:[{name:"OnTimelapsAdded"},{name:"OnClipAdded"},{name:"OnClipUpdated"},{name:"OnClipDeleted"},{name:"OnArchiveAdded"},{name:"OnArchiveUpdated"},{name:"OnArchiveDeleted"},{name:"OnArchiveRecordCreated"}]};!function(e){e[e.CONNECTING=0]="CONNECTING",e[e.CONNECTED=1]="CONNECTED",e[e.RECONNECTING=2]="RECONNECTING",e[e.DISCONNECTED=3]="DISCONNECTED"}(pa||(pa={})),function(e){e[e.INFO=0]="INFO",e[e.WARN=1]="WARN",e[e.ERROR=2]="ERROR"}(fa||(fa={}));class va{static create(e,t,n){return new va(null!==e?e:da,t,n)}connectionShutdown$=new w;connection$=new _(null);events=new w;logLevel=fa.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!==pa.DISCONNECTED?t.qs.access_token=e.accessToken:this.connect(e)})),this.connection$.pipe(B((e=>null!==e||!t.isAuthenticated||t.token&&t.token.invalid?b:(this.log(fa.WARN,"disconnected by some reason"),E(5e3)))),l((()=>t.isAuthenticated&&!!t.token&&!t.token.invalid))).subscribe((()=>{this.connect(t.token),this.log(fa.WARN,"attempting to reconnect")})),this.connection$.pipe(l(Boolean),O(100)).subscribe(this.subscribeToEvents)}log=(e,...t)=>{if(e<this.logLevel)return;console[["log","warn","error"][e]](...t)};connect(e){if(this.connection$.getValue()&&this.connection$.getValue().state===pa.CONNECTED)return;const{accessToken:t}=e,n=this.createConnection(t);Object.keys(this.apiConfig).forEach((e=>n.createHubProxy(e))),Object.entries(ma).forEach((([e,t])=>{t&&n.proxies[e]&&t.forEach((({name:t})=>{n.proxies[e].on(t,(n=>this.events.next({hub:e,event:t,data:n})))}))})),n.start().done((()=>{this.log(fa.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(fa.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(fa.WARN,"authentication error, invalidating token"),this.authStore.invalidateToken();this.log(fa.ERROR,"connection error",e)})),n.disconnected((()=>{this.connection$.getValue()?this.log(fa.WARN,"disconnected",this.connection$.getValue().lastError):this.log(fa.WARN,"disconnected. this connection is already null"),this.connection$.next(null)})),n.reconnecting((()=>this.log(fa.WARN,"reconnecting"))),n.reconnected((()=>{this.connection$.getValue()===n&&(this.log(fa.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===pa.CONNECTED)),A(1)).pipe(d((n=>new Promise(((r,i)=>{n.proxies[e].invoke(t,...s).done((e=>r(e))).fail((e=>i(e)))})))),j((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(fa.WARN,e.message),n(...s)):e instanceof Error&&e.message&&e.message.startsWith("Caller is not authorized to invoke the ")?(this.log(fa.WARN,e.message),this.connection$.getValue().stop(),this.authStore.invalidateToken(),n(...s)):f((()=>e)))),S(this.connectionShutdown$));return n};subscribeToEvents=e=>{Object.entries(ma).forEach((([t,n])=>{n&&e.proxies[t]&&e.state===pa.CONNECTED&&n.filter((({explicit:e})=>e)).forEach((({name:n})=>{e.proxies[t].invoke("SubscribeToEvent",n)}))}))}}class ya{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;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 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: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 R((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)):E(2**Math.min(t+1,6)*1e3)}));if(!e.invalid){const n=Math.max(.75*(+e.accessTokenExpires-Date.now()),0);return E(n).pipe(d((()=>t)))}return t})),j((e=>(console.error(e),o((()=>this.token=null)),v))));v.subscribe((e=>{o((()=>this.token=e))})),m.pipe(N(null),U(),l((([e,t])=>!!(t||!t&&e))),q((([,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 ya(e)}))};invalidateToken=()=>{this.token&&o((()=>{this.token={...this.token,invalid:!0}}))};async getTokenFromStorage(){const e=await this.storage.getItem(this.tokenStorageKey);return e?new ya(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 ya(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})}),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 ya({widgetId:t,widgetToken:n,...e})}catch(e){return Promise.reject(i)}}}class ba{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 Ia="default",wa=new Map;class Ta{name;initialized=!1;cameras=new Vt;archives=new Wt(this.cameras);events=new ca(this.cameras);eventSchema=new oa;thumbnails=new ha;account=new Dt;notification=new ba({success:console.log,warn:console.warn,error:console.error});auth;api;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=Ia){return r||(r=`@3deye-toolkit/${u}/token`),wa.has(u)?(console.warn("Can`t init two apps with the same name"),wa.get(u)):this.auth&&u===this.name?(console.warn("Can`t init already inited app"),this):this.auth||this.name===Ia&&u!==Ia?new Ta(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 ga({tokenServiceUrl:a,tokenStorageKey:r,storage:s,clientId:t,deviceInfo:null}),this.api=va.create(da,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})),wa.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(),wa.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 ka=new Ta(Ia);var Sa=F.createContext(null);export{Sa as AppContext,ka as app};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@3deye-toolkit/core",
3
- "version": "0.0.5",
3
+ "version": "0.0.6",
4
4
  "module": "dist/core.js",
5
5
  "types": "dist/core.d.ts",
6
6
  "files": [