client + server + host fixes
[henge/kiak.git] / client.js
1 const body = document.createElement('body')
2 const root = document.createElement('div')
3 document.title = "Strapp.io Client"
4 body.appendChild(root)
5 document.body = body
6
7 /* Poll the server. Send get request, wait for timeout, send another request.
8 Do this until...? Can be used for either reconnecting or waiting for answer*/
9 function pollServerTimeout(url, data, resolve, reject) {
10 console.log('Polling server with offer ' + data)
11 const request = XMLHttpRequest()
12 request.open('GET', url)
13 request.setRequestHeader('Content-Type', 'application/json' )
14 request.onreadystatechange = () => {
15 if (request.status === 200) {
16 console.log('recieved answer from host ' + request.response)
17 resolve(request.response)
18 }
19 else if (request.status === 504) {
20 pollServerTimeout(url, data, resolve, reject)
21 }
22 else {
23 reject('server errored out with ' + request.status)
24 }
25 }
26 request.send(data)
27 }
28
29 /* TODO: Possible to pass resolve/reject to functions? */
30 function pollServer(url, clientPubKey, func) {
31 return new Promise((resolve, reject) => {
32 func(url, clientPubKey, resolve, reject )
33 })
34 }
35
36 /* TODO: duplicate in both client.js and host.js */
37 function getPublicKey() {
38 /* Check local storage for public key */
39 if (window.localStorage.getItem('public-key') === undefined) {
40 /* If doesn't exist, generate public and private key pair, store in
41 local storage */
42 crypto.subtle.generateKey({name:'RSA-OAEP', length: 192}, true, ['encrypt', 'decrypt'])
43 .then((keyPair) => {
44 /* TODO: Do we need to store the private key as well? */
45 window.localStorage.setItem('public-key', keyPair.type.public.toString())
46 })
47 }
48 console.log(window.localStorage.getItem('public-key'))
49 return window.localStorage.getItem('public-key')
50 }
51
52 /* Create, set, and get client Offer. Poll server for host answer.
53 Set host answer as client remoteDescription */
54 const cpc = new RTCPeerConnection()
55 cpc.createOffer().then((offer) => {
56 console.log('creating offer which is ' + offer)
57 return cpc.setLocalDescription(offer)
58 }).then(() => {
59 console.log('sessionDescriptionInit = ' + cpc.localDescription)
60 const cpk = getPublicKey()
61 let offer = {
62 cmd: '> sdp pubKey'
63 sdp: cpc.localDescription,
64 pubKey: cpk
65 }
66 /* Poll for answer */
67 return pollServer(window.location, offer, pollServerTimeout)
68 }).then((answer) => {
69 console.log(answer)
70 /* TODO: State machine to parse answer */
71 cpc.setRemoteDescription(answer.sdp)
72 })