X-Git-Url: https://git.kengrimes.com/?p=henge%2Fkiak.git;a=blobdiff_plain;f=host-test.js;fp=host-test.js;h=ec53c3d98fee67373dd1c9df110a5a7617d1a985;hp=25a7b62e556ba19b7a254262aef6814cd98d6f59;hb=c8d3d5f035df084549d35fbf9880f92a5a8d9e00;hpb=bfecfec52e8ce28c6eefc336ee42df3263b6cef3 diff --git a/host-test.js b/host-test.js index 25a7b62..ec53c3d 100644 --- a/host-test.js +++ b/host-test.js @@ -1,233 +1,233 @@ -document.title = "Strapp.io Host" - - -const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] } -const clients = new Map([]) -const iceCandidates = [] -let dataChannel -let screenStream /* TODO: Remove if can access localStreams */ -let tracks = [] -let hpk - -/* TODO: duplicate in both client.js and host.jhs */ -function getPublicKey() { - return new Promise( (resolve, reject) => { - /* Check local storage for public key */ - if (!window.localStorage.getItem('public-key')) { - console.log('public key is undefined') - /* If doesn't exist, generate public and private key pair, store in - local storage */ - crypto.subtle.generateKey( - { name:'RSA-OAEP', - modulusLength: 2048, - publicExponent: new Uint8Array([0x01, 0x00, 0x01]), - hash: {name: "SHA-256"} - }, - true, - ['encrypt', 'decrypt'] - ).then((keyPair) => { - /* TODO: Do we need to store the private key as well? */ - crypto.subtle.exportKey('jwk', keyPair.publicKey) - .then((exportedKey) => { - window.localStorage.setItem('publicKey', exportedKey) - console.log('public key is' + window.localStorage.getItem('publicKey')) - resolve(exportedKey) - }) - - }) - } - else { - resolve(window.localStorage.getItem('publicKey')) - } - }) -} - -function sendClientICE(clientPubKey, hostPubKey, iceCandidate) { - console.log('Host: Allocating ice candidate for client') - console.log(iceCandidate) - iceCandidates.push(JSON.stringify({ - cmd: "< ice pubKey", - ice: iceCandidate, - hostPubKey: hostPubKey, /* TODO: do we need to send this? */ - clientPubKey: clientPubKey, - iceState: "a" - })) -} - -function handleNewClientConnection(pubKey, sdpOffer) { - /* New Client Connection*/ - hpc = new RTCPeerConnection(conf) - console.log('handleNewClientConnections()') - console.log(sdpOffer) - clients.set(pubKey, hpc) - console.log(pubKey) - hpc.setRemoteDescription(sdpOffer) - .then(() => { - hpc.createAnswer().then((answer) => { - return hpc.setLocalDescription(answer) - }) - .then(() => { - - hpc.onicecandidate = (event) => { - if (event.candidate) { - sendClientICE(pubKey, hpk.n, event.candidate) - } - else { - console.log('Host: Finished allocating ICE candidates') - } - } - console.log('Host: Sending answer to Client ') - wsock.send(JSON.stringify({ - cmd: '< sdp pubKey', - sdp: hpc.localDescription, - hostPubKey: hpk.n, - clientPubKey: pubKey - })) - - }).catch((err) => { - console.log(`error in host answer ${err}`) - }) - }).catch((error) => { - console.log(`error in setRemoteDescription ${error}`) - }) - hpc.oniceconnectionstatechange = () => { - console.log('iceConnectionState = ' + hpc.iceConnectionState) - } - hpc.ondatachannel = (evt) => { - dataChannel = evt.channel - dataChannel.onmessage = (msg) => { - let clientMessage = JSON.parse(msg.data) - console.log(`client message is ${clientMessage}`) - hpc.setRemoteDescription(clientMessage.sdp).then(() => { - console.log('should be streaming now') - }) - } - dataChannel.onopen = () => { - /* If !screenStream, gUM */ - screenStream.getTracks().forEach( (track) => { - hpc.addTrack(track, screenStream) - }) - console.log(hpc.getSenders()) - /* Create offer */ - hpc.createOffer().then((offer) => { - return hpc.setLocalDescription(offer) - }).then( () => { - dataChannel.send(JSON.stringify({ - "cmd": "< screen dataChannel", - "sdp": hpc.localDescription, - "pubKey": hpc['hpk'].n - })) - }) - } - } - hpc.onnegotiationneeded = () => { - console.log('negotiation needed') - } - -} - -function handleNewIceCandidate(msg) { - console.log('Host: Adding new ice candidate') - const hpc = clients.get(msg.pubKey) - let candidate = new RTCIceCandidate(msg.ice) - hpc.addIceCandidate(candidate) -} - -function handleIceRequest(msg) { - console.log('Host: Handling ice candidate request') - console.log(iceCandidates) - const hpc = clients.get(msg.pubKey) - const iceCandidate = iceCandidates.pop() - if (iceCandidate !== undefined) { - wsock.send(iceCandidate) - } else { - if (hpc.iceGatheringState.localeCompare('gathering') === 0) { - wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceState": "g"}`) - } - else if (hpc.iceGatheringState.localeCompare('complete') === 0) { - wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceState": "c"}`) - } - - } - -} -if ("WebSocket" in window) { - document.addEventListener('DOMContentLoaded', (event) => { - document.body.innerHTML = '
Choose options for client
' - navigator.mediaDevices.getUserMedia({ - video : { mediaSource: "screen", - width: {max: '1920'}, - height: {max: '1080'}, - frameRate: {max: '10'}} }) - .then(function(mediaStream) { - let video = document.querySelector('video') - screenStream = mediaStream - console.log(mediaStream) - video.srcObject = mediaStream - console.log('Grabbed media') - video.onloadedmetadata = function(e) { - console.log(e) - video.play() - } - }) - .catch(function(err) { - document.body.innerHTML = 'Help me help you. Reload the page and allow screen sharing!' - console.log(err); - }); // always check for errors at the end. - - getPublicKey() - .then((hpkVal) => { - hpk = hpkVal - }) - wsock = new WebSocket(`${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`) - wsock.onopen = () => { - console.log(`Strapped to ${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`) - } - - wsock.onmessage = (serverMsg) => { - /* msg is either offer or ice candidate or ice candidate request*/ - - /* What if data null? */ - console.log(`serverMsg = ${serverMsg.data}`) - - let msg = serverMsg.data.split(' ') - let clientID = msg[0] - let type = msg[1] - let data = JSON.parse(msg.splice(2).join()) - - if (clients.has(clientID)) { - switch (type) { - case 'ice-candidate-submission': - handleNewIceCandidate(msg) - break - case 'ice-candidate-request': - handleIceRequest(msg) - break - case 'client-sdp-offer': - //repeatedoffer shouldnt happen here - } - } - else { - switch (type) { - case 'client-sdp-offer': - handleNewClientConnection(clientID, data) - break - case 'ice-candidate-request': - handleIceRequest() - break - case 'ice-candidate-submission': - handleNewIceCandidate - break - } - } - } - - - - }) -} -else { - document.addEventListener('DOMContentLoaded', () => { - document.body.innerHTML = 'Websockets not supported in your browser' - }) -} +document.title = "Strapp.io Host" + + +const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] } +const clients = new Map([]) +const iceCandidates = [] +let dataChannel +let screenStream /* TODO: Remove if can access localStreams */ +let tracks = [] +let hpk + +/* TODO: duplicate in both client.js and host.jhs */ +function getPublicKey() { + return new Promise( (resolve, reject) => { + /* Check local storage for public key */ + if (!window.localStorage.getItem('public-key')) { + console.log('public key is undefined') + /* If doesn't exist, generate public and private key pair, store in + local storage */ + crypto.subtle.generateKey( + { name:'RSA-OAEP', + modulusLength: 2048, + publicExponent: new Uint8Array([0x01, 0x00, 0x01]), + hash: {name: "SHA-256"} + }, + true, + ['encrypt', 'decrypt'] + ).then((keyPair) => { + /* TODO: Do we need to store the private key as well? */ + crypto.subtle.exportKey('jwk', keyPair.publicKey) + .then((exportedKey) => { + window.localStorage.setItem('publicKey', exportedKey) + console.log('public key is' + window.localStorage.getItem('publicKey')) + resolve(exportedKey) + }) + + }) + } + else { + resolve(window.localStorage.getItem('publicKey')) + } + }) +} + +function sendClientICE(clientPubKey, hostPubKey, iceCandidate) { + console.log('Host: Allocating ice candidate for client') + console.log(iceCandidate) + iceCandidates.push(JSON.stringify({ + cmd: "< ice pubKey", + ice: iceCandidate, + hostPubKey: hostPubKey, /* TODO: do we need to send this? */ + clientPubKey: clientPubKey, + iceState: "a" + })) +} + +function handleNewClientConnection(pubKey, sdpOffer) { + /* New Client Connection*/ + hpc = new RTCPeerConnection(conf) + console.log('handleNewClientConnections()') + console.log(sdpOffer) + clients.set(pubKey, hpc) + console.log(pubKey) + hpc.setRemoteDescription(sdpOffer) + .then(() => { + hpc.createAnswer().then((answer) => { + return hpc.setLocalDescription(answer) + }) + .then(() => { + + hpc.onicecandidate = (event) => { + if (event.candidate) { + sendClientICE(pubKey, hpk.n, event.candidate) + } + else { + console.log('Host: Finished allocating ICE candidates') + } + } + console.log('Host: Sending answer to Client ') + wsock.send(JSON.stringify({ + cmd: '< sdp pubKey', + sdp: hpc.localDescription, + hostPubKey: hpk.n, + clientPubKey: pubKey + })) + + }).catch((err) => { + console.log(`error in host answer ${err}`) + }) + }).catch((error) => { + console.log(`error in setRemoteDescription ${error}`) + }) + hpc.oniceconnectionstatechange = () => { + console.log('iceConnectionState = ' + hpc.iceConnectionState) + } + hpc.ondatachannel = (evt) => { + dataChannel = evt.channel + dataChannel.onmessage = (msg) => { + let clientMessage = JSON.parse(msg.data) + console.log(`client message is ${clientMessage}`) + hpc.setRemoteDescription(clientMessage.sdp).then(() => { + console.log('should be streaming now') + }) + } + dataChannel.onopen = () => { + /* If !screenStream, gUM */ + screenStream.getTracks().forEach( (track) => { + hpc.addTrack(track, screenStream) + }) + console.log(hpc.getSenders()) + /* Create offer */ + hpc.createOffer().then((offer) => { + return hpc.setLocalDescription(offer) + }).then( () => { + dataChannel.send(JSON.stringify({ + "cmd": "< screen dataChannel", + "sdp": hpc.localDescription, + "pubKey": hpc['hpk'].n + })) + }) + } + } + hpc.onnegotiationneeded = () => { + console.log('negotiation needed') + } + +} + +function handleNewIceCandidate(msg) { + console.log('Host: Adding new ice candidate') + const hpc = clients.get(msg.pubKey) + let candidate = new RTCIceCandidate(msg.ice) + hpc.addIceCandidate(candidate) +} + +function handleIceRequest(msg) { + console.log('Host: Handling ice candidate request') + console.log(iceCandidates) + const hpc = clients.get(msg.pubKey) + const iceCandidate = iceCandidates.pop() + if (iceCandidate !== undefined) { + wsock.send(iceCandidate) + } else { + if (hpc.iceGatheringState.localeCompare('gathering') === 0) { + wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceState": "g"}`) + } + else if (hpc.iceGatheringState.localeCompare('complete') === 0) { + wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceState": "c"}`) + } + + } + +} +if ("WebSocket" in window) { + document.addEventListener('DOMContentLoaded', (event) => { + document.body.innerHTML = '
Choose options for client
' + navigator.mediaDevices.getUserMedia({ + video : { mediaSource: "screen", + width: {max: '1920'}, + height: {max: '1080'}, + frameRate: {max: '10'}} }) + .then(function(mediaStream) { + let video = document.querySelector('video') + screenStream = mediaStream + console.log(mediaStream) + video.srcObject = mediaStream + console.log('Grabbed media') + video.onloadedmetadata = function(e) { + console.log(e) + video.play() + } + }) + .catch(function(err) { + document.body.innerHTML = 'Help me help you. Reload the page and allow screen sharing!' + console.log(err); + }); // always check for errors at the end. + + getPublicKey() + .then((hpkVal) => { + hpk = hpkVal + }) + wsock = new WebSocket(`${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`) + wsock.onopen = () => { + console.log(`Strapped to ${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`) + } + + wsock.onmessage = (serverMsg) => { + /* msg is either offer or ice candidate or ice candidate request*/ + + /* What if data null? */ + console.log(`serverMsg = ${serverMsg.data}`) + + let msg = serverMsg.data.split(' ') + let clientID = msg[0] + let type = msg[1] + let data = JSON.parse(msg.slice(2).join(' ')) + + if (clients.has(clientID)) { + switch (type) { + case 'ice-candidate-submission': + handleNewIceCandidate(msg) + break + case 'ice-candidate-request': + handleIceRequest(msg) + break + case 'client-sdp-offer': + //repeatedoffer shouldnt happen here + } + } + else { + switch (type) { + case 'client-sdp-offer': + handleNewClientConnection(clientID, data) + break + case 'ice-candidate-request': + handleIceRequest() + break + case 'ice-candidate-submission': + handleNewIceCandidate + break + } + } + } + + + + }) +} +else { + document.addEventListener('DOMContentLoaded', () => { + document.body.innerHTML = 'Websockets not supported in your browser' + }) +}