data channel between host + client, sending/receiving ice candidates when needed...
[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 let dataChannel
8
9 /* TODO: duplicate in both client.js and host.js */
10 function getPublicKey() {
11 return new Promise( (resolve, reject) => {
12 /* Check local storage for public key */
13 if (!window.localStorage.getItem('public-key')) {
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. Allows pollServerForAnswer
51 to call itself recursively with the same promise */
52 function pollServer(url, clientPubKey, func) {
53 return new Promise((resolve, reject) => {
54 func(url, clientPubKey, resolve, reject )
55 })
56 }
57
58 /* Poll the server. Send get request, wait for timeout, send another request.
59 Do this until...? Can be used for either reconnecting or waiting for answer*/
60 function pollServerForAnswer(url, data, resolve, reject) {
61 const request = new XMLHttpRequest()
62 request.open('GET', url, true)
63 /* But there is no JSON? */
64 request.setRequestHeader('Content-Type', 'application/json' )
65 request.setRequestHeader('X-Strapp-Type', 'client-sdp-offer')
66 request.setRequestHeader('X-Client-Offer', JSON.stringify(data))
67 request.onreadystatechange = () => {
68 if (request.status === 200) {
69 if(request.readyState === 4) {
70 console.log('Client: Recieved Answer from Host')
71 console.log(request)
72 resolve(request.response)
73 }
74 }
75 else if (request.status === 504) {
76 console.log('timed out, resending')
77 pollServerForAnswer(url, data, resolve, reject)
78 }
79 else {
80 reject('server unhandled response of status ' + request.status)
81 }
82 }
83 request.send()
84 }
85
86 /* Poll server for ice candidates until ice is complete */
87 function pollServerForICECandidate(cpc, url, pubKey) {
88 let intervalID = window.setInterval(() => {
89 if (cpc.iceConnectionState.localeCompare('connected') !== 0
90 && cpc.iceConnectionState.localeCompare('completed') !== 0) {
91 console.log('Client: Polling server begin for intervalID = ' + intervalID)
92 console.log('Client: Requesting ICE Candidates from server')
93 const request = new XMLHttpRequest()
94 request.open('GET', url, true)
95 request.setRequestHeader('Content-Type', 'application/json' )
96 request.setRequestHeader('X-Strapp-Type', 'ice-candidate-request')
97 request.setRequestHeader('X-client-pubkey', pubKey)
98 request.onreadystatechange = () => {
99 if (request.status === 200) {
100 if(request.readyState === 4) {
101 console.log('Client: Recieved ICE Candidate from Host')
102 cpc.addIceCandidate(new RTCIceCandidate(JSON.parse(request.response).ice))
103 }
104 }
105 else if (request.status === 204) {
106 console.log('Ice Candidate unavailable, trying again in one second')
107 }
108 else {
109 console.log('server unhandled response of status ' + request.status)
110 clearInterval(intervalID)
111 }
112 }
113 request.send()
114 }
115 else {
116 clearTimeout()
117 clearInterval(intervalID)
118 }
119 }, 5000)
120 }
121
122 /* Create and send offer -> Send ICE Candidates -> Poll for ICE Candidates */
123 getPublicKey().then((cpk) => {
124 console.log('Client: Create and send offer')
125 const cpc = new RTCPeerConnection(conf)
126 /* Start data channel */
127 dataChannel = cpc.createDataChannel("sendChannel");
128 dataChannel.onmessage = (msg) => {
129 console.log(msg.data)
130 }
131 dataChannel.onopen = () => {
132 dataChannel.send(`Hi from the Client`)
133 }
134
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 })