getUserMedia problem in firefox
[henge/kiak.git] / client.js
1 const body = document.createElement('body')
2 const root = document.createElement('div')
3 document.title = "Strapp.io Client"
4 const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] }
5 let dataChannel
6
7 /* TODO: duplicate in both client.js and host.js */
8 function getPublicKey() {
9 return new Promise( (resolve, reject) => {
10 /* Check local storage for public key */
11 if (!window.localStorage.getItem('public-key')) {
12 /* If doesn't exist, generate public and private key pair, store in
13 local storage */
14 crypto.subtle.generateKey(
15 { name:'RSA-OAEP',
16 modulusLength: 2048,
17 publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
18 hash: {name: "SHA-256"}
19 },
20 true,
21 ['encrypt', 'decrypt']
22 ).then((keyPair) => {
23 /* TODO: Do we need to store the private key as well? */
24 crypto.subtle.exportKey('jwk', keyPair.publicKey)
25 .then((exportedKey) => {
26 window.localStorage.setItem('publicKey', exportedKey)
27 console.log('public key is' + window.localStorage.getItem('publicKey'))
28 resolve(exportedKey)
29 })
30
31 })
32 }
33 else {
34 resolve(window.localStorage.getItem('publicKey'))
35 }
36 })
37
38 }
39
40 function postServer(url, data) {
41 const request = new XMLHttpRequest()
42 request.open('POST', url, true)
43 request.setRequestHeader('Content-Type', 'application/json' )
44 request.setRequestHeader('X-Strapp-Type', 'ice-candidate-submission')
45 request.send(data)
46 }
47
48 /* TODO: All this does is wrap a function in a promise. Allows pollServerForAnswer
49 to call itself recursively with the same promise */
50 function pollServer(url, clientPubKey, func) {
51 return new Promise((resolve, reject) => {
52 func(url, clientPubKey, resolve, reject )
53 })
54 }
55
56 /* Poll the server. Send get request, wait for timeout, send another request.
57 Do this until...? Can be used for either reconnecting or waiting for answer*/
58 function pollServerForAnswer(url, data, resolve, reject) {
59 const request = new XMLHttpRequest()
60 request.open('GET', url, true)
61 /* But there is no JSON? */
62 request.setRequestHeader('Content-Type', 'application/json' )
63 request.setRequestHeader('X-Strapp-Type', 'client-sdp-offer')
64 request.setRequestHeader('X-Client-Offer', JSON.stringify(data))
65 request.onreadystatechange = () => {
66 if (request.status === 200) {
67 if(request.readyState === 4) {
68 console.log('Client: Recieved Answer from Host')
69 console.log(request)
70 resolve(request.response)
71 }
72 }
73 else if (request.status === 504) {
74 console.log('timed out, resending')
75 pollServerForAnswer(url, data, resolve, reject)
76 }
77 else {
78 reject('server unhandled response of status ' + request.status)
79 }
80 }
81 request.send()
82 }
83
84 /* Poll server for ice candidates until ice is complete */
85 function pollServerForICECandidate(cpc, url, pubKey) {
86 let intervalID = window.setInterval(() => {
87 if (cpc.iceConnectionState.localeCompare('connected') !== 0
88 && cpc.iceConnectionState.localeCompare('completed') !== 0) {
89 console.log('Client: Polling server begin for intervalID = ' + intervalID)
90 console.log('Client: Requesting ICE Candidates from server')
91 const request = new XMLHttpRequest()
92 request.open('GET', url, true)
93 request.setRequestHeader('Content-Type', 'application/json' )
94 request.setRequestHeader('X-Strapp-Type', 'ice-candidate-request')
95 request.setRequestHeader('X-client-pubkey', pubKey)
96 request.onreadystatechange = () => {
97 if (request.status === 200) {
98 if(request.readyState === 4) {
99 console.log('Client: Recieved ICE response from Host')
100 let response = JSON.parse(request.response)
101 switch(response['iceState']) {
102 case "a":
103 cpc.addIceCandidate(new RTCIceCandidate(response.ice))
104 break
105 case "g": /* Gathering so let interval keep polling */
106 break
107 case "c": /* host iceState == Complete, stop bugging it */
108 clearInterval(intervalID)
109 clearTimeout()
110 break
111 default:
112 console.log('Unhandled iceState in pollServerForICECandidate()' + response['iceState'])
113 break
114 }
115 }
116 }
117 else {
118 console.log('server unhandled response of status ' + request.status)
119 clearInterval(intervalID)
120 }
121 }
122 request.send()
123 }
124 else {
125 clearTimeout()
126 clearInterval(intervalID)
127 }
128 }, 5000)
129 }
130
131 /* Create and send offer -> Send ICE Candidates -> Poll for ICE Candidates */
132 getPublicKey().then((cpk) => {
133 console.log('Client: Create and send offer')
134 const cpc = new RTCPeerConnection(conf)
135
136 cpc.oniceconnectionstatechange = () => {
137 console.log('iceConnectionState = ' + cpc.iceConnectionState)
138 }
139
140 cpc.onnegotiationneeded = () => {
141 console.log('negotiation needed!')
142 cpc.createOffer().then((offer) => {
143 return cpc.setLocalDescription(offer)
144 })
145 .then(() => {
146 console.log('Client: Sending offer to host')
147 let offer = {
148 cmd: '> sdp pubKey',
149 sdp: cpc.localDescription,
150 pubKey: cpk.n
151 }
152 return pollServer(window.location, offer, pollServerForAnswer)
153 }).then((serverResponse) => {
154 const answer = JSON.parse(serverResponse)
155 console.log('Client: Polling for ICE candidates')
156 pollServerForICECandidate(cpc, window.location, cpk.n)
157 cpc.setRemoteDescription(answer.sdp)
158 cpc.onicecandidate = (event) => {
159 if (event.candidate) {
160 console.log('Client: Sending ice candidate to host')
161 postServer(window.location, JSON.stringify({
162 cmd: '> ice pubkey',
163 ice: event.candidate,
164 pubKey: cpk.n
165 }))
166 }
167 else {
168 console.log('Client: No more Ice Candidates to send')
169 }
170 }
171
172
173 }).catch( (err) => {
174 console.log('error in sdp handshake: ' + err)
175 })
176 }
177 /* Start data channel */
178 dataChannel = cpc.createDataChannel("sendChannel");
179 dataChannel.onmessage = (msg) => {
180 /* Get mediaStream from host and add it to the video */
181 let video = document.querySelector('')
182 }
183 dataChannel.onopen = () => {
184 dataChannel.send(`Hi from the Client`)
185 document.write('<button> Connection with host established! </button> <video autoplay id="screenOutput"></video>')
186 }
187
188 })
189 document.addEventListener('DOMContentLoaded', () => {
190
191 document.body.innerHTML = `<button> Setting up connection with host </button>`
192
193 });