Added comments to src/client.js src/index.js

Added more comments.
Changed '/login' post to check if the data isn't null
This commit is contained in:
ShakedAp
2023-06-26 22:49:40 +03:00
parent 3fd791dce7
commit 555f5e632d
2 changed files with 75 additions and 31 deletions

View File

@@ -1,21 +1,22 @@
const vid = document.querySelector('video') const vid = document.querySelector('video');
const socket = new WebSocket(`ws://${window.location.hostname}:${window.location.port}`); const socket = new WebSocket(`ws://${window.location.hostname}:${window.location.port}`);
// if the new tms is within this margin of the current tms, then the change is ignored for smoother viewing // if the new tms is within this margin of the current tms, then the change is ignored for smoother viewing
const PLAYING_THRESH = 1 const PLAYING_THRESH = 1;
const PAUSED_THRESH = 0.01 const PAUSED_THRESH = 0.01;
// local state // local state
let video_playing = false let video_playing = false;
let last_updated = 0 let last_updated = 0;
let client_uid = null let client_uid = null;
// clocks sync variables // clocks sync variables
const num_time_sync_cycles = 10 const num_time_sync_cycles = 10;
let over_estimates = new Array() let over_estimates = new Array();
let under_estimates = new Array() let under_estimates = new Array();
let over_estimate = 0 let over_estimate = 0;
let under_estimate = 0 let under_estimate = 0;
let correction = 0 let correction = 0;
// Connection opened // Connection opened
@@ -26,6 +27,7 @@ socket.addEventListener('open', function (event) {
// Got message from the server // Got message from the server
socket.addEventListener("message", (event) => { socket.addEventListener("message", (event) => {
// Time syncing backward server-response
if (event.data.startsWith("time_sync_response_backward")) { if (event.data.startsWith("time_sync_response_backward")) {
let time_at_server = Number(event.data.slice("time_sync_response_backward".length + 1)); let time_at_server = Number(event.data.slice("time_sync_response_backward".length + 1));
let under_estimate_latest = time_at_server - get_global_time(0); let under_estimate_latest = time_at_server - get_global_time(0);
@@ -37,6 +39,8 @@ socket.addEventListener("message", (event) => {
console.log(`%c Updated val for under_estimate is ${under_estimate}`, "color:green"); console.log(`%c Updated val for under_estimate is ${under_estimate}`, "color:green");
console.log(`%c New correction time is ${correction} miliseconds`, 'color:red; font-size:12px'); console.log(`%c New correction time is ${correction} miliseconds`, 'color:red; font-size:12px');
} }
// Time syncing forward server-response
if (event.data.startsWith("time_sync_response_forward")) { if (event.data.startsWith("time_sync_response_forward")) {
let calculated_diff = Number(event.data.slice("time_sync_response_forward".length + 1)); let calculated_diff = Number(event.data.slice("time_sync_response_forward".length + 1));
over_estimates.push(calculated_diff); over_estimates.push(calculated_diff);
@@ -46,6 +50,8 @@ socket.addEventListener("message", (event) => {
console.log(`%c Updated val for over_estimate is ${over_estimate}`, "color:green"); console.log(`%c Updated val for over_estimate is ${over_estimate}`, "color:green");
console.log(`%c New correction time is ${correction} miliseconds`, 'color:red; font-size:12px'); console.log(`%c New correction time is ${correction} miliseconds`, 'color:red; font-size:12px');
} }
// Video state update from server
if (event.data.startsWith("state_update_from_server")) { if (event.data.startsWith("state_update_from_server")) {
let state = JSON.parse(event.data.slice("state_update_from_server".length + 1)); let state = JSON.parse(event.data.slice("state_update_from_server".length + 1));
@@ -55,21 +61,21 @@ socket.addEventListener("message", (event) => {
} }
// calculating the new timestamp for both cases - when the video is playing and when it is paused // calculating the new timestamp for both cases - when the video is playing and when it is paused
let proposed_time = (state.playing) ? ((get_global_time(correction) - state.global_timestamp) / 1000 + state.video_timestamp) : (state.video_timestamp) let proposed_time = (state.playing) ? ((get_global_time(correction) - state.global_timestamp) / 1000 + state.video_timestamp) : (state.video_timestamp);
let gap = Math.abs(proposed_time - vid.currentTime) let gap = Math.abs(proposed_time - vid.currentTime);
console.log(`%cGap was ${proposed_time - vid.currentTime}`, 'font-size:12px; color:purple') console.log(`%cGap was ${proposed_time - vid.currentTime}`, 'font-size:12px; color:purple');
if (state.playing) { if (state.playing) {
// tolerance while the video is playing // tolerance while the video is playing
if (gap > PLAYING_THRESH) { if (gap > PLAYING_THRESH) {
vid.currentTime = proposed_time vid.currentTime = proposed_time;
} }
vid.play() vid.play()
} else { } else {
vid.pause() vid.pause()
// condition to prevent an unnecessary seek // condition to prevent an unnecessary seek
if (gap > PAUSED_THRESH) { if (gap > PAUSED_THRESH) {
vid.currentTime = proposed_time vid.currentTime = proposed_time;
} }
} }
} }
@@ -79,10 +85,12 @@ socket.addEventListener("message", (event) => {
// Connection closed // Connection closed
socket.addEventListener('close', function (event) { socket.addEventListener('close', function (event) {
console.log('Disconnected from the WS Server'); console.log('Disconnected from the WS Server');
client_uid = null client_uid = null;
}); });
// Send video state update to the server
// event: the video event (ex: seeking, pause play)
function state_change_handler(event) { function state_change_handler(event) {
if (event !== null && event !== undefined) { if (event !== null && event !== undefined) {
if (event.type === 'pause') if (event.type === 'pause')
@@ -99,9 +107,9 @@ function state_change_handler(event) {
playing: video_playing, playing: video_playing,
global_timestamp: get_global_time(correction), global_timestamp: get_global_time(correction),
client_uid: client_uid client_uid: client_uid
} };
socket.send(`state_update_from_client ${JSON.stringify(state_image)}`) socket.send(`state_update_from_client ${JSON.stringify(state_image)}`);
} }
// assigning event handlers // assigning event handlers
@@ -118,12 +126,16 @@ vid.onended = () => {
} }
// Helper Functions //// Helper Functions ////
// Get
function get_global_time(delta = 0) { function get_global_time(delta = 0) {
let d = new Date(); let d = new Date();
return d.getTime() + delta; return d.getTime() + delta;
} }
// Get the saved settings from settings.json
async function get_settings() { async function get_settings() {
let s = null; let s = null;
await fetch('settings.json') await fetch('settings.json')
@@ -134,6 +146,8 @@ async function get_settings() {
return s; return s;
} }
// Find the median of an array
function median(values) { function median(values) {
if (values.length === 0) { if (values.length === 0) {
return 0; return 0;
@@ -147,21 +161,25 @@ function median(values) {
return (values[half - 1] + values[half]) / 2.0; return (values[half - 1] + values[half]) / 2.0;
} }
// Wait certain given amount of miliseconds
function timeout(ms) { function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise(resolve => setTimeout(resolve, ms));
} }
// Send the backward update request to the server
function do_time_sync_one_cycle_backward() { function do_time_sync_one_cycle_backward() {
socket.send("time_sync_request_backward"); socket.send("time_sync_request_backward");
} }
// Send the forward update request to the server
function do_time_sync_one_cycle_forward() { function do_time_sync_one_cycle_forward() {
socket.send(`time_sync_request_forward ${get_global_time()}`); socket.send(`time_sync_request_forward ${get_global_time()}`);
} }
// time requests are made every second // Sync the client and the server, using backward and forward syncing
async function do_time_sync() { async function do_time_sync() {
for (let i = 0; i < num_time_sync_cycles; i++) { for (let i = 0; i < num_time_sync_cycles; i++) {
await timeout(500); await timeout(500);

View File

@@ -6,11 +6,14 @@ const WebSocket = require('ws');
const app = express(); const app = express();
const server = require('http').createServer(app); const server = require('http').createServer(app);
// creating the server web socket
const wss = new WebSocket.Server({ const wss = new WebSocket.Server({
server: server server: server
}); });
// importing settings from settings.json
const settings = JSON.parse(fs.readFileSync("settings.json")); const settings = JSON.parse(fs.readFileSync("settings.json"));
// server variables and video state
const THRESH_IGNORANCE = 250; const THRESH_IGNORANCE = 250;
let users_amount = 0; let users_amount = 0;
let unique_id = 0; let unique_id = 0;
@@ -23,17 +26,20 @@ let state = {
}; };
wss.on('connection', function connection(ws) { wss.on('connection', function connection(ws) {
// on connection from client send update
users_amount += 1; users_amount += 1;
console.log('A new client Connected. Amount of users: ', users_amount); console.log('A new client Connected. Amount of users: ', users_amount);
state.client_uid = unique_id; state.client_uid = unique_id;
unique_id += 1; unique_id += 1;
ws.send(`state_update_from_server ${JSON.stringify(state)}`); ws.send(`state_update_from_server ${JSON.stringify(state)}`);
// log web socket error
ws.on('error', console.error); ws.on('error', console.error);
ws.on('message', function message(data) { ws.on('message', function message(data) {
data = data.toString(); data = data.toString();
// syncing requests from the client
if (data.startsWith("time_sync_request_backward")) { if (data.startsWith("time_sync_request_backward")) {
ws.send(`time_sync_response_backward ${get_time()}`); ws.send(`time_sync_response_backward ${get_time()}`);
} }
@@ -41,15 +47,18 @@ wss.on('connection', function connection(ws) {
let client_time = Number(data.slice("time_sync_request_forward".length + 1)); let client_time = Number(data.slice("time_sync_request_forward".length + 1));
ws.send(`time_sync_response_forward ${get_time() - client_time}`); ws.send(`time_sync_response_forward ${get_time() - client_time}`);
} }
// video state update from client. Update state and broadcast to all users
if (data.startsWith("state_update_from_client")) { if (data.startsWith("state_update_from_client")) {
let new_state = JSON.parse(data.slice("state_update_from_client".length + 1)); let new_state = JSON.parse(data.slice("state_update_from_client".length + 1));
let too_soon = (get_time() - state.last_updated) < THRESH_IGNORANCE; let too_soon = (get_time() - state.last_updated) < THRESH_IGNORANCE;
let other_ip = (new_state.client_uid != state.client_uid); let other_ip = (new_state.client_uid != state.client_uid);
let stale = (new_state.last_updated < state.last_updated) let stale = (new_state.last_updated < state.last_updated)
// checking if we should update, in order not to update too much
if (!stale && !(too_soon && other_ip)) { if (!stale && !(too_soon && other_ip)) {
state = new_state; state = new_state;
// broadcasting to all other clients the new state
wss.clients.forEach(function each(client) { wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) { if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(`state_update_from_server ${JSON.stringify(state)}`); client.send(`state_update_from_server ${JSON.stringify(state)}`);
@@ -59,6 +68,7 @@ wss.on('connection', function connection(ws) {
} }
}); });
// client disconnect
ws.on('close', function close() { ws.on('close', function close() {
users_amount -= 1; users_amount -= 1;
console.log('Client diconnected. Amount of users: ', users_amount); console.log('Client diconnected. Amount of users: ', users_amount);
@@ -66,6 +76,10 @@ wss.on('connection', function connection(ws) {
}); });
//// Web server ////
// app settings
app.use('/', express.static(__dirname)); app.use('/', express.static(__dirname));
app.use(bodyParser.urlencoded({ app.use(bodyParser.urlencoded({
extended: true extended: true
@@ -78,6 +92,8 @@ app.use(session({
logged: false logged: false
})); }));
// home page
app.get("/", function (req, res) { app.get("/", function (req, res) {
if (req.session.logged) if (req.session.logged)
res.sendFile(__dirname + "/main.html"); res.sendFile(__dirname + "/main.html");
@@ -85,19 +101,26 @@ app.get("/", function (req, res) {
res.sendFile(__dirname + "/login.html"); res.sendFile(__dirname + "/login.html");
}); });
// receive login info
app.post("/login", function (req, res) { app.post("/login", function (req, res) {
const data = req.body; const data = req.body;
if (!data) if (!data)
res.sendStatus(400); res.sendStatus(400);
if (data.password == settings.password)
req.session.logged = true;
else else
req.session.logged = false; {
if (data.password == settings.password)
req.session.logged = true;
else
req.session.logged = false;
res.redirect("/");
}
res.redirect("/");
}); });
// video streaming
app.get("/video", function (req, res) { app.get("/video", function (req, res) {
// Ensure there is a range given for the video // Ensure there is a range given for the video
const range = req.headers.range; const range = req.headers.range;
@@ -109,13 +132,13 @@ app.get("/video", function (req, res) {
const videoPath = settings.video_path; const videoPath = settings.video_path;
const videoSize = fs.statSync(videoPath).size; const videoSize = fs.statSync(videoPath).size;
// Parse Range // parse Range
// Example: "bytes=32324-" // Example: "bytes=32324-"
const CHUNK_SIZE = 10 ** 6; // 1MB const CHUNK_SIZE = 10 ** 6; // 1MB
const start = Number(range.replace(/\D/g, "")); const start = Number(range.replace(/\D/g, ""));
const end = Math.min(start + CHUNK_SIZE, videoSize - 1); const end = Math.min(start + CHUNK_SIZE, videoSize - 1);
// Create headers // create headers
const contentLength = end - start + 1; const contentLength = end - start + 1;
const headers = { const headers = {
"Content-Range": `bytes ${start}-${end}/${videoSize}`, "Content-Range": `bytes ${start}-${end}/${videoSize}`,
@@ -133,14 +156,17 @@ app.get("/video", function (req, res) {
end end
}); });
// Stream the video chunk to the client // stream the video chunk to the client
videoStream.pipe(res); videoStream.pipe(res);
}); });
// host server on given ip and port
server.listen(settings.server_port, settings.server_ip, server.listen(settings.server_port, settings.server_ip,
() => console.log(`Server started at ${settings.server_ip}:${settings.server_port}`)); () => console.log(`Server started at ${settings.server_ip}:${settings.server_port}`));
// function to get the current time
function get_time() { function get_time() {
let d = new Date(); let d = new Date();
return d.getTime(); return d.getTime();