UNPKG

podchat-browser

Version:

Javascript SDK to use POD's Chat Service - Browser Only

1,361 lines (1,171 loc) 46.6 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator")); var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _webrtcPeer = require("./webrtcPeer"); var _utility = _interopRequireDefault(require("../../../utility/utility")); var _errorHandler = require("../../errorHandler"); var _midManager = _interopRequireDefault(require("./midManager")); var PeerConnectionManager = /*#__PURE__*/function () { function PeerConnectionManager(_ref) { var app = _ref.app, callId = _ref.callId, direction = _ref.direction, rtcPeerConfig = _ref.rtcPeerConfig, brokerAddress = _ref.brokerAddress, onPeerFailed = _ref.onPeerFailed, onSendTrackFailed = _ref.onSendTrackFailed; (0, _classCallCheck2["default"])(this, PeerConnectionManager); this._app = app; this._callId = callId; this._brokerAddress = brokerAddress; this._nextTrackMid = 0; this._trackList = []; this._addTrackQueue = []; this._sendTrackQueue = []; this._addIceQueue = []; this._direction = direction; this._firstSub = true; this._canProcessNextTrack = true; this._isDestroyed = false; this._requestTimeouts = {}; this._negotiationOfferUpdate = []; this._isReconnecting = false; this._subscribeOrUpdateFailedCount = 0; this._peerStates = { DISCONNECTED: 0, CONNECTING: 1, FAILED: 3, CONNECTED: 4 }; this._state = 0; //0: disconnected, 1: connecting, 2: failed, 3: connected, 4: disconnected this._defaultConfig = { callId: callId, direction: direction, rtcPeerConfig: rtcPeerConfig, connectionStateChange: this._onConnectionStateChange.bind(this), iceConnectionStateChange: this._onIceConnectionStateChange.bind(this) }; this._onPeerFailed = onPeerFailed; this._onSendTrackFailed = onSendTrackFailed; this._peer = new _webrtcPeer.WebrtcPeerConnection(this._defaultConfig); this._onTrackCalls = 0; this._sendOpenDone = false; this._sendOpenDoneTimeout = null; this.watchConnectionStateChange(); this._addTrackLock = false; this._addTrackQueueTriggerTimeout = null; this._midManager = new _midManager["default"]({ app: app }); var that = this; window.trackList = function () { return that._trackList; }; } (0, _createClass2["default"])(PeerConnectionManager, [{ key: "_nextTrack", value: function _nextTrack() { var _this = this; var retries = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; if (this.isDestroyed()) return; if (this._canProcessNextTrack) { if (this._direction == 'send' && this._canProcessNextTrack && this._addTrackQueue.length) { if (this._firstSub || this._peer && this._peer.peerConnection && this._peer.peerConnection.connectionState == 'connected') { this._canProcessNextTrack = false; var item = this._addTrackQueue[0]; this._requestAddSendTrack(item); } else if (retries <= 3) { setTimeout(function () { _this._nextTrack(retries++); }, 3000); } } else if (this._direction == 'receive' && this._canProcessNextTrack) { if (this._negotiationOfferUpdate.length) { this._canProcessNextTrack = false; this._sendTrackQueue = []; this.handleProcessSDPOfferForRenegotiate(); } else if (this._addTrackQueue.length && !this._isReconnecting) { this._canProcessNextTrack = false; this._sendTrackQueue = []; while (this._addTrackQueue.length > 0) { // if (this._addTrackQueue[0].mediaType != 2) { var track = this._addTrackQueue.shift(); this._sendTrackQueue.push(track); // } else { // if (this._sendTrackQueue.length) { // break; // } // this._sendTrackQueue.push(this._addTrackQueue.shift()); // break; // } } this._requestReceiveTrack(); } } } } }, { key: "_requestAddSendTrack", value: function _requestAddSendTrack(item) { var _this2 = this; var that = this, localTrackIndex, uuid = _utility["default"].generateUUID(); item.uniqueId = uuid; var sender = this._peer.peerConnection.getSenders().find(function (s, index) { if (s.track == item.stream.getTracks()[0]) { localTrackIndex = index; return true; } }); if (sender) { console.warn('Track already exists in connection, direction: send'); // item.onTrackCallback(item, item.stream.getTracks()[localTrackIndex]) } var localStream; if (item.topic.indexOf('Vi-') > -1 || item.topic.indexOf('screen') > -1) { if (item.isScreenShare) { localStream = this._app.call.deviceManager.mediaStreams.getScreenShareInput(); } else { localStream = this._app.call.deviceManager.mediaStreams.getVideoInput(); } if (localStream && !sender) { this._peer.addTrack(localStream.getTracks()[0], localStream); } } else { localStream = this._app.call.deviceManager.mediaStreams.getAudioInput(); if (localStream && !sender) { this._peer.addTrack(localStream.getTracks()[0], localStream); } } this._peer.peerConnection.onicecandidate = function (_ref2) { var candidate = _ref2.candidate; if (!candidate) return; _this2._app.call.currentCall().sendCallMessage({ id: "SEND_ADD_ICE_CANDIDATE", token: _this2._app.sdkParams.token, chatId: _this2._callId, brokerAddress: _this2._brokerAddress, iceCandidate: JSON.stringify(candidate) }, null, {}); }; item.onTrackCallback(item, localStream.getTracks()[0]); if (this._firstSub) { this._firstSub = false; item.isFirstSub = true; if (!item.offer) { that._peer.peerConnection.createOffer().then(function (offer) { if (_this2._addTrackQueue[0]) _this2._addTrackQueue[0].offer = offer;else return; return that._peer.peerConnection.setLocalDescription(offer); }).then(function () { // console.log('[debug][_requestAddSendTrack] SEND_SDP_OFFER', this._peer.peerConnection.localDescription.sdp, [{ // mline: item.mline, // topic: item.topic, // mediaType: item.mediaType // }]); that._sendSdpOfferMessage(item, uuid); })["catch"](function (error) { return console.error({ error: error }); }); } else { that._sendSdpOfferMessage(item, uuid); } } else { if (!item.offer) { that._peer.peerConnection.createOffer().then(function (offer) { _this2._addTrackQueue[0].offer = offer; return that._peer.peerConnection.setLocalDescription(offer); }).then(function () { _this2._app.logger.log(_this2._app.logger.tags.CALL_PROCESS, "[_requestAddSendTrack][SEND_NEGOTIATION] ", item); // console.log('[debug][_requestAddSendTrack] SEND_NEGOTIATION', this._peer.peerConnection.localDescription.sdp, [{ // mline: item.mline, // topic: item.topic, // mediaType: item.mediaType // }]); that._sendNegotioateMessage(item, uuid); }); } else { that._sendNegotioateMessage(item, uuid); } } this.setSendRequestTimeout(uuid, item); } }, { key: "_requestRemoveSendTrackNoMessage", value: function _requestRemoveSendTrackNoMessage(item) { if (this._isDestroyed) return; var localTrackIndex; var sender = this._peer.peerConnection.getSenders().find(function (s, index) { if (s.track == item.stream.getTracks()[0]) { localTrackIndex = index; return true; } }); if (sender) { this._peer.peerConnection.removeTrack(sender); } } }, { key: "_sendSdpOfferMessage", value: function _sendSdpOfferMessage(item, uuid) { this._app.call.currentCall().sendCallMessage({ id: "SEND_SDP_OFFER", sdpOffer: this._peer.peerConnection.localDescription.sdp, token: this._app.sdkParams.token, chatId: this._callId, brokerAddress: this._brokerAddress, addition: [{ mline: item.mline, topic: item.topic, mediaType: item.mediaType }], uniqueId: uuid }, null, {}); } }, { key: "_sendNegotioateMessage", value: function _sendNegotioateMessage(item, uuid) { this._app.call.currentCall().sendCallMessage({ id: "SEND_NEGOTIATION", sdpOffer: this._peer.peerConnection.localDescription.sdp, token: this._app.sdkParams.token, chatId: this._callId, brokerAddress: this._brokerAddress, addition: [{ mline: item.mline, topic: item.topic, mediaType: item.mediaType }], uniqueId: uuid }, null, {}); } }, { key: "_requestRemoveSendTrack", value: function _requestRemoveSendTrack(item) { var _this3 = this; if (this._isDestroyed) return; var localTrackIndex; var sender = this._peer.peerConnection.getSenders().find(function (s, index) { if (s.track == item.stream.getTracks()[0]) { localTrackIndex = index; return true; } }); if (sender) { this._peer.peerConnection.removeTrack(sender); // this._trackList.forEach((it, index) => { // if (item.topic == it.topic) { // delete this._trackList[index] // } // }) this._peer.peerConnection.createOffer().then(function (offer) { return _this3._peer.peerConnection.setLocalDescription(offer); }).then(function () { _this3._app.call.currentCall().sendCallMessage({ id: "SEND_NEGOTIATION", sdpOffer: _this3._peer.peerConnection.localDescription.sdp, token: _this3._app.sdkParams.token, chatId: _this3._callId, brokerAddress: _this3._brokerAddress, deletion: [{ mline: item.mline, topic: item.topic, mediaType: item.mediaType }] }, null, {}); }); } } }, { key: "_requestReceiveTrack", value: function _requestReceiveTrack() { var list = []; var includedItem = []; this._sendTrackQueue.forEach(function (item) { if (!includedItem.includes(item.topic)) { list.push({ clientId: item.clientId, mline: item.mline, topic: item.topic, mediaType: item.mediaType }); includedItem.push(item.topic); } }); var uuid = _utility["default"].generateUUID(); this._sendRequestReceiveTrack(uuid, list); // this._sendTrackQueue = this._sendTrackQueue.filter(it => { // return !items.find(ite => ite.topic == it.topic); // }); } }, { key: "_sendRequestReceiveTrack", value: function _sendRequestReceiveTrack(uuid, list) { console.log('[media][SUBSCRIBE/UPDATE] Sending.. , clientIds: ', list.map(function (it) { return it.clientId; }).join(','), ' ||| topics: ', list.map(function (it) { return it.topic; }).join(','), '||| _trackList: ', JSON.stringify(this._trackList), '||| _sendTrackQueue: ', JSON.stringify(this._sendTrackQueue), '||| _addTrackQueue: ', JSON.stringify(this._addTrackQueue)); if (this._firstSub) { this._app.call.currentCall().sendCallMessage({ id: 'SUBSCRIBE', uniqueId: uuid, token: this._app.sdkParams.token, chatId: this._callId, brokerAddress: this._brokerAddress, addition: list }, null, {}); } else { this._app.call.currentCall().sendCallMessage({ id: 'UPDATE', uniqueId: uuid, token: this._app.sdkParams.token, chatId: this._callId, brokerAddress: this._brokerAddress, addition: list }, null, {}); } this.setRequestTimeout(uuid, list); } }, { key: "setSendRequestTimeout", value: function setSendRequestTimeout(uuid, item) { var _this4 = this; this._requestTimeouts[uuid] = { timeout: setTimeout(function () { // this.removeFailedTrack(item); // item.onOpenFailure && item.onOpenFailure(item); delete _this4._requestTimeouts[uuid]; _this4._onSendTrackFailed(); return; if (item.isFirstSub) { _this4._firstSub = true; } // this._requestRemoveSendTrackNoMessage(item); // this.processingCurrentTrackCompleted(); _this4._unlockProcessingNextTrack(); _this4._nextTrack(); delete _this4._requestTimeouts[uuid]; }, 10000) }; } }, { key: "resetSubscribeOrUpdateFailedCount", value: function resetSubscribeOrUpdateFailedCount() { this._subscribeOrUpdateFailedCount = 0; } }, { key: "setRequestTimeout", value: function setRequestTimeout(uuid, list) { var _this5 = this; this._requestTimeouts[uuid] = { timeout: setTimeout(function () { if (!_this5._app.call.currentCall() || _this5._isDestroyed) return; if (_this5._subscribeOrUpdateFailedCount < 3) { _this5._subscribeOrUpdateFailedCount += 1; /** * This will resend the request and waits for the response */ delete _this5._requestTimeouts[uuid]; _this5._sendRequestReceiveTrack(uuid, list); // this._app.call.currentCall().sendCallMessage({ // id: 'REQUEST_RECEIVING_MEDIA', // token: this._app.sdkParams.token, // chatId: this._callId, // brokerAddress: this._brokerAddress, // }, null, {}); // this.processingCurrentTrackCompleted(); // delete this._requestTimeouts[uuid]; } else { // items.forEach(it => { // this.removeFailedTrack(it); // it.onOpenFailure && it.onOpenFailure(it); // }); _this5.resetSubscribeOrUpdateFailedCount(); if (_this5._app.call.currentCall()) { // this._app.chatEvents.fireEvent('callEvents', { // type: 'CALL_ENDED', // callId: this._app.call.currentCall().getCallId() // }); _this5._app.call.currentCall().raiseCallError(_errorHandler.errorList.UPDATE_TRACK_REQUEST_TIMEOUT, null, true); _this5._app.chatEvents.fireEvent('callEvents', { type: 'YOU_DROPPED_FROM_CALL', callId: _this5._app.call.currentCall().getCallId(), result: { callId: _this5._app.call.currentCall().getCallId(), userId: _this5._app.store.user.get().id } }); _this5._app.call.endCall({ callId: _this5._app.call.currentCall().getCallId() }); } } }, 2000) }; } }, { key: "removeFailedTrack", value: function removeFailedTrack(item) { this._addTrackQueue = this._addTrackQueue.filter(function (it) { return it.topic != item.topic; }); this._sendTrackQueue = []; this._trackList = this._trackList.filter(function (it) { return it.topic != item.topic; }); // console.log('debug removed failed track', {item}, JSON.stringify(this._trackList), JSON.stringify(this._addTrackQueue)); } }, { key: "requestReceiveError", value: function requestReceiveError(uuid) { var _this6 = this; if (this._requestTimeouts[uuid]) { var item = this._trackList.find(function (item) { return item && item.topic === _this6._requestTimeouts[uuid].topic; }); this.removeRequestTimeout(uuid); this.removeFailedTrack(item); this.processingCurrentTrackCompleted(); item.onOpenFailure(item); } } }, { key: "removeRequestTimeout", value: function removeRequestTimeout(uuid) { var record = this._requestTimeouts[uuid]; if (record) { if (record.timeout) clearTimeout(record.timeout); delete this._requestTimeouts[uuid]; } } }, { key: "removeRequestTimeoutByTopic", value: function removeRequestTimeoutByTopic(topic) { var _this7 = this; this._trackList.forEach(function (item) { if (item.topic == topic) { if (_this7._requestTimeouts[item.uniqueId]) { if (_this7._requestTimeouts[item.uniqueId].timeout) { clearTimeout(_this7._requestTimeouts[item.uniqueId].timeout); } if (_this7._requestTimeouts[item.uniqueId]) delete _this7._requestTimeouts[item.uniqueId]; } } }); } }, { key: "_unlockProcessingNextTrack", value: function _unlockProcessingNextTrack() { this._canProcessNextTrack = true; } }, { key: "_setPeerState", value: function _setPeerState(state) { this._state = state; } }, { key: "addTrack", value: function addTrack(data) { var _this8 = this; var existingTrack = this._trackList.some(function (item) { return item.topic == data.topic; }); if (existingTrack) return 2; if (this._direction == 'send') { data.mline = this._nextTrackMid; this._nextTrackMid++; } this._trackList.push(data); this._addTrackQueue.push(data); if (this._direction == 'send') { this._nextTrack(); } else { /** * Gives some time so other users have enough time to add their tracks. * Otherwise, if receiving_media gives 5 tracks together they will open one by one */ this._addTrackQueueTriggerTimeout && clearTimeout(this._addTrackQueueTriggerTimeout); this._addTrackQueueTriggerTimeout = setTimeout(function () { _this8._nextTrack(); }, 20); } return 1; } }, { key: "removeTrack", value: function removeTrack(topic) { var item = this._trackList.find(function (it) { return it && it.topic === topic; }); if (this._direction == 'send') { if (item) { this._requestRemoveSendTrack(item); } } if (item) { this._midManager.removeTopic(topic); this._trackList = this._trackList.filter(function (it) { return it.topic != item.topic; }); } } }, { key: "processingCurrentTrackCompleted", value: function processingCurrentTrackCompleted() { if (this._direction == 'send') this._addTrackQueue.shift(); this._unlockProcessingNextTrack(); this._nextTrack(); } }, { key: "maybeNextTrack", value: function maybeNextTrack() { this._nextTrack(); } }, { key: "isPeerConnecting", value: function isPeerConnecting() { return this._state === this._peerStates.CONNECTING; } }, { key: "isPeerFailed", value: function isPeerFailed() { return this._state === this._peerStates.FAILED; } }, { key: "isPeerConnected", value: function isPeerConnected() { return this._state === this._peerStates.CONNECTED; } }, { key: "isPeerDisconnected", value: function isPeerDisconnected() { return this._state === this._peerStates.DISCONNECTED; } }, { key: "_onConnectionStateChange", value: function _onConnectionStateChange() { if (!this._peer || this.isDestroyed()) { return; } this._app.chatEvents.fireEvent("callStreamEvents", { type: 'WEBRTC_CONNECTION_STATE_CHANGE', callId: this._callId, direction: this._direction, connectionState: this._peer.peerConnection.connectionState }); this._app.logger.log(this._app.logger.tags.CALL_PROCESS.id, "[peerConnection.onconnectionstatechange]", "peer: " + this._direction + " peerConnection.connectionState: " + this._peer.peerConnection.connectionState); // this._app.sdkParams.consoleLogging && console.log("[SDK][peerConnection.onconnectionstatechange] ", "peer: ", this._direction, " peerConnection.connectionState: ", this._peer.peerConnection.connectionState); switch (this._peer.peerConnection.connectionState) { case 'disconnected': if (this.isPeerDisconnected()) return; this._state = this._peerStates.DISCONNECTED; this._app.call.currentCall().sendCallStatusEvent(); break; case 'failed': if (this.isPeerFailed()) return; this._app.chatEvents.fireEvent('callEvents', { type: 'PEER_FAILED', callId: this._callId, direction: this._direction }); this._handlePeerFailed(); break; case 'connected': if (this.isPeerConnected()) return; this._nextTrack(); this._state = this._peerStates.CONNECTED; this._app.call.currentCall().sendCallStatusEvent(); this._app.chatEvents.fireEvent('callEvents', { type: 'PEER_CONNECTED', callId: this._callId, direction: this._direction }); break; } } }, { key: "_onIceConnectionStateChange", value: function _onIceConnectionStateChange() { if (!this._peer || this.isDestroyed()) { return; //avoid log errors } this._app.logger.log(this._app.logger.tags.CALL_PROCESS.id, "[peerConnection.oniceconnectionstatechange]", "peer: " + this._direction + " peerConnection.connectionState: " + this._peer.peerConnection.connectionState); // this._app.sdkParams.consoleLogging && console.log("[SDK][oniceconnectionstatechange] ", "peer: ", this._direction, " peerConnection.connectionState: ", this._peer.peerConnection.iceConnectionState); switch (this._peer.peerConnection.iceConnectionState) { case 'disconnected': if (this.isPeerDisconnected()) return; this._state = this._peerStates.DISCONNECTED; this._app.call.currentCall().sendCallStatusEvent(); // this._app.chatEvents.fireEvent('callEvents', { // type: 'CALL_STATUS', // callId: this._callId, // errorCode: 7000, // errorMessage: `Call Peer (${this._direction}) is disconnected!`, // errorInfo: this._peer // }); // this._app.sdkParams.consoleLogging && console.log('[SDK][oniceconnectionstatechange]:[disconnected] Internet connection failed, Reconnect your call, peer:', this._direction); break; case 'failed': if (this.isPeerFailed()) return; this._app.chatEvents.fireEvent('callEvents', { type: 'PEER_FAILED', callId: this._callId, direction: this._direction }); this._handlePeerFailed(); break; case 'connected': if (this.isPeerConnected()) return; this._state = this._peerStates.CONNECTED; this._app.call.currentCall().sendCallStatusEvent(); this._app.chatEvents.fireEvent('callEvents', { type: 'PEER_CONNECTED', callId: this._callId, direction: this._direction }); // this._app.chatEvents.fireEvent('callEvents', { // type: 'CALL_STATUS', // callId: this._callId, // errorCode: 7000, // errorMessage: `Call Peer (${this._direction}) has connected!`, // errorInfo: this._peer.peerConnection // }); break; } } }, { key: "_handlePeerFailed", value: function _handlePeerFailed() { this._state = this._peerStates.FAILED; this._app.call.currentCall().sendCallStatusEvent(); // this._app.chatEvents.fireEvent('callEvents', { // type: 'CALL_STATUS', // callId: this._callId, // errorCode: 7000, // errorMessage: `Call Peer (${this._direction}) has failed!`, // errorInfo: this._peer // }); this._onPeerFailed(this._direction); } }, { key: "addIceCandidateToQueue", value: function addIceCandidateToQueue(candidate) { var _this9 = this; if (this._peer.peerConnection.signalingState === 'stable' && !!this._peer.peerConnection.currentRemoteDescription) { this.addIceCandidate(candidate)["catch"](function (error) { _this9._addIceQueue.push(candidate); }); } else { this._addIceQueue.push(candidate); } } }, { key: "addIceOnPeer", value: function addIceOnPeer(event) { var that = this; that._addIceQueue.forEach(function (item) { that.addIceCandidate(item); }); } }, { key: "watchConnectionStateChange", value: function watchConnectionStateChange() { var that = this; this._peer.peerConnection.onsignalingstatechange = function (event) { if (that._peer.peerConnection.signalingState === 'stable' && !!that._peer.peerConnection.currentRemoteDescription) { that.addIceOnPeer(event); } }; } }, { key: "addIceCandidate", value: function () { var _addIceCandidate = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee(data) { var _this10 = this; return _regenerator["default"].wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: return _context.abrupt("return", new Promise(function (resolve, reject) { _this10._peer.peerConnection.addIceCandidate(data)["catch"](function (err) { if (err) { console.warn("[peerConnectionManager addIceCandidate" + _this10._direction + "] " + err); reject(err); } }); })); case 1: case "end": return _context.stop(); } } }, _callee); })); function addIceCandidate(_x) { return _addIceCandidate.apply(this, arguments); } return addIceCandidate; }() }, { key: "reconnectPeer", value: function reconnectPeer() { this._destroyPeer(); this._peer = new _webrtcPeer.WebrtcPeerConnection(this._defaultConfig); } }, { key: "handleProcessSDPOfferForReceiveTrack", value: function () { var _handleProcessSDPOfferForReceiveTrack = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee2(jsonMessage, callback) { var _this11 = this; var topics, timeoutsList, that, normalTopicHandler, screenShareTopicHandler; return _regenerator["default"].wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: screenShareTopicHandler = function _screenShareTopicHand(transceiver) { var cTrackData; cTrackData = that._trackList.find(function (item) { return item.mediaType == 2; }); if (cTrackData) { clearTimeout(timeoutsList[cTrackData.topic]); cTrackData.track = transceiver.receiver.track; cTrackData.onTrackCallback(cTrackData, transceiver.receiver.track); } else { console.error('[SDK][ontrack] screenShareTopicHandler cTrackData not found.', { transceiver: transceiver }, { topics: topics }); } }; normalTopicHandler = function _normalTopicHandler(topics2, transceiver) { var cTrackData; topics2.forEach(function (item) { if (item.mids.includes(transceiver.mid)) { that._trackList.forEach(function (it) { if (it.topic === item.topic) { clearTimeout(timeoutsList[it.topic]); console.log('[media][onTrack][match] , clientId: ', it.clientId, ' , topic: ', it.topic, ', mid: ', transceiver.mid, { transceiver: transceiver }); it.mid = transceiver.mid; it.transceiver = transceiver; cTrackData = it; } }); } }); if (cTrackData) { cTrackData.track = transceiver.receiver.track; cTrackData.onTrackCallback(cTrackData, transceiver.receiver.track); } else { console.error('[media][onTrack][mismatch] normalTopicHandler cTrackData not found.', { transceiver: transceiver }, { topics: topics }); } }; this._firstSub = false; topics = JSON.parse(jsonMessage.topic); _context2.next = 6; return this._midManager.reOpenExistingDuplicateMids(topics); case 6: console.log('[media][PROCESS_SDP_OFFER/UPDATE] Received.. , clientIds: ', topics.map(function (it) { return it.clientId; }).join(','), ' ||| topics: ', topics.map(function (it) { return it.topic; }).join(','), ', sendTrackQueue: ', this._sendTrackQueue); this._sendTrackQueue.forEach(function (item) { topics.forEach(function (it) { if (item.topic == it.topic) { item.onUpdateSuccess(item); } }); }); this._bindReceiveIceCandidateCallback(); timeoutsList = {}; this._sendTrackQueue.forEach(function (item) { topics.forEach(function (it) { if (item.topic == it.topic) { timeoutsList[it.topic] = setTimeout(function () { var uId = _this11._app.call.currentCall().users().findUserIdByTopic(it.topic); if (!uId) return; // this._app.call.currentCall().users().get(uId).trackOpenQueue.add(); if (it.mediaType == 0 || it.mediaType == 2) { _this11._app.call.currentCall().users().get(uId).stopVideo(); setTimeout(function () { _this11._app.call.currentCall().users().get(uId).startVideo(it.topic.replace('Vi-', ''), it); setTimeout(function () { _this11.maybeNextTrack(); }, 200); }, 200); } else if (it.mediaType == 0) { _this11._app.call.currentCall().users().get(uId).stopAudio(); setTimeout(function () { _this11._app.call.currentCall().users().get(uId).startAudio(it.topic.replace('Vo-', ''), it); setTimeout(function () { _this11.maybeNextTrack(); }, 200); }, 200); } }, 5000); } }); }); this._peer.peerConnection.ontrack = function (event) { var transceiver = event.transceiver; console.log('[media][ontrack] ', { topics: topics, transceiver: transceiver }); if (transceiver.receiver.track) { transceiver.receiver.track.onunmute = function () { console.log('[media][track.onunmute] ', { topics: topics, transceiver: transceiver }); // if (topics.length == 1 && topics[0].mediaType == 2) // screenShareTopicHandler(transceiver); // else normalTopicHandler(topics, transceiver); transceiver.receiver.track.onunmute = null; }; transceiver.receiver.track.onmute = function () { console.log('[media][track.onmute] debug transceiver.receiver.track.onmute', { transceiver: transceiver }); transceiver.receiver.track.onmute = null; // this.repairMutedTracks(); }; } /** * Disable on track when we are done adding requested tracks */ _this11._onTrackCalls++; if (_this11._onTrackCalls == topics.length) { _this11._peer.peerConnection.ontrack = null; _this11._onTrackCalls = 0; } }; that = this; this._peer.processOffer(jsonMessage.sdpOffer, function (error, sdpAnswer) { if (error) { console.error('[SDK][processOffer] Error: ', { error: error }); return; } console.log('[media][RECIVE_SDP_ANSWER] Sending.. , clientIds: ', topics.map(function (it) { return it.clientId; }).join(','), ' ||| topics: ', topics.map(function (it) { return it.topic; }).join(',')); _this11._app.call.currentCall().sendCallMessage({ id: "RECIVE_SDP_ANSWER", sdpAnswer: sdpAnswer, token: _this11._app.sdkParams.token, brokerAddress: _this11._brokerAddress, addition: topics }, null, {}); setTimeout(function () { callback && callback(); }); }); case 14: case "end": return _context2.stop(); } } }, _callee2, this); })); function handleProcessSDPOfferForReceiveTrack(_x2, _x3) { return _handleProcessSDPOfferForReceiveTrack.apply(this, arguments); } return handleProcessSDPOfferForReceiveTrack; }() }, { key: "handleProcessSDPOfferForReceiveTrackUseExsistingTracks", value: function handleProcessSDPOfferForReceiveTrackUseExsistingTracks(jsonMessage, callback) { var _this12 = this; var that = this; this._firstSub = false; var topics = JSON.parse(jsonMessage.topic); console.log('[media][PROCESS_SDP_OFFER/UPDATE using exist tracks] Received.. , clientIds: ', topics.map(function (it) { return it.clientId; }).join(','), ' ||| topics: ', topics.map(function (it) { return it.topic; }).join(','), ', sendTrackQueue: ', this._sendTrackQueue); this._sendTrackQueue.forEach(function (item) { topics.forEach(function (it) { if (item.topic == it.topic) { it.onTrackCallback(it); } }); }); // this._bindReceiveIceCandidateCallback(); // this._peer.peerConnection.ontrack = (event) => { // const transceiver = event.transceiver; // console.log('[media][ontrack] ', {topics, transceiver}); // if (transceiver.receiver.track) { // transceiver.receiver.track.onunmute = () => { // console.log('[media][track.onunmute] ', {topics, transceiver}); // // if (topics.length == 1 && topics[0].mediaType == 2) // screenShareTopicHandler(transceiver); // else // normalTopicHandler(topics, transceiver); // // transceiver.receiver.track.onunmute = null; // } // transceiver.receiver.track.onmute = () => { // console.log('[media][track.onmute] debug transceiver.receiver.track.onmute', {transceiver}); // transceiver.receiver.track.onmute = null; // this.repairMutedTracks(); // } // // } // // /** // * Disable on track when we are done adding requested tracks // */ // this._onTrackCalls++; // if (this._onTrackCalls == topics.length) { // this._peer.peerConnection.ontrack = null; // this._onTrackCalls = 0; // } // } // function normalTopicHandler(topics2, transceiver) { // let cTrackData; // topics2.forEach(item => { // if (item.mids.includes(transceiver.mid)) { // that._trackList.forEach(it => { // if (it.topic === item.topic) { // console.log('[media][onTrack][match] , clientId: ', it.clientId,' , topic: ', it.topic, ', mid: ', transceiver.mid, {transceiver}); // // console.log('debug matched mid: ', transceiver.mid, ' for topic: ', item.topic, transceiver); // it.mid = transceiver.mid; // cTrackData = it; // } // }); // } // }); // if (cTrackData) { // cTrackData.track = transceiver.receiver.track; // cTrackData.onTrackCallback(cTrackData, transceiver.receiver.track); // } else { // console.error('[media][onTrack][mismatch] normalTopicHandler cTrackData not found.', {transceiver}, {topics}); // // console.error('[SDK][ontrack] normalTopicHandler cTrackData not found.', {transceiver}, {topics}); // } // } // function screenShareTopicHandler(transceiver) { // let cTrackData; // cTrackData = that._trackList.find(item => item.mediaType == 2); // if (cTrackData) { // cTrackData.track = transceiver.receiver.track; // cTrackData.onTrackCallback(cTrackData, transceiver.receiver.track); // } else { // console.error('[SDK][ontrack] screenShareTopicHandler cTrackData not found.', {transceiver}, {topics}); // } // } this._peer.processOffer(jsonMessage.sdpOffer, function (error, sdpAnswer) { if (error) { console.error('[SDK][processOffer] Error: ', { error: error }); return; } console.log('[media][RECIVE_SDP_ANSWER] Sending.. , clientIds: ', topics.map(function (it) { return it.clientId; }).join(','), ' ||| topics: ', topics.map(function (it) { return it.topic; }).join(',')); _this12._app.call.currentCall().sendCallMessage({ id: "RECIVE_SDP_ANSWER", sdpAnswer: sdpAnswer, token: _this12._app.sdkParams.token, brokerAddress: _this12._brokerAddress, addition: topics }, null, {}); setTimeout(function () { callback && callback(); }); }); } }, { key: "addNegotiationOfferToQueue", value: function addNegotiationOfferToQueue(offer, topics) { this._negotiationOfferUpdate.push({ offer: offer, topics: topics }); // this._negotiationOfferUpdate.sdpOffer = offer; // this._negotiationOfferUpdate.topics = topics; } }, { key: "_bindReceiveIceCandidateCallback", value: function _bindReceiveIceCandidateCallback() { var _this13 = this; this._peer.peerConnection.onicecandidate = function (_ref3) { var candidate = _ref3.candidate; if (!candidate) return; _this13._app.call.currentCall().sendCallMessage({ id: "RECIVE_ADD_ICE_CANDIDATE", brokerAddress: _this13._brokerAddress, token: _this13._app.sdkParams.token, chatId: _this13._callId, iceCandidate: JSON.stringify(candidate) }, null, {}); }; } }, { key: "handleProcessSDPOfferForRenegotiate", value: function handleProcessSDPOfferForRenegotiate() { var _this14 = this; this._bindReceiveIceCandidateCallback(); var localSdpObject = this._negotiationOfferUpdate.shift(); this._peer.processOffer(localSdpObject.offer, function (error, sdpAnswer) { if (error) { console.error('[SDK][processOffer] Error: ', { error: error }); _this14._onPeerFailed(_this14._direction); return; } _this14._app.call.currentCall().sendCallMessage({ id: "RECIVE_SDP_ANSWER", sdpAnswer: sdpAnswer, token: _this14._app.sdkParams.token, brokerAddress: _this14._brokerAddress, deletion: !Array.isArray(localSdpObject.topics) ? JSON.parse(localSdpObject.topics) : localSdpObject.topics }, null, {}); // setTimeout(() => { // callback && callback(); // }); }); } }, { key: "handleProcessLatestSDPOffer", value: function handleProcessLatestSDPOffer(jsonMessage, callback) { var _this15 = this; this._bindReceiveIceCandidateCallback(); this._peer.processOffer(jsonMessage.sdpOffer, function (error, sdpAnswer) { if (error) { return; } _this15._app.call.currentCall().sendCallMessage({ id: "RECIVE_SDP_ANSWER", sdpAnswer: sdpAnswer, token: _this15._app.sdkParams.token, brokerAddress: _this15._brokerAddress }, null, {}); setTimeout(function () { callback && callback(); }, 100); }); } }, { key: "repairMutedTracks", value: function repairMutedTracks() { var _this16 = this; this._trackList.forEach(function (item) { if (item.track && item.track.mute) { console.log('[media] repairMutedTracks()', item.topic, { item: item }); _this16.removeFailedTrack(item); _this16.processingCurrentTrackCompleted(); item.onOpenFailure(item); } }); } }, { key: "getPeer", value: function getPeer() { return this._peer; } }, { key: "_destroyPeer", value: function _destroyPeer() { if (this._peer) { this._peer.dispose(); this._peer = null; } } }, { key: "destroy", value: function () { var _destroy = (0, _asyncToGenerator2["default"])( /*#__PURE__*/_regenerator["default"].mark(function _callee3() { return _regenerator["default"].wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: this._isDestroyed = true; this._destroyPeer(); case 2: case "end": return _context3.stop(); } } }, _callee3, this); })); function destroy() { return _destroy.apply(this, arguments); } return destroy; }() }, { key: "isDestroyed", value: function isDestroyed() { return this._isDestroyed; } }, { key: "changeVideoSendStream", value: function changeVideoSendStream(stream) { var currentTrack = this._trackList.find(function (it) { return it.mediaType === 0; }); if (!currentTrack) { console.error("webcam src not found"); } var newTrackId = this._app.call.currentCall().sendPeerManager().getPeer().switchVideoStream(currentTrack.currentTrackId, stream); if (newTrackId) { currentTrack.currentTrackId = newTrackId; } } }, { key: "getTracksList", value: function getTracksList() { return this._trackList; } }, { key: "getIsReConnecting", value: function getIsReConnecting() { return this._isReconnecting; } }, { key: "setIsReconnecting", value: function setIsReconnecting(val) { this._isReconnecting = val; } }, { key: "sendOpenDone", value: function sendOpenDone() { this._sendOpenDone = true; } }, { key: "isSendOpenDone", value: function isSendOpenDone() { return this._sendOpenDone; } }, { key: "getPeerStatus", value: function getPeerStatus() { if (this.isPeerConnected()) return 'connected';else if (this.isPeerFailed()) return 'failed';else if (this.isPeerConnecting()) return 'connecting';else if (this.isPeerDisconnected()) return 'disconnected'; } }, { key: "resetSendQueue", value: function resetSendQueue() { this._addTrackQueue = []; this._sendTrackQueue = []; this._canProcessNextTrack = true; this._negotiationOfferUpdate = []; } }]); return PeerConnectionManager; }(); var _default = PeerConnectionManager; exports["default"] = _default;