ice candidate addition for host + client now works
[henge/kiak.git] / client.js
index d389945..2aa4950 100644 (file)
--- a/client.js
+++ b/client.js
@@ -3,26 +3,78 @@ const root = document.createElement('div')
 document.title = "Strapp.io Client"
 body.appendChild(root)
 document.body = body
-const conf = {"iceServers": [{ "url": "stun:stun.1.google.com:19302" }] }
+const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] }
+let dataChannel
+
+/* TODO: duplicate 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 postServer(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)
+}
+
+/* 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 pollServerTimeout(url, data, resolve, reject) {
-  console.log(`Polling server ${url} with ${data}`)
+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', JSON.stringify(data))
+  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('Client: Recieved Answer from Host')
         console.log(request)
         resolve(request.response)
       }
     }
     else if (request.status === 504) {
       console.log('timed out, resending')
-      pollServerTimeout(url, data, resolve, reject)
+      pollServerForAnswer(url, data, resolve, reject)
     }
     else {
       reject('server unhandled response of status ' + request.status)
@@ -31,94 +83,106 @@ function pollServerTimeout(url, data, resolve, reject) {
   request.send()
 }
 
-/* TODO: All this does is wrap a function in a promise */
-function pollServer(url, clientPubKey, func) {
-  return new Promise((resolve, reject) => {
-    func(url, clientPubKey, resolve, reject )
-  })
-}
-
-/* TODO: duplicate 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')) {
-      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)
-          })
-
-        })
+/* Poll server for ice candidates until ice is complete */
+function pollServerForICECandidate(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 pollServerForICECandidate()' + response['iceState'])
+                break
+            }
+          }
+        }
+        else {
+          console.log('server unhandled response of status ' + request.status)
+          clearInterval(intervalID)
+        }
+      }
+      request.send()
     }
     else {
-      resolve(window.localStorage.getItem('publicKey'))
+      clearTimeout()
+      clearInterval(intervalID)
     }
-  })
-
+  }, 5000)
 }
 
-/* Create, set, and get client Offer. Poll server for host answer.
-   Set host answer as client remoteDescription */
-const cpc = new RTCPeerConnection(conf)
-cpc.oniceconnectionstatechange = () => {
-  console.log('iceConnectionState = ' + cpc.iceConnectionState)
-}
-cpc.createOffer().then((offer) => {
-  return cpc.setLocalDescription(offer)
-})
-  .then(() => {
-  console.log('sessionDescriptionInit = ' + cpc.localDescription)
-  getPublicKey().then((cpk) => {
-    console.log('cpk is' + cpk)
-    let offer = {
-      cmd: '> sdp pubKey',
-      sdp: cpc.localDescription,
-      pubKey: cpk
-    }
-    cpc.onicecandidate = (event) => {
-      if (event.candidate) {
-        console.log('Client: Sending ice candidate to host')
-        pollServer(window.location, wsock.send(JSON.stringify({
-          cmd: '> ice pubkey',
-          ice: event.candidate,
-          pubKey: cpk /* TODO: do we need to send this? */
-        })), pollServerTimeout)
+/* Create and send offer -> Send ICE Candidates -> Poll for ICE Candidates */
+getPublicKey().then((cpk) => {
+  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
       }
-      else {
-        /* Set up data channel here */
-        console.log('Client: Finished setting up ICE candidates')
+      return pollServer(window.location, offer, pollServerForAnswer)
+    }).then((serverResponse) => {
+      const answer = JSON.parse(serverResponse)
+      console.log('Client: Polling for ICE candidates')
+      pollServerForICECandidate(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({
+            cmd: '> ice pubkey',
+            ice: event.candidate,
+            pubKey: cpk.n
+          }))
+        }
+        else {
+          console.log('Client: No more Ice Candidates to send')
+        }
       }
-    }
-    /* TODO: start polling for ice candidates, and then addIceCandidate() to cpc */
-    //pollServer(window.location, {ice}, pollServerTimeout)
 
 
-    /* Poll for answer */
-    return pollServer(window.location, offer, pollServerTimeout)
-  }).then((serverResponse) => {
-    const answer = JSON.parse(serverResponse)
-    console.log(answer)
-    /* TODO: State machine to parse answer */
-    console.log('Setting Remote Description')
-    cpc.setRemoteDescription(answer.sdp)
-  }).catch( (err) => {
-    console.log('error in sdp handshake: ' + err)
-  })
-}).catch((err) => {
-    console.log(err)
+    }).catch( (err) => {
+      console.log('error in sdp handshake: ' + err)
+    })
+  }
+  /* Start data channel */
+  dataChannel = cpc.createDataChannel("sendChannel");
+  dataChannel.onmessage = (msg) => {
+    console.log(msg.data)
+  }
+  dataChannel.onopen = () => {
+    dataChannel.send(`Hi from the Client`)
+  }
+
 })