Browse Source

Clean up the web front end a little

Will Munn 5 years ago
parent
commit
f3954c8742
2 changed files with 95 additions and 71 deletions
  1. 83 67
      web-client/answerScript.js
  2. 12 4
      web-client/answerer.html

+ 83 - 67
web-client/answerScript.js

@@ -1,80 +1,96 @@
 (function (){
-    const urlParams = new URLSearchParams(window.location.search);
-    const connectionParam = urlParams.get('connection')
-    console.log(atob(connectionParam));
-    const decoded = atob(connectionParam);
-    const bits = decoded.split('xxxxx');
-    const connection = {description: bits[0], candidate: bits[1]}
-    console.dir(connection);
-    createRemoteConnection(connection);
+  const connectionParam = getQueryParameter('connection');
+  const parsedConnection = atob(connectionParam).split(',');
+  const connectionMetadata = {
+    description: parsedConnection[0],
+    candidate: parsedConnection[1]
+  };
+  createRemoteConnection(connectionMetadata);
 })();
 
-function createRemoteConnection(remoteDescJSON) {
-    const remoteDesc = {
-        type: "offer",
-        sdp: remoteDescJSON.description 
-    }
-    const remoteCandidate = {
-        candidate: remoteDescJSON.candidate,
-        sdpMid: "0", // Media stream ID for audio
-        sdpMLineIndex: 0 // Something to do with media
-    }
-    const remoteConnection = new RTCPeerConnection();
-    let connectionDescription = '';
+function createRemoteConnection(connectionMetadata) {
+  console.log(connectionMetadata);
+  const connection = new RTCPeerConnection();
 
-    remoteConnection.setRemoteDescription(remoteDesc).then((e) => {
-        console.log(e)
-    });
-    remoteConnection.addIceCandidate(remoteCandidate).then(
-        () => {console.log('yes')}
-    )
+  const remoteDesc = {
+    type: 'offer',
+    sdp: connectionMetadata.description
+  };
+  connection.setRemoteDescription(remoteDesc)
+    .then(() => UI.setConnectionState('set remote description'));
+  let connectionDescription = '';
 
-    remoteConnection.createAnswer().then((desc) => {
-        remoteConnection.setLocalDescription(desc);
-        console.dir(desc);
-        connectionDescription = desc.sdp;
-    })
+  const remoteCandidate = {
+    candidate: connectionMetadata.candidate,
+    sdpMid: '0', // Media stream ID for audio
+    sdpMLineIndex: 0 // Something to do with media
+  };
+  connection.addIceCandidate(remoteCandidate).then(
+    () => UI.setConnectionState('candidate added')
+  );
 
+  connection.createAnswer().then((desc) => {
+    connection.setLocalDescription(desc);
+    connectionDescription = desc.sdp;
+  });
 
-    remoteConnection.onicecandidate = e => {
-        if (e.candidate) {
-            const candidate = e.candidate.candidate;
-            const body = connectionDescription;
-            fetch(
-                'http://localhost:8000/state/json',
-                {
-                    method: 'post',
-                    headers: {'Content-Type': 'text/plain'},
-                    body
-                }
-            ).then(response => {
-                if (response.status !== 200) {
-                    throw new Error('bad status ' + response.status);
-                }
-            })
-        }
-    }
-    remoteConnection.onicecandidateerror = err => {
-        console.log(err)
-    }
-    remoteConnection.ondatachannel = (e) => {
-        console.log('onDataChannel')
-        const receiveChannel = e.channel;
-        console.dir(receiveChannel);
-        const sendButton = document.getElementById('sendDataBtn')
-        sendButton.addEventListener('click', sendMessage, false)
-        function sendMessage() {
-            const messageText = document.getElementById('sendData').value;
-            receiveChannel.send(messageText);   
+  connection.onicecandidate = e => {
+    if (e.candidate) {
+      const body = connectionDescription;
+      fetch(
+        'http://localhost:8000/state/json',
+        {
+          method: 'post',
+          headers: {'Content-Type': 'text/plain'},
+          body
         }
-        receiveChannel.onopen = () => {
-            console.log('channel open')
-            receiveChannel.send('testing testing 123'); 
-        }
-        receiveChannel.onmessage = (msg) => {
-            document.body.append(msg.data);
+      ).then(response => {
+        if (response.status !== 200) {
+          throw new Error('bad status ' + response.status);
         }
+      });
     }
+  };
+  connection.ondatachannel = (e) => {
+    UI.setConnectionState('received channel');
+    const channel = e.channel;
+    console.dir(channel);
+    const sendButton = document.getElementById('sendDataBtn');
+    sendButton.addEventListener('click', sendMessage.bind(null, channel), false);
+    channel.onopen = () => {
+      console.log('channel open');
+      UI.setConnectionState('channel open');
+    };
+    channel.onmessage = (msg) => {
+      UI.createMessageElement('from-them', msg.data);
+    };
+  };
 }
 
+const UI = {
+  createMessageElement: function(style, message) {
+    const conversation =  document.getElementById('messages');
+    const messageElement = document.createElement('p');
+    messageElement.setAttribute('class', style);
+    messageElement.append(message);
+    conversation.append(messageElement);
+  },
+  messageInputValue: function() {
+    return document.getElementById('sendData').value;
+  },
+  setConnectionState: function(state) {
+    const stateEl = document.getElementById('connection-state');
+    stateEl.innerHTML = state;
+  }
+};
+
+function sendMessage(channel) {
+  const message = UI.messageInputValue();
+  UI.createMessageElement('from-me', message);
+  channel.send(message);
+}
 
+function getQueryParameter(name) {
+  const urlParams = new URLSearchParams(window.location.search);
+  return urlParams.get(name);
+}

+ 12 - 4
web-client/answerer.html

@@ -2,12 +2,20 @@
 <html>
     <head>
         <title>Web Rtc Answerer</title>
+        <link rel="stylesheet" href="/style.css" />
     </head>
     <body>
         <h1>Web Rtc</h1>
-        <textarea id="sendData" placeholder="Send a message" style="width: 500px; height: 50px"></textarea>
-        <br/>
-        <button id="sendDataBtn">Send Data</button>
+        <div>
+            <p id="connection-state">Pending</p>
+            <textarea id="sendData"
+                placeholder="Send a message"
+            ></textarea>
+            <br/>
+            <button id="sendDataBtn">Send Data</button>
+        </div>
+        <div id="messages">
+        <div>
         <script src="/answerScript.js"></script>
     </body>
-</html>
+</html>