New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

conectar-middleware

Package Overview
Dependencies
Maintainers
1
Versions
70
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

conectar-middleware - npm Package Compare versions

Comparing version 0.4.2 to 0.4.3

86

dist/conectar-middleware.cjs.development.js

@@ -162,3 +162,4 @@ 'use strict';

appointmentId: appointmentId,
sender: "USR-" + sender
sender: "USR-" + sender,
token: localStorage.getItem('token') || ''
});

@@ -515,2 +516,7 @@

function formatUserId(recipient) {
if (recipient.includes('USR-')) return recipient;
return "USR-" + recipient;
}
var CallService = /*#__PURE__*/function () {

@@ -565,2 +571,22 @@ function CallService(eventService, websocketService, peerConnectionService) {

_proto.closeAndDeleteConnection = function closeAndDeleteConnection(userId) {
for (var _i = 0, _arr = ['mic', 'camera']; _i < _arr.length; _i++) {
var media = _arr[_i];
for (var _i2 = 0, _arr2 = ['out', 'in']; _i2 < _arr2.length; _i2++) {
var _this$peerConnections, _this$peerConnections2, _this$peerConnections3, _this$peerConnections4;
var direction = _arr2[_i2];
var peerConnection = (_this$peerConnections = this.peerConnections) === null || _this$peerConnections === void 0 ? void 0 : (_this$peerConnections2 = _this$peerConnections[userId]) === null || _this$peerConnections2 === void 0 ? void 0 : _this$peerConnections2[media + "_" + direction];
peerConnection === null || peerConnection === void 0 ? void 0 : peerConnection.close();
if ((_this$peerConnections3 = this.peerConnections) === null || _this$peerConnections3 === void 0 ? void 0 : (_this$peerConnections4 = _this$peerConnections3[userId]) === null || _this$peerConnections4 === void 0 ? void 0 : _this$peerConnections4[media + "_" + direction]) {
delete this.peerConnections[userId][media + "_" + direction];
}
}
}
delete this.peerConnections[userId];
};
_proto.endMedia = function endMedia(stream) {

@@ -590,38 +616,31 @@ var _this4 = this;

_proto.hangUp = function hangUp(recipient) {
_proto.hangUp = function hangUp(user) {
try {
var _this6 = this;
for (var userId in _this6.peerConnections) {
for (var _i = 0, _arr = ['mic', 'camera']; _i < _arr.length; _i++) {
var media = _arr[_i];
if (user) {
_this6.closeAndDeleteConnection(formatUserId(user));
} else {
Object.keys(_this6.peerConnections).forEach(function (pc) {
_this6.closeAndDeleteConnection(pc);
for (var _i2 = 0, _arr2 = ['out', 'in']; _i2 < _arr2.length; _i2++) {
var _this6$peerConnection, _this6$peerConnection2, _this6$peerConnection3, _this6$peerConnection4;
_this6.send('private_event', {
recipient: pc,
data: JSON.stringify({
payload: 'hang_up'
})
});
});
}
var direction = _arr2[_i2];
var peerConnection = (_this6$peerConnection = _this6.peerConnections) === null || _this6$peerConnection === void 0 ? void 0 : (_this6$peerConnection2 = _this6$peerConnection[userId]) === null || _this6$peerConnection2 === void 0 ? void 0 : _this6$peerConnection2[media + "_" + direction];
peerConnection === null || peerConnection === void 0 ? void 0 : peerConnection.close();
if ((_this6$peerConnection3 = _this6.peerConnections) === null || _this6$peerConnection3 === void 0 ? void 0 : (_this6$peerConnection4 = _this6$peerConnection3[userId]) === null || _this6$peerConnection4 === void 0 ? void 0 : _this6$peerConnection4[media + "_" + direction]) {
delete _this6.peerConnections[userId][media + "_" + direction];
}
}
}
if (!Object.keys(_this6.peerConnections).length) {
['mic', 'camera', 'screen'].forEach(function (stream) {
var localStream = _this6.localStreams[stream];
localStream === null || localStream === void 0 ? void 0 : localStream.getTracks().forEach(function (track) {
return track.stop();
});
delete _this6.localStreams[stream];
});
}
_this6.send('private_event', {
recipient: recipient,
data: JSON.stringify({
payload: 'hang_up'
})
});
['mic', 'camera', 'screen'].forEach(function (stream) {
var localStream = _this6.localStreams[stream];
localStream === null || localStream === void 0 ? void 0 : localStream.getTracks().forEach(function (track) {
return track.stop();
});
delete _this6.localStreams[stream];
});
return Promise.resolve();

@@ -903,7 +922,2 @@ } catch (e) {

function formatUserId(recipient) {
if (recipient.includes('USR-')) return recipient;
return "USR-" + recipient;
}
var WebsocketService = /*#__PURE__*/function () {

@@ -1335,3 +1349,3 @@ function WebsocketService(eventService, config) {

_proto.hangUp = function hangUp(userId) {
return this.callService.hangUp(userId && formatUserId(userId));
return this.callService.hangUp(userId);
};

@@ -1338,0 +1352,0 @@

@@ -1,2 +0,2 @@

"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),require("reflect-metadata");var e,t=require("inversify"),n=require("tslib"),r=(e=require("axios"))&&"object"==typeof e&&"default"in e?e.default:e,i=require("rxjs"),o=require("@google-cloud/translate");function a(){return(a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}var c,s={CallService:Symbol.for("ICallService"),EventService:Symbol.for("IEventService"),ConfigService:Symbol.for("IConfigService"),WebsocketService:Symbol.for("IWebsocketService"),AttachmentService:Symbol.for("IAttachmentService"),WhiteboardService:Symbol.for("IWhiteboardService"),TranslationService:Symbol.for("ITranslationService"),ConversationService:Symbol.for("IConversationService"),PeerConnectionService:Symbol.for("IPeerConnectionService")},d=function(){function e(e,t,n){this.configService=e,this.websocketService=t,this.eventService=n}var t=e.prototype;return t.createConnection=function(e){return this.websocketService.createObservableSocket(e)},t.setConfig=function(e,t){this.configService.setBaseUrl(e),this.configService.setApiToken(t)},t.getConversationByUserId=function(e){try{var t=this.resolveParams(),n=t[1];return Promise.resolve(r.get(t[0]+"/users/"+e+"/conversations",{headers:n&&{Authorization:"Bearer "+n}}).then((function(e){return e.data})).catch((function(e){return e})))}catch(e){return Promise.reject(e)}},t.getUserConversations=function(){try{var e=this.resolveParams(),t=e[1];return Promise.resolve(r.get(e[0]+"/conversations/",{headers:t&&{Authorization:"Bearer "+t}}))}catch(e){return Promise.reject(e)}},t.getMessages=function(e){try{var t=this.resolveParams(),n=t[1];return Promise.resolve(r.get(t[0]+"/"+e.conversationId+"/messages?lastEvaluatedKey="+e.lastEvaluatedKey,{headers:n&&{Authorization:"Bearer "+n}}))}catch(e){return Promise.reject(e)}},t.getRoomConversation=function(e){try{var t=this.resolveParams(),n=t[1];return Promise.resolve(r.get(t[0]+"/"+e+"/room",{headers:n&&{Authorization:"Bearer "+n}}))}catch(e){return Promise.reject(e)}},t.joinRoom=function(e,t){try{return this.websocketService.send({event:"join",appointmentId:t,sender:"USR-"+e}),Promise.resolve()}catch(e){return Promise.reject(e)}},t.resolveParams=function(){var e=this.configService,t=[e.getBaseUrl(),e.getApiToken()];return[t[0],t[1]]},t.sendMessage=function(e){var t=e.event,n=e.sender,r=e.recipient,i=e.privateConversationId,o=void 0===i?"":i,a=function(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)t.indexOf(n=o[r])>=0||(i[n]=e[n]);return i}(e,["event","sender","recipient","privateConversationId"]),c=JSON.stringify(a);this.websocketService.send({data:c,event:t,sender:n,recipient:r,privateConversationId:o})},t.addEventListener=function(e,t){this.eventService.addEventListener(e,t)},e}();d=n.__decorate([t.injectable(),n.__param(0,t.inject(s.ConfigService)),n.__param(1,t.inject(s.WebsocketService)),n.__param(2,t.inject(s.EventService)),n.__metadata("design:paramtypes",[Object,Object,Object])],d),function(e){e.JOIN="join",e.LEAVE="leave",e.WEBRTC="webrtc",e.NEW_FILE="new_file",e.ENDING="class_ending",e.MOUSE_MOVE="mouse_move",e.CLASS_ERROR="class_error",e.PRIVATE_EVENT="private_event",e.NEW_WHITEBOARD="new_whiteboard",e.ADD_ROOM_META="update_room_meta",e.PRIVATE_MESSAGE="private_message",e.CLEAR_WHITEBOARD="clear_whiteboard",e.SET_ACTIVE_BOARD="set_active_board",e.REMOVE_WHITEBOARD="remove_whiteboard",e.RENAME_WHITEBOARD="rename_whiteboard",e.ACTIVE_PARTICIPANTS="active_participants",e.ADD_WHITEBOARD_OBJECT="add_whiteboard_object",e.UPDATE_WHITEBOARD_META="update_whiteboard_meta",e.REMOVE_WHITEBOARD_OBJECT="remove_whiteboard_object",e.UPDATE_WHITEBOARD_OBJECT="update_whiteboard_object",e.OFFER="offer",e.ANSWER="answer",e.CANDIDATE="candidate"}(c||(c={}));var u=function(){function e(e){this.websocketService=e}var t=e.prototype;return t.addWhiteboardMetadata=function(e,t){this.sendEvent(c.UPDATE_WHITEBOARD_META,e,{meta:t})},t.addWhiteboardObject=function(e,t){this.sendEvent(c.ADD_WHITEBOARD_OBJECT,e,{object:t})},t.clearWhiteboard=function(e){this.sendEvent(c.CLEAR_WHITEBOARD,e)},t.createWhiteboard=function(e,t){this.sendEvent(c.NEW_WHITEBOARD,e,{name:t})},t.removeWhiteboard=function(e){this.sendEvent(c.REMOVE_WHITEBOARD,e)},t.removeWhiteBoardObject=function(e,t){this.sendEvent(c.REMOVE_WHITEBOARD_OBJECT,e,{objectId:t})},t.renameWhiteboard=function(e,t){this.sendEvent(c.RENAME_WHITEBOARD,e,{name:t})},t.setActiveBoard=function(e){var t=e.isFile,n=e.item;this.sendEvent(c.SET_ACTIVE_BOARD,e.whiteboardId,{isFile:void 0!==t&&t,item:void 0===n?"":n})},t.updateWhiteboardObject=function(e,t){this.sendEvent(c.UPDATE_WHITEBOARD_OBJECT,e,{object:t})},t.sendEvent=function(e,t,n){var r={event:e,whiteboardId:t};if(n){var i=n.meta,o=n.object;i&&Object.assign(r,{meta:i}),o&&Object.assign(r,{objectId:o.id}),Object.assign(r,{data:JSON.stringify(n)})}this.websocketService.send(r)},e}();u=n.__decorate([t.injectable(),n.__param(0,t.inject(s.WebsocketService)),n.__metadata("design:paramtypes",[Object])],u);const v=function(){function e(){}return e.prototype.then=function(t,n){const r=new e,i=this.s;if(i){const e=1&i?t:n;if(e){try{l(r,1,e(this.v))}catch(e){l(r,2,e)}return r}return this}return this.o=function(e){try{const i=e.v;1&e.s?l(r,1,t?t(i):i):n?l(r,1,n(i)):l(r,2,i)}catch(e){l(r,2,e)}},r},e}();function l(e,t,n){if(!e.s){if(n instanceof v){if(!n.s)return void(n.o=l.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(l.bind(null,e,t),l.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}function h(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}"undefined"!=typeof Symbol&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator"))),"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator")));var f=function(){function e(e,t,n){var r=this;this.eventService=e,this.websocketService=t,this.peerConnectionService=n,this.eventService.getObservableForEvent("webrtc").subscribe({next:function(e){var t=Object.assign(e,JSON.parse(e.data));r.handleWebRTCEvent({type:t.type,media:t.media,sender:t.sender,payload:t.payload,direction:t.direction})}}),this.localStreams={},this.remoteStreams={},this.peerConnections={},this.iceServers=[{urls:"turn:conectar.demo.forasoft.com?transport=tcp",username:"conectar",credential:"ZVp1NaagEN7r"},{urls:"stun:stun.l.google.com:19302"}]}var t=e.prototype;return t.startDevice=function(e){try{return Promise.resolve(this.startStream(e)).then((function(){}))}catch(e){return Promise.reject(e)}},t.endMedia=function(e){var t=this,n=this.localStreams[e];null==n||n.getTracks().forEach((function(e){return e.stop()})),delete this.localStreams[e],Object.keys(this.peerConnections).forEach((function(n){t.send("private_event",{recipient:n,data:JSON.stringify({stream:e,enabled:!1,payload:"media_deleted"})})}))},t.getLocalStreams=function(){return this.localStreams},t.hangUp=function(e){try{var t=this;for(var n in t.peerConnections)for(var r=0,i=["mic","camera"];r<i.length;r++)for(var o=i[r],a=0,c=["out","in"];a<c.length;a++){var s,d,u,v,l=c[a],h=null===(s=t.peerConnections)||void 0===s||null===(d=s[n])||void 0===d?void 0:d[o+"_"+l];null==h||h.close(),(null===(u=t.peerConnections)||void 0===u||null===(v=u[n])||void 0===v?void 0:v[o+"_"+l])&&delete t.peerConnections[n][o+"_"+l]}return t.send("private_event",{recipient:e,data:JSON.stringify({payload:"hang_up"})}),["mic","camera","screen"].forEach((function(e){var n=t.localStreams[e];null==n||n.getTracks().forEach((function(e){return e.stop()})),delete t.localStreams[e]})),Promise.resolve()}catch(e){return Promise.reject(e)}},t.makeCall=function(e,t){try{var n,r=function(n){if(!n)throw new Error("Cannot find audio stream");return i.addStream(n,"mic",e),function(){if("video"===t){var n,r=function(t){if(!t)throw new Error("Cannot find video stream");i.addStream(t,"camera",e)},o=null===(n=i.localStreams)||void 0===n?void 0:n.camera;return o?r(o):Promise.resolve(i.startStream("camera")).then(r)}}()},i=this,o=null===(n=i.localStreams)||void 0===n?void 0:n.mic;return Promise.resolve(o?r(o):Promise.resolve(i.startStream("mic")).then(r))}catch(e){return Promise.reject(e)}},t.send=function(e,t){try{try{this.websocketService.send(a({event:e},t))}catch(e){console.error(e)}return Promise.resolve()}catch(e){return Promise.reject(e)}},t.shareScreen=function(e){try{var t=this;return Promise.resolve(t.startStream("screen")).then((function(n){return function(){if(n){try{t.addStream(n,"screen",e)}catch(e){console.log("create connection failed due to "+e)}return function(){if(!t.localStreams.mic)return Promise.resolve(t.startStream("mic")).then((function(n){if(!n)throw new Error("Cannot find mic stream");t.addStream(n,"mic",e)}))}()}throw new Error("Cannot find screen stream.")}()}))}catch(e){return Promise.reject(e)}},t.toggleMedia=function(e){var t,n;if(this.localStreams[e]){var r=null===(t=this.localStreams)||void 0===t||null===(n=t[e])||void 0===n?void 0:n["mic"===e?"getAudioTracks":"getVideoTracks"]()[0];r&&(r.enabled=!r.enabled)}},t.addStream=function(e,t,n){var r=this;if(this.localStreams[t]=e,n){var i=this.createPeerConnection(n,t,"out");e.getTracks().forEach((function(e){return i.addTrack(e)})),this.initiateOffer(i,n,t,"out")}else Object.keys(this.peerConnections).forEach((function(n){var i=r.createPeerConnection(n,t,"out");e.getTracks().forEach((function(e){return i.addTrack(e)})),r.initiateOffer(i,n,t,"out")}))},t.initiateOffer=function(e,t,n,r){try{var i=this,o=h((function(){return Promise.resolve(e.createOffer()).then((function(o){return Promise.resolve(e.setLocalDescription(o)).then((function(){i.send("webrtc",{direction:r,recipient:t,data:JSON.stringify({media:n,type:"offer",payload:o.sdp})})}))}))}),(function(e){console.error(e)}));return Promise.resolve(o&&o.then?o.then((function(){})):void 0)}catch(e){return Promise.reject(e)}},t.createPeerConnection=function(e,t,n){var r;return r=new RTCPeerConnection({iceServers:this.iceServers}),console.log("create connection"),this.peerConnectionService.processEventFromPeerConnection(r,e,t,n),this.peerConnections[e]||(this.peerConnections[e]={}),this.peerConnections[e][t+"_"+n]=r,r},t.handleWebRTCEvent=function(e){try{var t,n,r;return t=e.type===c.OFFER?this.createPeerConnection(e.sender,e.media,e.direction):null===(n=this.peerConnections)||void 0===n||null===(r=n[e.sender])||void 0===r?void 0:r[e.media+"_"+e.direction],Promise.resolve(this.peerConnectionService.processWebRTCEventFromWebsocket(e,t)).then((function(){}))}catch(e){return Promise.reject(e)}},t.startStream=function(e){try{var t=function(t){return n?t:Promise.resolve(r.localStreams[e])},n=!1,r=this,i=function(){if(!r.localStreams[e])return Promise.resolve(r.peerConnectionService.getUserMedia(e)).then((function(t){return r.localStreams[e]=t,n=!0,t}))}();return Promise.resolve(i&&i.then?i.then(t):t(i))}catch(e){return Promise.reject(e)}},e}();f=n.__decorate([t.injectable(),n.__param(0,t.inject(s.EventService)),n.__param(1,t.inject(s.WebsocketService)),n.__param(2,t.inject(s.PeerConnectionService)),n.__metadata("design:paramtypes",[Object,Object,Object])],f);var m=function(){function e(e){this.configService=e}var t=e.prototype;return t.uploadAttachment=function(e,t){try{Object.entries(e).forEach((function(e){t.append(e[0],e[1])}));var n=e.ConversationId||e.PrivateConversationId;return Promise.resolve(r.post(this.configService.getBaseUrl()+"/"+e.UserId+"/attachment/"+n+"/upload",t,{headers:this.configService.getApiToken()&&{"Content-type":"multipart/form-data",Authorization:"Bearer "+this.configService.getApiToken()}}))}catch(e){return Promise.reject(e)}},t.getRoomFiles=function(e){try{return Promise.resolve(r.get(this.configService.getBaseUrl()+"/"+e+"/room/",{headers:this.configService.getApiToken()&&{Authorization:"Bearer "+this.configService.getApiToken()}}))}catch(e){return Promise.reject(e)}},e}();function S(e){return e.includes("USR-")?e:"USR-"+e}m=n.__decorate([t.injectable(),n.__param(0,t.inject(s.ConfigService)),n.__metadata("design:paramtypes",[Object])],m);var p=function(){function e(e,t){this.eventService=e,this.config=t,this.connectionIsOpen=1}var t=e.prototype;return t.createObservableSocket=function(e){var t=this;return new Promise((function(n,r){t.connection=new WebSocket("wss://892oeasi03.execute-api.eu-central-1.amazonaws.com/Prod?id=USR-"+e),t.connection.onopen=function(){console.log("CONNECTED"),t.eventService.publish("event",{payload:"connected"}),n(t.connection)},t.connection.onmessage=function(e){console.log({WSEvent:e});var n=JSON.parse(e.data);console.log(n.event+"_payload"),t.eventService.publish(n.event,n)},t.connection.onerror=function(){console.error("WEBSOCKET_CONNECTION_ERROR"),r(t.connection)},t.connection.onclose=function(){console.error("WEBSOCKET_CONNECTION_CLOSED"),r(t.connection)}}))},t.send=function(e){var t;if(console.log({payload:e,connection:this.connection}),(null===(t=this.connection)||void 0===t?void 0:t.readyState)===this.connectionIsOpen){var n=e.sender||localStorage.getItem("userId"),r=localStorage.getItem("conversationId")||"";return this.connection.send(JSON.stringify(a({},e,{conversationId:r,action:"subscribe",sender:S(n)}))),"Sent to server"}throw new Error("NO_CONNECTION")},e}();p=n.__decorate([t.injectable(),n.__param(0,t.inject(s.EventService)),n.__param(1,t.inject(s.ConfigService)),n.__metadata("design:paramtypes",[Object,Object])],p);var b=function(){function e(){this.allEvents=new Map}var t=e.prototype;return t.publish=function(e,t){var n;if(console.log({eventName:e}),!this.allEvents.has(e))throw new Error("EVENT_NOT_REGISTERED");null===(n=this.allEvents.get(e))||void 0===n||n.next(t)},t.getObservableForEvent=function(e){return console.log("got here"),this.allEvents.has(e)||this.allEvents.set(e,new i.Subject),this.allEvents.get(e)},t.addEventListener=function(e,t){var n;this.allEvents.has(e)||this.allEvents.set(e,new i.Subject),null===(n=this.allEvents.get(e))||void 0===n||n.subscribe(t)},e}();b=n.__decorate([t.injectable()],b);var _=function(){function e(){this.CLASSROOM_BASE_URL=this.resolveBaseURL(),this.API_TOKEN=localStorage.getItem("token")}var t=e.prototype;return t.setApiToken=function(e){this.API_TOKEN=e},t.setBaseUrl=function(e){this.CLASSROOM_BASE_URL=e},t.getApiToken=function(){return this.API_TOKEN},t.getBaseUrl=function(){return this.CLASSROOM_BASE_URL},t.resolveBaseURL=function(){return"https://classroom-api-dev.conectar.ru"},e}();_=n.__decorate([t.injectable(),n.__metadata("design:paramtypes",[])],_);var g=function(){function e(e,t){this.eventService=e,this.websocketService=t,this.iceCandidates=[]}var t=e.prototype;return t.addStoredIceCandidates=function(e){this.iceCandidates.forEach((function(t){try{return Promise.resolve(e.addIceCandidate(t)).then((function(){}))}catch(e){return Promise.reject(e)}})),this.iceCandidates=[]},t.processEventFromPeerConnection=function(e,t,n,r){var i=this,o=new MediaStream;e.ontrack=function(e){o.addTrack(e.track),i.eventService.publish("new_stream",{media:n,userId:t,stream:o})},e.onicecandidate=function(e){e.candidate&&i.websocketService.send({direction:r,event:"webrtc",recipient:t,data:JSON.stringify({media:n,type:"candidate",payload:JSON.stringify(e.candidate.toJSON())})})},e.oniceconnectionstatechange=function(){switch(e.iceConnectionState){case"connected":break;case"failed":console.error("Peer connection "+t+" "+n+"_"+r+" failed");break;case"closed":case"disconnected":i.runListeners("closed",{media:n,userId:t,direction:r})}}},t.processWebRTCEventFromWebsocket=function(e,t){try{var n=function(){},r=this,i=function(e,t){var n,r=-1;e:{for(var i=0;i<t.length;i++){var o=t[i][0];if(o){var a=o();if(a&&a.then)break e;if(a===e){r=i;break}}else r=i}if(-1!==r){do{for(var c=t[r][1];!c;)r++,c=t[r][1];var s=c();if(s&&s.then){n=!0;break e}var d=t[r][2];r++}while(d&&!d());return s}}const u=new v,h=l.bind(null,u,2);return(n?s.then(f):a.then((function n(a){for(;;){if(a===e){r=i;break}if(++i===t.length){if(-1!==r)break;return void l(u,1,s)}if(o=t[i][0]){if((a=o())&&a.then)return void a.then(n).then(void 0,h)}else r=i}do{for(var c=t[r][1];!c;)r++,c=t[r][1];var s=c();if(s&&s.then)return void s.then(f).then(void 0,h);var d=t[r][2];r++}while(d&&!d());l(u,1,s)}))).then(void 0,h),u;function f(e){for(;;){var n=t[r][2];if(!n||n())break;r++;for(var i=t[r][1];!i;)r++,i=t[r][1];if((e=i())&&e.then)return void e.then(f).then(void 0,h)}l(u,1,e)}}(e.type,[[function(){return c.OFFER},function(){var i=new RTCSessionDescription({type:"offer",sdp:e.payload}),o=h((function(){return Promise.resolve(t.setRemoteDescription(i)).then((function(){return r.addStoredIceCandidates(t),Promise.resolve(t.createAnswer()).then((function(n){return Promise.resolve(t.setLocalDescription(n)).then((function(){r.websocketService.send({event:"webrtc",recipient:e.sender,direction:e.direction,data:JSON.stringify({type:"answer",media:e.media,payload:n.sdp})})}))}))}))}),(function(e){console.error(e)}));return o&&o.then?o.then(n):void 0}],[function(){return c.ANSWER},function(){var n=new RTCSessionDescription({type:"answer",sdp:e.payload});return Promise.resolve(t.setRemoteDescription(n)).then((function(){}))}],[function(){return c.CANDIDATE},function(){var n=new RTCIceCandidate(JSON.parse(e.payload)),i=function(){var e;if(null==t||null===(e=t.remoteDescription)||void 0===e?void 0:e.type){var i=h((function(){return Promise.resolve(t.addIceCandidate(n)).then((function(){}))}),(function(e){console.error(e,n)}));if(i&&i.then)return i.then((function(){}))}else r.iceCandidates.push(n)}();return i&&i.then?i.then((function(){})):void 0}]]);return Promise.resolve(i&&i.then?i.then((function(){})):void 0)}catch(e){return Promise.reject(e)}},t.getUserMedia=function(e){try{var t;return Promise.resolve(navigator.mediaDevices["screen"===e?"getDisplayMedia":"getUserMedia"](((t={})["mic"===e?"audio":"video"]="screen"!==e||{cursor:"always"},t)))}catch(e){return Promise.reject(e)}},t.runListeners=function(e){for(var t,n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];null===(t=this.eventService.getObservableForEvent(e))||void 0===t||t.next.apply(t,r)},e}();g=n.__decorate([t.injectable(),n.__param(0,t.inject(s.EventService)),n.__param(1,t.inject(s.WebsocketService)),n.__metadata("design:paramtypes",[Object,Object])],g);var E=function(){function e(){this.translator=new o.v2.Translate({key:process.env.REACT_APP_TRANSLATE_API_KEY})}return e.prototype.translateText=function(e,t){try{var n=this;return Promise.resolve(h((function(){return Promise.resolve(n.translator.translate(e,t)).then((function(e){return e[0]}))}),(function(e){console.log({err:e}),console.error("Error in getting translation: "+e.message)})))}catch(e){return Promise.reject(e)}},e}();E=n.__decorate([t.injectable()],E);var C=function(){function e(e){this.diContainer=new t.Container,"mocks"!==e&&this.configureServices()}return e.prototype.configureServices=function(){this.diContainer.bind(s.CallService).to(f),this.diContainer.bind(s.WhiteboardService).to(u),this.diContainer.bind(s.AttachmentService).to(m),this.diContainer.bind(s.TranslationService).to(E),this.diContainer.bind(s.ConversationService).to(d),this.diContainer.bind(s.EventService).to(b).inSingletonScope(),this.diContainer.bind(s.ConfigService).to(_).inSingletonScope(),this.diContainer.bind(s.WebsocketService).to(p).inSingletonScope(),this.diContainer.bind(s.PeerConnectionService).to(g).inSingletonScope()},e}(),y=function(){function e(e){this.callService=e}var t=e.prototype;return t.endCamera=function(){return this.callService.endMedia("camera")},t.endMic=function(){return this.callService.endMedia("mic")},t.endScreenSharing=function(){return this.callService.endMedia("screen")},t.getLocalStreams=function(){return this.callService.getLocalStreams()},t.hangUp=function(e){return this.callService.hangUp(e&&S(e))},t.makeVideoCall=function(e){return this.callService.makeCall(S(e),"video")},t.makeVoiceCall=function(e){return this.callService.makeCall(S(e),"voice")},t.send=function(e,t){return this.callService.send(e,t)},t.sendCallDecline=function(e){return this.send("private_event",{recipient:e,data:JSON.stringify({payload:"call_decline"})})},t.sendCallEvent=function(e,t,n){this.send("private_event",{recipient:S(e),data:JSON.stringify({payload:t+"_call_"+n})})},t.sendVideoCallAccept=function(e){return this.sendCallEvent(e,"video","accept")},t.sendVideoCallRequest=function(e){return this.sendCallEvent(e,"video","request")},t.sendVoiceCallAccept=function(e){return this.sendCallEvent(e,"audio","accept")},t.sendVoiceCallRequest=function(e){return this.sendCallEvent(e,"audio","request")},t.shareScreen=function(e){return this.callService.shareScreen(S(e))},t.startCamera=function(){return this.callService.startDevice("camera")},t.startMic=function(){return this.callService.startDevice("screen")},t.toggleMic=function(){return this.callService.toggleMedia("mic")},t.toggleVideo=function(){return this.callService.toggleMedia("camera")},e}();y=n.__decorate([t.injectable(),n.__param(0,t.inject(s.CallService)),n.__metadata("design:paramtypes",[Object])],y);var O=function(){function e(e){this.messageService=e}var t=e.prototype;return t.setConfig=function(e,t){this.messageService.setConfig(e,t)},t.createConnection=function(e){return this.messageService.createConnection(e)},t.addEventListener=function(e,t){this.messageService.addEventListener(e,t)},t.getMessages=function(e){try{return Promise.resolve(this.messageService.getMessages(e))}catch(e){return Promise.reject(e)}},t.getConversations=function(){try{return Promise.resolve(this.messageService.getUserConversations())}catch(e){return Promise.reject(e)}},t.getConversationByUserId=function(e){try{return Promise.resolve(this.messageService.getConversationByUserId(e))}catch(e){return Promise.reject(e)}},t.joinRoom=function(e,t){try{return Promise.resolve(this.messageService.joinRoom(e,t))}catch(e){return Promise.reject(e)}},t.sendMessage=function(e){try{return Promise.resolve(this.messageService.sendMessage(e))}catch(e){return Promise.reject(e)}},e}();O=n.__decorate([t.injectable(),n.__param(0,t.inject(s.ConversationService)),n.__metadata("design:paramtypes",[Object])],O);var j=function(){function e(e){this.whiteBoardService=e}var t=e.prototype;return t.addWhiteboardObject=function(e,t){return this.whiteBoardService.addWhiteboardObject(e,t)},t.clearWhiteboard=function(e){return this.whiteBoardService.clearWhiteboard(e)},t.createWhiteboard=function(e,t){return this.whiteBoardService.createWhiteboard(e,t)},t.renameWhiteboard=function(e,t){return this.whiteBoardService.renameWhiteboard(e,t)},t.addWhiteboardMetadata=function(e,t){return this.whiteBoardService.addWhiteboardMetadata(e,t)},t.removeWhiteboard=function(e){return this.whiteBoardService.removeWhiteboard(e)},t.removeWhiteBoardObject=function(e,t){return this.whiteBoardService.removeWhiteBoardObject(e,t)},t.setActiveBoard=function(e){return this.whiteBoardService.setActiveBoard(e)},t.updateWhiteboardObject=function(e,t){return this.whiteBoardService.updateWhiteboardObject(e,t)},e}();j=n.__decorate([t.injectable(),n.__param(0,t.inject(s.WhiteboardService)),n.__metadata("design:paramtypes",[Object])],j);var P=function(){function e(e){this.translationService=e}return e.prototype.translateTextToRussian=function(e){return this.translationService.translateText(e,"ru")},e}();P=n.__decorate([t.injectable(),n.__param(0,t.inject(s.TranslationService)),n.__metadata("design:paramtypes",[Object])],P);var A=function(){function e(e){this.attachmentService=e}var t=e.prototype;return t.uploadAttachment=function(e,t){try{return Promise.resolve(this.attachmentService.uploadAttachment(e,t))}catch(e){return Promise.reject(e)}},t.getRoomFiles=function(e){try{return Promise.resolve(this.attachmentService.getRoomFiles(e))}catch(e){return Promise.reject(e)}},e}();A=n.__decorate([t.injectable(),n.__param(0,t.inject(s.AttachmentService)),n.__metadata("design:paramtypes",[Object])],A);var T=new function(){this.bootstrap=new C("main"),this.Call=this.bootstrap.diContainer.resolve(y),this.Messaging=this.bootstrap.diContainer.resolve(O),this.Attachment=this.bootstrap.diContainer.resolve(A),this.Whiteboard=this.bootstrap.diContainer.resolve(j),this.Translate=this.bootstrap.diContainer.resolve(P)},w=T.Call,I=T.Messaging,R=T.Whiteboard,W=T.Translate;exports.Attachment=T.Attachment,exports.Call=w,exports.Messaging=I,exports.Translate=W,exports.Whiteboard=R,exports.default=T;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),require("reflect-metadata");var e,t=require("inversify"),n=require("tslib"),r=(e=require("axios"))&&"object"==typeof e&&"default"in e?e.default:e,i=require("rxjs"),o=require("@google-cloud/translate");function a(){return(a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}var c,s={CallService:Symbol.for("ICallService"),EventService:Symbol.for("IEventService"),ConfigService:Symbol.for("IConfigService"),WebsocketService:Symbol.for("IWebsocketService"),AttachmentService:Symbol.for("IAttachmentService"),WhiteboardService:Symbol.for("IWhiteboardService"),TranslationService:Symbol.for("ITranslationService"),ConversationService:Symbol.for("IConversationService"),PeerConnectionService:Symbol.for("IPeerConnectionService")},d=function(){function e(e,t,n){this.configService=e,this.websocketService=t,this.eventService=n}var t=e.prototype;return t.createConnection=function(e){return this.websocketService.createObservableSocket(e)},t.setConfig=function(e,t){this.configService.setBaseUrl(e),this.configService.setApiToken(t)},t.getConversationByUserId=function(e){try{var t=this.resolveParams(),n=t[1];return Promise.resolve(r.get(t[0]+"/users/"+e+"/conversations",{headers:n&&{Authorization:"Bearer "+n}}).then((function(e){return e.data})).catch((function(e){return e})))}catch(e){return Promise.reject(e)}},t.getUserConversations=function(){try{var e=this.resolveParams(),t=e[1];return Promise.resolve(r.get(e[0]+"/conversations/",{headers:t&&{Authorization:"Bearer "+t}}))}catch(e){return Promise.reject(e)}},t.getMessages=function(e){try{var t=this.resolveParams(),n=t[1];return Promise.resolve(r.get(t[0]+"/"+e.conversationId+"/messages?lastEvaluatedKey="+e.lastEvaluatedKey,{headers:n&&{Authorization:"Bearer "+n}}))}catch(e){return Promise.reject(e)}},t.getRoomConversation=function(e){try{var t=this.resolveParams(),n=t[1];return Promise.resolve(r.get(t[0]+"/"+e+"/room",{headers:n&&{Authorization:"Bearer "+n}}))}catch(e){return Promise.reject(e)}},t.joinRoom=function(e,t){try{return this.websocketService.send({event:"join",appointmentId:t,sender:"USR-"+e,token:localStorage.getItem("token")||""}),Promise.resolve()}catch(e){return Promise.reject(e)}},t.resolveParams=function(){var e=this.configService,t=[e.getBaseUrl(),e.getApiToken()];return[t[0],t[1]]},t.sendMessage=function(e){var t=e.event,n=e.sender,r=e.recipient,i=e.privateConversationId,o=void 0===i?"":i,a=function(e,t){if(null==e)return{};var n,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)t.indexOf(n=o[r])>=0||(i[n]=e[n]);return i}(e,["event","sender","recipient","privateConversationId"]),c=JSON.stringify(a);this.websocketService.send({data:c,event:t,sender:n,recipient:r,privateConversationId:o})},t.addEventListener=function(e,t){this.eventService.addEventListener(e,t)},e}();d=n.__decorate([t.injectable(),n.__param(0,t.inject(s.ConfigService)),n.__param(1,t.inject(s.WebsocketService)),n.__param(2,t.inject(s.EventService)),n.__metadata("design:paramtypes",[Object,Object,Object])],d),function(e){e.JOIN="join",e.LEAVE="leave",e.WEBRTC="webrtc",e.NEW_FILE="new_file",e.ENDING="class_ending",e.MOUSE_MOVE="mouse_move",e.CLASS_ERROR="class_error",e.PRIVATE_EVENT="private_event",e.NEW_WHITEBOARD="new_whiteboard",e.ADD_ROOM_META="update_room_meta",e.PRIVATE_MESSAGE="private_message",e.CLEAR_WHITEBOARD="clear_whiteboard",e.SET_ACTIVE_BOARD="set_active_board",e.REMOVE_WHITEBOARD="remove_whiteboard",e.RENAME_WHITEBOARD="rename_whiteboard",e.ACTIVE_PARTICIPANTS="active_participants",e.ADD_WHITEBOARD_OBJECT="add_whiteboard_object",e.UPDATE_WHITEBOARD_META="update_whiteboard_meta",e.REMOVE_WHITEBOARD_OBJECT="remove_whiteboard_object",e.UPDATE_WHITEBOARD_OBJECT="update_whiteboard_object",e.OFFER="offer",e.ANSWER="answer",e.CANDIDATE="candidate"}(c||(c={}));var u=function(){function e(e){this.websocketService=e}var t=e.prototype;return t.addWhiteboardMetadata=function(e,t){this.sendEvent(c.UPDATE_WHITEBOARD_META,e,{meta:t})},t.addWhiteboardObject=function(e,t){this.sendEvent(c.ADD_WHITEBOARD_OBJECT,e,{object:t})},t.clearWhiteboard=function(e){this.sendEvent(c.CLEAR_WHITEBOARD,e)},t.createWhiteboard=function(e,t){this.sendEvent(c.NEW_WHITEBOARD,e,{name:t})},t.removeWhiteboard=function(e){this.sendEvent(c.REMOVE_WHITEBOARD,e)},t.removeWhiteBoardObject=function(e,t){this.sendEvent(c.REMOVE_WHITEBOARD_OBJECT,e,{objectId:t})},t.renameWhiteboard=function(e,t){this.sendEvent(c.RENAME_WHITEBOARD,e,{name:t})},t.setActiveBoard=function(e){var t=e.isFile,n=e.item;this.sendEvent(c.SET_ACTIVE_BOARD,e.whiteboardId,{isFile:void 0!==t&&t,item:void 0===n?"":n})},t.updateWhiteboardObject=function(e,t){this.sendEvent(c.UPDATE_WHITEBOARD_OBJECT,e,{object:t})},t.sendEvent=function(e,t,n){var r={event:e,whiteboardId:t};if(n){var i=n.meta,o=n.object;i&&Object.assign(r,{meta:i}),o&&Object.assign(r,{objectId:o.id}),Object.assign(r,{data:JSON.stringify(n)})}this.websocketService.send(r)},e}();u=n.__decorate([t.injectable(),n.__param(0,t.inject(s.WebsocketService)),n.__metadata("design:paramtypes",[Object])],u);const v=function(){function e(){}return e.prototype.then=function(t,n){const r=new e,i=this.s;if(i){const e=1&i?t:n;if(e){try{l(r,1,e(this.v))}catch(e){l(r,2,e)}return r}return this}return this.o=function(e){try{const i=e.v;1&e.s?l(r,1,t?t(i):i):n?l(r,1,n(i)):l(r,2,i)}catch(e){l(r,2,e)}},r},e}();function l(e,t,n){if(!e.s){if(n instanceof v){if(!n.s)return void(n.o=l.bind(null,e,t));1&t&&(t=n.s),n=n.v}if(n&&n.then)return void n.then(l.bind(null,e,t),l.bind(null,e,2));e.s=t,e.v=n;const r=e.o;r&&r(e)}}function h(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}function f(e){return e.includes("USR-")?e:"USR-"+e}"undefined"!=typeof Symbol&&(Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator"))),"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator")));var m=function(){function e(e,t,n){var r=this;this.eventService=e,this.websocketService=t,this.peerConnectionService=n,this.eventService.getObservableForEvent("webrtc").subscribe({next:function(e){var t=Object.assign(e,JSON.parse(e.data));r.handleWebRTCEvent({type:t.type,media:t.media,sender:t.sender,payload:t.payload,direction:t.direction})}}),this.localStreams={},this.remoteStreams={},this.peerConnections={},this.iceServers=[{urls:"turn:conectar.demo.forasoft.com?transport=tcp",username:"conectar",credential:"ZVp1NaagEN7r"},{urls:"stun:stun.l.google.com:19302"}]}var t=e.prototype;return t.startDevice=function(e){try{return Promise.resolve(this.startStream(e)).then((function(){}))}catch(e){return Promise.reject(e)}},t.closeAndDeleteConnection=function(e){for(var t=0,n=["mic","camera"];t<n.length;t++)for(var r=n[t],i=0,o=["out","in"];i<o.length;i++){var a,c,s,d,u=o[i],v=null===(a=this.peerConnections)||void 0===a||null===(c=a[e])||void 0===c?void 0:c[r+"_"+u];null==v||v.close(),(null===(s=this.peerConnections)||void 0===s||null===(d=s[e])||void 0===d?void 0:d[r+"_"+u])&&delete this.peerConnections[e][r+"_"+u]}delete this.peerConnections[e]},t.endMedia=function(e){var t=this,n=this.localStreams[e];null==n||n.getTracks().forEach((function(e){return e.stop()})),delete this.localStreams[e],Object.keys(this.peerConnections).forEach((function(n){t.send("private_event",{recipient:n,data:JSON.stringify({stream:e,enabled:!1,payload:"media_deleted"})})}))},t.getLocalStreams=function(){return this.localStreams},t.hangUp=function(e){try{var t=this;return e?t.closeAndDeleteConnection(f(e)):Object.keys(t.peerConnections).forEach((function(e){t.closeAndDeleteConnection(e),t.send("private_event",{recipient:e,data:JSON.stringify({payload:"hang_up"})})})),Object.keys(t.peerConnections).length||["mic","camera","screen"].forEach((function(e){var n=t.localStreams[e];null==n||n.getTracks().forEach((function(e){return e.stop()})),delete t.localStreams[e]})),Promise.resolve()}catch(e){return Promise.reject(e)}},t.makeCall=function(e,t){try{var n,r=function(n){if(!n)throw new Error("Cannot find audio stream");return i.addStream(n,"mic",e),function(){if("video"===t){var n,r=function(t){if(!t)throw new Error("Cannot find video stream");i.addStream(t,"camera",e)},o=null===(n=i.localStreams)||void 0===n?void 0:n.camera;return o?r(o):Promise.resolve(i.startStream("camera")).then(r)}}()},i=this,o=null===(n=i.localStreams)||void 0===n?void 0:n.mic;return Promise.resolve(o?r(o):Promise.resolve(i.startStream("mic")).then(r))}catch(e){return Promise.reject(e)}},t.send=function(e,t){try{try{this.websocketService.send(a({event:e},t))}catch(e){console.error(e)}return Promise.resolve()}catch(e){return Promise.reject(e)}},t.shareScreen=function(e){try{var t=this;return Promise.resolve(t.startStream("screen")).then((function(n){return function(){if(n){try{t.addStream(n,"screen",e)}catch(e){console.log("create connection failed due to "+e)}return function(){if(!t.localStreams.mic)return Promise.resolve(t.startStream("mic")).then((function(n){if(!n)throw new Error("Cannot find mic stream");t.addStream(n,"mic",e)}))}()}throw new Error("Cannot find screen stream.")}()}))}catch(e){return Promise.reject(e)}},t.toggleMedia=function(e){var t,n;if(this.localStreams[e]){var r=null===(t=this.localStreams)||void 0===t||null===(n=t[e])||void 0===n?void 0:n["mic"===e?"getAudioTracks":"getVideoTracks"]()[0];r&&(r.enabled=!r.enabled)}},t.addStream=function(e,t,n){var r=this;if(this.localStreams[t]=e,n){var i=this.createPeerConnection(n,t,"out");e.getTracks().forEach((function(e){return i.addTrack(e)})),this.initiateOffer(i,n,t,"out")}else Object.keys(this.peerConnections).forEach((function(n){var i=r.createPeerConnection(n,t,"out");e.getTracks().forEach((function(e){return i.addTrack(e)})),r.initiateOffer(i,n,t,"out")}))},t.initiateOffer=function(e,t,n,r){try{var i=this,o=h((function(){return Promise.resolve(e.createOffer()).then((function(o){return Promise.resolve(e.setLocalDescription(o)).then((function(){i.send("webrtc",{direction:r,recipient:t,data:JSON.stringify({media:n,type:"offer",payload:o.sdp})})}))}))}),(function(e){console.error(e)}));return Promise.resolve(o&&o.then?o.then((function(){})):void 0)}catch(e){return Promise.reject(e)}},t.createPeerConnection=function(e,t,n){var r;return r=new RTCPeerConnection({iceServers:this.iceServers}),console.log("create connection"),this.peerConnectionService.processEventFromPeerConnection(r,e,t,n),this.peerConnections[e]||(this.peerConnections[e]={}),this.peerConnections[e][t+"_"+n]=r,r},t.handleWebRTCEvent=function(e){try{var t,n,r;return t=e.type===c.OFFER?this.createPeerConnection(e.sender,e.media,e.direction):null===(n=this.peerConnections)||void 0===n||null===(r=n[e.sender])||void 0===r?void 0:r[e.media+"_"+e.direction],Promise.resolve(this.peerConnectionService.processWebRTCEventFromWebsocket(e,t)).then((function(){}))}catch(e){return Promise.reject(e)}},t.startStream=function(e){try{var t=function(t){return n?t:Promise.resolve(r.localStreams[e])},n=!1,r=this,i=function(){if(!r.localStreams[e])return Promise.resolve(r.peerConnectionService.getUserMedia(e)).then((function(t){return r.localStreams[e]=t,n=!0,t}))}();return Promise.resolve(i&&i.then?i.then(t):t(i))}catch(e){return Promise.reject(e)}},e}();m=n.__decorate([t.injectable(),n.__param(0,t.inject(s.EventService)),n.__param(1,t.inject(s.WebsocketService)),n.__param(2,t.inject(s.PeerConnectionService)),n.__metadata("design:paramtypes",[Object,Object,Object])],m);var S=function(){function e(e){this.configService=e}var t=e.prototype;return t.uploadAttachment=function(e,t){try{Object.entries(e).forEach((function(e){t.append(e[0],e[1])}));var n=e.ConversationId||e.PrivateConversationId;return Promise.resolve(r.post(this.configService.getBaseUrl()+"/"+e.UserId+"/attachment/"+n+"/upload",t,{headers:this.configService.getApiToken()&&{"Content-type":"multipart/form-data",Authorization:"Bearer "+this.configService.getApiToken()}}))}catch(e){return Promise.reject(e)}},t.getRoomFiles=function(e){try{return Promise.resolve(r.get(this.configService.getBaseUrl()+"/"+e+"/room/",{headers:this.configService.getApiToken()&&{Authorization:"Bearer "+this.configService.getApiToken()}}))}catch(e){return Promise.reject(e)}},e}();S=n.__decorate([t.injectable(),n.__param(0,t.inject(s.ConfigService)),n.__metadata("design:paramtypes",[Object])],S);var p=function(){function e(e,t){this.eventService=e,this.config=t,this.connectionIsOpen=1}var t=e.prototype;return t.createObservableSocket=function(e){var t=this;return new Promise((function(n,r){t.connection=new WebSocket("wss://892oeasi03.execute-api.eu-central-1.amazonaws.com/Prod?id=USR-"+e),t.connection.onopen=function(){console.log("CONNECTED"),t.eventService.publish("event",{payload:"connected"}),n(t.connection)},t.connection.onmessage=function(e){console.log({WSEvent:e});var n=JSON.parse(e.data);console.log(n.event+"_payload"),t.eventService.publish(n.event,n)},t.connection.onerror=function(){console.error("WEBSOCKET_CONNECTION_ERROR"),r(t.connection)},t.connection.onclose=function(){console.error("WEBSOCKET_CONNECTION_CLOSED"),r(t.connection)}}))},t.send=function(e){var t;if(console.log({payload:e,connection:this.connection}),(null===(t=this.connection)||void 0===t?void 0:t.readyState)===this.connectionIsOpen){var n=e.sender||localStorage.getItem("userId"),r=localStorage.getItem("conversationId")||"";return this.connection.send(JSON.stringify(a({},e,{conversationId:r,action:"subscribe",sender:f(n)}))),"Sent to server"}throw new Error("NO_CONNECTION")},e}();p=n.__decorate([t.injectable(),n.__param(0,t.inject(s.EventService)),n.__param(1,t.inject(s.ConfigService)),n.__metadata("design:paramtypes",[Object,Object])],p);var b=function(){function e(){this.allEvents=new Map}var t=e.prototype;return t.publish=function(e,t){var n;if(console.log({eventName:e}),!this.allEvents.has(e))throw new Error("EVENT_NOT_REGISTERED");null===(n=this.allEvents.get(e))||void 0===n||n.next(t)},t.getObservableForEvent=function(e){return console.log("got here"),this.allEvents.has(e)||this.allEvents.set(e,new i.Subject),this.allEvents.get(e)},t.addEventListener=function(e,t){var n;this.allEvents.has(e)||this.allEvents.set(e,new i.Subject),null===(n=this.allEvents.get(e))||void 0===n||n.subscribe(t)},e}();b=n.__decorate([t.injectable()],b);var _=function(){function e(){this.CLASSROOM_BASE_URL=this.resolveBaseURL(),this.API_TOKEN=localStorage.getItem("token")}var t=e.prototype;return t.setApiToken=function(e){this.API_TOKEN=e},t.setBaseUrl=function(e){this.CLASSROOM_BASE_URL=e},t.getApiToken=function(){return this.API_TOKEN},t.getBaseUrl=function(){return this.CLASSROOM_BASE_URL},t.resolveBaseURL=function(){return"https://classroom-api-dev.conectar.ru"},e}();_=n.__decorate([t.injectable(),n.__metadata("design:paramtypes",[])],_);var g=function(){function e(e,t){this.eventService=e,this.websocketService=t,this.iceCandidates=[]}var t=e.prototype;return t.addStoredIceCandidates=function(e){this.iceCandidates.forEach((function(t){try{return Promise.resolve(e.addIceCandidate(t)).then((function(){}))}catch(e){return Promise.reject(e)}})),this.iceCandidates=[]},t.processEventFromPeerConnection=function(e,t,n,r){var i=this,o=new MediaStream;e.ontrack=function(e){o.addTrack(e.track),i.eventService.publish("new_stream",{media:n,userId:t,stream:o})},e.onicecandidate=function(e){e.candidate&&i.websocketService.send({direction:r,event:"webrtc",recipient:t,data:JSON.stringify({media:n,type:"candidate",payload:JSON.stringify(e.candidate.toJSON())})})},e.oniceconnectionstatechange=function(){switch(e.iceConnectionState){case"connected":break;case"failed":console.error("Peer connection "+t+" "+n+"_"+r+" failed");break;case"closed":case"disconnected":i.runListeners("closed",{media:n,userId:t,direction:r})}}},t.processWebRTCEventFromWebsocket=function(e,t){try{var n=function(){},r=this,i=function(e,t){var n,r=-1;e:{for(var i=0;i<t.length;i++){var o=t[i][0];if(o){var a=o();if(a&&a.then)break e;if(a===e){r=i;break}}else r=i}if(-1!==r){do{for(var c=t[r][1];!c;)r++,c=t[r][1];var s=c();if(s&&s.then){n=!0;break e}var d=t[r][2];r++}while(d&&!d());return s}}const u=new v,h=l.bind(null,u,2);return(n?s.then(f):a.then((function n(a){for(;;){if(a===e){r=i;break}if(++i===t.length){if(-1!==r)break;return void l(u,1,s)}if(o=t[i][0]){if((a=o())&&a.then)return void a.then(n).then(void 0,h)}else r=i}do{for(var c=t[r][1];!c;)r++,c=t[r][1];var s=c();if(s&&s.then)return void s.then(f).then(void 0,h);var d=t[r][2];r++}while(d&&!d());l(u,1,s)}))).then(void 0,h),u;function f(e){for(;;){var n=t[r][2];if(!n||n())break;r++;for(var i=t[r][1];!i;)r++,i=t[r][1];if((e=i())&&e.then)return void e.then(f).then(void 0,h)}l(u,1,e)}}(e.type,[[function(){return c.OFFER},function(){var i=new RTCSessionDescription({type:"offer",sdp:e.payload}),o=h((function(){return Promise.resolve(t.setRemoteDescription(i)).then((function(){return r.addStoredIceCandidates(t),Promise.resolve(t.createAnswer()).then((function(n){return Promise.resolve(t.setLocalDescription(n)).then((function(){r.websocketService.send({event:"webrtc",recipient:e.sender,direction:e.direction,data:JSON.stringify({type:"answer",media:e.media,payload:n.sdp})})}))}))}))}),(function(e){console.error(e)}));return o&&o.then?o.then(n):void 0}],[function(){return c.ANSWER},function(){var n=new RTCSessionDescription({type:"answer",sdp:e.payload});return Promise.resolve(t.setRemoteDescription(n)).then((function(){}))}],[function(){return c.CANDIDATE},function(){var n=new RTCIceCandidate(JSON.parse(e.payload)),i=function(){var e;if(null==t||null===(e=t.remoteDescription)||void 0===e?void 0:e.type){var i=h((function(){return Promise.resolve(t.addIceCandidate(n)).then((function(){}))}),(function(e){console.error(e,n)}));if(i&&i.then)return i.then((function(){}))}else r.iceCandidates.push(n)}();return i&&i.then?i.then((function(){})):void 0}]]);return Promise.resolve(i&&i.then?i.then((function(){})):void 0)}catch(e){return Promise.reject(e)}},t.getUserMedia=function(e){try{var t;return Promise.resolve(navigator.mediaDevices["screen"===e?"getDisplayMedia":"getUserMedia"](((t={})["mic"===e?"audio":"video"]="screen"!==e||{cursor:"always"},t)))}catch(e){return Promise.reject(e)}},t.runListeners=function(e){for(var t,n=arguments.length,r=new Array(n>1?n-1:0),i=1;i<n;i++)r[i-1]=arguments[i];null===(t=this.eventService.getObservableForEvent(e))||void 0===t||t.next.apply(t,r)},e}();g=n.__decorate([t.injectable(),n.__param(0,t.inject(s.EventService)),n.__param(1,t.inject(s.WebsocketService)),n.__metadata("design:paramtypes",[Object,Object])],g);var E=function(){function e(){this.translator=new o.v2.Translate({key:process.env.REACT_APP_TRANSLATE_API_KEY})}return e.prototype.translateText=function(e,t){try{var n=this;return Promise.resolve(h((function(){return Promise.resolve(n.translator.translate(e,t)).then((function(e){return e[0]}))}),(function(e){console.log({err:e}),console.error("Error in getting translation: "+e.message)})))}catch(e){return Promise.reject(e)}},e}();E=n.__decorate([t.injectable()],E);var C=function(){function e(e){this.diContainer=new t.Container,"mocks"!==e&&this.configureServices()}return e.prototype.configureServices=function(){this.diContainer.bind(s.CallService).to(m),this.diContainer.bind(s.WhiteboardService).to(u),this.diContainer.bind(s.AttachmentService).to(S),this.diContainer.bind(s.TranslationService).to(E),this.diContainer.bind(s.ConversationService).to(d),this.diContainer.bind(s.EventService).to(b).inSingletonScope(),this.diContainer.bind(s.ConfigService).to(_).inSingletonScope(),this.diContainer.bind(s.WebsocketService).to(p).inSingletonScope(),this.diContainer.bind(s.PeerConnectionService).to(g).inSingletonScope()},e}(),y=function(){function e(e){this.callService=e}var t=e.prototype;return t.endCamera=function(){return this.callService.endMedia("camera")},t.endMic=function(){return this.callService.endMedia("mic")},t.endScreenSharing=function(){return this.callService.endMedia("screen")},t.getLocalStreams=function(){return this.callService.getLocalStreams()},t.hangUp=function(e){return this.callService.hangUp(e)},t.makeVideoCall=function(e){return this.callService.makeCall(f(e),"video")},t.makeVoiceCall=function(e){return this.callService.makeCall(f(e),"voice")},t.send=function(e,t){return this.callService.send(e,t)},t.sendCallDecline=function(e){return this.send("private_event",{recipient:e,data:JSON.stringify({payload:"call_decline"})})},t.sendCallEvent=function(e,t,n){this.send("private_event",{recipient:f(e),data:JSON.stringify({payload:t+"_call_"+n})})},t.sendVideoCallAccept=function(e){return this.sendCallEvent(e,"video","accept")},t.sendVideoCallRequest=function(e){return this.sendCallEvent(e,"video","request")},t.sendVoiceCallAccept=function(e){return this.sendCallEvent(e,"audio","accept")},t.sendVoiceCallRequest=function(e){return this.sendCallEvent(e,"audio","request")},t.shareScreen=function(e){return this.callService.shareScreen(f(e))},t.startCamera=function(){return this.callService.startDevice("camera")},t.startMic=function(){return this.callService.startDevice("screen")},t.toggleMic=function(){return this.callService.toggleMedia("mic")},t.toggleVideo=function(){return this.callService.toggleMedia("camera")},e}();y=n.__decorate([t.injectable(),n.__param(0,t.inject(s.CallService)),n.__metadata("design:paramtypes",[Object])],y);var O=function(){function e(e){this.messageService=e}var t=e.prototype;return t.setConfig=function(e,t){this.messageService.setConfig(e,t)},t.createConnection=function(e){return this.messageService.createConnection(e)},t.addEventListener=function(e,t){this.messageService.addEventListener(e,t)},t.getMessages=function(e){try{return Promise.resolve(this.messageService.getMessages(e))}catch(e){return Promise.reject(e)}},t.getConversations=function(){try{return Promise.resolve(this.messageService.getUserConversations())}catch(e){return Promise.reject(e)}},t.getConversationByUserId=function(e){try{return Promise.resolve(this.messageService.getConversationByUserId(e))}catch(e){return Promise.reject(e)}},t.joinRoom=function(e,t){try{return Promise.resolve(this.messageService.joinRoom(e,t))}catch(e){return Promise.reject(e)}},t.sendMessage=function(e){try{return Promise.resolve(this.messageService.sendMessage(e))}catch(e){return Promise.reject(e)}},e}();O=n.__decorate([t.injectable(),n.__param(0,t.inject(s.ConversationService)),n.__metadata("design:paramtypes",[Object])],O);var j=function(){function e(e){this.whiteBoardService=e}var t=e.prototype;return t.addWhiteboardObject=function(e,t){return this.whiteBoardService.addWhiteboardObject(e,t)},t.clearWhiteboard=function(e){return this.whiteBoardService.clearWhiteboard(e)},t.createWhiteboard=function(e,t){return this.whiteBoardService.createWhiteboard(e,t)},t.renameWhiteboard=function(e,t){return this.whiteBoardService.renameWhiteboard(e,t)},t.addWhiteboardMetadata=function(e,t){return this.whiteBoardService.addWhiteboardMetadata(e,t)},t.removeWhiteboard=function(e){return this.whiteBoardService.removeWhiteboard(e)},t.removeWhiteBoardObject=function(e,t){return this.whiteBoardService.removeWhiteBoardObject(e,t)},t.setActiveBoard=function(e){return this.whiteBoardService.setActiveBoard(e)},t.updateWhiteboardObject=function(e,t){return this.whiteBoardService.updateWhiteboardObject(e,t)},e}();j=n.__decorate([t.injectable(),n.__param(0,t.inject(s.WhiteboardService)),n.__metadata("design:paramtypes",[Object])],j);var P=function(){function e(e){this.translationService=e}return e.prototype.translateTextToRussian=function(e){return this.translationService.translateText(e,"ru")},e}();P=n.__decorate([t.injectable(),n.__param(0,t.inject(s.TranslationService)),n.__metadata("design:paramtypes",[Object])],P);var A=function(){function e(e){this.attachmentService=e}var t=e.prototype;return t.uploadAttachment=function(e,t){try{return Promise.resolve(this.attachmentService.uploadAttachment(e,t))}catch(e){return Promise.reject(e)}},t.getRoomFiles=function(e){try{return Promise.resolve(this.attachmentService.getRoomFiles(e))}catch(e){return Promise.reject(e)}},e}();A=n.__decorate([t.injectable(),n.__param(0,t.inject(s.AttachmentService)),n.__metadata("design:paramtypes",[Object])],A);var T=new function(){this.bootstrap=new C("main"),this.Call=this.bootstrap.diContainer.resolve(y),this.Messaging=this.bootstrap.diContainer.resolve(O),this.Attachment=this.bootstrap.diContainer.resolve(A),this.Whiteboard=this.bootstrap.diContainer.resolve(j),this.Translate=this.bootstrap.diContainer.resolve(P)},w=T.Call,I=T.Messaging,R=T.Whiteboard,W=T.Translate;exports.Attachment=T.Attachment,exports.Call=w,exports.Messaging=I,exports.Translate=W,exports.Whiteboard=R,exports.default=T;
//# sourceMappingURL=conectar-middleware.cjs.production.min.js.map

@@ -156,3 +156,4 @@ import 'reflect-metadata';

appointmentId: appointmentId,
sender: "USR-" + sender
sender: "USR-" + sender,
token: localStorage.getItem('token') || ''
});

@@ -509,2 +510,7 @@

function formatUserId(recipient) {
if (recipient.includes('USR-')) return recipient;
return "USR-" + recipient;
}
var CallService = /*#__PURE__*/function () {

@@ -559,2 +565,22 @@ function CallService(eventService, websocketService, peerConnectionService) {

_proto.closeAndDeleteConnection = function closeAndDeleteConnection(userId) {
for (var _i = 0, _arr = ['mic', 'camera']; _i < _arr.length; _i++) {
var media = _arr[_i];
for (var _i2 = 0, _arr2 = ['out', 'in']; _i2 < _arr2.length; _i2++) {
var _this$peerConnections, _this$peerConnections2, _this$peerConnections3, _this$peerConnections4;
var direction = _arr2[_i2];
var peerConnection = (_this$peerConnections = this.peerConnections) === null || _this$peerConnections === void 0 ? void 0 : (_this$peerConnections2 = _this$peerConnections[userId]) === null || _this$peerConnections2 === void 0 ? void 0 : _this$peerConnections2[media + "_" + direction];
peerConnection === null || peerConnection === void 0 ? void 0 : peerConnection.close();
if ((_this$peerConnections3 = this.peerConnections) === null || _this$peerConnections3 === void 0 ? void 0 : (_this$peerConnections4 = _this$peerConnections3[userId]) === null || _this$peerConnections4 === void 0 ? void 0 : _this$peerConnections4[media + "_" + direction]) {
delete this.peerConnections[userId][media + "_" + direction];
}
}
}
delete this.peerConnections[userId];
};
_proto.endMedia = function endMedia(stream) {

@@ -584,38 +610,31 @@ var _this4 = this;

_proto.hangUp = function hangUp(recipient) {
_proto.hangUp = function hangUp(user) {
try {
var _this6 = this;
for (var userId in _this6.peerConnections) {
for (var _i = 0, _arr = ['mic', 'camera']; _i < _arr.length; _i++) {
var media = _arr[_i];
if (user) {
_this6.closeAndDeleteConnection(formatUserId(user));
} else {
Object.keys(_this6.peerConnections).forEach(function (pc) {
_this6.closeAndDeleteConnection(pc);
for (var _i2 = 0, _arr2 = ['out', 'in']; _i2 < _arr2.length; _i2++) {
var _this6$peerConnection, _this6$peerConnection2, _this6$peerConnection3, _this6$peerConnection4;
_this6.send('private_event', {
recipient: pc,
data: JSON.stringify({
payload: 'hang_up'
})
});
});
}
var direction = _arr2[_i2];
var peerConnection = (_this6$peerConnection = _this6.peerConnections) === null || _this6$peerConnection === void 0 ? void 0 : (_this6$peerConnection2 = _this6$peerConnection[userId]) === null || _this6$peerConnection2 === void 0 ? void 0 : _this6$peerConnection2[media + "_" + direction];
peerConnection === null || peerConnection === void 0 ? void 0 : peerConnection.close();
if ((_this6$peerConnection3 = _this6.peerConnections) === null || _this6$peerConnection3 === void 0 ? void 0 : (_this6$peerConnection4 = _this6$peerConnection3[userId]) === null || _this6$peerConnection4 === void 0 ? void 0 : _this6$peerConnection4[media + "_" + direction]) {
delete _this6.peerConnections[userId][media + "_" + direction];
}
}
}
if (!Object.keys(_this6.peerConnections).length) {
['mic', 'camera', 'screen'].forEach(function (stream) {
var localStream = _this6.localStreams[stream];
localStream === null || localStream === void 0 ? void 0 : localStream.getTracks().forEach(function (track) {
return track.stop();
});
delete _this6.localStreams[stream];
});
}
_this6.send('private_event', {
recipient: recipient,
data: JSON.stringify({
payload: 'hang_up'
})
});
['mic', 'camera', 'screen'].forEach(function (stream) {
var localStream = _this6.localStreams[stream];
localStream === null || localStream === void 0 ? void 0 : localStream.getTracks().forEach(function (track) {
return track.stop();
});
delete _this6.localStreams[stream];
});
return Promise.resolve();

@@ -897,7 +916,2 @@ } catch (e) {

function formatUserId(recipient) {
if (recipient.includes('USR-')) return recipient;
return "USR-" + recipient;
}
var WebsocketService = /*#__PURE__*/function () {

@@ -1329,3 +1343,3 @@ function WebsocketService(eventService, config) {

_proto.hangUp = function hangUp(userId) {
return this.callService.hangUp(userId && formatUserId(userId));
return this.callService.hangUp(userId);
};

@@ -1332,0 +1346,0 @@

@@ -15,5 +15,6 @@ import { ICallService, IPeerConnectionService } from '../interfaces';

startDevice(stream: keyof Streams): Promise<void>;
private closeAndDeleteConnection;
endMedia(stream: StreamKeys): void;
getLocalStreams(): Streams;
hangUp(recipient?: string): Promise<void>;
hangUp(user?: string): Promise<void>;
makeCall(peerId: string, callType: string): Promise<void>;

@@ -20,0 +21,0 @@ send(event: string, params: any): Promise<any>;

{
"version": "0.4.2",
"version": "0.4.3",
"license": "MIT",

@@ -4,0 +4,0 @@ "main": "dist/index.js",

@@ -32,3 +32,3 @@ import { formatUserId } from '../utils';

hangUp(userId?: string) {
return this.callService.hangUp(userId && formatUserId(userId));
return this.callService.hangUp(userId);
}

@@ -35,0 +35,0 @@

@@ -33,7 +33,12 @@ import 'reflect-metadata';

it('should hang up', async () => {
it('should handle single user hang up', async () => {
await callService.hangUp('test_recipient');
expect(websocketMock.send).toBeCalled();
expect(websocketMock.send).not.toBeCalled();
});
it('should handle multi user hang up', async () => {
await callService.hangUp();
expect(websocketMock.send).not.toBeCalled();
});
it('should make voice call', () => {

@@ -40,0 +45,0 @@ expect(() => {

@@ -0,1 +1,2 @@

import { formatUserId } from '../utils';
import { inject, injectable } from 'inversify';

@@ -56,2 +57,17 @@ import { TYPES } from '../../global_module/constants/types';

private closeAndDeleteConnection(userId: string) {
for (const media of ['mic', 'camera']) {
for (const direction of ['out', 'in']) {
const peerConnection = this.peerConnections?.[userId]?.[`${media}_${direction}`];
peerConnection?.close();
if (this.peerConnections?.[userId]?.[`${media}_${direction}`]) {
delete this.peerConnections[userId][`${media}_${direction}`];
}
}
}
delete this.peerConnections[userId];
}
endMedia(stream: StreamKeys) {

@@ -74,26 +90,22 @@ const localStream = this.localStreams[stream];

async hangUp(recipient?: string) {
for (const userId in this.peerConnections) {
for (const media of ['mic', 'camera']) {
for (const direction of ['out', 'in']) {
const peerConnection = this.peerConnections?.[userId]?.[`${media}_${direction}`];
peerConnection?.close();
async hangUp(user?: string) {
if (user) {
this.closeAndDeleteConnection(formatUserId(user));
} else {
Object.keys(this.peerConnections).forEach(pc => {
this.closeAndDeleteConnection(pc);
this.send('private_event', {
recipient: pc,
data: JSON.stringify({ payload: 'hang_up' }),
});
});
}
if (this.peerConnections?.[userId]?.[`${media}_${direction}`]) {
delete this.peerConnections[userId][`${media}_${direction}`];
}
}
}
if (!Object.keys(this.peerConnections).length) {
['mic' as StreamKeys, 'camera' as StreamKeys, 'screen' as StreamKeys].forEach(stream => {
const localStream = this.localStreams[stream];
localStream?.getTracks().forEach(track => track.stop());
delete this.localStreams[stream];
});
}
this.send('private_event', {
recipient,
data: JSON.stringify({ payload: 'hang_up' }),
});
['mic' as StreamKeys, 'camera' as StreamKeys, 'screen' as StreamKeys].forEach(stream => {
const localStream = this.localStreams[stream];
localStream?.getTracks().forEach(track => track.stop());
delete this.localStreams[stream];
});
}

@@ -100,0 +112,0 @@

@@ -77,2 +77,3 @@ import axios from 'axios';

sender: `USR-${sender}`,
token: localStorage.getItem('token') || '',
});

@@ -79,0 +80,0 @@ }

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc