client + server + host fixes
[henge/kiak.git] / host.js
1 document.title = "Strapp.io Host"
2 const clients = [] //TODO: Change to Map
3 if ("WebSocket" in window) {
4 document.addEventListener('DOMContentLoaded', (event) => {
5 const wsock = new WebSocket(`${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
6 wsock.onopen = () => {
7 console.log(`Strapped to ${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
8
9 }
10 wsock.onmessage = (msg) => {
11 /* Message is offer from client */
12 console.log("Incoming connection " + msg)
13
14 /* TODO: State machine to parse offer */
15
16 /* New Client Connection*/
17 hpc = new RTCPeerConnection()
18
19 hpc.createAnswer().then((offer) => {
20 return hpc.setLocalDescription(offer)
21 }).then(() => {
22 return hpc.setRemoteDescription(msg.sdp)
23 }).then(() => {
24 const hpk = getPublicKey()
25 wsock.send({
26 cmd: '< sdp pubKey'
27 sdp: hpc.localDescription
28 pubKey: hpk
29 })
30 clients.push({
31 host-sdp: hpc.localDescription,
32 client-sdp: hpc.remoteDescription,
33 clientPubKey: msg.pubKey
34 })
35 })
36 }
37 })
38 }
39 else {
40 document.addEventListener('DOMContentLoaded', () => {
41 document.body.innerHTML = 'Websockets not supported in your browser'
42 })
43 }
44 /* TODO: duplicate in both client.js and host.jhs */
45 function getPublicKey() {
46 /* Check local storage for public key */
47 if (window.localStorage.getItem('public-key') === undefined) {
48 /* If doesn't exist, generate public and private key pair, store in
49 local storage */
50 crypto.subtle.generateKey({name:'RSA-OAEP', length: 192}, true, ['encrypt', 'decrypt'])
51 .then((keyPair) => {
52 /* TODO: Do we need to store the private key as well? */
53 window.localStorage.setItem('public-key', keyPair.type.public.toString())
54 })
55 }
56 console.log(window.localStorage.getItem('public-key'))
57 return window.localStorage.getItem('public-key')
58 }