name changes to client.js
[henge/kiak.git] / host.js
1 document.title = "Strapp.io Host"
2
3
4 const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] }
5 const clients = new Map([])
6 const iceCandidates = []
7 let dataChannel
8 let screenStream /* TODO: Remove if can access localStreams */
9 let tracks = []
10
11
12 /* TODO: duplicate in both client.js and host.jhs */
13 function getPublicKey() {
14 return new Promise( (resolve, reject) => {
15 /* Check local storage for public key */
16 if (!window.localStorage.getItem('public-key')) {
17 console.log('public key is undefined')
18 /* If doesn't exist, generate public and private key pair, store in
19 local storage */
20 crypto.subtle.generateKey(
21 { name:'RSA-OAEP',
22 modulusLength: 2048,
23 publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
24 hash: {name: "SHA-256"}
25 },
26 true,
27 ['encrypt', 'decrypt']
28 ).then((keyPair) => {
29 /* TODO: Do we need to store the private key as well? */
30 crypto.subtle.exportKey('jwk', keyPair.publicKey)
31 .then((exportedKey) => {
32 window.localStorage.setItem('publicKey', exportedKey)
33 console.log('public key is' + window.localStorage.getItem('publicKey'))
34 resolve(exportedKey)
35 })
36
37 })
38 }
39 else {
40 resolve(window.localStorage.getItem('publicKey'))
41 }
42 })
43 }
44
45 function handleNewClientConnection(offer) {
46 /* New Client Connection*/
47 hpc = new RTCPeerConnection(conf)
48 //console.log(offer)
49 clients.set(offer.pubKey, hpc)
50 hpc.setRemoteDescription(offer.sdp)
51 .then(() => {
52 hpc.createAnswer().then((answer) => {
53 return hpc.setLocalDescription(answer)
54 })
55 .then(() => {
56 getPublicKey().then((hpk) => {
57 hpc['hpk'] = hpk
58 hpc.onicecandidate = (event) => {
59 if (event.candidate) {
60 console.log('Host: Allocating ice candidate for client')
61 iceCandidates.push(JSON.stringify({
62 cmd: "< ice pubKey",
63 ice: event.candidate,
64 hostPubKey: hpk.n, /* TODO: do we need to send this? */
65 clientPubKey: offer.pubKey,
66 iceState: "a"
67 }))
68 }
69 else {
70 console.log('Host: Finished sending ICE candidates')
71 }
72 }
73 console.log('Host: Sending answer to Client ')
74 wsock.send(JSON.stringify({
75 cmd: '< sdp pubKey',
76 sdp: hpc.localDescription,
77 hostPubKey: hpk.n,
78 clientPubKey: offer.pubKey
79 }))
80
81
82 })
83 }).catch((err) => {
84 console.log(`error in host answer ${err}`)
85 })
86 })
87 hpc.oniceconnectionstatechange = () => {
88 console.log('iceConnectionState = ' + hpc.iceConnectionState)
89 }
90 hpc.ondatachannel = (evt) => {
91 dataChannel = evt.channel
92 dataChannel.onmessage = (msg) => {
93 let clientMessage = JSON.parse(msg.data)
94 console.log(clientMessage)
95 hpc.setRemoteDescription(clientMessage.sdp).then(() => {
96 console.log('should be streaming now')
97 })
98 }
99 dataChannel.onopen = () => {
100 screenStream.getTracks().forEach( (track) => {
101 hpc.addTrack(track, screenStream)
102 })
103 console.log(hpc.getSenders())
104 /* Create offer */
105 hpc.createOffer().then((offer) => {
106 return hpc.setLocalDescription(offer)
107 }).then( () => {
108 dataChannel.send(JSON.stringify({
109 "cmd": "< screen dataChannel",
110 "sdp": hpc.localDescription,
111 "pubKey": hpc['hpk'].n
112 }))
113 })
114 }
115 }
116 hpc.onnegotiationneeded = () => {
117 console.log('negotiation needed')
118 }
119
120 }
121
122 function handleNewIceSubmission(msg) {
123 console.log('Host: Adding new ice candidate')
124 const hpc = clients.get(msg.pubKey)
125 let candidate = new RTCIceCandidate(msg.ice)
126 hpc.addIceCandidate(candidate)
127 }
128
129 function handleIceRequest(msg) {
130 console.log('Host: Handling ice candidate request')
131 console.log(iceCandidates)
132 const hpc = clients.get(msg.pubKey)
133 const iceCandidate = iceCandidates.pop()
134 if (iceCandidate !== undefined) {
135 wsock.send(iceCandidate)
136 } else {
137 if (hpc.iceGatheringState.localeCompare('gathering') === 0) {
138 wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceState": "g"}`)
139 }
140 else if (hpc.iceGatheringState.localeCompare('complete') === 0) {
141 wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceState": "c"}`)
142 }
143
144 }
145
146 }
147 if ("WebSocket" in window) {
148 document.addEventListener('DOMContentLoaded', (event) => {
149 document.body.innerHTML = '<div>Choose options for client</div> <video autoplay></video>'
150 navigator.mediaDevices.getUserMedia({
151 video : { mediaSource: "screen",
152 width: {max: '1920'},
153 height: {max: '1080'},
154 frameRate: {max: '10'}} })
155 .then(function(mediaStream) {
156 let video = document.querySelector('video')
157 screenStream = mediaStream
158 console.log(mediaStream)
159 video.srcObject = mediaStream
160 console.log('Grabbed media')
161 video.onloadedmetadata = function(e) {
162 console.log(e)
163 video.play()
164 }
165 })
166 .catch(function(err) {
167 document.body.innerHTML = 'Help me help you. Reload the page and allow screen sharing!'
168 console.log(err);
169 }); // always check for errors at the end.
170
171 wsock = new WebSocket(`${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
172 wsock.onopen = () => {
173 console.log(`Strapped to ${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
174 }
175
176 wsock.onmessage = (serverMsg) => {
177 /* msg is either offer or ice candidate or ice candidate request*/
178
179 /* What if data null? */
180 let msg = JSON.parse(serverMsg.data)
181
182 const clientID = msg.pubKey
183
184 /* TODO: redo this trash */
185 if (clients.has(clientID)) {
186 if (msg.ice) {
187 handleNewIceSubmission(msg)
188 } else if (msg.sdp) {
189 //handleRepeatedOffer
190 } else {
191 handleIceRequest(msg)
192 }
193 }
194 else {
195 if (msg.ice) {
196 console.log('Host: Client that doesnt exist is sending ice submissions')
197 } else if (msg.sdp) {
198 handleNewClientConnection(msg)
199 } else {
200 console.log('Host: Client that doesnt exist is sending ice requests')
201 }
202 }
203 }
204
205
206
207 })
208 }
209 else {
210 document.addEventListener('DOMContentLoaded', () => {
211 document.body.innerHTML = 'Websockets not supported in your browser'
212 })
213 }