works on localhost, time to test on the server
[henge/kiak.git] / client.js
1 const body = document.createElement('body')
2 const root = document.createElement('div')
3 document.title = "Strapp.io Client"
4 body.appendChild(root)
5 document.body = body
6 const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] }
7
8 /* TODO: duplicate in both client.js and host.js */
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
42 function postServer(url, data) {
43 const request = new XMLHttpRequest()
44 request.open('POST', url, true)
45 request.setRequestHeader('Content-Type', 'application/json' )
46 request.setRequestHeader('X-Strapp-Type', 'ice-candidate-submission')
47 request.send(data)
48 }
49
50 /* TODO: All this does is wrap a function in a promise */
51 function pollServer(url, clientPubKey, func) {
52 return new Promise((resolve, reject) => {
53 func(url, clientPubKey, resolve, reject )
54 })
55 }
56
57 /* Poll the server. Send get request, wait for timeout, send another request.
58 Do this until...? Can be used for either reconnecting or waiting for answer*/
59 function pollServerForAnswer(url, data, resolve, reject) {
60 const request = new XMLHttpRequest()
61 request.open('GET', url, true)
62 /* But there is no JSON? */
63 request.setRequestHeader('Content-Type', 'application/json' )
64 request.setRequestHeader('X-Strapp-Type', 'client-sdp-offer')
65 request.setRequestHeader('X-Client-Offer', JSON.stringify(data))
66 request.onreadystatechange = () => {
67 if (request.status === 200) {
68 if(request.readyState === 4) {
69 console.log('Client: Recieved response from Host')
70 console.log(request)
71 resolve(request.response)
72 }
73 }
74 else if (request.status === 504) {
75 console.log('timed out, resending')
76 pollServerTimeout(url, data, resolve, reject)
77 }
78 else {
79 reject('server unhandled response of status ' + request.status)
80 }
81 }
82 request.send()
83 }
84
85 /* Poll server for ice candidates until ice is complete */
86 function pollServerForICECandidate(cpc) {
87 window.setInterval(() => {
88 if (cpc.iceGatheringState !== 'complete') {
89 return new Promise((resolve, reject) => {
90 console.log('Client: Requesting ICE Candidates from server')
91 const request = new XMLHttpRequest()
92 request.open('GET', window.location, true)
93 request.setRequestHeader('Content-Type', 'application/json' )
94 request.setRequestHeader('X-Strapp-Type', 'ice-candidate-request')
95 request.onreadystatechange = () => {
96 if (request.status === 200) {
97 if(request.readyState === 4) {
98 console.log('Client: Recieved ICE Candidate from Host')
99 resolve(request.response)
100 }
101 }
102 else if (request.status === 204) {
103 console.log('Ice Candidate unavailable, trying again in one second')
104 }
105 else {
106 reject('server unhandled response of status ' + request.status)
107 }
108 }
109 request.send(cpc.pubKey)
110 }).then((response) => {
111 cpc.addIceCandidate(response.candidate)
112 }).catch((err) => {
113 console.log('pollServerForICECandidate: ' + err)
114 })
115 }
116 else {
117 clearTimeout()
118 }
119 }, 2000)
120 }
121
122 /* Create, set, and get client Offer. Poll server for host answer.
123 Set host answer as client remoteDescription */
124 getPublicKey().then((cpk) => {
125 const cpc = new RTCPeerConnection(conf)
126 /* Start data channel */
127 sendChannel = cpc.createDataChannel("sendChannel");
128 sendChannel.onopen = () => {
129 console.log('client data channel on line')
130 sendChannel.onmessage = (message) => {
131 console.log(message.data)
132 }
133 sendChannel.send('Hi from the Client')
134 };
135 /* Start polling for ice candidate */
136
137
138 console.log(cpc.iceConnectionState)
139 cpc.oniceconnectionstatechange = () => {
140 console.log('iceConnectionState = ' + cpc.iceConnectionState)
141 }
142
143
144
145 cpc.onnegotiationneeded = () => {
146 cpc.createOffer().then((offer) => {
147 return cpc.setLocalDescription(offer)
148 })
149 .then(() => {
150 console.log('Client: Sending offer to host')
151 let offer = {
152 cmd: '> sdp pubKey',
153 sdp: cpc.localDescription,
154 pubKey: cpk.n
155 }
156 return pollServer(window.location, offer, pollServerForAnswer)
157 }).then((serverResponse) => {
158 const answer = JSON.parse(serverResponse)
159 console.log('Client: received host answer')
160 cpc.setRemoteDescription(answer.sdp).then(() => {
161 console.log('Client: Polling for ICE candidates')
162 pollServerForICECandidate(cpc)
163 })
164 cpc.onicecandidate = (event) => {
165 if (event.candidate) {
166 console.log('Client: Sending ice candidate to host')
167 postServer(window.location, JSON.stringify({
168 cmd: '> ice pubkey',
169 ice: event.candidate,
170 pubKey: cpk.n
171 }))
172 }
173 else {
174 console.log('Client: No more Ice Candidates to send')
175 }
176 }
177 }).catch( (err) => {
178 console.log('error in sdp handshake: ' + err)
179 })
180 }
181 })