From 3dd0aa3d2f0b3523148d3fc95d03599b3a3b1150 Mon Sep 17 00:00:00 2001 From: abiprabh <66801849+abiprabh@users.noreply.github.com> Date: Thu, 11 Jun 2020 14:44:11 -0600 Subject: [PATCH] Update app.js --- public/app.js | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 57 insertions(+), 1 deletion(-) diff --git a/public/app.js b/public/app.js index c5d9e52..5b3e36b 100644 --- a/public/app.js +++ b/public/app.js @@ -37,7 +37,18 @@ async function createRoom() { registerPeerConnectionListeners(); - // Add code for creating a room here + const offer = await peerConnection.createOffer(); + await peerConnection.setLocalDescription(offer); + + const roomWithOffer = { + offer: { + type: offer.type, + sdp: offer.sdp + } + } + const roomRef = await db.collection('rooms').add(roomWithOffer); + const roomId = roomRef.id; + document.querySelector('#currentRoom').innerText = `Current room is ${roomId} - You are the caller!` // Code for creating room above @@ -46,10 +57,41 @@ async function createRoom() { }); // Code for creating a room below + + roomRef.onSnapshot(async snapshot -> { + console.log('Got updated room:', snapshot.data()); + const data = snapshot.data(); + if (!peerConnection.currentRemoteDescription && data.answer) { + console.log('Set remote description: ', data.answer); + const answer = new RTCSessionDescription(data.answer) + await peerConnection.setRemoteDescription(answer); + } + }); // Code for creating a room above // Code for collecting ICE candidates below + + async function collectIceCandidates(roomRef, peerConneciton, + localName, remoteName) { + const candidatesCollection = roomRef.collection(localName); + + peerConnection.addEventListener('icecandidate', event -> { + if (event.candidate) { + const json = event.candidate.toJSON(); + candidatesCollection.add(json); + } + }); + + roomRef.collection(remoteName).onSnapshot(snapshot -> { + snapshot.docChanges().forEach(change -> { + if (change.type === "added") { + const candidate = new RTCIceCandidate(change.doc.data()); + peerConneciton.addIceCandidate(candidate); + } + }); + }) + } // Code for collecting ICE candidates above @@ -62,10 +104,24 @@ async function createRoom() { }); // Listening for remote session description below + + const offer = roomSnapshot.data().offer; + await peerConnection.setRemoteDescription(offer); + const answer = await peerConnection.createAnswer(); + await peerConnection.setLocalDescription(answer); + + const roomWithAnswer = { + answer: { + type: answer.type, + sdp: answer.sdp + } + } + await roomRef.update(roomWithAnswer); // Listening for remote session description above // Listen for remote ICE candidates below + // Listen for remote ICE candidates above }