Changed spacing in html and JS files.

Changed spacing based to tab based
This commit is contained in:
ShakedAp 2023-06-26 20:23:35 +03:00
parent 8227bb1861
commit 3fd791dce7
4 changed files with 206 additions and 204 deletions

View File

@ -20,93 +20,88 @@ let correction = 0
// Connection opened // Connection opened
socket.addEventListener('open', function (event) { socket.addEventListener('open', function (event) {
console.log('Connected to WS Server'); console.log('Connected to WS Server');
}); });
// Got message from the server // Got message from the server
socket.addEventListener("message", (event) => { socket.addEventListener("message", (event) => {
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);
under_estimates.push(under_estimate_latest); under_estimates.push(under_estimate_latest);
under_estimate = median(under_estimates); under_estimate = median(under_estimates);
correction = (under_estimate + over_estimate)/2; correction = (under_estimate + over_estimate) / 2;
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');
} }
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); over_estimate = median(over_estimates);
over_estimate = median(over_estimates); correction = (under_estimate + over_estimate) / 2;
correction = (under_estimate + over_estimate)/2;
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');
} }
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));
// Whenever the client connects or reconnects // Whenever the client connects or reconnects
if (client_uid == null){ if (client_uid == null) {
client_uid = state.client_uid; client_uid = state.client_uid;
} }
// 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 }
} }
} }
}
}); });
// 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
}); });
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')
video_playing = false; video_playing = false;
else if (event.type === 'play') else if (event.type === 'play')
video_playing = true; video_playing = true;
} }
last_updated = get_global_time(correction); last_updated = get_global_time(correction);
state_image = { state_image = {
video_timestamp: vid.currentTime, video_timestamp: vid.currentTime,
last_updated: last_updated, last_updated: last_updated,
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
@ -130,17 +125,21 @@ function get_global_time(delta = 0) {
} }
async function get_settings() { async function get_settings() {
let s = null; let s = null;
await fetch('settings.json') await fetch('settings.json')
.then((response)=>response.json()) .then((response) => response.json())
.then((responseJson)=>{s = responseJson}); .then((responseJson) => {
return s; s = responseJson
});
return s;
} }
function median(values) { function median(values) {
if(values.length === 0) { return 0; } if (values.length === 0) {
return 0;
}
values.sort((x,y) => (x-y)); values.sort((x, y) => (x - y));
let half = Math.floor(values.length / 2); let half = Math.floor(values.length / 2);
if (values.length % 2) { if (values.length % 2) {
return values[half]; return values[half];
@ -149,21 +148,22 @@ function median(values) {
} }
function timeout(ms) { function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms)); return new Promise(resolve => setTimeout(resolve, ms));
} }
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");
} }
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 // time requests are made every second
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);
do_time_sync_one_cycle_backward(); do_time_sync_one_cycle_backward();
await timeout(500); await timeout(500);

View File

@ -6,140 +6,142 @@ const WebSocket = require('ws');
const app = express(); const app = express();
const server = require('http').createServer(app); const server = require('http').createServer(app);
const wss = new WebSocket.Server({ server:server }); const wss = new WebSocket.Server({
server: server
});
const settings = JSON.parse(fs.readFileSync("settings.json")); const settings = JSON.parse(fs.readFileSync("settings.json"));
const THRESH_IGNORANCE = 250; const THRESH_IGNORANCE = 250;
let users_amount = 0; let users_amount = 0;
let unique_id = 0; let unique_id = 0;
let state = { let state = {
video_timestamp: 0, video_timestamp: 0,
last_updated: get_time(), last_updated: get_time(),
playing: false, playing: false,
global_timestamp: 0, global_timestamp: 0,
client_uid: null client_uid: null
}; };
wss.on('connection', function connection(ws) { wss.on('connection', function connection(ws) {
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)}`);
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();
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()}`); }
} if (data.startsWith("time_sync_request_forward")) {
if(data.startsWith("time_sync_request_forward")) let client_time = Number(data.slice("time_sync_request_forward".length + 1));
{ ws.send(`time_sync_response_forward ${get_time() - client_time}`);
let client_time = Number(data.slice("time_sync_request_forward".length + 1)); }
ws.send(`time_sync_response_forward ${get_time() - client_time}`); if (data.startsWith("state_update_from_client")) {
} let new_state = JSON.parse(data.slice("state_update_from_client".length + 1));
if(data.startsWith("state_update_from_client")) let too_soon = (get_time() - state.last_updated) < THRESH_IGNORANCE;
{ let other_ip = (new_state.client_uid != state.client_uid);
let new_state = JSON.parse(data.slice("state_update_from_client".length + 1)); let stale = (new_state.last_updated < state.last_updated)
let too_soon = (get_time() - state.last_updated) < THRESH_IGNORANCE;
let other_ip = (new_state.client_uid != state.client_uid); if (!stale && !(too_soon && other_ip)) {
let stale = (new_state.last_updated < state.last_updated) state = new_state;
if (!stale && !(too_soon && other_ip)) wss.clients.forEach(function each(client) {
{ if (client !== ws && client.readyState === WebSocket.OPEN) {
state = new_state; client.send(`state_update_from_server ${JSON.stringify(state)}`);
}
wss.clients.forEach(function each(client) { });
if (client !== ws && client.readyState === WebSocket.OPEN) { }
client.send(`state_update_from_server ${JSON.stringify(state)}`); }
} });
});
} ws.on('close', function close() {
} users_amount -= 1;
}); console.log('Client diconnected. Amount of users: ', users_amount);
});
ws.on('close', function close() {
users_amount -= 1;
console.log('Client diconnected. Amount of users: ', users_amount);
});
}); });
app.use('/', express.static(__dirname)); app.use('/', express.static(__dirname));
app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use(session({ app.use(session({
secret: 'secret key', secret: 'secret key',
resave: false, resave: false,
saveUninitialized: false, saveUninitialized: false,
logged: false logged: false
})); }));
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");
else else
res.sendFile(__dirname + "/login.html"); res.sendFile(__dirname + "/login.html");
}); });
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) if (data.password == settings.password)
req.session.logged = true; req.session.logged = true;
else else
req.session.logged = false; req.session.logged = false;
res.redirect("/"); res.redirect("/");
}); });
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;
if (!range) { if (!range) {
res.status(400).send("Requires Range header"); res.status(400).send("Requires Range header");
} }
// get video stats (about 61MB) // get video stats (about 61MB)
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}`,
"Accept-Ranges": "bytes", "Accept-Ranges": "bytes",
"Content-Length": contentLength, "Content-Length": contentLength,
"Content-Type": "video/mp4", "Content-Type": "video/mp4",
}; };
// HTTP Status 206 for Partial Content // HTTP Status 206 for Partial Content
res.writeHead(206, headers); res.writeHead(206, headers);
// create video read stream for this particular chunk // create video read stream for this particular chunk
const videoStream = fs.createReadStream(videoPath, { start, end }); const videoStream = fs.createReadStream(videoPath, {
start,
// Stream the video chunk to the client end
videoStream.pipe(res); });
// Stream the video chunk to the client
videoStream.pipe(res);
}); });
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 get_time(){ function get_time() {
let d = new Date(); let d = new Date();
return d.getTime(); return d.getTime();
} }

View File

@ -1,21 +1,21 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="login.css"> <link rel="stylesheet" href="login.css">
<title>Login Page</title> <title>Login Page</title>
</head> </head>
<body> <body>
<div class="login-page"> <div class="login-page">
<h1> Login To Watch-Together Server</h1> <h1> Login To Watch-Together Server</h1>
<div class="form"> <div class="form">
<form action="/login" method="post" class="login-form"> <form action="/login" method="post" class="login-form">
<input type="text" placeholder="your username" name="username"/> <input type="text" placeholder="your username" name="username"/>
<input type="password" placeholder="server password" name="password"/> <input type="password" placeholder="server password" name="password"/>
<button>login</button> <button>login</button>
</form> </form>
</div> </div>
</div> </div>
</body> </body>
</html> </html>

View File

@ -1,22 +1,22 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="main.css"> <link rel="stylesheet" type="text/css" href="main.css">
<script defer type="text/javascript" src="client.js"></script> <script defer type="text/javascript" src="client.js"></script>
<title>Client</title> <title>Client</title>
</head> </head>
<body> <body>
<div class="container"> <div class="container">
<header> <header>
<h1>Watch-Together</h1> <h1>Watch-Together</h1>
</header> </header>
<div class="video-wrapper"> <div class="video-wrapper">
<video id="videoPlayer" controls disablePictureInPicture controlsList="nodownload noplaybackrate" muted> <video id="videoPlayer" controls disablePictureInPicture controlsList="nodownload noplaybackrate" muted>
<source src="/video" type="video/mp4" /> <source src="/video" type="video/mp4" />
</video> </video>
</div> </div>
</div> </div>
</body> </body>
</html> </html>