Merge branch 'master' of github.com:Jlavatai/strapp
[henge/kiak.git] / client.js
index 2aa4950..a4b6953 100644 (file)
--- a/client.js
+++ b/client.js
@@ -1,12 +1,9 @@
 const body = document.createElement('body')
 const root = document.createElement('div')
 document.title = "Strapp.io Client"
-body.appendChild(root)
-document.body = body
 const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] }
-let dataChannel
 
-/* TODO: duplicate in both client.js and host.js */
+/* TODO: This is duplicated in both client.js and host.js */
 function getPublicKey() {
   return new Promise( (resolve, reject) => {
     /* Check local storage for public key */
@@ -39,52 +36,46 @@ function getPublicKey() {
 
 }
 
-function postServer(url, data) {
+function sendHost(url, data) {
   const request = new XMLHttpRequest()
-  request.open('POST', url, true)
+  request.open('GET', url, true)
   request.setRequestHeader('Content-Type', 'application/json' )
-  request.setRequestHeader('X-Strapp-Type', 'ice-candidate-submission')
+  request.setRequestHeader('x-strapp-type', 'ice-candidate-submission')
   request.send(data)
 }
 
-/* TODO: All this does is wrap a function in a promise. Allows pollServerForAnswer
-to call itself recursively with the same promise */
-function pollServer(url, clientPubKey, func) {
-  return new Promise((resolve, reject) => {
-    func(url, clientPubKey, resolve, reject )
-  })
-}
-
 /* 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 pollServerForAnswer(url, data, 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-Client-Offer', JSON.stringify(data))
-  request.onreadystatechange = () => {
-    if (request.status === 200) {
-      if(request.readyState === 4) {
-        console.log('Client: Recieved Answer from Host')
-        console.log(request)
-        resolve(request.response)
+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)
       }
     }
-    else if (request.status === 504) {
-      console.log('timed out, resending')
-      pollServerForAnswer(url, data, resolve, reject)
-    }
-    else {
-      reject('server unhandled response of status ' + request.status)
-    }
-  }
-  request.send()
+    request.send(data)
+  })
 }
 
 /* Poll server for ice candidates until ice is complete */
-function pollServerForICECandidate(cpc, url, pubKey) {
+function requestHostICE(cpc, url, pubKey) {
   let intervalID = window.setInterval(() => {
     if (cpc.iceConnectionState.localeCompare('connected') !== 0
     && cpc.iceConnectionState.localeCompare('completed') !== 0) {
@@ -93,8 +84,8 @@ function pollServerForICECandidate(cpc, url, pubKey) {
       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.setRequestHeader('x-strapp-Type', 'ice-candidate-request')
+      request.setRequestHeader('x-client-pubkey', pubKey)
       request.onreadystatechange = () => {
         if (request.status === 200) {
           if(request.readyState === 4) {
@@ -102,17 +93,17 @@ function pollServerForICECandidate(cpc, url, pubKey) {
             let response = JSON.parse(request.response)
             switch(response['iceState']) {
               case "a":
-                cpc.addIceCandidate(new RTCIceCandidate(response.ice))
-                break
+              cpc.addIceCandidate(new RTCIceCandidate(response.ice))
+              break
               case "g": /* Gathering so let interval keep polling */
-                break
+              break
               case "c": /* host iceState == Complete, stop bugging it */
-                clearInterval(intervalID)
-                clearTimeout()
-                break
+              clearInterval(intervalID)
+              clearTimeout()
+              break
               default:
-                console.log('Unhandled iceState in pollServerForICECandidate()' + response['iceState'])
-                break
+              console.log('Unhandled iceState in requestHostICE()' + response['iceState'])
+              break
             }
           }
         }
@@ -132,6 +123,7 @@ function pollServerForICECandidate(cpc, url, pubKey) {
 
 /* 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)
 
@@ -151,16 +143,17 @@ getPublicKey().then((cpk) => {
         sdp: cpc.localDescription,
         pubKey: cpk.n
       }
-      return pollServer(window.location, offer, pollServerForAnswer)
-    }).then((serverResponse) => {
+      return requestHostAnswer(window.location, offer)
+    })
+    .then((serverResponse) => {
       const answer = JSON.parse(serverResponse)
       console.log('Client: Polling for ICE candidates')
-      pollServerForICECandidate(cpc, window.location, cpk.n)
+      requestHostICE(cpc, window.location, cpk.n)
       cpc.setRemoteDescription(answer.sdp)
       cpc.onicecandidate = (event) => {
         if (event.candidate) {
           console.log('Client: Sending ice candidate to host')
-          postServer(window.location, JSON.stringify({
+          sendHost(window.location, JSON.stringify({
             cmd: '> ice pubkey',
             ice: event.candidate,
             pubKey: cpk.n
@@ -176,13 +169,52 @@ getPublicKey().then((cpk) => {
       console.log('error in sdp handshake: ' + err)
     })
   }
-  /* Start data channel */
+  /* 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) => {
-    console.log(msg.data)
+    /* 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 = () => {
-    dataChannel.send(`Hi from the Client`)
+    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>`
+
+});