Ran prettier on code

This commit is contained in:
Taichi Kato 2020-05-31 10:54:40 +08:00
parent 804ace168f
commit c56b521c5e
3 changed files with 137 additions and 67 deletions

3
public/chat.html vendored
View File

@ -46,8 +46,7 @@
</div> </div>
<p id="remote-video-text"></p> <p id="remote-video-text"></p>
<div id="wrapper"> <div id="wrapper"></div>
</div>
<div id="moveable"> <div id="moveable">
<p id="local-video-text">No webcam input</p> <p id="local-video-text">No webcam input</p>
<video id="local-video" autoplay muted playsinline></video> <video id="local-video" autoplay muted playsinline></video>

View File

@ -28,7 +28,6 @@ const chatZone = $("#chat-zone");
var dataChannel = new Map(); var dataChannel = new Map();
var VideoChat = { var VideoChat = {
nickname: undefined, nickname: undefined,
videoEnabled: true, videoEnabled: true,
@ -101,7 +100,10 @@ var VideoChat = {
VideoChat.nickname = prompt("Please enter a nickname", ""); VideoChat.nickname = prompt("Please enter a nickname", "");
while (VideoChat.nickname == null || VideoChat.nickname.trim() === "") { while (VideoChat.nickname == null || VideoChat.nickname.trim() === "") {
VideoChat.nickname = prompt("Nickname cannot be empty. Please enter a nickname", ""); VideoChat.nickname = prompt(
"Nickname cannot be empty. Please enter a nickname",
""
);
} }
VideoChat.localVideo.srcObject = stream; VideoChat.localVideo.srcObject = stream;
@ -128,42 +130,54 @@ var VideoChat = {
logIt("readyToCall"); logIt("readyToCall");
}, },
call: function (uuid, room) { call: function (uuid, room) {
logIt("Initiating call"); logIt("Initiating call");
VideoChat.startCall(uuid); VideoChat.startCall(uuid);
}, },
// Set up a callback to run when we have the ephemeral token to use Twilio's TURN server. // Set up a callback to run when we have the ephemeral token to use Twilio's TURN server.
startCall: function (uuid) { startCall: function (uuid) {
VideoChat.socket.on("token", VideoChat.establishConnection(uuid, function(a) {VideoChat.createOffer(a);})); VideoChat.socket.on(
"token",
VideoChat.establishConnection(uuid, function (a) {
VideoChat.createOffer(a);
})
);
VideoChat.socket.emit("token", roomHash, uuid); VideoChat.socket.emit("token", roomHash, uuid);
}, },
establishConnection: function (correctUuid, callback) { establishConnection: function (correctUuid, callback) {
return function(token, uuid) { return function (token, uuid) {
if (correctUuid != uuid) { if (correctUuid != uuid) {
return; return;
} }
console.log("establishing connection to", uuid); console.log("establishing connection to", uuid);
VideoChat.localICECandidates[uuid] = []; // initialise uuid with empty array VideoChat.localICECandidates[uuid] = []; // initialise uuid with empty array
VideoChat.connected.set(uuid, false); VideoChat.connected.set(uuid, false);
// Set up a new RTCPeerConnection using the token's iceServers. // Set up a new RTCPeerConnection using the token's iceServers.
VideoChat.peerConnections.set(uuid, new RTCPeerConnection({ VideoChat.peerConnections.set(
iceServers: token.iceServers, uuid,
})) new RTCPeerConnection({
iceServers: token.iceServers,
})
);
// Add the local video stream to the peerConnection. // Add the local video stream to the peerConnection.
VideoChat.localStream.getTracks().forEach(function (track) { VideoChat.localStream.getTracks().forEach(function (track) {
VideoChat.peerConnections.get(uuid).addTrack(track, VideoChat.localStream); VideoChat.peerConnections
.get(uuid)
.addTrack(track, VideoChat.localStream);
}); });
// Add general purpose data channel to peer connection, // Add general purpose data channel to peer connection,
// used for text chats, captions, and toggling sending captions // used for text chats, captions, and toggling sending captions
dataChannel.set(uuid, VideoChat.peerConnections.get(uuid).createDataChannel("chat", { dataChannel.set(
negotiated: true, uuid,
// both peers must have same id VideoChat.peerConnections.get(uuid).createDataChannel("chat", {
id: 0, negotiated: true,
})); // both peers must have same id
id: 0,
})
);
// Called when dataChannel is successfully opened // Called when dataChannel is successfully opened
dataChannel.get(uuid).onopen = function (event) { dataChannel.get(uuid).onopen = function (event) {
logIt("dataChannel opened"); logIt("dataChannel opened");
@ -185,12 +199,17 @@ var VideoChat = {
// Set up callbacks for the connection generating iceCandidates or // Set up callbacks for the connection generating iceCandidates or
// receiving the remote media stream. // receiving the remote media stream.
VideoChat.peerConnections.get(uuid).onicecandidate = function(u) {VideoChat.onIceCandidate(u, uuid)}; VideoChat.peerConnections.get(uuid).onicecandidate = function (u) {
VideoChat.peerConnections.get(uuid).onaddstream = function(u) {VideoChat.onAddStream(u, uuid)}; VideoChat.onIceCandidate(u, uuid);
};
VideoChat.peerConnections.get(uuid).onaddstream = function (u) {
VideoChat.onAddStream(u, uuid);
};
// Called when there is a change in connection state // Called when there is a change in connection state
VideoChat.peerConnections.get(uuid).oniceconnectionstatechange = function (event) { VideoChat.peerConnections.get(
uuid
).oniceconnectionstatechange = function (event) {
switch (VideoChat.peerConnections.get(uuid).iceConnectionState) { switch (VideoChat.peerConnections.get(uuid).iceConnectionState) {
case "connected": case "connected":
logIt("connected"); logIt("connected");
@ -213,7 +232,7 @@ var VideoChat = {
} }
}; };
callback(uuid); callback(uuid);
} };
}, },
// When the peerConnection generates an ice candidate, send it over the socket to the peer. // When the peerConnection generates an ice candidate, send it over the socket to the peer.
@ -237,7 +256,6 @@ var VideoChat = {
// The peer may not have created the RTCPeerConnection yet, so we are waiting for the 'answer' // The peer may not have created the RTCPeerConnection yet, so we are waiting for the 'answer'
// to arrive. This will signal that the peer is ready to receive signaling. // to arrive. This will signal that the peer is ready to receive signaling.
VideoChat.localICECandidates[uuid].push(event.candidate); VideoChat.localICECandidates[uuid].push(event.candidate);
} }
} }
}, },
@ -256,7 +274,12 @@ var VideoChat = {
// Create an offer that contains the media capabilities of the browser. // Create an offer that contains the media capabilities of the browser.
createOffer: function (uuid) { createOffer: function (uuid) {
console.log(">>> Creating offer to UUID: ", uuid, ". my UUID is", VideoChat.socket.id); console.log(
">>> Creating offer to UUID: ",
uuid,
". my UUID is",
VideoChat.socket.id
);
VideoChat.peerConnections.get(uuid).createOffer( VideoChat.peerConnections.get(uuid).createOffer(
function (offer) { function (offer) {
// If the offer is created successfully, set it as the local description // If the offer is created successfully, set it as the local description
@ -280,12 +303,22 @@ var VideoChat = {
createAnswer: function (offer, uuid) { createAnswer: function (offer, uuid) {
logIt("createAnswer"); logIt("createAnswer");
rtcOffer = new RTCSessionDescription(JSON.parse(offer)); rtcOffer = new RTCSessionDescription(JSON.parse(offer));
console.log("createAnswer: setting remote description of " + uuid + " on " + VideoChat.socket.id); console.log(
"createAnswer: setting remote description of " +
uuid +
" on " +
VideoChat.socket.id
);
VideoChat.peerConnections.get(uuid).setRemoteDescription(rtcOffer); VideoChat.peerConnections.get(uuid).setRemoteDescription(rtcOffer);
VideoChat.peerConnections.get(uuid).createAnswer( VideoChat.peerConnections.get(uuid).createAnswer(
function (answer) { function (answer) {
VideoChat.peerConnections.get(uuid).setLocalDescription(answer); VideoChat.peerConnections.get(uuid).setLocalDescription(answer);
console.log(">>> Creating answer to UUID: ", uuid, ". my UUID is", VideoChat.socket.id); console.log(
">>> Creating answer to UUID: ",
uuid,
". my UUID is",
VideoChat.socket.id
);
VideoChat.socket.emit("answer", JSON.stringify(answer), roomHash, uuid); VideoChat.socket.emit("answer", JSON.stringify(answer), roomHash, uuid);
}, },
function (err) { function (err) {
@ -300,32 +333,54 @@ var VideoChat = {
onOffer: function (offer, uuid) { onOffer: function (offer, uuid) {
logIt("onOffer <<< Received offer"); logIt("onOffer <<< Received offer");
// VideoChat.socket.on("token", VideoChat.establishConnection(uuid, function(a) {VideoChat.createOffer(a);})); // VideoChat.socket.on("token", VideoChat.establishConnection(uuid, function(a) {VideoChat.createOffer(a);}));
VideoChat.socket.on("token", VideoChat.establishConnection(uuid, function(a) {VideoChat.createAnswer(offer, a);})); VideoChat.socket.on(
"token",
VideoChat.establishConnection(uuid, function (a) {
VideoChat.createAnswer(offer, a);
})
);
VideoChat.socket.emit("token", roomHash, uuid); VideoChat.socket.emit("token", roomHash, uuid);
}, },
// When an answer is received, add it to the peerConnection as the remote description. // When an answer is received, add it to the peerConnection as the remote description.
onAnswer: function (answer, uuid) { onAnswer: function (answer, uuid) {
console.log("onAnswer <<< Received answer", uuid, ". my UUID is", VideoChat.socket.id); console.log(
"onAnswer <<< Received answer",
uuid,
". my UUID is",
VideoChat.socket.id
);
// if (!VideoChat.answerCreatedUUIDs.includes(uuid)) { // if (!VideoChat.answerCreatedUUIDs.includes(uuid)) {
VideoChat.answerCreatedUUIDs.push(uuid); VideoChat.answerCreatedUUIDs.push(uuid);
// logIt("onAnswer <<< Received answer" + ""); // logIt("onAnswer <<< Received answer" + "");
var rtcAnswer = new RTCSessionDescription(JSON.parse(answer)); var rtcAnswer = new RTCSessionDescription(JSON.parse(answer));
// Set remote description of RTCSession // Set remote description of RTCSession
console.log("onAnswer: setting remote description of " + uuid + " on " + VideoChat.socket.id); console.log(
VideoChat.peerConnections.get(uuid).setRemoteDescription(rtcAnswer); "onAnswer: setting remote description of " +
// The caller now knows that the callee is ready to accept new ICE candidates, so sending the buffer over uuid +
VideoChat.localICECandidates[uuid].forEach((candidate) => { " on " +
logIt(`>>> Sending local ICE candidate (${candidate.address})`); VideoChat.socket.id
// Send ice candidate over websocket );
VideoChat.socket.emit("candidate", JSON.stringify(candidate), roomHash, uuid); VideoChat.peerConnections.get(uuid).setRemoteDescription(rtcAnswer);
}); // The caller now knows that the callee is ready to accept new ICE candidates, so sending the buffer over
VideoChat.localICECandidates[uuid].forEach((candidate) => {
logIt(`>>> Sending local ICE candidate (${candidate.address})`);
// Send ice candidate over websocket
VideoChat.socket.emit(
"candidate",
JSON.stringify(candidate),
roomHash,
uuid
);
});
}, },
// Called when a stream is added to the peer connection // Called when a stream is added to the peer connection
onAddStream: function (event, uuid) { onAddStream: function (event, uuid) {
logIt("onAddStream <<< Received new stream from remote. Adding it..." + event); logIt(
"onAddStream <<< Received new stream from remote. Adding it..." + event
);
// Create new remote video source in wrapper // Create new remote video source in wrapper
// Create a <video> node // Create a <video> node
var node = document.createElement("video"); var node = document.createElement("video");
@ -412,7 +467,8 @@ function rePositionCaptions() {
// Get remote video position // Get remote video position
var bounds = remoteVideosWrapper.position(); var bounds = remoteVideosWrapper.position();
bounds.top -= 10; bounds.top -= 10;
bounds.top = bounds.top + remoteVideosWrapper.height() - 1 * captionText.height(); bounds.top =
bounds.top + remoteVideosWrapper.height() - 1 * captionText.height();
// Reposition captions // Reposition captions
captionText.css(bounds); captionText.css(bounds);
} }
@ -428,7 +484,7 @@ function isConnected() {
var connected = false; var connected = false;
// No way to 'break' forEach -> we go through all anyway // No way to 'break' forEach -> we go through all anyway
VideoChat.connected.forEach(function(value, key, map) { VideoChat.connected.forEach(function (value, key, map) {
if (value) { if (value) {
connected = true; connected = true;
} }
@ -439,7 +495,7 @@ function isConnected() {
function sendToAllDataChannels(message) { function sendToAllDataChannels(message) {
// key is UUID, value is dataChannel object // key is UUID, value is dataChannel object
dataChannel.forEach(function(value, key, map) { dataChannel.forEach(function (value, key, map) {
value.send(message); value.send(message);
}); });
} }
@ -494,12 +550,12 @@ function muteMicrophone() {
VideoChat.audioEnabled = !VideoChat.audioEnabled; VideoChat.audioEnabled = !VideoChat.audioEnabled;
var audioTrack = null; var audioTrack = null;
VideoChat.peerConnections.forEach(function(value, key, map) { VideoChat.peerConnections.forEach(function (value, key, map) {
value.getSenders().find(function (s) { value.getSenders().find(function (s) {
if (s.track.kind === "audio") { if (s.track.kind === "audio") {
audioTrack = s.track; audioTrack = s.track;
} }
}) });
audioTrack.enabled = VideoChat.audioEnabled; audioTrack.enabled = VideoChat.audioEnabled;
}); });
@ -524,14 +580,14 @@ function pauseVideo() {
VideoChat.videoEnabled = !VideoChat.videoEnabled; VideoChat.videoEnabled = !VideoChat.videoEnabled;
// Communicate pause to all the peers' video tracks // Communicate pause to all the peers' video tracks
VideoChat.peerConnections.forEach(function(value, key, map) { VideoChat.peerConnections.forEach(function (value, key, map) {
console.log("pausing video for ", key); console.log("pausing video for ", key);
value.getSenders().find(function (s) { value.getSenders().find(function (s) {
if (s.track.kind === "video") { if (s.track.kind === "video") {
console.log("found video track") console.log("found video track");
videoTrack = s.track; videoTrack = s.track;
} }
}) });
videoTrack.enabled = VideoChat.videoEnabled; videoTrack.enabled = VideoChat.videoEnabled;
}); });
@ -632,12 +688,15 @@ function switchStreamHelper(stream) {
}; };
// Swap video for every peer connection // Swap video for every peer connection
VideoChat.connected.forEach(function(value, key, map) { VideoChat.connected.forEach(function (value, key, map) {
// Just to be safe, check if connected before swapping video channel // Just to be safe, check if connected before swapping video channel
if (VideoChat.connected.get(key)) { if (VideoChat.connected.get(key)) {
const sender = VideoChat.peerConnections.get(key).getSenders().find (function(s) { const sender = VideoChat.peerConnections
return s.track.kind === videoTrack.kind; .get(key)
}) .getSenders()
.find(function (s) {
return s.track.kind === videoTrack.kind;
});
sender.replaceTrack(videoTrack); sender.replaceTrack(videoTrack);
} }
}); });
@ -727,7 +786,7 @@ function startSpeech() {
sendToAllDataChannels( sendToAllDataChannels(
"cap:" + "cap:" +
interimTranscript.substring(interimTranscript.length - charsToKeep) interimTranscript.substring(interimTranscript.length - charsToKeep)
); );
} }
} }
}; };

View File

@ -8,11 +8,14 @@ var twillioAccountSID =
var twilio = require("twilio")(twillioAccountSID, twillioAuthToken); var twilio = require("twilio")(twillioAccountSID, twillioAuthToken);
var express = require("express"); var express = require("express");
var app = express(); var app = express();
const fs = require('fs'); const fs = require("fs");
var http = require("https").createServer({ var http = require("https").createServer(
key: fs.readFileSync('/Users/khushjammu/certs/privkey.pem'), {
cert: fs.readFileSync('/Users/khushjammu/certs/cert.pem') key: fs.readFileSync("/Users/khushjammu/certs/privkey.pem"),
}, app); cert: fs.readFileSync("/Users/khushjammu/certs/cert.pem"),
},
app
);
// var http = require("http").createServer(app); // var http = require("http").createServer(app);
var io = require("socket.io")(http); var io = require("socket.io")(http);
var path = require("path"); var path = require("path");
@ -94,9 +97,9 @@ io.on("connection", function (socket) {
}); });
} else if (numClients < 4) { } else if (numClients < 4) {
socket.join(room); socket.join(room);
logIt("Connected clients", room) logIt("Connected clients", room);
for (var clientId in clients.sockets) { for (var clientId in clients.sockets) {
logIt('ID: ' + clientId, room); logIt("ID: " + clientId, room);
} }
// When the client is not the first to join the room, all clients are ready. // When the client is not the first to join the room, all clients are ready.
@ -106,7 +109,10 @@ io.on("connection", function (socket) {
socket.emit("ready", room).to(room); socket.emit("ready", room).to(room);
socket.broadcast.to(room).emit("ready", room); socket.broadcast.to(room).emit("ready", room);
} else { } else {
logIt("room already full with " + numClients + " people in the room.", room); logIt(
"room already full with " + numClients + " people in the room.",
room
);
socket.emit("full", room); socket.emit("full", room);
} }
}); });
@ -133,13 +139,19 @@ io.on("connection", function (socket) {
// Relay offers // Relay offers
socket.on("offer", function (offer, room, uuid) { socket.on("offer", function (offer, room, uuid) {
logIt("Received offer from " + socket.id + " and emitting to " + uuid, room); logIt(
"Received offer from " + socket.id + " and emitting to " + uuid,
room
);
io.to(uuid).emit("offer", offer, socket.id); io.to(uuid).emit("offer", offer, socket.id);
}); });
// Relay answers // Relay answers
socket.on("answer", function (answer, room, uuid) { socket.on("answer", function (answer, room, uuid) {
logIt("Received answer from " + socket.id + " and emitting to " + uuid, room); logIt(
"Received answer from " + socket.id + " and emitting to " + uuid,
room
);
io.to(uuid).emit("answer", answer, socket.id); io.to(uuid).emit("answer", answer, socket.id);
}); });
}); });