import{a as N,d as O}from"./chunk-5HOZEP3O.js";import{a as D}from"./chunk-RB5TOXJE.js";import{Qb as A,rb as W}from"./chunk-YSQLW2JA.js";import{Aa as w,Cb as x,Id as m,Pd as _,Qf as P,Sc as y,Sd as T,bb as R,dd as k,ea as C,h as l,j as p,jb as v,m as f,pc as E,wa as b,x as u,ya as S}from"./chunk-SKPDQO4E.js";var I=`<ng-container *ngIf="visibleComponent">
    <div class="modal-header">
        <div class="d-flex align-items-center justify-content-between w-100">
            <div class="d-flex flex-column">
                <span class="text-lg">{{cameraData.camera.name}}</span>
                <span *ngIf="cameraData.remoteAccessPoint" class="text-md">{{cameraData.remoteAccessPoint.name}}</span>
            </div>
            <div>
                <span class="spinner-grow spinner-grow-sm text-primary" *ngIf="visibleSpinner"></span>
                <div class="d-flex flex-column align-items-end" *ngIf="!visibleSpinner">
                    <span class="text-xs">{{'WIDGET.LAST_UPDATE_DATE'|translate}}</span>
                    <span class="ms-2 text-sm fw-medium">{{updateDate|date:'HH:mm:ss'}}</span>
                </div>
            </div>
        </div>
    </div>
    <div class="modal-body body-container d-flex justify-content-center">
        <!-- <img [src]="streamUrl  | secure:cameraData.camera.userName:cameraData.camera.password | async" #streamImage
            *ngIf="!visibleStreamFailed" class="stream-image img-fluid" (load)="streamLoaded()"
            (error)="streamLoadFailed()" [hidden]="true"> -->
        <img [src]="streamUrl" #streamImage class="stream-image img-fluid" (load)="streamLoaded()"
            [hidden]="visibleStreamFailed" (error)="streamLoadFailed()">
        <img class="stream-image img-fluid" [src]="base64Data" *ngIf="base64Data">
        <div *ngIf="visibleStreamFailed" class="stream-failed img-fluid">
            <cds-icon shape="warning-standard" solid size="lg"></cds-icon>
            <span class="error-text">{{'CAMERA.ERROR_STREAM_FAILED' | translate}}</span>
        </div>
    </div>
    <div class="modal-footer justify-content-between">
        <div class="remote-buttons">
            <armon-remote-control-item-buttons *ngIf="cameraData.remoteAccessPoint"
                [remoteAccessPoint]="cameraData.remoteAccessPoint">
            </armon-remote-control-item-buttons>
        </div>
        <button class="btn btn-outline-primary" (click)="closeClicked($event)">
            {{'BUTTON.CLOSE' | translate}}
        </button>
    </div>
</ng-container>`;var U=`.justify-content-center{-webkit-box-pack:center;-moz-box-pack:center;-webkit-flex-pack:center;-ms-flex-pack:center;-moz-justify-content:center;-webkit-justify-content:center;justify-content:center}.justify-content-flex-end{-webkit-box-pack:end;-moz-box-pack:end;-webkit-flex-pack:end;-ms-flex-pack:end;-moz-justify-content:flex-end;-webkit-justify-content:flex-end;justify-content:flex-end}.card-footer{padding:.28rem .7rem}.alert{font-size:.756rem}@media screen and (min-width: 992px){.modal-xxl{max-width:1640px}}@media screen and (min-width: 1200px){.modal-xxxl{max-width:1860px}}.modal-fs{max-width:none;position:absolute;margin:auto;inset:16px;height:100vh;display:flex}.btn-link{text-decoration:none}.btn-link:hover{text-decoration:underline}.invalid-feedback{margin-top:0!important;font-size:.672rem!important}:host .header-container{margin-bottom:18px;display:-webkit-box;display:-moz-box;display:-webkit-flexbox;display:-ms-flexbox;display:-webkit-flex;display:flex;-webkit-box-orient:horizontal;-moz-box-orient:horizontal;-webkit-flex-direction:row;-moz-flex-direction:row;-ms-flex-direction:row;flex-direction:row}:host .header-container .title-container{-webkit-flex-grow:1;-moz-flex-grow:1;-ms-flex-positive:1;flex-grow:1;-webkit-flex-shrink:1;-webkit-box-flex:1;-moz-flex-shrink:1;-ms-flex-negative:1;flex-shrink:1;-webkit-flex-basis:auto;-moz-flex-basis:auto;-ms-flex-preferred-size:auto;flex-basis:auto;display:-webkit-box;display:-moz-box;display:-webkit-flexbox;display:-ms-flexbox;display:-webkit-flex;display:flex;-webkit-box-orient:vertical;-moz-box-orient:vertical;-webkit-flex-direction:column;-moz-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-box-pack:center;-moz-box-pack:center;-webkit-flex-pack:center;-ms-flex-pack:center;-moz-justify-content:center;-webkit-justify-content:center;justify-content:center}:host .header-container .title-container .camera-name{font-size:.84rem}:host .header-container .title-container .remote-access-name{font-size:.714rem}:host .body-container{position:relative;background-color:#000}:host .body-container .stream-image{min-height:360px;-webkit-border-radius:.56rem;-moz-border-radius:.56rem;border-radius:.56rem}:host .body-container .stream-canvas{max-width:100%}:host .body-container .stream-failed{padding:36px;background-color:#000;color:#c82602;display:-webkit-box;display:-moz-box;display:-webkit-flexbox;display:-ms-flexbox;display:-webkit-flex;display:flex;-webkit-box-orient:vertical;-moz-box-orient:vertical;-webkit-flex-direction:column;-moz-flex-direction:column;-ms-flex-direction:column;flex-direction:column;-webkit-box-pack:center;-moz-box-pack:center;-webkit-flex-pack:center;-ms-flex-pack:center;-moz-justify-content:center;-webkit-justify-content:center;justify-content:center;-webkit-box-align:center;-ms-flex-align:center;-webkit-align-items:center;-moz-align-items:center;align-items:center}:host .body-container .stream-failed .error-text{margin-top:18px;color:#fff;text-align:center}:host .body-container .base-overlay{position:absolute;margin:auto;inset:0}:host .body-container .stream-spinner{display:-webkit-box;display:-moz-box;display:-webkit-flexbox;display:-ms-flexbox;display:-webkit-flex;display:flex;-webkit-box-pack:center;-moz-box-pack:center;-webkit-flex-pack:center;-ms-flex-pack:center;-moz-justify-content:center;-webkit-justify-content:center;justify-content:center;-webkit-box-align:center;-ms-flex-align:center;-webkit-align-items:center;-moz-align-items:center;align-items:center}:host .remote-buttons{width:200px}
`;function z(s=0,e=0,t,n,i){if(t.length>64)throw new Error("WebRTC Data Channel Protocol Error webprequest cameraId length must be less than 48");let o=new Uint8Array([1,s,e]),a=i.encode(t),r=i.encode(n),c=new Uint8Array(o.length+a.length+r.length);return c.set(o,0),c.set(a,o.length),c.set(r,o.length+a.length),c.buffer}function q(s,e){if(s.length>64)throw new Error("WebRTC Data Channel Protocol Error webprequest cancel requestId length must be less than 48");let t=new Uint8Array([4]),n=e.encode(s),i=new Uint8Array(t.length+n.length);return i.set(t,0),i.set(n,t.length),i.buffer}function j(s,e,t){let n=new Uint8Array(s.data);switch(n[0]){case 0:return e.onPing(t.decode(n.slice(1)));case 1:return e.onWebpRequest(H(n,t));case 2:return e.onWebpResponse(K(n,t));case 3:return e.onWebpFailResponse(Q(n,t));case 4:return e.onWebpCancelRequest(J(n,t));default:throw new Error("Unknown protocol message")}}function H(s,e){return{chunkSize:s[1],interval:s[2],cameraId:e.decode(s.slice(3,39)),requestId:e.decode(s.slice(39))}}function K(s,e){let t=e.decode(s.slice(2,38)),n=e.decode(s.slice(38,74));return{isFirst:s[1]===0,isLast:s[1]===2,requestId:t,webpId:n,chunk:s.slice(74)}}function Q(s,e){let t=e.decode(s.slice(1,37)),n=e.decode(s.slice(37,73)),i=e.decode(s.slice(73));return{requestId:t,webpId:n,error:i}}function J(s,e){return e.decode(s.slice(1,37))}var V=new TextDecoder,B=new TextEncoder,h=class s{socketService;utilityInitializerService;static instance;downloadingImages={};imageRequests={};connections={};constructor(e,t){this.socketService=e,this.utilityInitializerService=t,this.init()}init(){return l(this,null,function*(){this.socketService.onWebRTCOfferReceived.subscribe(e=>{}),this.socketService.onWebRTCAnswerReceived.subscribe(e=>l(this,null,function*(){if(e.proxyTerminalId)if(e.sdp){let t=new RTCSessionDescription(e.sdp);yield this.connections[e.proxyTerminalId].peer.setRemoteDescription(t).catch(n=>{this.reportError(n,e.proxyTerminalId)})}else this.connections[e.proxyTerminalId].receiveChannelSubject.error("noConnection"),this.closeConnection(e.proxyTerminalId);this.connections[e.proxyTerminalId]&&this.connections[e.proxyTerminalId].pendingCandidates&&this.connections[e.proxyTerminalId].pendingCandidates.length>0&&(yield this.addPendingRemoteCandidates(e.proxyTerminalId))})),this.socketService.onWebRTCNewIceCandidateReceived.subscribe(e=>l(this,null,function*(){console.log("*** Adding received ICE candidate: "+JSON.stringify(e.candidateData));try{yield this.addRemoteCandidate(e.proxyTerminalId,new RTCIceCandidate(e.candidateData))}catch{this.closeConnection(e.proxyTerminalId)}}))})}static getInstance(e,t){return s.instance||(s.instance=new s(e,t)),s.instance}getImage(e,t,n=0,i=null,o=null){return new p(r=>{if(this.utilityInitializerService.hasWebRTCSupport)if(i||(i=m()),this.imageRequests[i]={peerId:e,cameraId:t,observer:r,interval:n},this.isConnectionUp(e))this.requestImage(i);else if(this.connections&&this.connections[e])u([this.connections[e].sendChannelSubject,this.connections[e].receiveChannelSubject]).subscribe(c=>{},c=>{this.cancelImage(i)},()=>{console.log("CONNECTED (Recorded) >> "+e),this.connections[e].ready=!0,this.requestImage(i)});else{let c=new f(null),g=new f(null);this.createPeerConnection(e,t,c,g,o),u([c,g]).subscribe(L=>{},L=>{this.cancelImage(i)},()=>{console.log("CONNECTED (New) >> "+e),this.connections[e].ready=!0,this.requestImage(i)})}else setTimeout(()=>{r.error("noWebRTCSupport")},300)})}isConnectionUp(e){let t=!1;return this.connections&&this.connections[e]&&this.connections[e].ready&&(t=!0),t}requestImage(e){this.connections[this.imageRequests[e].peerId].sendChannel.send(z(0,this.imageRequests[e].interval,this.imageRequests[e].cameraId,e,B))}addRemoteCandidate(e,t){return l(this,null,function*(){if(this.connections[e])try{this.connections[e].peer.remoteDescription&&this.connections[e].peer.remoteDescription.type?yield this.connections[e].peer.addIceCandidate(t).catch(n=>{this.reportError(n,e)}):this.connections[e]&&this.connections[e].pendingCandidates&&this.connections[e].pendingCandidates.push(t)}catch(n){this.reportError(n,e)}})}addPendingRemoteCandidates(e){return l(this,null,function*(){try{this.connections[e]&&this.connections[e].pendingCandidates&&this.connections[e].pendingCandidates.forEach(t=>{this.addRemoteCandidate(e,t)})}catch(t){this.reportError(t,e)}})}cancelAllConnections(){Object.keys(this.connections).forEach(e=>{this.closeConnection(e)})}cancelImage(e,t=!0,n="cancelled"){if(t)try{this.imageRequests[e]&&this.connections[this.imageRequests[e].peerId]&&this.connections[this.imageRequests[e].peerId].sendChannel&&this.connections[this.imageRequests[e].peerId].sendChannel.readyState=="open"&&this.connections[this.imageRequests[e].peerId].sendChannel.send(q(e,B))}catch(i){console.log(i)}this.imageRequests[e]&&(this.cancelDownloadingImage(e),delete this.downloadingImages[e],this.imageRequests[e]&&this.imageRequests[e].observer&&this.imageRequests[e].observer.error(n),delete this.imageRequests[e])}cancelDownloadingImage(e){e&&this.downloadingImages[e]&&delete this.downloadingImages[e]}generatWebRtcHandle(e){return{onPing:t=>{},onWebpResponse:t=>{if(t.isFirst)this.downloadingImages[t.requestId]=[],this.downloadingImages[t.requestId].push(t.chunk);else if(t.isLast)if(this.downloadingImages[t.requestId]){this.downloadingImages[t.requestId].push(t.chunk);let n=new Blob(this.downloadingImages[t.requestId]);t.requestId&&this.imageRequests[t.requestId]&&(this.imageRequests[t.requestId]?.observer.next(URL.createObjectURL(n)),this.imageRequests[t.requestId].interval==0&&setTimeout(()=>{this.cancelImage(t.requestId,!1)},1e3)),this.cancelDownloadingImage(t.requestId)}else this.cancelImage(t.requestId,!1);else this.downloadingImages[t.requestId]?this.downloadingImages[t.requestId].push(t.chunk):this.cancelImage(t.requestId,!1)},onWebpRequest:t=>{},onWebpFailResponse:t=>{this.cancelDownloadingImage(t.requestId)},onWebpCancelRequest:t=>{}}}createPeerConnection(e,t,n,i,o=null){console.log("Setting up peer connection");let a=new RTCPeerConnection({iceServers:o||[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:global.stun.twilio.com:3478?transport=udp"}]});a.ondatachannel=c=>{this.receiveChannelCallback(e,c)},a.onicecandidate=c=>{this.handleICECandidateEvent(e,a,c)},a.oniceconnectionstatechange=c=>{this.handleICEConnectionStateChangeEvent(e,a,c)},a.onicegatheringstatechange=c=>{this.handleICEGatheringStateChangeEvent(e,a,c)},a.onsignalingstatechange=c=>{this.handleSignalingStateChangeEvent(e,a,c)},a.onnegotiationneeded=c=>{this.handleNegotiationNeededEvent(e,a,c)};let r=a.createDataChannel("Binary");r.binaryType="arraybuffer",r.onopen=c=>{this.handleSendChannelStatusChange(e,r,c)},r.onclose=c=>{this.handleSendChannelStatusChange(e,r,c)},r.onmessage=c=>{let g=new TextDecoder().decode(c.data)},this.connections[e]={peerId:e,cameraId:t,peer:a,sendChannel:r,sendChannelSubject:n,receiveChannelSubject:i,pendingCandidates:[],ready:!1,readyIceCandidates:!1,readyOffer:!1,offerSent:!1,trickle:!0}}handleSendChannelStatusChange=(e,t,n)=>{if(t)switch(console.log("Send channel's status has changed to "+t.readyState),t.readyState){case"open":this.connections[e].sendChannelSubject.complete();break;case"closed":this.closeConnection(e);break}};receiveChannelCallback=(e,t)=>{let n=t.channel;this.connections[e].receiveChannel=n,n.binaryType="arraybuffer",n.onmessage=i=>{j(i,this.generatWebRtcHandle(e),V)},n.onopen=i=>{this.handleReceiveChannelStatusChange(e,n,i)},n.onclose=i=>{this.handleReceiveChannelStatusChange(e,n,i)}};handleReceiveChannelStatusChange=(e,t,n)=>{if(t)switch(console.log("Receive channel's status has changed to "+t.readyState),t.readyState){case"open":this.connections[e].receiveChannelSubject.complete();break;case"closed":this.closeConnection(e);break}};handleICECandidateEvent=(e,t,n)=>{n.candidate&&this.connections[e].trickle?(console.log("*** Outgoing ICE candidate: "+n.candidate.candidate),this.socketService.emitWebRTCNewIceCandidate(e,n.candidate),setTimeout(()=>{this.connections[e]&&(this.connections[e].readyIceCandidates=!0),this.trytoSendConnectionOffer(e)},3e3)):!n.candidate&&this.connections[e]&&!this.connections[e].readyIceCandidates&&(this.connections[e]&&(this.connections[e].readyIceCandidates=!0),this.trytoSendConnectionOffer(e))};handleICEConnectionStateChangeEvent=(e,t,n)=>{switch(console.log("*** ICE connection state changed to "+t.iceConnectionState),t.iceGatheringState==="complete"&&this.trytoSendConnectionOffer(e),t.iceConnectionState){case"closed":case"failed":case"disconnected":this.closeConnection(e);break}};handleICEGatheringStateChangeEvent=(e,t,n)=>{console.log("*** ICE gathering state changed to: "+t.iceGatheringState)};handleSignalingStateChangeEvent=(e,t,n)=>{switch(console.log("*** WebRTC signaling state changed to: "+t.signalingState),t.signalingState){case"closed":this.closeConnection(e);break}};handleNegotiationNeededEvent(e,t,n){return l(this,null,function*(){console.log("*** Negotiation needed");try{console.log("---> Creating offer");let i=yield t.createOffer();if(t.signalingState!="stable"){console.log("     -- The connection isn't stable yet; postponing...");return}console.log("---> Setting local description to the offer"),yield t.setLocalDescription(i),console.log("---> Sending the offer to the remote peer"),this.connections[e].readyOffer=!0,this.connections[e].trickle&&this.trytoSendConnectionOffer(e,!0)}catch(i){console.log("*** The following error occurred while handling the negotiationneeded event:"),this.reportError(i)}})}trytoSendConnectionOffer(e,t=!1){e&&this.connections[e]&&this.connections[e].peer?t||!this.connections[e].offerSent&&this.connections[e].readyIceCandidates&&this.connections[e].readyOffer?(this.connections[e].offerSent=!0,console.log("%c READY TO OFFER","background: #555; color: #bada55"),this.socketService.emitWebRTCOffer(e,this.connections[e].peer.localDescription)):this.connections[e].offerSent||console.log("%c NOT READY TO OFFER","background: #555; color: #ff7a7a"):this.closeConnection(e)}reportError(e,t=null){console.log("reportError !!!"),console.log(e),t&&this.closeConnection(t)}closeConnection(e,t=null){if(e&&this.connections[e]?.peer){console.log("closeCall >> "+e);let n=[];Object.keys(this.imageRequests).forEach(i=>{this.imageRequests[i].peerId==e&&n.push(i)}),n.forEach(i=>{this.cancelImage(i,!0,"closedConnection")}),this.connections[e]?.sendChannelSubject&&this.connections[e].sendChannelSubject.error(t||"closedConnection"),this.connections[e]?.receiveChannelSubject&&this.connections[e].receiveChannelSubject.error(t||"closedConnection"),this.connections[e].peer.ondatachannel=null,this.connections[e].peer.onicecandidate=null,this.connections[e].peer.oniceconnectionstatechange=null,this.connections[e].peer.onsignalingstatechange=null,this.connections[e].peer.onicegatheringstatechange=null,this.connections[e].peer.onnegotiationneeded=null,this.connections[e].sendChannel.close(),this.connections[e].receiveChannel&&this.connections[e].receiveChannel.close(),this.connections[e].peer.close(),delete this.connections[e]}}};var Y=function(s,e,t,n){var i=arguments.length,o=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,n);else for(var r=s.length-1;r>=0;r--)(a=s[r])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o},d=class extends y{interactionService;socketService;utilityService;settingsService;sessionService;_webRTCCamera;_stunUrls;constructor(e,t,n,i,o){super(e,o),this.interactionService=e,this.socketService=t,this.utilityService=n,this.settingsService=i,this.sessionService=o,this.init()}resetStoredData(){super.resetStoredData()}init(){this._webRTCCamera=h.getInstance(this.socketService,this.utilityService),this.settingsService.getOrganizationSettings().subscribe(e=>{e?.webRtc?.iceServers?.length>0&&(this._stunUrls=e.webRtc.iceServers)}),this.socketService.onWebRTCIceServersUpdated.subscribe(e=>{this._stunUrls=e.iceServers,this._webRTCCamera.cancelAllConnections(),console.log(this._stunUrls)})}getImage(e,t,n=0,i=null){return this._webRTCCamera.getImage(e,t,n,i,this._stunUrls)}cancelImage(e){this._webRTCCamera.cancelImage(e)}static ctorParameters=()=>[{type:P},{type:A},{type:D},{type:W},{type:_}]};d=Y([C({providedIn:"root"})],d);var $=function(s,e,t,n){var i=arguments.length,o=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,t):n,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(s,e,t,n);else for(var r=s.length-1;r>=0;r--)(a=s[r])&&(o=(i<3?a(o):i>3?a(e,t,o):a(e,t))||o);return i>3&&o&&Object.defineProperty(e,t,o),o},F=class extends T{webRtcCameraService;sanitizer;cameraData;streamUrl;timeout;animationState="in";updateDate;visibleComponent=!1;visibleSpinner=!0;visibleStreamFailed=!1;base64Data=null;imageSubscription;imageRequestId;streamImage;streamImageCanvas;constructor(e,t){super(),this.webRtcCameraService=e,this.sanitizer=t}onModalInitialized(){super.onModalInitialized(),this.setUrl(),this.visibleComponent=!0}onModalDestroyed(){super.onModalDestroyed(),this.timeout&&clearTimeout(this.timeout),this.closeStream()}setUrl(){this.timeout&&clearTimeout(this.timeout),this.imageRequestId=m(),this.imageSubscription=this.webRtcCameraService.getImage(this.cameraData.camera.proxyTerminalId,this.cameraData.camera.id,3,this.imageRequestId).subscribe(e=>{this.streamUrl=this.sanitizer.bypassSecurityTrustResourceUrl(e),this.visibleSpinner&&setTimeout(()=>{this.visibleSpinner=!1},300),this.updateDate=new Date},e=>{console.log("CAMERA PREVIEW >> "+e),this.visibleStreamFailed=!0})}setSnapToCanvas(){let e=this.streamImage.nativeElement;this.base64Data=E(e,e.height/e.naturalWidth).toDataURL("image/jpeg",.8)}setSpinner(e){this.visibleSpinner=e,this.animationState=e?"in":"out"}closeStream(){this.imageSubscription.unsubscribe(),this.imageRequestId&&this.webRtcCameraService.cancelImage(this.imageRequestId)}streamLoaded(){}streamLoadFailed(){}closeClicked(e){this.closeStream(),this.cancelModal()}static ctorParameters=()=>[{type:d},{type:x}];static propDecorators={cameraData:[{type:w}],streamImage:[{type:b,args:["streamImage"]}],streamImageCanvas:[{type:b,args:["streamImageCanvas"]}]}};F=$([S({selector:"armon-camera-stream-modal",template:I,animations:N,standalone:!0,imports:[R,O,v,k],styles:[U]})],F);export{d as a,F as b};
