Merge branch 'master' of github.com:Jlavatai/strapp
authorJordan <jordanlavatai@gmail.com>
Thu, 13 Jul 2017 00:14:31 +0000 (00:14 +0000)
committerJordan <jordanlavatai@gmail.com>
Thu, 13 Jul 2017 00:14:31 +0000 (00:14 +0000)
1  2 
client-test.js

diff --cc client-test.js
- const body = document.createElement('body')\r
- const root = document.createElement('div')\r
- document.title = "Strapp.io Client"\r
- const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] }\r
\r
- /* TODO: This is duplicated in both client.js and host.js */\r
- function getPublicKey() {\r
-   return new Promise( (resolve, reject) => {\r
-     /* Check local storage for public key */\r
-     if (!window.localStorage.getItem('public-key')) {\r
-       /* If doesn't exist, generate public and private key pair, store in\r
-       local storage */\r
-       crypto.subtle.generateKey(\r
-         { name:'RSA-OAEP',\r
-         modulusLength: 2048,\r
-         publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\r
-         hash: {name: "SHA-256"}\r
-       },\r
-       true,\r
-       ['encrypt', 'decrypt']\r
-     ).then((keyPair) => {\r
-       /* TODO: Do we need to store the private key as well? */\r
-       crypto.subtle.exportKey('jwk', keyPair.publicKey)\r
-       .then((exportedKey) => {\r
-         window.localStorage.setItem('publicKey', exportedKey)\r
-         console.log('public key is' + window.localStorage.getItem('publicKey'))\r
-         resolve(exportedKey)\r
-       })\r
\r
-     })\r
-   }\r
-   else {\r
-     resolve(window.localStorage.getItem('publicKey'))\r
-   }\r
- })\r
\r
- }\r
\r
- function sendHost(url, data) {\r
-   const request = new XMLHttpRequest()\r
-   request.open('POST', url, true)\r
-   request.setRequestHeader('Content-Type', 'application/json' )\r
-   request.setRequestHeader('X-Strapp-Type', 'ice-candidate-submission')\r
-   request.send(data)\r
- }\r
\r
- /* Poll the server. Send get request, wait for timeout, send another request.\r
- Do this until...? Can be used for either reconnecting or waiting for answer*/\r
- function requestHostAnswer(url, data) {\r
-   return new Promise((resolve, reject) => {\r
-     const request = new XMLHttpRequest()\r
-     request.open('GET', url, true)\r
-     /* But there is no JSON? */\r
-     request.setRequestHeader('Content-Type', 'application/json' )\r
-     request.setRequestHeader('X-Strapp-Type', 'client-sdp-offer')\r
-     request.setRequestHeader('X-Strapp-Pubkey', data.pubKey)\r
-     request.setRequestHeader('X-Strapp-Offer', JSON.stringify(data.sdp))\r
-     request.onreadystatechange = () => {\r
-       if (request.status === 200) {\r
-         if(request.readyState === 4) {\r
-           console.log('Client: Recieved Answer from Host')\r
-           console.log(request)\r
-           resolve(request.response)\r
-         }\r
-       }\r
-       else if (request.status === 504) {\r
-         console.log('timed out, resending')\r
-         resolve(requestHostAnswer(url, data))\r
-       }\r
-       else {\r
-         reject('server unhandled response of status ' + request.status)\r
-       }\r
-     }\r
-     request.send()\r
-   })\r
- }\r
\r
- /* Poll server for ice candidates until ice is complete */\r
- function requestHostICE(cpc, url, pubKey) {\r
-   let intervalID = window.setInterval(() => {\r
-     if (cpc.iceConnectionState.localeCompare('connected') !== 0\r
-     && cpc.iceConnectionState.localeCompare('completed') !== 0) {\r
-       console.log('Client: Polling server begin for intervalID = ' + intervalID)\r
-       console.log('Client: Requesting ICE Candidates from server')\r
-       const request = new XMLHttpRequest()\r
-       request.open('GET', url, true)\r
-       request.setRequestHeader('Content-Type', 'application/json' )\r
-       request.setRequestHeader('X-Strapp-Type', 'ice-candidate-request')\r
-       request.setRequestHeader('X-client-pubkey', pubKey)\r
-       request.onreadystatechange = () => {\r
-         if (request.status === 200) {\r
-           if(request.readyState === 4) {\r
-             console.log('Client: Recieved ICE response from Host')\r
-             let response = JSON.parse(request.response)\r
-             switch(response['iceState']) {\r
-               case "a":\r
-               cpc.addIceCandidate(new RTCIceCandidate(response.ice))\r
-               break\r
-               case "g": /* Gathering so let interval keep polling */\r
-               break\r
-               case "c": /* host iceState == Complete, stop bugging it */\r
-               clearInterval(intervalID)\r
-               clearTimeout()\r
-               break\r
-               default:\r
-               console.log('Unhandled iceState in requestHostICE()' + response['iceState'])\r
-               break\r
-             }\r
-           }\r
-         }\r
-         else {\r
-           console.log('server unhandled response of status ' + request.status)\r
-           clearInterval(intervalID)\r
-         }\r
-       }\r
-       request.send()\r
-     }\r
-     else {\r
-       clearTimeout()\r
-       clearInterval(intervalID)\r
-     }\r
-   }, 5000)\r
- }\r
\r
- /* Create and send offer -> Send ICE Candidates -> Poll for ICE Candidates */\r
- getPublicKey().then((cpk) => {\r
-   let dataChannel\r
-   console.log('Client: Create and send offer')\r
-   const cpc = new RTCPeerConnection(conf)\r
\r
-   cpc.oniceconnectionstatechange = () => {\r
-     console.log('iceConnectionState = ' + cpc.iceConnectionState)\r
-   }\r
\r
-   cpc.onnegotiationneeded = () => {\r
-     console.log('negotiation needed!')\r
-     cpc.createOffer().then((offer) => {\r
-       return cpc.setLocalDescription(offer)\r
-     })\r
-     .then(() => {\r
-       console.log('Client: Sending offer to host')\r
-       let offer = {\r
-         cmd: '> sdp pubKey',\r
-         sdp: cpc.localDescription,\r
-         pubKey: cpk.n\r
-       }\r
-       console.log(offer)\r
-       return requestHostAnswer(window.location, offer)\r
-     })\r
-     .then((serverResponse) => {\r
-       const answer = JSON.parse(serverResponse)\r
-       console.log('Client: Polling for ICE candidates')\r
-       requestHostICE(cpc, window.location, cpk.n)\r
-       cpc.setRemoteDescription(answer.sdp)\r
-       cpc.onicecandidate = (event) => {\r
-         if (event.candidate) {\r
-           console.log('Client: Sending ice candidate to host')\r
-           sendHost(window.location, JSON.stringify({\r
-             cmd: '> ice pubkey',\r
-             ice: event.candidate,\r
-             pubKey: cpk.n\r
-           }))\r
-         }\r
-         else {\r
-           console.log('Client: No more Ice Candidates to send')\r
-         }\r
-       }\r
\r
\r
-     }).catch( (err) => {\r
-       console.log('error in sdp handshake: ' + err)\r
-     })\r
-   }\r
-   /* Start data channel, triggers on negotiation needed */\r
-   dataChannel = cpc.createDataChannel("sendChannel");\r
\r
-   /* Triggered when Host adds track to peer connection */\r
-   cpc.ontrack = (event) => {\r
-     let remoteRTPReceivers = cpc.getReceivers()\r
-     let hostScreen\r
-     let video = document.querySelector('video')\r
-     /* TODO: Audio, video, or other track? */\r
-     console.log(remoteRTPReceivers)\r
-     console.log(video)\r
-     hostScreen = new MediaStream([remoteRTPReceivers[0].track])\r
-     if(!video.srcObject) {\r
-       video.srcObject = hostScreen\r
-     }\r
-     console.log(hostScreen.getVideoTracks())\r
-     console.log(video.srcObject)\r
-     video.onloadedmetadata = () => {\r
-       video.play()\r
-     }\r
-   }\r
\r
-   dataChannel.onmessage = (msg) => {\r
-     /* Get mediaStream from host and add it to the video */\r
-     let hostMessage = JSON.parse(msg.data)\r
-     console.log('Client: Renego')\r
-     cpc.setRemoteDescription(hostMessage.sdp).then(() => {\r
-       cpc.createAnswer().then((answer) => {\r
-         return cpc.setLocalDescription(answer)\r
-       }).then(() => {\r
-         dataChannel.send(JSON.stringify({\r
-           "cmd": "> screen dataChannel",\r
-           "sdp": cpc.localDescription\r
-         }))\r
-       })\r
-     })\r
\r
\r
-   }\r
-   dataChannel.onopen = () => {\r
-     document.body.innerHTML = (`<div><button> Connection with host established! </button></div> <video controls></video>`)\r
-   }\r
\r
- })\r
- document.addEventListener('DOMContentLoaded', () => {\r
\r
-   document.body.innerHTML = `<button> Setting up connection with host  </button>`\r
\r
- });\r
+ 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)
+     request.setRequestHeader('X-Strapp-Offer', JSON.stringify(data.sdp))
+     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()
+   })
+ }
+ /* 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
+       }
+       console.log(offer)
+       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 = (`<div><button> Connection with host established! </button></div> <video controls></video>`)
+   }
+ })
+ document.addEventListener('DOMContentLoaded', () => {
+   document.body.innerHTML = `<button> Setting up connection with host  </button>`
+ });
++>>>>>>> 2fa4d84ec6b04eec92a8a1e76f8b33b2a04f3c58