From 2fa4d84ec6b04eec92a8a1e76f8b33b2a04f3c58 Mon Sep 17 00:00:00 2001 From: ken Date: Wed, 12 Jul 2017 21:20:15 +0000 Subject: [PATCH] small fixes --- client.js | 438 ++++++++++++++++++++++++------------------------- host-test.js | 2 +- router.js | 6 +- www/Thumbs.db | Bin 8192 -> 0 bytes www/index.html | 5 + 5 files changed, 229 insertions(+), 222 deletions(-) delete mode 100644 www/Thumbs.db create mode 100644 www/index.html diff --git a/client.js b/client.js index 6cdf150..a4b6953 100644 --- a/client.js +++ b/client.js @@ -1,220 +1,220 @@ -const body = document.createElement('body') -const root = document.createElement('div') -document.title = "Strapp.io Client" -const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] } - -/* TODO: This is duplicated in both client.js and host.js */ -function getPublicKey() { - return new Promise( (resolve, reject) => { - /* Check local storage for public key */ - if (!window.localStorage.getItem('public-key')) { - /* 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 sendHost(url, data) { - const request = new XMLHttpRequest() - request.open('POST', url, true) - request.setRequestHeader('Content-Type', 'application/json' ) - request.setRequestHeader('X-Strapp-Type', 'ice-candidate-submission') - request.send(data) -} - -/* Poll the server. Send get request, wait for timeout, send another request. -Do this until...? Can be used for either reconnecting or waiting for answer*/ -function requestHostAnswer(url, data) { - return new Promise((resolve, reject) => { - const request = new XMLHttpRequest() - request.open('GET', url, true) - /* But there is no JSON? */ - request.setRequestHeader('Content-Type', 'application/json' ) - request.setRequestHeader('X-Strapp-Type', 'client-sdp-offer') - request.setRequestHeader('X-Strapp-Pubkey', data.pubKey) +const body = document.createElement('body') +const root = document.createElement('div') +document.title = "Strapp.io Client" +const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] } + +/* TODO: This is duplicated in both client.js and host.js */ +function getPublicKey() { + return new Promise( (resolve, reject) => { + /* Check local storage for public key */ + if (!window.localStorage.getItem('public-key')) { + /* 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 sendHost(url, data) { + const request = new XMLHttpRequest() + request.open('GET', url, true) + request.setRequestHeader('Content-Type', 'application/json' ) + request.setRequestHeader('x-strapp-type', 'ice-candidate-submission') + request.send(data) +} + +/* Poll the server. Send get request, wait for timeout, send another request. +Do this until...? Can be used for either reconnecting or waiting for answer*/ +function requestHostAnswer(url, data) { + return new Promise((resolve, reject) => { + const request = new XMLHttpRequest() + request.open('GET', url, true) + /* But there is no JSON? */ + request.setRequestHeader('Content-Type', 'application/json' ) + request.setRequestHeader('x-strapp-type', 'client-sdp-offer') + request.setRequestHeader('x-strapp-pubkey', data.pubKey) request.onreadystatechange = () => { - if (request.status === 200) { - if(request.readyState === 4) { - console.log('Client: Recieved Answer from Host') - console.log(request) - resolve(request.response) - } - } - else if (request.status === 504) { - console.log('timed out, resending') - resolve(requestHostAnswer(url, data)) - } - else { - reject('server unhandled response of status ' + request.status) - } - } - request.send(data) - }) -} - -/* Poll server for ice candidates until ice is complete */ -function requestHostICE(cpc, url, pubKey) { - let intervalID = window.setInterval(() => { - if (cpc.iceConnectionState.localeCompare('connected') !== 0 - && cpc.iceConnectionState.localeCompare('completed') !== 0) { - console.log('Client: Polling server begin for intervalID = ' + intervalID) - console.log('Client: Requesting ICE Candidates from server') - const request = new XMLHttpRequest() - request.open('GET', url, true) - request.setRequestHeader('Content-Type', 'application/json' ) - request.setRequestHeader('X-Strapp-Type', 'ice-candidate-request') - request.setRequestHeader('X-client-pubkey', pubKey) - request.onreadystatechange = () => { - if (request.status === 200) { - if(request.readyState === 4) { - console.log('Client: Recieved ICE response from Host') - let response = JSON.parse(request.response) - switch(response['iceState']) { - case "a": - cpc.addIceCandidate(new RTCIceCandidate(response.ice)) - break - case "g": /* Gathering so let interval keep polling */ - break - case "c": /* host iceState == Complete, stop bugging it */ - clearInterval(intervalID) - clearTimeout() - break - default: - console.log('Unhandled iceState in requestHostICE()' + response['iceState']) - break - } - } - } - else { - console.log('server unhandled response of status ' + request.status) - clearInterval(intervalID) - } - } - request.send() - } - else { - clearTimeout() - clearInterval(intervalID) - } - }, 5000) -} - -/* Create and send offer -> Send ICE Candidates -> Poll for ICE Candidates */ -getPublicKey().then((cpk) => { - let dataChannel - console.log('Client: Create and send offer') - const cpc = new RTCPeerConnection(conf) - - cpc.oniceconnectionstatechange = () => { - console.log('iceConnectionState = ' + cpc.iceConnectionState) - } - - cpc.onnegotiationneeded = () => { - console.log('negotiation needed!') - cpc.createOffer().then((offer) => { - return cpc.setLocalDescription(offer) - }) - .then(() => { - console.log('Client: Sending offer to host') - let offer = { - cmd: '> sdp pubKey', - sdp: cpc.localDescription, - pubKey: cpk.n - } - return requestHostAnswer(window.location, offer) - }) - .then((serverResponse) => { - const answer = JSON.parse(serverResponse) - console.log('Client: Polling for ICE candidates') - requestHostICE(cpc, window.location, cpk.n) - cpc.setRemoteDescription(answer.sdp) - cpc.onicecandidate = (event) => { - if (event.candidate) { - console.log('Client: Sending ice candidate to host') - sendHost(window.location, JSON.stringify({ - cmd: '> ice pubkey', - ice: event.candidate, - pubKey: cpk.n - })) - } - else { - console.log('Client: No more Ice Candidates to send') - } - } - - - }).catch( (err) => { - console.log('error in sdp handshake: ' + err) - }) - } - /* Start data channel, triggers on negotiation needed */ - dataChannel = cpc.createDataChannel("sendChannel"); - - /* Triggered when Host adds track to peer connection */ - cpc.ontrack = (event) => { - let remoteRTPReceivers = cpc.getReceivers() - let hostScreen - let video = document.querySelector('video') - /* TODO: Audio, video, or other track? */ - console.log(remoteRTPReceivers) - console.log(video) - hostScreen = new MediaStream([remoteRTPReceivers[0].track]) - if(!video.srcObject) { - video.srcObject = hostScreen - } - console.log(hostScreen.getVideoTracks()) - console.log(video.srcObject) - video.onloadedmetadata = () => { - video.play() - } - } - - dataChannel.onmessage = (msg) => { - /* Get mediaStream from host and add it to the video */ - let hostMessage = JSON.parse(msg.data) - console.log('Client: Renego') - cpc.setRemoteDescription(hostMessage.sdp).then(() => { - cpc.createAnswer().then((answer) => { - return cpc.setLocalDescription(answer) - }).then(() => { - dataChannel.send(JSON.stringify({ - "cmd": "> screen dataChannel", - "sdp": cpc.localDescription - })) - }) - }) - - - } - dataChannel.onopen = () => { - document.body.innerHTML = (`
`) - } - -}) -document.addEventListener('DOMContentLoaded', () => { - - document.body.innerHTML = `` - -}); + if (request.status === 200) { + if(request.readyState === 4) { + console.log('Client: Recieved Answer from Host') + console.log(request) + resolve(request.response) + } + } + else if (request.status === 504) { + console.log('timed out, resending') + resolve(requestHostAnswer(url, data)) + } + else { + reject('server unhandled response of status ' + request.status) + } + } + request.send(data) + }) +} + +/* Poll server for ice candidates until ice is complete */ +function requestHostICE(cpc, url, pubKey) { + let intervalID = window.setInterval(() => { + if (cpc.iceConnectionState.localeCompare('connected') !== 0 + && cpc.iceConnectionState.localeCompare('completed') !== 0) { + console.log('Client: Polling server begin for intervalID = ' + intervalID) + console.log('Client: Requesting ICE Candidates from server') + const request = new XMLHttpRequest() + request.open('GET', url, true) + request.setRequestHeader('Content-Type', 'application/json' ) + request.setRequestHeader('x-strapp-Type', 'ice-candidate-request') + request.setRequestHeader('x-client-pubkey', pubKey) + request.onreadystatechange = () => { + if (request.status === 200) { + if(request.readyState === 4) { + console.log('Client: Recieved ICE response from Host') + let response = JSON.parse(request.response) + switch(response['iceState']) { + case "a": + cpc.addIceCandidate(new RTCIceCandidate(response.ice)) + break + case "g": /* Gathering so let interval keep polling */ + break + case "c": /* host iceState == Complete, stop bugging it */ + clearInterval(intervalID) + clearTimeout() + break + default: + console.log('Unhandled iceState in requestHostICE()' + response['iceState']) + break + } + } + } + else { + console.log('server unhandled response of status ' + request.status) + clearInterval(intervalID) + } + } + request.send() + } + else { + clearTimeout() + clearInterval(intervalID) + } + }, 5000) +} + +/* Create and send offer -> Send ICE Candidates -> Poll for ICE Candidates */ +getPublicKey().then((cpk) => { + let dataChannel + console.log('Client: Create and send offer') + const cpc = new RTCPeerConnection(conf) + + cpc.oniceconnectionstatechange = () => { + console.log('iceConnectionState = ' + cpc.iceConnectionState) + } + + cpc.onnegotiationneeded = () => { + console.log('negotiation needed!') + cpc.createOffer().then((offer) => { + return cpc.setLocalDescription(offer) + }) + .then(() => { + console.log('Client: Sending offer to host') + let offer = { + cmd: '> sdp pubKey', + sdp: cpc.localDescription, + pubKey: cpk.n + } + return requestHostAnswer(window.location, offer) + }) + .then((serverResponse) => { + const answer = JSON.parse(serverResponse) + console.log('Client: Polling for ICE candidates') + requestHostICE(cpc, window.location, cpk.n) + cpc.setRemoteDescription(answer.sdp) + cpc.onicecandidate = (event) => { + if (event.candidate) { + console.log('Client: Sending ice candidate to host') + sendHost(window.location, JSON.stringify({ + cmd: '> ice pubkey', + ice: event.candidate, + pubKey: cpk.n + })) + } + else { + console.log('Client: No more Ice Candidates to send') + } + } + + + }).catch( (err) => { + console.log('error in sdp handshake: ' + err) + }) + } + /* Start data channel, triggers on negotiation needed */ + dataChannel = cpc.createDataChannel("sendChannel"); + + /* Triggered when Host adds track to peer connection */ + cpc.ontrack = (event) => { + let remoteRTPReceivers = cpc.getReceivers() + let hostScreen + let video = document.querySelector('video') + /* TODO: Audio, video, or other track? */ + console.log(remoteRTPReceivers) + console.log(video) + hostScreen = new MediaStream([remoteRTPReceivers[0].track]) + if(!video.srcObject) { + video.srcObject = hostScreen + } + console.log(hostScreen.getVideoTracks()) + console.log(video.srcObject) + video.onloadedmetadata = () => { + video.play() + } + } + + dataChannel.onmessage = (msg) => { + /* Get mediaStream from host and add it to the video */ + let hostMessage = JSON.parse(msg.data) + console.log('Client: Renego') + cpc.setRemoteDescription(hostMessage.sdp).then(() => { + cpc.createAnswer().then((answer) => { + return cpc.setLocalDescription(answer) + }).then(() => { + dataChannel.send(JSON.stringify({ + "cmd": "> screen dataChannel", + "sdp": cpc.localDescription + })) + }) + }) + + + } + dataChannel.onopen = () => { + document.body.innerHTML = (`
`) + } + +}) +document.addEventListener('DOMContentLoaded', () => { + + document.body.innerHTML = `` + +}); diff --git a/host-test.js b/host-test.js index 9c9fe56..ec53c3d 100644 --- a/host-test.js +++ b/host-test.js @@ -193,7 +193,7 @@ if ("WebSocket" in window) { let msg = serverMsg.data.split(' ') let clientID = msg[0] let type = msg[1] - let data = JSON.parse(msg.splice(2).join()) + let data = JSON.parse(msg.slice(2).join(' ')) if (clients.has(clientID)) { switch (type) { diff --git a/router.js b/router.js index 0e8edf8..2085e9b 100644 --- a/router.js +++ b/router.js @@ -221,7 +221,7 @@ exports = { serveClient: function (request, response, route) { const type = request.headers['x-strapp-type'] const pubKey = request.headers['x-strapp-pubkey'] - dlog(`Client ${type || 'HT'} request routed to ${route.name}`) + dlog(`Client ${type || 'HT GET'} request routed to ${route.name}`) switch (type) { case null: case undefined: @@ -236,6 +236,8 @@ exports = { if (pubKey) { let data = request.headers['x-strapp-offer'] route.pendingResponses.addResponse(pubKey, response) + dlog(`${route.origin}=>\n${pubKey}\n${type}`) + dlog(JSON.parse(data)) route.socket.send(`${pubKey} ${type} ${data}`) } else { @@ -336,7 +338,7 @@ exports = { * @arg {Object} route - the route over */ hostMessage: function (message, route) { - const argv = message.split(' ') + let argv = message.split(' ') const command = argv[0][0] argv = argv.slice(1) dlog(`Received host message from ${route.name}: ${command}`) diff --git a/www/Thumbs.db b/www/Thumbs.db deleted file mode 100644 index fa4a059f8ae8283b2075bd332c6913c9bb4f4caa..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8192 zcmeI0Yj6`)6vxkIH?Jm!ZkqNr`NSdZcwNB+^;MN~Way0|FvZkfX|?~FvVMKdW@`T>Xy!oNex5UZ{L-y|jt?9IlGpzPl<^5r z<3a)QLf`~Etu8PTOahZZF}N6%0FEPgbz_V2YLLdxgf?1#zTn+f0ImqikJ!k-P!936in!tR}47hG9@&(`; za4onFECknsHqZ_h0j`^E!gIuHM~eG{XzShBeP+pO<%n{e@>`o)nn)1XNg&E+7$!*+ zB~darI7i5p&rxr*BPfzoookU{6u|p_6WZN6%Voo@?Ty$;A~@r&Ug`3IwZbLgATn=QTFX zZ*FN_bi?8sZ@PKOEz!=l?nXzi_@ex$pmfHy8gf{z<%vfShO!Em+u7I+P9ZZz(Mu z_wi3Ze+c5Np#wYU0Cv(fIQ8JOm@o+96e6bXw6*z7O>zE^IQ!teZ|d{W%6ytr689Hf ze;C?*&>h9@JqFET^umj4Kj4$0baFoWXQQzf#3wV+ zbn0<7F?Rb~lJuu-cnlAc&m6|^np#!c7w7)}{p)+r4CAT(|FJLbkMAu$UH9NV+L8_N w(?gzdA3w*{`WeNiQ~ftow|CX79lO_Mga5k8o%7%EwEr2!f5-a0{J+)z6I$9C+yDRo diff --git a/www/index.html b/www/index.html new file mode 100644 index 0000000..ba9672b --- /dev/null +++ b/www/index.html @@ -0,0 +1,5 @@ + + + Strapp.io /www index +

Index

+ -- 2.18.0