need to do ICE step
[henge/kiak.git] / client.js
index 3f0aeec..d389945 100644 (file)
--- a/client.js
+++ b/client.js
@@ -3,3 +3,122 @@ 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" }] }
+/* 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}`)
+  const request = new XMLHttpRequest()
+  request.open('GET', url, true)
+  request.setRequestHeader('Content-Type', 'application/json' )
+  request.setRequestHeader('X-Strapp-Type', 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)
+      }
+    }
+    else if (request.status === 504) {
+      console.log('timed out, resending')
+      pollServerTimeout(url, data, resolve, reject)
+    }
+    else {
+      reject('server unhandled response of status ' + request.status)
+    }
+  }
+  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)
+          })
+
+        })
+    }
+    else {
+      resolve(window.localStorage.getItem('publicKey'))
+    }
+  })
+
+}
+
+/* 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)
+      }
+      else {
+        /* Set up data channel here */
+        console.log('Client: Finished setting up ICE candidates')
+      }
+    }
+    /* 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)
+})