works on localhost, time to test on the server
[henge/kiak.git] / host.js
1 document.title = "Strapp.io Host"
2 const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] }
3 const clients = new Map([])
4 const iceCandidates = []
5 let dataChannel
6
7
8 /* TODO: duplicate in both client.js and host.jhs */
9 function getPublicKey() {
10 return new Promise( (resolve, reject) => {
11 /* Check local storage for public key */
12 if (!window.localStorage.getItem('public-key')) {
13 console.log('public key is undefined')
14 /* If doesn't exist, generate public and private key pair, store in
15 local storage */
16 crypto.subtle.generateKey(
17 { name:'RSA-OAEP',
18 modulusLength: 2048,
19 publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
20 hash: {name: "SHA-256"}
21 },
22 true,
23 ['encrypt', 'decrypt']
24 ).then((keyPair) => {
25 /* TODO: Do we need to store the private key as well? */
26 crypto.subtle.exportKey('jwk', keyPair.publicKey)
27 .then((exportedKey) => {
28 window.localStorage.setItem('publicKey', exportedKey)
29 console.log('public key is' + window.localStorage.getItem('publicKey'))
30 resolve(exportedKey)
31 })
32
33 })
34 }
35 else {
36 resolve(window.localStorage.getItem('publicKey'))
37 }
38 })
39 }
40
41 function handleNewClientConnection(offer) {
42 /* New Client Connection*/
43 hpc = new RTCPeerConnection(conf)
44 //console.log(offer)
45 clients.set(offer.pubKey, hpc)
46 hpc.setRemoteDescription(offer.sdp)
47 .then(() => {
48 hpc.createAnswer().then((answer) => {
49 return hpc.setLocalDescription(answer)
50 })
51 .then(() => {
52 getPublicKey().then((hpk) => {
53 hpc.onicecandidate = (event) => {
54 if (event.candidate) {
55 iceCandidates.push(JSON.stringify({
56 cmd: '< ice pubKey',
57 ice: event.candidate,
58 hostPubKey: hpk.n, /* TODO: do we need to send this? */
59 clientPubKey: offer.pubKey,
60 iceCandidateAvailable: true
61 }))
62 }
63 else {
64 console.log('Host: Finished sending ICE candidates')
65 }
66 }
67 console.log('Host: Sending answer to Client')
68 wsock.send(JSON.stringify({
69 cmd: '< sdp pubKey',
70 sdp: hpc.localDescription,
71 hostPubKey: hpk.n,
72 clientPubKey: offer.pubKey
73 }))
74 hpc.ondatachannel = (evt) => {
75 dataChannel = evt.channel
76 console.log(evt)
77 dataChannel.onmessage = (msg) => {
78 console.log(msg.data)
79 }
80 dataChannel.send('Hi from the host')
81 }
82 hpc.oniceconnectionstatechange = () => {
83 console.log('iceConnectionState = ' + hpc.iceConnectionState)
84 }
85 })
86 }).catch((err) => {
87 console.log(`error in host answer ${err}`)
88 })
89 })
90
91
92
93 }
94
95 function handleNewIceSubmission(msg) {
96 console.log('Host: Adding new ice candidate')
97 const hpc = clients.get(msg.pubKey)
98 let candidate = new RTCIceCandidate(msg.ice)
99 hpc.addIceCandidate(candidate)
100 }
101
102 function handleIceRequest(msg) {
103 console.log('Host: Sending ice candidate to client')
104 const hpc = clients.get(msg)
105 const iceCandidates = iceCandidates.pop()
106 if (iceCandidate !== undefined) {
107 wsock.send(iceCandidate)
108 } else {
109 wsock.send('no ice candidates')
110 }
111
112 }
113 if ("WebSocket" in window) {
114 document.addEventListener('DOMContentLoaded', (event) => {
115 wsock = new WebSocket(`${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
116 wsock.onopen = () => {
117 console.log(`Strapped to ${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
118 }
119
120 wsock.onmessage = (serverMsg) => {
121 /* msg is either offer or ice candidate or ice candidate request*/
122
123
124 let msg = JSON.parse(serverMsg.data)
125
126 const clientID = msg.pubKey || msg
127
128 /* TODO: redo this trash */
129 if (clients.has(clientID)) {
130 if (msg.ice) {
131 handleNewIceSubmission(msg)
132 } else if (msg.sdp) {
133 //handleRepeatedOffer
134 } else {
135 handleIceRequest(msg)
136 }
137 }
138 else {
139 if (msg.ice) {
140 console.log('Host: Client that doesnt exist is sending ice submissions')
141 } else if (msg.sdp) {
142 handleNewClientConnection(msg)
143 } else {
144 console.log('Host: Client that doesnt exist is sending ice requests')
145 }
146 }
147 }
148 })
149 }
150 else {
151 document.addEventListener('DOMContentLoaded', () => {
152 document.body.innerHTML = 'Websockets not supported in your browser'
153 })
154 }