document.title = "Strapp.io Host"
-const clients = [] //TODO: Change to Map
+const conf = {"iceServers": [{ "urls": "stun:stun.1.google.com:19302" }] }
+const clients = new Map([])
+const iceCandidates = []
+let dataChannel
+
+
+/* TODO: duplicate in both client.js and host.jhs */
+function getPublicKey() {
+ return new Promise( (resolve, reject) => {
+ /* Check local storage for public key */
+ if (!window.localStorage.getItem('public-key')) {
+ console.log('public key is undefined')
+ /* If doesn't exist, generate public and private key pair, store in
+ local storage */
+ crypto.subtle.generateKey(
+ { name:'RSA-OAEP',
+ modulusLength: 2048,
+ publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
+ hash: {name: "SHA-256"}
+ },
+ true,
+ ['encrypt', 'decrypt']
+ ).then((keyPair) => {
+ /* TODO: Do we need to store the private key as well? */
+ crypto.subtle.exportKey('jwk', keyPair.publicKey)
+ .then((exportedKey) => {
+ window.localStorage.setItem('publicKey', exportedKey)
+ console.log('public key is' + window.localStorage.getItem('publicKey'))
+ resolve(exportedKey)
+ })
+
+ })
+ }
+ else {
+ resolve(window.localStorage.getItem('publicKey'))
+ }
+ })
+}
+
+function handleNewClientConnection(offer) {
+ /* New Client Connection*/
+ hpc = new RTCPeerConnection(conf)
+ //console.log(offer)
+ clients.set(offer.pubKey, hpc)
+ hpc.setRemoteDescription(offer.sdp)
+ .then(() => {
+ hpc.createAnswer().then((answer) => {
+ return hpc.setLocalDescription(answer)
+ })
+ .then(() => {
+ getPublicKey().then((hpk) => {
+ hpc.onicecandidate = (event) => {
+ if (event.candidate) {
+ console.log('Host: Allocating ice candidate for client')
+ iceCandidates.push(JSON.stringify({
+ cmd: "< ice pubKey",
+ ice: event.candidate,
+ hostPubKey: hpk.n, /* TODO: do we need to send this? */
+ clientPubKey: offer.pubKey,
+ iceState: "a"
+ }))
+ }
+ else {
+ console.log('Host: Finished sending ICE candidates')
+ console.log(hpc)
+ }
+ }
+ console.log('Host: Sending answer to Client')
+ wsock.send(JSON.stringify({
+ cmd: '< sdp pubKey',
+ sdp: hpc.localDescription,
+ hostPubKey: hpk.n,
+ clientPubKey: offer.pubKey
+ }))
+ hpc.ondatachannel = (evt) => {
+ dataChannel = evt.channel
+ console.log(evt)
+ dataChannel.onmessage = (msg) => {
+ console.log(msg.data)
+ }
+ dataChannel.onopen = () => {
+ dataChannel.send(`Hi ${offer.pubKey} -host`)
+ }
+ }
+ hpc.oniceconnectionstatechange = () => {
+ console.log('iceConnectionState = ' + hpc.iceConnectionState)
+ }
+ })
+ }).catch((err) => {
+ console.log(`error in host answer ${err}`)
+ })
+ })
+
+}
+
+function handleNewIceSubmission(msg) {
+ console.log('Host: Adding new ice candidate')
+ const hpc = clients.get(msg.pubKey)
+ let candidate = new RTCIceCandidate(msg.ice)
+ hpc.addIceCandidate(candidate)
+}
+
+function handleIceRequest(msg) {
+ console.log('Host: Handling ice candidate request')
+ console.log(iceCandidates)
+ const hpc = clients.get(msg.pubKey)
+ const iceCandidate = iceCandidates.pop()
+ if (iceCandidate !== undefined) {
+ wsock.send(iceCandidate)
+ } else {
+ if (hpc.iceGatheringState.localeCompare('gathering') === 0) {
+ wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceState": "g"}`)
+ }
+ else if (hpc.iceGatheringState.localeCompare('complete') === 0) {
+ wsock.send(`{"cmd" : "< ice pubKey", "clientPubKey":"${msg.pubKey}", "iceState": "c"}`)
+ }
+
+ }
+
+}
if ("WebSocket" in window) {
document.addEventListener('DOMContentLoaded', (event) => {
- const wsock = new WebSocket(`${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
+ wsock = new WebSocket(`${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
wsock.onopen = () => {
console.log(`Strapped to ${_strapp_protocol}://${window.location.hostname}:${_strapp_port}`)
-
}
- wsock.onmessage = (msg) => {
- /* Message is offer from client */
- /* TODO: Determine which client ?? */
- console.log("Incoming connection " + msg)
-
- /* TODO: State machine to parse offer */
-
- /* New Client Connection*/
- hpc = new RTCPeerConnection()
-
- hpc.createAnswer().then((offer) => {
- return hpc.setLocalDescription(offer)
- }).then(() => {
- return hpc.setRemoteDescription(msg.sdp)
- }).then(() => {
- const hpk = getPublicKey()
- wsock.send({
- cmd: '< sdp pubKey',
- sdp: hpc.localDescription,
- pubKey: hpk
- })
- clients.push({
- hostsdp: hpc.localDescription,
- clientsdp: hpc.remoteDescription,
- clientPubKey: msg.pubKey
- })
- })
+ wsock.onmessage = (serverMsg) => {
+ /* msg is either offer or ice candidate or ice candidate request*/
+
+ /* What if data null? */
+ let msg = JSON.parse(serverMsg.data)
+
+ const clientID = msg.pubKey
+
+ /* TODO: redo this trash */
+ if (clients.has(clientID)) {
+ if (msg.ice) {
+ handleNewIceSubmission(msg)
+ } else if (msg.sdp) {
+ //handleRepeatedOffer
+ } else {
+ handleIceRequest(msg)
+ }
+ }
+ else {
+ if (msg.ice) {
+ console.log('Host: Client that doesnt exist is sending ice submissions')
+ } else if (msg.sdp) {
+ handleNewClientConnection(msg)
+ } else {
+ console.log('Host: Client that doesnt exist is sending ice requests')
+ }
+ }
}
})
}
document.body.innerHTML = 'Websockets not supported in your browser'
})
}
-/* TODO: duplicate in both client.js and host.jhs */
-function getPublicKey() {
- /* Check local storage for public key */
- if (window.localStorage.getItem('public-key') === undefined) {
- /* If doesn't exist, generate public and private key pair, store in
- local storage */
- crypto.subtle.generateKey({name:'RSA-OAEP', length: 192}, true, ['encrypt', 'decrypt'])
- .then((keyPair) => {
- /* TODO: Do we need to store the private key as well? */
- window.localStorage.setItem('public-key', keyPair.type.public.toString())
- })
- }
- console.log(window.localStorage.getItem('public-key'))
- return window.localStorage.getItem('public-key')
-}