Advertisement
Guest User

app.js

a guest
Mar 17th, 2020
808
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. mdc.ripple.MDCRipple.attachTo(document.querySelector('.mdc-button'));
  2.  
  3. // DEfault configuration - Change these if you have a different STUN or TURN server.
  4. const configuration = {
  5.   iceServers: [
  6.     {
  7.       urls: [
  8.         'stun:stun1.l.google.com:19302',
  9.         'stun:stun2.l.google.com:19302',
  10.       ],
  11.     },
  12.   ],
  13.   iceCandidatePoolSize: 10,
  14. };
  15.  
  16. let peerConnection = null;
  17. let localStream = null;
  18. let remoteStream = null;
  19. let roomDialog = null;
  20. let roomId = null;
  21.  
  22. function init() {
  23.   document.querySelector('#cameraBtn').addEventListener('click', openUserMedia);
  24.   document.querySelector('#hangupBtn').addEventListener('click', hangUp);
  25.   document.querySelector('#createBtn').addEventListener('click', createRoom);
  26.   document.querySelector('#joinBtn').addEventListener('click', joinRoom);
  27.   roomDialog = new mdc.dialog.MDCDialog(document.querySelector('#room-dialog'));
  28. }
  29.  
  30. async function createRoom() {
  31.   document.querySelector('#createBtn').disabled = true;
  32.   document.querySelector('#joinBtn').disabled = true;
  33.   const db = firebase.firestore();
  34.  
  35.   console.log('Create PeerConnection with configuration: ', configuration);
  36.   peerConnection = new RTCPeerConnection(configuration);
  37.  
  38.   registerPeerConnectionListeners();
  39.  
  40.   // Add code for creating a room here
  41.   const offer = await peerConnection.createOffer();
  42.   await peerConnection.setLocalDescription(offer);
  43.  
  44.     const roomWithOffer = {
  45.         offer: {
  46.             type: offer.type,
  47.             sdp: offer.sdp
  48.         }
  49.     }
  50.     const roomRef = await db.collection('rooms').add(roomWithOffer);
  51.     const roomId = roomRef.id;
  52.     document.querySelector('#currentRoom').innerText = `Current room is ${roomId} - You are the caller!`
  53.      
  54.   // Code for creating room above
  55.  
  56.   localStream.getTracks().forEach(track => {
  57.     peerConnection.addTrack(track, localStream);
  58.   });
  59.  
  60.   // Code for creating a room below
  61.  
  62.   // Code for creating a room above
  63.  
  64.   // Code for collecting ICE candidates below
  65.  
  66.   // Code for collecting ICE candidates above
  67.  
  68.   peerConnection.addEventListener('track', event => {
  69.     console.log('Got remote track:', event.streams[0]);
  70.     event.streams[0].getTracks().forEach(track => {
  71.       console.log('Add a track to the remoteStream:', track);
  72.       remoteStream.addTrack(track);
  73.     });
  74.   });
  75.  
  76.   // Listening for remote session description below
  77.   roomRef.onSnapshot(async snapshot => {
  78.     console.log('Got updated room:', snapshot.data());
  79.     const data = snapshot.data();
  80.     if (!peerConnection.currentRemoteDescription && data.answer) {
  81.         console.log('Set remote description: ', data.answer);
  82.         const answer = new RTCSessionDescription(data.answer)
  83.         await peerConnection.setRemoteDescription(answer);
  84.     }
  85. });
  86.  
  87.   // Listening for remote session description above
  88.  
  89.   // Listen for remote ICE candidates below
  90.  
  91.   // Listen for remote ICE candidates above
  92. }
  93.  
  94. function joinRoom() {
  95.   document.querySelector('#createBtn').disabled = true;
  96.   document.querySelector('#joinBtn').disabled = true;
  97.  
  98.   document.querySelector('#confirmJoinBtn').
  99.       addEventListener('click', async () => {
  100.         roomId = document.querySelector('#room-id').value;
  101.         console.log('Join room: ', roomId);
  102.         document.querySelector(
  103.             '#currentRoom').innerText = `Current room is ${roomId} - You are the callee!`;
  104.         await joinRoomById(roomId);
  105.       }, {once: true});
  106.   roomDialog.open();
  107. }
  108.  
  109. async function joinRoomById(roomId) {
  110.   const db = firebase.firestore();
  111.   const roomRef = db.collection('rooms').doc(`${roomId}`);
  112.   const roomSnapshot = await roomRef.get();
  113.   console.log('Got room:', roomSnapshot.exists);
  114.  
  115.   if (roomSnapshot.exists) {
  116.     console.log('Create PeerConnection with configuration: ', configuration);
  117.     peerConnection = new RTCPeerConnection(configuration);
  118.     registerPeerConnectionListeners();
  119.     localStream.getTracks().forEach(track => {
  120.       peerConnection.addTrack(track, localStream);
  121.     });
  122.  
  123.     // Code for collecting ICE candidates below
  124.     async function collectIceCandidates(roomRef, peerConneciton,    
  125.                                     localName, remoteName) {
  126.     const candidatesCollection = roomRef.collection(localName);
  127.  
  128.     peerConnection.addEventListener('icecandidate', event => {
  129.         if (event.candidate) {
  130.             const json = event.candidate.toJSON();
  131.             candidatesCollection.add(json);
  132.         }
  133.     });
  134.  
  135.     roomRef.collection(remoteName).onSnapshot(snapshot => {
  136.         snapshot.docChanges().forEach(change => {
  137.             if (change.type === "added") {
  138.                 const candidate = new RTCIceCandidate(change.doc.data());
  139.                 peerConneciton.addIceCandidate(candidate);
  140.             }
  141.         });
  142.     })
  143. }
  144.  
  145.     // Code for collecting ICE candidates above
  146.  
  147.     peerConnection.addEventListener('track', event => {
  148.       console.log('Got remote track:', event.streams[0]);
  149.       event.streams[0].getTracks().forEach(track => {
  150.         console.log('Add a track to the remoteStream:', track);
  151.         remoteStream.addTrack(track);
  152.       });
  153.     });
  154.  
  155.     // Code for creating SDP answer below
  156.     const offer = roomSnapshot.data().offer;
  157. await peerConnection.setRemoteDescription(offer);
  158. const answer = await peerConnection.createAnswer();
  159. await peerConnection.setLocalDescription(answer);
  160.  
  161. const roomWithAnswer = {
  162.     answer: {
  163.         type: answer.type,
  164.         sdp: answer.sdp
  165.     }
  166. }
  167. await roomRef.update(roomWithAnswer);
  168.  
  169.     // Code for creating SDP answer above
  170.  
  171.     // Listening for remote ICE candidates below
  172.  
  173.     // Listening for remote ICE candidates above
  174.   }
  175. }
  176.  
  177. async function openUserMedia(e) {
  178.   const stream = await navigator.mediaDevices.getUserMedia(
  179.       {video: true, audio: true});
  180.   document.querySelector('#localVideo').srcObject = stream;
  181.   localStream = stream;
  182.   remoteStream = new MediaStream();
  183.   document.querySelector('#remoteVideo').srcObject = remoteStream;
  184.  
  185.   console.log('Stream:', document.querySelector('#localVideo').srcObject);
  186.   document.querySelector('#cameraBtn').disabled = true;
  187.   document.querySelector('#joinBtn').disabled = false;
  188.   document.querySelector('#createBtn').disabled = false;
  189.   document.querySelector('#hangupBtn').disabled = false;
  190. }
  191.  
  192. async function hangUp(e) {
  193.   const tracks = document.querySelector('#localVideo').srcObject.getTracks();
  194.   tracks.forEach(track => {
  195.     track.stop();
  196.   });
  197.  
  198.   if (remoteStream) {
  199.     remoteStream.getTracks().forEach(track => track.stop());
  200.   }
  201.  
  202.   if (peerConnection) {
  203.     peerConnection.close();
  204.   }
  205.  
  206.   document.querySelector('#localVideo').srcObject = null;
  207.   document.querySelector('#remoteVideo').srcObject = null;
  208.   document.querySelector('#cameraBtn').disabled = false;
  209.   document.querySelector('#joinBtn').disabled = true;
  210.   document.querySelector('#createBtn').disabled = true;
  211.   document.querySelector('#hangupBtn').disabled = true;
  212.   document.querySelector('#currentRoom').innerText = '';
  213.  
  214.   // Delete room on hangup
  215.   if (roomId) {
  216.     const db = firebase.firestore();
  217.     const roomRef = db.collection('rooms').doc(roomId);
  218.     const calleeCandidates = await roomRef.collection('calleeCandidates').get();
  219.     calleeCandidates.forEach(async candidate => {
  220.       await candidate.delete();
  221.     });
  222.     const callerCandidates = await roomRef.collection('callerCandidates').get();
  223.     callerCandidates.forEach(async candidate => {
  224.       await candidate.delete();
  225.     });
  226.     await roomRef.delete();
  227.   }
  228.  
  229.   document.location.reload(true);
  230. }
  231.  
  232. function registerPeerConnectionListeners() {
  233.   peerConnection.addEventListener('icegatheringstatechange', () => {
  234.     console.log(
  235.         `ICE gathering state changed: ${peerConnection.iceGatheringState}`);
  236.   });
  237.  
  238.   peerConnection.addEventListener('connectionstatechange', () => {
  239.     console.log(`Connection state change: ${peerConnection.connectionState}`);
  240.   });
  241.  
  242.   peerConnection.addEventListener('signalingstatechange', () => {
  243.     console.log(`Signaling state change: ${peerConnection.signalingState}`);
  244.   });
  245.  
  246.   peerConnection.addEventListener('iceconnectionstatechange ', () => {
  247.     console.log(
  248.         `ICE connection state change: ${peerConnection.iceConnectionState}`);
  249.   });
  250. }
  251.  
  252. init();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement