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