working on client-server communication
[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 /* TODO: Determine which client ?? */
13 console.log("Incoming connection " + msg)
14
15 /* TODO: State machine to parse offer */
16
17 /* New Client Connection*/
18 hpc = new RTCPeerConnection()
19
20 hpc.createAnswer().then((offer) => {
21 return hpc.setLocalDescription(offer)
22 }).then(() => {
23 return hpc.setRemoteDescription(msg.sdp)
24 }).then(() => {
25 const hpk = getPublicKey()
26 wsock.send({
27 cmd: '< sdp pubKey',
28 sdp: hpc.localDescription,
29 pubKey: hpk
30 })
31 clients.push({
32 hostsdp: hpc.localDescription,
33 clientsdp: hpc.remoteDescription,
34 clientPubKey: msg.pubKey
35 })
36
37 })
38 }
39 })
40 }
41 else {
42 document.addEventListener('DOMContentLoaded', () => {
43 document.body.innerHTML = 'Websockets not supported in your browser'
44 })
45 }
46 /* TODO: duplicate in both client.js and host.jhs */
47 function getPublicKey() {
48 /* Check local storage for public key */
49 if (window.localStorage.getItem('public-key') === undefined) {
50 /* If doesn't exist, generate public and private key pair, store in
51 local storage */
52 crypto.subtle.generateKey({name:'RSA-OAEP', length: 192}, true, ['encrypt', 'decrypt'])
53 .then((keyPair) => {
54 /* TODO: Do we need to store the private key as well? */
55 window.localStorage.setItem('public-key', keyPair.type.public.toString())
56 })
57 }
58 console.log(window.localStorage.getItem('public-key'))
59 return window.localStorage.getItem('public-key')
60 }