ice candidate addition for host + client now works
authorjordan lavatai <jordanlavatai@gmail.com>
Wed, 5 Jul 2017 19:07:41 +0000 (12:07 -0700)
committerjordan lavatai <jordanlavatai@gmail.com>
Wed, 5 Jul 2017 19:07:41 +0000 (12:07 -0700)
client.js
host.js
main.js

index 956971a..2aa4950 100644 (file)
--- a/client.js
+++ b/client.js
@@ -15,27 +15,27 @@ function getPublicKey() {
       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)
-          })
+        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'))
-    }
-  })
+    })
+  }
+  else {
+    resolve(window.localStorage.getItem('publicKey'))
+  }
+})
 
 }
 
@@ -48,7 +48,7 @@ function postServer(url, data) {
 }
 
 /* TODO: All this does is wrap a function in a promise. Allows pollServerForAnswer
-         to call itself recursively with the same promise */
+to call itself recursively with the same promise */
 function pollServer(url, clientPubKey, func) {
   return new Promise((resolve, reject) => {
     func(url, clientPubKey, resolve, reject )
@@ -56,7 +56,7 @@ function pollServer(url, clientPubKey, func) {
 }
 
 /* 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*/
+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)
@@ -87,30 +87,41 @@ function pollServerForAnswer(url, data, resolve, reject) {
 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 Candidate from Host')
-               cpc.addIceCandidate(new RTCIceCandidate(JSON.parse(request.response).ice))
-             }
-           }
-           else if (request.status === 204) {
-             console.log('Ice Candidate unavailable, trying again in one second')
-           }
-           else {
-             console.log('server unhandled response of status ' + request.status)
-             clearInterval(intervalID)
-           }
-         }
-         request.send()
+    && 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 {
       clearTimeout()
diff --git a/host.js b/host.js
index 3af3426..01c56a2 100644 (file)
--- a/host.js
+++ b/host.js
@@ -58,11 +58,12 @@ function handleNewClientConnection(offer) {
               ice: event.candidate,
               hostPubKey: hpk.n, /* TODO: do we need to send this? */
               clientPubKey: offer.pubKey,
-              iceCandidateAvailable: true
+              iceState: "a"
             }))
           }
           else {
             console.log('Host: Finished sending ICE candidates')
+            console.log(hpc)
           }
         }
         console.log('Host: Sending answer to Client')
@@ -91,8 +92,6 @@ function handleNewClientConnection(offer) {
     })
   })
 
-
-
 }
 
 function handleNewIceSubmission(msg) {
@@ -105,12 +104,18 @@ function handleNewIceSubmission(msg) {
 function handleIceRequest(msg) {
   console.log('Host: Handling ice candidate request')
   console.log(iceCandidates)
-  const hpc = clients.get(msg)
+  const hpc = clients.get(msg.pubKey)
   const iceCandidate = iceCandidates.pop()
   if (iceCandidate !== undefined) {
     wsock.send(iceCandidate)
   } else {
-    wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceCandidateAvailable": false}`)
+    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"}`)
+    }
+
   }
 
 }
diff --git a/main.js b/main.js
index 9ef0b49..321af88 100644 (file)
--- a/main.js
+++ b/main.js
@@ -138,22 +138,31 @@ const router = {
             }
             else if (hostMessage['cmd'].localeCompare('< ice pubKey') === 0){
               /* if the host response is an ice candidate */
-              console.log('Server: Sending host ice candidate')
-              let iceCandidateAvailable = hostMessage['iceCandidateAvailable']
+              console.log('Server: Handling host ICE message')
+              let iceState = hostMessage['iceState']              
               /* If there are any ice candidates, send them back */
-              if (iceCandidateAvailable) {
-                response.writeHead('200', {'x-strapp-type': 'ice-candidate-available'})
-                response.write(JSON.stringify(hostMessage))
-                response.end()
-              }
-              else { /* If not, srequest processed successfully, but there isnt anything yet*/
-                console.log('Server: No ice candidate available for response')
-                response.writeHead('204', {'x-strapp-type': 'ice-candidate-unavailable'})
-                response.end()
-              }
-            }
-            else {
-              console.log('unhandled message cmd from host')
+              switch(iceState) {
+                case "a":
+                  response.writeHead('200', {'x-strapp-type': 'ice-candidate-available'})
+                  response.write(JSON.stringify(hostMessage))
+                  response.end()
+                  break
+                case "g":
+                  console.log('Server: Host is still gathering candidates, keep trying')
+                  response.writeHead('200', {'x-strapp-type': 'ice-state-gathering'})
+                  response.write(JSON.stringify(hostMessage))
+                  response.end()
+                break
+                case "c":
+                  console.log('Server: Host has completed gathering candidates')
+                  response.writeHead('200', {'x-strapp-type': 'ice-state-complete'})
+                  response.write(JSON.stringify(hostMessage))
+                  response.end()
+                  break
+                default:
+                  console.log('unhandled iceState from host')
+                  break
+                }
             }
 
           })