ice candidate addition for host + client now works
[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 console.log('Host: Allocating ice candidate for client')
56 iceCandidates.push(JSON.stringify({
57 cmd: "< ice pubKey",
58 ice: event.candidate,
59 hostPubKey: hpk.n, /* TODO: do we need to send this? */
60 clientPubKey: offer.pubKey,
61 iceState: "a"
62 }))
63 }
64 else {
65 console.log('Host: Finished sending ICE candidates')
66 console.log(hpc)
67 }
68 }
69 console.log('Host: Sending answer to Client')
70 wsock.send(JSON.stringify({
71 cmd: '< sdp pubKey',
72 sdp: hpc.localDescription,
73 hostPubKey: hpk.n,
74 clientPubKey: offer.pubKey
75 }))
76 hpc.ondatachannel = (evt) => {
77 dataChannel = evt.channel
78 console.log(evt)
79 dataChannel.onmessage = (msg) => {
80 console.log(msg.data)
81 }
82 dataChannel.onopen = () => {
83 dataChannel.send(`Hi ${offer.pubKey} -host`)
84 }
85 }
86 hpc.oniceconnectionstatechange = () => {
87 console.log('iceConnectionState = ' + hpc.iceConnectionState)
88 }
89 })
90 }).catch((err) => {
91 console.log(`error in host answer ${err}`)
92 })
93 })
94
95 }
96
97 function handleNewIceSubmission(msg) {
98 console.log('Host: Adding new ice candidate')
99 const hpc = clients.get(msg.pubKey)
100 let candidate = new RTCIceCandidate(msg.ice)
101 hpc.addIceCandidate(candidate)
102 }
103
104 function handleIceRequest(msg) {
105 console.log('Host: Handling ice candidate request')
106 console.log(iceCandidates)
107 const hpc = clients.get(msg.pubKey)
108 const iceCandidate = iceCandidates.pop()
109 if (iceCandidate !== undefined) {
110 wsock.send(iceCandidate)
111 } else {
112 if (hpc.iceGatheringState.localeCompare('gathering') === 0) {
113 wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceState": "g"}`)
114 }
115 else if (hpc.iceGatheringState.localeCompare('complete') === 0) {
116 wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceState": "c"}`)
117 }
118
119 }
120
121 }
122 if ("WebSocket" in window) {
123 document.addEventListener('DOMContentLoaded', (event) => {
124 wsock = new WebSocket(`${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
125 wsock.onopen = () => {
126 console.log(`Strapped to ${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
127 }
128
129 wsock.onmessage = (serverMsg) => {
130 /* msg is either offer or ice candidate or ice candidate request*/
131
132 /* What if data null? */
133 let msg = JSON.parse(serverMsg.data)
134
135 const clientID = msg.pubKey
136
137 /* TODO: redo this trash */
138 if (clients.has(clientID)) {
139 if (msg.ice) {
140 handleNewIceSubmission(msg)
141 } else if (msg.sdp) {
142 //handleRepeatedOffer
143 } else {
144 handleIceRequest(msg)
145 }
146 }
147 else {
148 if (msg.ice) {
149 console.log('Host: Client that doesnt exist is sending ice submissions')
150 } else if (msg.sdp) {
151 handleNewClientConnection(msg)
152 } else {
153 console.log('Host: Client that doesnt exist is sending ice requests')
154 }
155 }
156 }
157 })
158 }
159 else {
160 document.addEventListener('DOMContentLoaded', () => {
161 document.body.innerHTML = 'Websockets not supported in your browser'
162 })
163 }