var Vue = window.Vue; var Peer = window.Peer; var app = new Vue({ el: '#app', data: { peer: new Peer(localStorage.getItem('yaswvc-peerId'), { host: '/', path: '/peerjs/myapp', config: { 'iceServers': [ { urls: 'stun:stun.snikket.freeddns.org:3478' }, { urls: 'turn:turn.snikket.freeddns.org:3478', username: window.TURN_USER, credential: window.TURN_PW } ], 'sdpSemantics': 'unified-plan', }, debug: 0 }), stream: null, calls: [], audioCalls: [], videoCalls:[], connections: [], chatInput: '', displayMediaStrean: false, outgoingScreenShareCalls: [], incomingScreenShareCalls: [], }, methods: { logMessage: function(message) { let newMessage = document.createElement('div'); newMessage.innerText = message; document.querySelector('.messages').appendChild(newMessage); }, renderVideo:function(stream, selector = '#remoteVideo') { console.log('renderVideo', {stream, selector}); document.querySelector(selector).srcObject = stream; }, connectToPeer: function(peerId) { if (!peerId) return; if (peerId === this.peer.id) { this.logMessage(`You played yourself! Can't connect to yourself.`); return; }; this.logMessage(`Connecting to ${peerId}...`); let conn = this.peer.connect(peerId); this.connections.push(conn); console.log('[Out] connected', conn); conn.on('data', (data) => { this.logMessage(`${conn.peer}: ${data}`); }); conn.on('open', () => { conn.send('hi!'); }); conn.on('close', () => { this.connections = this.connections.filter(c => c.connectionId === conn.connectionId); this.calls = this.calls.filter(c => c.peer !== conn.peer); this.logMessage(`${conn.peer} closed connection.`); console.log(`[Out] Connection closed with ${conn.peer}.`); }); conn.on('error', () => { this.connections = this.connections.filter(c => c.connectionId === conn.connectionId); this.calls = this.calls.filter(c => c.peer !== conn.peer); console.warn(`[Out] Connection error ${conn.connectionId} with ${conn.peer}.`); }); let call = this.peer.call(peerId, this.stream); console.log('Started call', call); this.handleCall(call); }, connectToPeer2: async function(peerId) { if (!peerId) return; if (peerId === this.peer.id) { this.logMessage(`You played yourself! Can't connect to yourself.`); return; }; this.logMessage(`Connecting to ${peerId}...`); let conn = this.peer.connect(peerId); this.connections.push(conn); console.log('[Out] connected', conn); conn.on('data', (data) => { this.logMessage(`${conn.peer}: ${data}`); }); conn.on('open', () => { conn.send('hi!'); }); conn.on('close', () => { this.connections = this.connections.filter(c => c.connectionId === conn.connectionId); this.calls = this.calls.filter(c => c.peer !== conn.peer); this.videoCalls = this.videoCalls.filter(c => c.peer !== conn.peer); this.audioCalls = this.audioCalls.filter(c => c.peer !== conn.peer); this.logMessage(`${conn.peer} closed connection.`); console.log(`[Out] Connection closed with ${conn.peer}.`); }); conn.on('error', () => { this.connections = this.connections.filter(c => c.connectionId === conn.connectionId); this.calls = this.calls.filter(c => c.peer !== conn.peer); this.videoCalls = this.videoCalls.filter(c => c.peer !== conn.peer); this.audioCalls = this.audioCalls.filter(c => c.peer !== conn.peer); this.logMessage(`${conn.peer} lost connection.`); console.warn(`[Out] Connection error ${conn.connectionId} with ${conn.peer}.`); }); const audioStream = await this.getAudioStream(); let audioCall = this.peer.call(peerId, audioStream); // console.log('Started audioCall', audioCall); this.handleCall(audioCall); const videoStream = await this.getVideoStream(); let videoCall = this.peer.call(peerId, videoStream); // console.log('Started videoCall', videoCall); this.handleCall(videoCall); }, hangUp: function() { this.calls.forEach(c => { console.log('hangUp - closing', c); c.close(); }); this.audioCalls.forEach(c => { console.log('hangUp - closing', c); c.close(); }); this.videoCalls.forEach(c => { console.log('hangUp - closing', c); c.close(); }); this.connections.forEach(c => { console.log('hangUp - closing', c); c.close(); }); }, sendMessage: function(text = this.chatInput) { this.connections.forEach(c => { c.send(text); this.logMessage(`Me: ${text}`); this.chatInput = ''; }); }, listenForPeerEvents: function () { this.peer.on('open', (id) => { localStorage.setItem('yaswvc-peerId', id); }); this.peer.on('error', (error) => { console.error(error); }); // Handle incoming data connection this.peer.on('connection', (conn) => { this.connections.push(conn); console.log('[INC] incoming peer connection!', conn); conn.on('data', (data) => { this.logMessage(`${conn.peer}: ${data}`); }); conn.on('open', () => { conn.send('hello!'); }); conn.on('close', () => { this.connections = this.connections.filter(c => c.connectionId === conn.connectionId); this.calls = this.calls.filter(c => c.peer !== conn.peer); this.videoCalls = this.videoCalls.filter(c => c.peer !== conn.peer); this.audioCalls = this.audioCalls.filter(c => c.peer !== conn.peer); this.logMessage(`${conn.peer} closed connection.`); console.log('[Inc] closed conenction', conn) }); conn.on('error', () => { this.connections = this.connections.filter(c => c.connectionId === conn.connectionId); this.calls = this.calls.filter(c => c.peer !== conn.peer); this.videoCalls = this.videoCalls.filter(c => c.peer !== conn.peer); this.audioCalls = this.audioCalls.filter(c => c.peer !== conn.peer); this.logMessage(`${conn.peer} lost connection.`); console.warn(`[Inc] Connection error ${conn.connectionId} with ${conn.peer}.`); }); }); // Handle incoming voice/video connection this.peer.on('call', (call) => { console.log('INCOMING CALL', call); call.answer(this.stream); // Answer the call with an A/V stream. this.handleCall(call); }); }, handleCall: function handleCall(call) { call.on('stream', (stream) => this.renderVideo(stream, '#video-'+call.connectionId)); call.on('close', () => { console.log(`Call with ${call.peer} was closed.`); this.calls = this.calls.filter(c => c.connectionId === call.connectionId); }); if ((call._localStream.getVideoTracks().length > 0) && (call._localStream.getAudioTracks().length > 0)) { this.calls.push(call); console.log('Call', call); } else { if (call._localStream.getVideoTracks().length > 0) { this.videoCalls.push(call); console.log('videoCall', call); } else if (call._localStream.getAudioTracks().length > 0) { this.audioCalls.push(call); console.log('audioCall', call); } } // call.peerConnection.onaddstream = (stream) => { // console.log('stream add', stream); // console.log('getRemoteStreams', stream.currentTarget.getRemoteStreams()[0]); // stream.stream.onaddtrack = (a,b) => { // console.log('got track', a, b) // }; // }; // call.peerConnection.onremovestream = (stream) => { // console.log('stream remove', stream); // }; }, gotDevices: function gotDevices(deviceInfos) { const selectors = [document.querySelector('select#audioSource'), document.querySelector('select#audioOutput'), document.querySelector('select#videoSource')]; // Handles being called several times to update labels. Preserve values. const values = selectors.map(select => select.value); selectors.forEach(select => { while (select.firstChild) { select.removeChild(select.firstChild); } }); for (let i = 0; i !== deviceInfos.length; ++i) { const deviceInfo = deviceInfos[i]; const option = document.createElement('option'); option.value = deviceInfo.deviceId; if (deviceInfo.kind === 'audioinput') { option.text = deviceInfo.label || `microphone ${document.querySelector('select#audioSource').length + 1}`; document.querySelector('select#audioSource').appendChild(option); } else if (deviceInfo.kind === 'audiooutput') { option.text = deviceInfo.label || `speaker ${document.querySelector('select#audioOutput').length + 1}`; document.querySelector('select#audioOutput').appendChild(option); } else if (deviceInfo.kind === 'videoinput') { option.text = deviceInfo.label || `camera ${document.querySelector('select#videoSource').length + 1}`; document.querySelector('select#videoSource').appendChild(option); } else { console.log('Some other kind of source/device: ', deviceInfo); } } selectors.forEach((select, selectorIndex) => { if (Array.prototype.slice.call(select.childNodes).some(n => n.value === values[selectorIndex])) { select.value = values[selectorIndex]; } }); }, // Attach audio output device to video element using device/sink ID. attachSinkId :function attachSinkId(element, sinkId) { if (typeof element.sinkId !== 'undefined') { element.setSinkId(sinkId) .then(() => { console.log(`Success, audio output device attached: ${sinkId}`); }) .catch(error => { let errorMessage = error; if (error.name === 'SecurityError') { errorMessage = `You need to use HTTPS for selecting audio output device: ${error}`; } console.error(errorMessage); // Jump back to first output device in the list as it's the default. document.querySelector('select#audioOutput').selectedIndex = 0; }); } else { console.warn('Browser does not support output device selection.'); } }, changeAudioDestination: function changeAudioDestination() { const audioDestination = document.querySelector('select#audioOutput').value; this.attachSinkId(document.querySelector('#localVideo'), audioDestination); }, gotStream: function gotStream(stream) { console.log('gotStream', this.stream, stream); if (this.calls && (this.calls.length > 0)) { this.calls.forEach(call => { // console.log('local streams',call.peerConnection.getLocalStreams()); // call.peerConnection.removeStream(this.stream); // console.log('local streams',call.peerConnection.getLocalStreams()); // console.log('Adding stream', stream) // call.peerConnection.addStream(stream); // console.log('local streams',call.peerConnection.getLocalStreams()); // // call.peerConnection.createOffer(); // console.log('gotStream 2', call.peerConnection, stream.getTracks()) // const target = call.peerConnection.getLocalStreams()[0]; // target.getTracks().forEach((track) => { // target.removeTrack(track); // }); // stream.getTracks().forEach((track) => { // target.addTrack(track); // }); const callPeerId = call.peer; console.log('CONNECTIONS', this.connections) const conns = this.connections.filter(c => c.peer === call.peer); conns.forEach(c => c.close()) this.connectToPeer(callPeerId); }); } this.stream = stream; // make stream available to console document.querySelector('#localVideo').srcObject = stream; // Refresh button list in case labels have become available return navigator.mediaDevices.enumerateDevices(); }, getAudioStream: async function getAudioStream() { const audioSource = document.querySelector('select#audioSource').value; const constraints = { audio: {deviceId: audioSource ? {exact: audioSource} : undefined}, video: null }; const audioStream = await navigator.mediaDevices.getUserMedia(constraints).catch(this.handleError); console.log('GOT AUDIO STREAM', audioStream); return audioStream; }, getVideoStream: async function getVideoStream() { // const audioSource = document.querySelector('select#audioSource').value; const videoSource = document.querySelector('select#videoSource').value; const constraints = { // audio: {deviceId: audioSource ? {exact: audioSource} : undefined}, video: {deviceId: videoSource ? {exact: videoSource} : undefined} }; const videoStream = await navigator.mediaDevices.getUserMedia(constraints).catch(this.handleError); console.log('GOT VIDEO STREAM', videoStream); return videoStream; }, shareScreen: async function shareScreen() { if (!this.displayMediaStream) { const displayMediaStream = await navigator.mediaDevices.getDisplayMedia(); console.log('screenShare', displayMediaStream) } else { // TODO stop stream this.displayMediaStream = false; } }, handleError: function handleError(error) { console.log('navigator.MediaDevices.getUserMedia error: ', error.message, error.name); }, start: function start() { if (this.stream) { this.stream.getTracks().forEach(track => { track.stop(); }); } const audioSource = document.querySelector('select#audioSource').value; const videoSource = document.querySelector('select#videoSource').value; const constraints = { audio: {deviceId: audioSource ? {exact: audioSource} : undefined}, video: {deviceId: videoSource ? {exact: videoSource} : undefined} }; navigator.mediaDevices.getUserMedia(constraints).then(this.gotStream).then(this.gotDevices).catch(this.handleError); }, copyToClipboard: function(selector) { let element = document.querySelector(selector); element.select(); element.setSelectionRange(0, 99999); /*For mobile devices*/ document.execCommand("copy"); alert("Copied the text: " + element.value); } }, mounted() { console.log('VUE is alive!'); this.listenForPeerEvents(); navigator.mediaDevices.enumerateDevices().then(this.gotDevices).catch(this.handleError); this.start(); document.querySelector('select#audioOutput').disabled = !('sinkId' in HTMLMediaElement.prototype); } });