1 document
.title
= "Strapp.io Host"
2 const conf
= {"iceServers": [{ "url": "stun:stun.1.google.com:19302" }] }
3 const clients
= new Map([])
4 const hpk
= getPublicKey()
6 /* TODO: duplicate in both client.js and host.jhs */
7 function getPublicKey() {
8 return new Promise( (resolve
, reject
) => {
9 /* Check local storage for public key */
10 if (!window
.localStorage
.getItem('public-key')) {
11 console
.log('public key is undefined')
12 /* If doesn't exist, generate public and private key pair, store in
14 crypto
.subtle
.generateKey(
17 publicExponent
: new Uint8Array([0x01, 0x00, 0x01]),
18 hash
: {name
: "SHA-256"}
21 ['encrypt', 'decrypt']
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'))
34 resolve(window
.localStorage
.getItem('publicKey'))
40 function handleNewClientConnection(offer
) {
41 /* New Client Connection*/
42 hpc
= new RTCPeerConnection(conf
)
43 hpc
.setRemoteDescription(offer
.sdp
)
45 hpc
.createAnswer().then((answer
) => {
46 return hpc
.setLocalDescription(answer
)
50 hpc
.onicecandidate
= (event
) => {
51 if (event
.candidate
) {
52 console
.log('Host: Sending ice candidate to client')
53 wsock
.send(JSON
.stringify({
56 pubKey
: hpk
/* TODO: do we need to send this? */
60 console
.log('Host: Finished setting up ICE candidates')
63 console
.log('Host: Sending answer to Host')
64 wsock
.send(JSON
.stringify({
66 sdp
: hpc
.localDescription
,
69 clients
.set(offer
.pubKey
, {
70 hostsdp
: hpc
.localDescription
,
71 clientsdp
: hpc
.remoteDescription
76 console
.log(`error in host answer ${err}`)
81 function handleNewIceCandidate(msg
) {
82 const hpc
= clients
.get(msg
.pubKey
)
83 let candidate
= new RTCIceCandidate(msg
.ice
)
84 hpc
.addIceCandidate(candidate
)
87 if ("WebSocket" in window
) {
88 document
.addEventListener('DOMContentLoaded', (event
) => {
89 wsock
= new WebSocket(`${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
90 wsock
.onopen
= () => {
91 console
.log(`Strapped to ${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
94 wsock
.onmessage
= (serverMsg
) => {
95 /* msg is either offer or ice candidate */
96 console
.log(serverMsg
.data
)
97 let msg
= JSON
.parse(serverMsg
.data
)
99 const clientID
= msg
.pubKey
100 const msgType
= msg
.hasOwnProperty('sdp') ? 'o' : 'i'
101 if (clients
.has(clientID
)) {
104 console
.log('client exist && sending an offer == error')
107 handleNewIceCandidate(msg
)
114 handleNewClientConnection(msg
)
117 console
.log('client !exist && ice candidate === error')
125 document
.addEventListener('DOMContentLoaded', () => {
126 document
.body
.innerHTML
= 'Websockets not supported in your browser'