Compare commits

...

22 Commits

Author SHA1 Message Date
Charlotte Som e6d09b14c5 Update cachebust version 2023-02-02 06:38:45 +00:00
Charlotte Som 4b61c44d6a Update editorconfig if using LF endings 2023-02-02 06:36:01 +00:00
easrng f3ee2ecc83 fuck it, converting the rest to unix line endings 2023-02-01 20:29:47 -05:00
easrng 1bd7071cec use plyr for video controls 2023-02-01 20:20:07 -05:00
easrng e43184ab49 fix the color input styles on chrome 2022-07-12 20:21:36 +00:00
Charlotte Som 61c456eceb Default captions to enabled 2022-04-29 23:50:35 +01:00
Charlotte Som 0fc8953a69 Textual feedback for personal colour 2022-04-29 23:41:33 +01:00
Charlotte Som 8e19d7b34d Don't allow controls by default 2022-04-29 23:28:11 +01:00
Charlotte Som 8717e0dff2 Bust cache 2022-04-29 23:25:31 +01:00
Charlotte Som bfdcf2afed Default personal colour to white 2022-04-29 23:24:37 +01:00
Charlotte Som 8531c83574 Sort unicode emoji before emojos, let enter fill an emoji 2022-04-29 23:22:23 +01:00
Charlotte Som 0d555adf21 Remove blobcat.png
It should be gitignored anyway
2022-04-29 23:08:10 +01:00
maia arson crimew b72a7d11d7 bust cache 2022-03-30 16:28:10 +02:00
maia arson crimew ee93fb84af turn the beep into a pling 2022-03-30 16:26:34 +02:00
maia arson crimew 40b20b2157 Improve global state handling 2022-03-30 15:02:08 +02:00
maia arson crimew 9a2ac1c432 make pings send browser notifications 2022-03-30 13:45:59 +02:00
maia arson crimew 2197d2b757 make the ping sound a lot more tolerable 2022-03-30 13:28:35 +02:00
maia arson crimew 3d4ea0773d Clicking the join chip will directly join the session without a reload
also adds a /join command (most likely still requires some further debugging)
2022-03-30 13:17:44 +02:00
easrng 2d544620ed add linkification and time and join chips 2022-03-09 18:38:22 -05:00
easrng 60672a04ef oh no aaaa 2022-03-08 15:35:12 -05:00
easrng c8ccb7afc4 fix broken things 2022-03-08 15:34:55 -05:00
easrng 2adc8b9d02 fix emoji name overflow (again) and sorting 2022-03-08 15:33:14 -05:00
23 changed files with 2331 additions and 2032 deletions

View File

@ -3,7 +3,7 @@ root = true
[*] [*]
indent_style = space indent_style = space
indent_size = 2 indent_size = 2
end_of_line = crlf end_of_line = lf
charset = utf-8 charset = utf-8
trim_trailing_whitespace = false trim_trailing_whitespace = false
insert_final_newline = true insert_final_newline = true

View File

@ -1,52 +1,52 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<title>watch party :D</title> <title>watch party :D</title>
<link rel="stylesheet" href="/styles.css?v=048af96" /> <link rel="stylesheet" href="/styles.css?v=4b61c4" />
</head> </head>
<body> <body>
<noscript> <noscript>
This site will <em>not</em> work without JavaScript, and there's not This site will <em>not</em> work without JavaScript, and there's not
really any way around that :( really any way around that :(
</noscript> </noscript>
<div id="create-controls"> <div id="create-controls">
<form id="create-session-form"> <form id="create-session-form">
<h2>Create a session</h2> <h2>Create a session</h2>
<label for="create-session-video">Video:</label> <label for="create-session-video">Video:</label>
<input <input
type="text" type="text"
id="create-session-video" id="create-session-video"
placeholder="https://video.example.com/example.mp4" placeholder="https://video.example.com/example.mp4"
required required
/> />
<!-- TODO: Ability to add multiple subtitles for different languages --> <!-- TODO: Ability to add multiple subtitles for different languages -->
<label for="create-session-subs">Subtitles:</label> <label for="create-session-subs">Subtitles:</label>
<input <input
type="text" type="text"
id="create-session-subs" id="create-session-subs"
placeholder="https://video.example.com/example.vtt" placeholder="https://video.example.com/example.vtt"
/> />
<label for="create-session-subs-name">Subtitle track name:</label> <label for="create-session-subs-name">Subtitle track name:</label>
<input <input
type="text" type="text"
id="create-session-subs-name" id="create-session-subs-name"
placeholder="English" placeholder="English"
/> />
<button>Create</button> <button>Create</button>
<p> <p>
Already have a session? Already have a session?
<a href="/">Join your session</a> instead. <a href="/">Join your session</a> instead.
</p> </p>
</form> </form>
</div> </div>
<script type="module" src="/create.mjs?v=048af96"></script> <script type="module" src="/create.mjs?v=4b61c4"></script>
</body> </body>
</html> </html>

View File

@ -1,11 +1,11 @@
import { setupCreateSessionForm } from "./lib/create-session.mjs?v=048af96"; import { setupCreateSessionForm } from "./lib/create-session.mjs?v=4b61c4";
const main = () => { const main = () => {
setupCreateSessionForm(); setupCreateSessionForm();
}; };
if (document.readyState === "complete") { if (document.readyState === "complete") {
main(); main();
} else { } else {
document.addEventListener("DOMContentLoaded", main); document.addEventListener("DOMContentLoaded", main);
} }

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

View File

@ -1,69 +1,85 @@
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<title>watch party :D</title> <title>watch party :D</title>
<link rel="stylesheet" href="/styles.css?v=048af96" /> <link rel="stylesheet" href="/lib/plyr-3.7.3.css" />
</head> <link rel="stylesheet" href="/styles.css?v=4b61c4" />
</head>
<body>
<noscript> <body>
This site will <em>not</em> work without JavaScript, and there's not <noscript>
really any way around that :( This site will <em>not</em> work without JavaScript, and there's not
</noscript> really any way around that :(
</noscript>
<div id="pre-join-controls">
<form id="join-session-form"> <div id="pre-join-controls">
<h2>Join a session</h2> <form id="join-session-form">
<h2>Join a session</h2>
<p id="post-create-message">
Your session has been created successfully. Copy the current url or <p id="post-create-message">
the Session ID below and share it with your friends. :) Your session has been created successfully. Copy the current url or
</p> the Session ID below and share it with your friends. :)
</p>
<label for="join-session-nickname">Nickname:</label>
<input <label for="join-session-nickname">Nickname:</label>
type="text" <input
id="join-session-nickname" type="text"
placeholder="Nickname" id="join-session-nickname"
maxlength="50" placeholder="Nickname"
required maxlength="50"
/> required
/>
<label for="join-session-colour">Colour:</label>
<input type="color" id="join-session-colour" value="#7ed0ff" required /> <label id="join-session-colour-label" for="join-session-colour">
Personal Colour:
<label for="join-session-id">Session ID:</label> </label>
<input <input type="color" id="join-session-colour" value="#ffffff" required />
type="text"
id="join-session-id" <label for="join-session-id">Session ID:</label>
placeholder="123e4567-e89b-12d3-a456-426614174000" <input
required type="text"
/> id="join-session-id"
<button id="join-session-button">Join</button> placeholder="123e4567-e89b-12d3-a456-426614174000"
required
<p> />
No session to join? <button id="join-session-button">Join</button>
<a href="/create.html">Create a session</a> instead.
</p> <p>
</form> No session to join?
</div> <a href="/create.html">Create a session</a> instead.
</p>
<div id="video-container"></div> </form>
<div id="chatbox-container"> </div>
<div id="viewer-list"></div>
<div id="chatbox"></div> <div id="video-container"></div>
<form id="chatbox-send"> <div id="chatbox-container">
<input <div id="viewer-list"></div>
type="text" <div id="chatbox"></div>
placeholder="Message... (/help for commands)" <form id="chatbox-send">
list="emoji-autocomplete" <input
/> type="text"
<div id="emoji-autocomplete"></div> placeholder="Message... (/help for commands)"
<!-- DO NOT ADD SPACING INSIDE THE TAG IT WILL BREAK THE CSS kthxbye --> list="emoji-autocomplete"
</form> />
</div> <div id="emoji-autocomplete"></div>
<!-- DO NOT ADD SPACING INSIDE THE TAG IT WILL BREAK THE CSS kthxbye -->
<script type="module" src="/main.mjs?v=048af96"></script> </form>
</body> </div>
</html>
<script type="module" src="/main.mjs?v=4b61c4"></script>
<script>
const updateColourLabel = () => {
const colour = document.querySelector("#join-session-colour").value;
document.querySelector(
"#join-session-colour-label"
).textContent = `Personal Colour: ${colour}`;
};
document
.querySelector("#join-session-colour")
.addEventListener("input", updateColourLabel);
updateColourLabel();
</script>
</body>
</html>

View File

@ -1,451 +1,453 @@
import { import {
setDebounce, setDebounce,
setVideoTime, setVideoTime,
setPlaying, setPlaying,
} from "./watch-session.mjs?v=048af96"; sync,
import { emojify, findEmojis } from "./emojis.mjs?v=048af96"; } from "./watch-session.mjs?v=4b61c4";
import { emojify, findEmojis } from "./emojis.mjs?v=4b61c4";
function setCaretPosition(elem, caretPos) { import { linkify } from "./links.mjs?v=4b61c4";
if (elem.createTextRange) { import { joinSession } from "./watch-session.mjs?v=4b61c4";
var range = elem.createTextRange(); import { pling } from "./pling.mjs?v=4b61c4";
range.move("character", caretPos); import { state } from "./state.mjs";
range.select();
} else { function setCaretPosition(elem, caretPos) {
if (elem.selectionStart) { if (elem.createTextRange) {
elem.focus(); var range = elem.createTextRange();
elem.setSelectionRange(caretPos, caretPos); range.move("character", caretPos);
} else elem.focus(); range.select();
} } else {
} if (elem.selectionStart) {
elem.focus();
const setupChatboxEvents = (socket) => { elem.setSelectionRange(caretPos, caretPos);
// clear events by just reconstructing the form } else elem.focus();
const oldChatForm = document.querySelector("#chatbox-send"); }
const chatForm = oldChatForm.cloneNode(true); }
const messageInput = chatForm.querySelector("input");
const emojiAutocomplete = chatForm.querySelector("#emoji-autocomplete"); const setupChatboxEvents = (socket) => {
oldChatForm.replaceWith(chatForm); // clear events by just reconstructing the form
const oldChatForm = document.querySelector("#chatbox-send");
let autocompleting = false, const chatForm = oldChatForm.cloneNode(true);
showListTimer; const messageInput = chatForm.querySelector("input");
const emojiAutocomplete = chatForm.querySelector("#emoji-autocomplete");
const replaceMessage = (message) => () => { oldChatForm.replaceWith(chatForm);
messageInput.value = message;
autocomplete(); let autocompleting = false,
}; showListTimer;
async function autocomplete(fromListTimeout) {
if (autocompleting) return; const replaceMessage = (message) => () => {
clearInterval(showListTimer); messageInput.value = message;
emojiAutocomplete.textContent = ""; autocomplete();
autocompleting = true; };
let text = messageInput.value.slice(0, messageInput.selectionStart); async function autocomplete(fromListTimeout) {
const match = text.match(/(:[^\s:]+)?:([^\s:]*)$/); if (autocompleting) return;
if (!match || match[1]) return (autocompleting = false); // We don't need to autocomplete. try {
const prefix = text.slice(0, match.index); clearInterval(showListTimer);
const search = text.slice(match.index + 1); emojiAutocomplete.textContent = "";
if (search.length < 1 && !fromListTimeout) { autocompleting = true;
autocompleting = false; let text = messageInput.value.slice(0, messageInput.selectionStart);
showListTimer = setTimeout(() => autocomplete(true), 500); const match = text.match(/(:[^\s:]+)?:([^\s:]{2,})$/);
return; if (!match || match[1]) return (autocompleting = false); // We don't need to autocomplete.
} const prefix = text.slice(0, match.index);
const suffix = messageInput.value.slice(messageInput.selectionStart); const search = text.slice(match.index + 1);
let selected; if (search.length < 1 && !fromListTimeout) {
const select = (button) => { autocompleting = false;
if (selected) selected.classList.remove("selected"); showListTimer = setTimeout(() => autocomplete(true), 500);
selected = button; return;
button.classList.add("selected"); }
}; const suffix = messageInput.value.slice(messageInput.selectionStart);
let results = await findEmojis(search); let selected;
let yieldAt = performance.now() + 13; const select = (button) => {
for (let i = 0; i < results.length; i += 100) { if (selected) selected.classList.remove("selected");
emojiAutocomplete.append.apply( selected = button;
emojiAutocomplete, button.classList.add("selected");
results.slice(i, i + 100).map(([name, replaceWith, ext], i) => { };
const button = Object.assign(document.createElement("button"), { let results = await findEmojis(search);
className: "emoji-option", let yieldAt = performance.now() + 13;
onmousedown: (e) => e.preventDefault(), for (let i = 0; i < results.length; i += 100) {
onclick: () => { emojiAutocomplete.append.apply(
messageInput.value = prefix + replaceWith + " " + suffix; emojiAutocomplete,
setCaretPosition( results.slice(i, i + 100).map(([name, replaceWith, ext], i) => {
messageInput, const button = Object.assign(document.createElement("button"), {
(prefix + " " + replaceWith).length className: "emoji-option",
); onmousedown: (e) => e.preventDefault(),
}, onclick: () => {
onmouseover: () => select(button), messageInput.value = prefix + replaceWith + " " + suffix;
onfocus: () => select(button), setCaretPosition(
type: "button", messageInput,
title: name, (prefix + " " + replaceWith).length
}); );
button.append( },
replaceWith[0] !== ":" onmouseover: () => select(button),
? Object.assign(document.createElement("span"), { onfocus: () => select(button),
textContent: replaceWith, type: "button",
className: "emoji", title: name,
}) });
: Object.assign(new Image(), { button.append(
loading: "lazy", replaceWith[0] !== ":"
src: `/emojis/${name}${ext}`, ? Object.assign(document.createElement("span"), {
className: "emoji", textContent: replaceWith,
}), className: "emoji",
Object.assign(document.createElement("span"), { })
textContent: name, : Object.assign(new Image(), {
className: "emoji-name", loading: "lazy",
}) src: `/emojis/${name}${ext}`,
); className: "emoji",
return button; }),
}) Object.assign(document.createElement("span"), {
); textContent: name,
if (i == 0 && emojiAutocomplete.children[0]) { className: "emoji-name",
emojiAutocomplete.children[0].scrollIntoView(); })
select(emojiAutocomplete.children[0]); );
} return button;
const now = performance.now(); })
if (now > yieldAt) { );
yieldAt = now + 13; if (i == 0 && emojiAutocomplete.children[0]) {
await new Promise((cb) => setTimeout(cb, 0)); emojiAutocomplete.children[0].scrollIntoView();
} select(emojiAutocomplete.children[0]);
} }
autocompleting = false; const now = performance.now();
} if (now > yieldAt) {
messageInput.addEventListener("input", () => autocomplete()); yieldAt = now + 13;
messageInput.addEventListener("selectionchange", () => autocomplete()); await new Promise((cb) => setTimeout(cb, 0));
messageInput.addEventListener("keydown", (event) => { }
if (event.key == "ArrowUp" || event.key == "ArrowDown") { }
let selected = document.querySelector(".emoji-option.selected"); autocompleting = false;
if (!selected) return; } catch (e) {
event.preventDefault(); autocompleting = false;
selected.classList.remove("selected"); }
selected = }
event.key == "ArrowDown" messageInput.addEventListener("input", () => autocomplete());
? selected.nextElementSibling || selected.parentElement.children[0] messageInput.addEventListener("selectionchange", () => autocomplete());
: selected.previousElementSibling || messageInput.addEventListener("keydown", (event) => {
selected.parentElement.children[ if (event.key == "ArrowUp" || event.key == "ArrowDown") {
selected.parentElement.children.length - 1 let selected = document.querySelector(".emoji-option.selected");
]; if (!selected) return;
selected.classList.add("selected"); event.preventDefault();
selected.scrollIntoView({ scrollMode: "if-needed", block: "nearest" }); selected.classList.remove("selected");
} selected =
if (event.key == "Tab") { event.key == "ArrowDown"
let selected = document.querySelector(".emoji-option.selected"); ? selected.nextElementSibling || selected.parentElement.children[0]
if (!selected) return; : selected.previousElementSibling ||
event.preventDefault(); selected.parentElement.children[
selected.onclick(); selected.parentElement.children.length - 1
} ];
}); selected.classList.add("selected");
selected.scrollIntoView({ scrollMode: "if-needed", block: "nearest" });
chatForm.addEventListener("submit", async (e) => { }
e.preventDefault(); if (event.key == "Tab" || event.key == "Enter") {
const content = messageInput.value; let selected = document.querySelector(".emoji-option.selected");
if (content.trim().length) { if (!selected) return;
messageInput.value = ""; event.preventDefault();
selected.onclick();
// handle commands }
if (content.startsWith("/")) { });
const command = content.toLowerCase().match(/^\/\S+/)[0];
const args = content.slice(command.length).trim(); chatForm.addEventListener("submit", async (e) => {
e.preventDefault();
let handled = false; const content = messageInput.value;
switch (command) { if (content.trim().length) {
case "/ping": messageInput.value = "";
socket.send(
JSON.stringify({ // handle commands
op: "Ping", if (content.startsWith("/")) {
data: args, const command = content.toLowerCase().match(/^\/\S+/)[0];
}) const args = content.slice(command.length).trim();
);
handled = true; let handled = false;
break; switch (command) {
case "/sync": case "/ping":
const sessionId = window.location.hash.slice(1); socket.send(
const { current_time_ms, is_playing } = await fetch( JSON.stringify({
`/sess/${sessionId}` op: "Ping",
).then((r) => r.json()); data: args,
})
setDebounce(); );
setPlaying(is_playing); handled = true;
setVideoTime(current_time_ms); break;
case "/sync":
const syncMessageContent = document.createElement("span"); await sync();
syncMessageContent.appendChild(
document.createTextNode("resynced you to ") const syncMessageContent = document.createElement("span");
); syncMessageContent.appendChild(
syncMessageContent.appendChild( document.createTextNode("resynced you to ")
document.createTextNode(formatTime(current_time_ms)) );
); syncMessageContent.appendChild(
printChatMessage("set-time", "/sync", "b57fdc", syncMessageContent); document.createTextNode(formatTime(current_time_ms))
handled = true; );
break; printChatMessage("set-time", "/sync", "b57fdc", syncMessageContent);
case "/shrug": handled = true;
socket.send( break;
JSON.stringify({ case "/shrug":
op: "ChatMessage", socket.send(
data: `${args} ¯\\_(ツ)_/¯`.trim(), JSON.stringify({
}) op: "ChatMessage",
); data: `${args} ¯\\_(ツ)_/¯`.trim(),
handled = true; })
break; );
case "/help": handled = true;
const helpMessageContent = document.createElement("span"); break;
helpMessageContent.innerHTML = case "/join":
"Available commands:<br>" + state().sessionId = args;
"&emsp;<code>/help</code> - display this help message<br>" + joinSession();
"&emsp;<code>/ping [message]</code> - ping all viewers<br>" + handled = true;
"&emsp;<code>/sync</code> - resyncs you with other viewers<br>" + break;
"&emsp;<code>/shrug</code> - appends ¯\\_(ツ)_/¯ to your message"; case "/help":
const helpMessageContent = document.createElement("span");
printChatMessage( helpMessageContent.innerHTML =
"command-message", "Available commands:<br>" +
"/help", "&emsp;<code>/help</code> - display this help message<br>" +
"b57fdc", "&emsp;<code>/ping [message]</code> - ping all viewers<br>" +
helpMessageContent "&emsp;<code>/sync</code> - resyncs you with other viewers<br>" +
); "&emsp;<code>/shrug</code> - appends ¯\\_(ツ)_/¯ to your message<br>" +
handled = true; "&emsp;<code>/join [session id]</code> - joins another session";
break;
default: printChatMessage(
break; "command-message",
} "/help",
"b57fdc",
if (handled) { helpMessageContent
return; );
} handled = true;
} break;
default:
// handle regular chat messages break;
socket.send( }
JSON.stringify({
op: "ChatMessage", if (handled) {
data: content, return;
}) }
); }
}
}); // handle regular chat messages
}; socket.send(
JSON.stringify({
/** op: "ChatMessage",
* @param {WebSocket} socket data: content,
*/ })
export const setupChat = async (socket) => { );
document.querySelector("#chatbox-container").style["display"] = "flex"; }
setupChatboxEvents(socket); });
};
window.addEventListener("keydown", (event) => {
try { /**
const isSelectionEmpty = window.getSelection().toString().length === 0; * @param {WebSocket} socket
if (event.code.match(/Key\w/) && isSelectionEmpty) messageInput.focus(); */
} catch (_err) {} export const setupChat = async (socket) => {
}); document.querySelector("#chatbox-container").style["display"] = "flex";
}; setupChatboxEvents(socket);
};
const addToChat = (node) => {
const chatbox = document.querySelector("#chatbox"); const addToChat = (node) => {
chatbox.appendChild(node); const chatbox = document.querySelector("#chatbox");
chatbox.scrollTop = chatbox.scrollHeight; chatbox.appendChild(node);
}; chatbox.scrollTop = chatbox.scrollHeight;
};
let lastTimeMs = null;
let lastPlaying = false; let lastTimeMs = null;
let lastPlaying = false;
const checkDebounce = (event) => {
let timeMs = null; const checkDebounce = (event) => {
let playing = null; let timeMs = null;
if (event.op == "SetTime") { let playing = null;
timeMs = event.data; if (event.op == "SetTime") {
} else if (event.op == "SetPlaying") { timeMs = event.data;
timeMs = event.data.time; } else if (event.op == "SetPlaying") {
playing = event.data.playing; timeMs = event.data.time;
} playing = event.data.playing;
}
let shouldIgnore = false;
let shouldIgnore = false;
if (timeMs != null) {
if (lastTimeMs && Math.abs(lastTimeMs - timeMs) < 500) { if (timeMs != null) {
shouldIgnore = true; if (lastTimeMs && Math.abs(lastTimeMs - timeMs) < 500) {
} shouldIgnore = true;
lastTimeMs = timeMs; }
} lastTimeMs = timeMs;
}
if (playing != null) {
if (lastPlaying != playing) { if (playing != null) {
shouldIgnore = false; if (lastPlaying != playing) {
} shouldIgnore = false;
lastPlaying = playing; }
} lastPlaying = playing;
}
return shouldIgnore;
}; return shouldIgnore;
};
/**
* @returns {string} /**
*/ * @returns {string}
const getCurrentTimestamp = () => { */
const t = new Date(); const getCurrentTimestamp = () => {
return `${matpad(t.getHours())}:${matpad(t.getMinutes())}:${matpad( const t = new Date();
t.getSeconds() return `${matpad(t.getHours())}:${matpad(t.getMinutes())}:${matpad(
)}`; t.getSeconds()
}; )}`;
};
/**
* https://media.discordapp.net/attachments/834541919568527361/931678814751301632/66d2c68c48daa414c96951381665ec2e.png /**
*/ * https://media.discordapp.net/attachments/834541919568527361/931678814751301632/66d2c68c48daa414c96951381665ec2e.png
const matpad = (n) => { */
return ("00" + n).slice(-2); const matpad = (n) => {
}; return ("00" + n).slice(-2);
};
/**
* @param {string} eventType /**
* @param {string?} user * @param {string} eventType
* @param {Node?} content * @param {string?} user
*/ * @param {Node?} content
const printChatMessage = (eventType, user, colour, content) => { */
const chatMessage = document.createElement("div"); export const printChatMessage = (eventType, user, colour, content) => {
chatMessage.classList.add("chat-message"); const chatMessage = document.createElement("div");
chatMessage.classList.add(eventType); chatMessage.classList.add("chat-message");
chatMessage.title = getCurrentTimestamp(); chatMessage.classList.add(eventType);
chatMessage.title = getCurrentTimestamp();
if (user != null) {
const userName = document.createElement("strong"); if (user != null) {
userName.style = `--user-color: #${colour}`; const userName = document.createElement("strong");
userName.textContent = user + " "; userName.style = `--user-color: #${colour}`;
chatMessage.appendChild(userName); userName.textContent = user + " ";
} chatMessage.appendChild(userName);
}
if (content != null) {
chatMessage.appendChild(content); if (content != null) {
} chatMessage.appendChild(content);
}
addToChat(chatMessage);
addToChat(chatMessage);
return chatMessage;
}; return chatMessage;
};
const formatTime = (ms) => {
const seconds = Math.floor((ms / 1000) % 60); const formatTime = (ms) => {
const minutes = Math.floor((ms / (60 * 1000)) % 60); const seconds = Math.floor((ms / 1000) % 60);
const hours = Math.floor((ms / (3600 * 1000)) % 3600); const minutes = Math.floor((ms / (60 * 1000)) % 60);
return `${hours < 10 ? "0" + hours : hours}:${ const hours = Math.floor((ms / (3600 * 1000)) % 3600);
minutes < 10 ? "0" + minutes : minutes return `${hours < 10 ? "0" + hours : hours}:${
}:${seconds < 10 ? "0" + seconds : seconds}`; minutes < 10 ? "0" + minutes : minutes
}; }:${seconds < 10 ? "0" + seconds : seconds}`;
};
export const logEventToChat = async (event) => {
if (checkDebounce(event)) { export const logEventToChat = async (event) => {
return; if (checkDebounce(event)) {
} return;
}
switch (event.op) {
case "UserJoin": { switch (event.op) {
printChatMessage( case "UserJoin": {
"user-join", printChatMessage(
event.user, "user-join",
event.colour, event.user,
document.createTextNode("joined") event.colour,
); document.createTextNode("joined")
break; );
} break;
case "UserLeave": { }
printChatMessage( case "UserLeave": {
"user-leave", printChatMessage(
event.user, "user-leave",
event.colour, event.user,
document.createTextNode("left") event.colour,
); document.createTextNode("left")
break; );
} break;
case "ChatMessage": { }
const messageContent = document.createElement("span"); case "ChatMessage": {
messageContent.classList.add("message-content"); const messageContent = document.createElement("span");
messageContent.append(...(await emojify(event.data))); messageContent.classList.add("message-content");
printChatMessage( messageContent.append(...(await linkify(event.data, emojify)));
"chat-message", printChatMessage(
event.user, "chat-message",
event.colour, event.user,
messageContent event.colour,
); messageContent
break; );
} break;
case "SetTime": { }
const messageContent = document.createElement("span"); case "SetTime": {
if (event.data.from != undefined) { const messageContent = document.createElement("span");
messageContent.appendChild( if (event.data.from != undefined) {
document.createTextNode("set the time from ") messageContent.appendChild(
); document.createTextNode("set the time from ")
);
messageContent.appendChild(
document.createTextNode(formatTime(event.data.from)) messageContent.appendChild(
); document.createTextNode(formatTime(event.data.from))
);
messageContent.appendChild(document.createTextNode(" to "));
} else { messageContent.appendChild(document.createTextNode(" to "));
messageContent.appendChild(document.createTextNode("set the time to ")); } else {
} messageContent.appendChild(document.createTextNode("set the time to "));
}
messageContent.appendChild(
document.createTextNode(formatTime(event.data.to)) messageContent.appendChild(
); document.createTextNode(formatTime(event.data.to))
);
printChatMessage("set-time", event.user, event.colour, messageContent);
break; printChatMessage("set-time", event.user, event.colour, messageContent);
} break;
case "SetPlaying": { }
const messageContent = document.createElement("span"); case "SetPlaying": {
messageContent.appendChild( const messageContent = document.createElement("span");
document.createTextNode( messageContent.appendChild(
event.data.playing ? "started playing" : "paused" document.createTextNode(
) event.data.playing ? "started playing" : "paused"
); )
messageContent.appendChild(document.createTextNode(" at ")); );
messageContent.appendChild( messageContent.appendChild(document.createTextNode(" at "));
document.createTextNode(formatTime(event.data.time)) messageContent.appendChild(
); document.createTextNode(formatTime(event.data.time))
);
printChatMessage("set-playing", event.user, event.colour, messageContent);
break; printChatMessage("set-playing", event.user, event.colour, messageContent);
} break;
case "Ping": { }
const messageContent = document.createElement("span"); case "Ping": {
if (event.data) { const messageContent = document.createElement("span");
messageContent.appendChild(document.createTextNode("pinged saying: ")); if (event.data) {
messageContent.appendChild(document.createTextNode(event.data)); messageContent.appendChild(document.createTextNode("pinged saying: "));
} else { messageContent.appendChild(document.createTextNode(event.data));
messageContent.appendChild(document.createTextNode("pinged")); } else {
} messageContent.appendChild(document.createTextNode("pinged"));
}
printChatMessage("ping", event.user, event.colour, messageContent);
beep(); printChatMessage("ping", event.user, event.colour, messageContent);
break; pling();
} if ("Notification" in window) {
} const title = "watch party :)";
}; const options = {
body: event.data
const beep = () => { ? `${event.user} pinged saying: ${event.data}`
const context = new AudioContext(); : `${event.user} pinged`,
};
const gain = context.createGain(); if (Notification.permission === "granted") {
gain.connect(context.destination); new Notification(title, options);
gain.gain.value = 0.1; } else if (Notification.permission !== "denied") {
Notification.requestPermission().then(function (permission) {
const oscillator = context.createOscillator(); if (permission === "granted") {
oscillator.connect(gain); new Notification(title, options);
oscillator.frequency.value = 520; }
oscillator.type = "square"; });
}
oscillator.start(context.currentTime); }
oscillator.stop(context.currentTime + 0.22); break;
}; }
}
export const updateViewerList = (viewers) => { };
const listContainer = document.querySelector("#viewer-list");
export const updateViewerList = (viewers) => {
// empty out the current list const listContainer = document.querySelector("#viewer-list");
listContainer.innerHTML = "";
// empty out the current list
// display the updated list listContainer.innerHTML = "";
for (const viewer of viewers) {
const viewerElem = document.createElement("div"); // display the updated list
const content = document.createElement("strong"); for (const viewer of viewers) {
content.textContent = viewer.nickname; const viewerElem = document.createElement("div");
content.style = `--user-color: #${viewer.colour}`; const content = document.createElement("strong");
viewerElem.appendChild(content); content.textContent = viewer.nickname;
listContainer.appendChild(viewerElem); content.style = `--user-color: #${viewer.colour}`;
} viewerElem.appendChild(content);
}; listContainer.appendChild(viewerElem);
}
};

View File

@ -1,18 +1,18 @@
import { createSession } from "./watch-session.mjs?v=048af96"; import { createSession } from "./watch-session.mjs?v=4b61c4";
export const setupCreateSessionForm = () => { export const setupCreateSessionForm = () => {
const form = document.querySelector("#create-session-form"); const form = document.querySelector("#create-session-form");
const videoUrl = form.querySelector("#create-session-video"); const videoUrl = form.querySelector("#create-session-video");
const subsUrl = form.querySelector("#create-session-subs"); const subsUrl = form.querySelector("#create-session-subs");
const subsName = form.querySelector("#create-session-subs-name"); const subsName = form.querySelector("#create-session-subs-name");
form.addEventListener("submit", (event) => { form.addEventListener("submit", (event) => {
event.preventDefault(); event.preventDefault();
let subs = []; let subs = [];
if (subsUrl.value) { if (subsUrl.value) {
subs.push({ url: subsUrl.value, name: subsName.value || "default" }); subs.push({ url: subsUrl.value, name: subsName.value || "default" });
} }
createSession(videoUrl.value, subs); createSession(videoUrl.value, subs);
}); });
}; };

View File

@ -1,69 +1,72 @@
export async function emojify(text) { export async function emojify(text) {
await emojisLoaded; await emojisLoaded;
let last = 0; let last = 0;
let nodes = []; let nodes = [];
text.replace(/:([^\s:]+):/g, (match, name, index) => { text.replace(/:([^\s:]+):/g, (match, name, index) => {
if (last <= index) if (last <= index)
nodes.push(document.createTextNode(text.slice(last, index))); nodes.push(document.createTextNode(text.slice(last, index)));
let emoji = emojis[name.toLowerCase()[0]].find((e) => e[0] == name); let emoji;
if (!emoji) { try {
nodes.push(document.createTextNode(match)); emoji = emojis[name.toLowerCase()[0]].find((e) => e[0] == name);
} else { } catch (e) {}
if (emoji[1][0] !== ":") { if (!emoji) {
nodes.push(document.createTextNode(emoji[1])); nodes.push(document.createTextNode(match));
} else { } else {
nodes.push( if (emoji[1][0] !== ":") {
Object.assign(new Image(), { nodes.push(document.createTextNode(emoji[1]));
src: `/emojis/${name}${emoji[2]}`, } else {
className: "emoji", nodes.push(
alt: name, Object.assign(new Image(), {
}) src: `/emojis/${name}${emoji[2]}`,
); className: "emoji",
} alt: name,
} })
last = index + match.length; );
}); }
if (last < text.length) nodes.push(document.createTextNode(text.slice(last))); }
return nodes; last = index + match.length;
} });
const emojis = {}; if (last < text.length) nodes.push(document.createTextNode(text.slice(last)));
return nodes;
export const emojisLoaded = Promise.all([ }
fetch("/emojis") const emojis = {};
.then((e) => e.json())
.then((a) => { export const emojisLoaded = Promise.all([
for (let e of a) { fetch("/emojis/unicode.json")
const name = e.slice(0, -4), .then((e) => e.json())
lower = name.toLowerCase(); .then((a) => {
emojis[lower[0]] = emojis[lower[0]] || []; for (let e of a) {
emojis[lower[0]].push([name, ":" + name + ":", e.slice(-4), lower]); emojis[e[0][0]] = emojis[e[0][0]] || [];
} emojis[e[0][0]].push([e[0], e[1], null, e[0]]);
}), }
fetch("/emojis/unicode.json") }),
.then((e) => e.json()) fetch("/emojos")
.then((a) => { .then((e) => e.json())
for (let e of a) { .then((a) => {
emojis[e[0][0]] = emojis[e[0][0]] || []; for (let e of a) {
emojis[e[0][0]].push([e[0], e[1], null, e[0]]); const name = e.slice(0, -4),
} lower = name.toLowerCase();
}), emojis[lower[0]] = emojis[lower[0]] || [];
]); emojis[lower[0]].push([name, ":" + name + ":", e.slice(-4), lower]);
}
export async function findEmojis(search) { }),
await emojisLoaded; ]);
let groups = [[], []];
if (search.length < 1) { export async function findEmojis(search) {
for (let letter in emojis) await emojisLoaded;
for (let emoji of emojis[letter]) { let groups = [[], []];
(emoji[1][0] === ":" ? groups[0] : groups[1]).push(emoji); if (search.length < 1) {
} for (let letter of Object.keys(emojis).sort())
} else { for (let emoji of emojis[letter]) {
search = search.toLowerCase(); (emoji[1][0] === ":" ? groups[0] : groups[1]).push(emoji);
for (let emoji of emojis[search[0]]) { }
if (search.length == 1 || emoji[3].startsWith(search)) { } else {
(emoji[1][0] === ":" ? groups[0] : groups[1]).push(emoji); search = search.toLowerCase();
} for (let emoji of emojis[search[0]]) {
} if (search.length == 1 || emoji[3].startsWith(search)) {
} (emoji[1][0] === ":" ? groups[0] : groups[1]).push(emoji);
return [...groups[0], ...groups[1]]; }
} }
}
return [...groups[1], ...groups[0]];
}

View File

@ -1,93 +1,95 @@
import { joinSession } from "./watch-session.mjs?v=048af96"; import { joinSession } from "./watch-session.mjs?v=4b61c4";
import { state } from "./state.mjs";
/**
* @param {HTMLInputElement} field /**
*/ * @param {HTMLInputElement} field
const loadNickname = (field) => { */
try { const loadNickname = (field) => {
const savedNickname = localStorage.getItem("watch-party-nickname"); try {
field.value = savedNickname; const savedNickname = localStorage.getItem("watch-party-nickname");
} catch (_err) { field.value = savedNickname;
// Sometimes localStorage is blocked from use } catch (_err) {
} // Sometimes localStorage is blocked from use
}; }
};
/**
* @param {HTMLInputElement} field /**
*/ * @param {HTMLInputElement} field
const saveNickname = (field) => { */
try { const saveNickname = (field) => {
localStorage.setItem("watch-party-nickname", field.value); try {
} catch (_err) { localStorage.setItem("watch-party-nickname", field.value);
// see loadNickname } catch (_err) {
} // see loadNickname
}; }
};
/**
* @param {HTMLInputElement} field /**
*/ * @param {HTMLInputElement} field
const loadColour = (field) => { */
try { const loadColour = (field) => {
const savedColour = localStorage.getItem("watch-party-colour"); try {
if (savedColour != null && savedColour != "") { const savedColour = localStorage.getItem("watch-party-colour");
field.value = savedColour; if (savedColour != null && savedColour != "") {
} field.value = savedColour;
} catch (_err) { }
// Sometimes localStorage is blocked from use } catch (_err) {
} // Sometimes localStorage is blocked from use
}; }
};
/**
* @param {HTMLInputElement} field /**
*/ * @param {HTMLInputElement} field
const saveColour = (field) => { */
try { const saveColour = (field) => {
localStorage.setItem("watch-party-colour", field.value); try {
} catch (_err) { localStorage.setItem("watch-party-colour", field.value);
// see loadColour } catch (_err) {
} // see loadColour
}; }
};
const displayPostCreateMessage = () => {
const params = new URLSearchParams(window.location.search); const displayPostCreateMessage = () => {
if (params.get("created") == "true") { const params = new URLSearchParams(window.location.search);
document.querySelector("#post-create-message").style["display"] = "block"; if (params.get("created") == "true") {
window.history.replaceState({}, document.title, `/${window.location.hash}`); document.querySelector("#post-create-message").style["display"] = "block";
} window.history.replaceState({}, document.title, `/${window.location.hash}`);
}; return true;
}
export const setupJoinSessionForm = () => { return false;
displayPostCreateMessage(); };
const form = document.querySelector("#join-session-form"); export const setupJoinSessionForm = () => {
const nickname = form.querySelector("#join-session-nickname"); const created = displayPostCreateMessage();
const colour = form.querySelector("#join-session-colour");
const sessionId = form.querySelector("#join-session-id"); const form = document.querySelector("#join-session-form");
const button = form.querySelector("#join-session-button"); const nickname = form.querySelector("#join-session-nickname");
const colour = form.querySelector("#join-session-colour");
loadNickname(nickname); const sessionId = form.querySelector("#join-session-id");
loadColour(colour); const button = form.querySelector("#join-session-button");
if (window.location.hash.match(/#[0-9a-f\-]+/)) { loadNickname(nickname);
sessionId.value = window.location.hash.substring(1); loadColour(colour);
}
if (window.location.hash.match(/#[0-9a-f\-]+/)) {
form.addEventListener("submit", async (event) => { sessionId.value = window.location.hash.substring(1);
event.preventDefault(); }
button.disabled = true; form.addEventListener("submit", async (event) => {
event.preventDefault();
saveNickname(nickname);
saveColour(colour); button.disabled = true;
try {
await joinSession( saveNickname(nickname);
nickname.value, saveColour(colour);
sessionId.value, try {
colour.value.replace(/^#/, "") state().nickname = nickname.value;
); state().sessionId = sessionId.value;
} catch (e) { state().colour = colour.value.replace(/^#/, "");
alert(e.message); await joinSession(created);
button.disabled = false; } catch (e) {
} alert(e.message);
}); button.disabled = false;
}; }
});
};

121
frontend/lib/links.mjs Normal file
View File

@ -0,0 +1,121 @@
import { joinSession } from "./watch-session.mjs?v=4b61c4";
import { state } from "./state.mjs";
export async function linkify(
text,
next = async (t) => [document.createTextNode(t)]
) {
let last = 0;
let nodes = [];
let promise = Promise.resolve();
// matching non-urls isn't a problem, we use the browser's url parser to filter them out
text.replace(
/[^:/?#\s]+:\/\/\S+/g,
(match, index) =>
(promise = promise.then(async () => {
if (last <= index) nodes.push(...(await next(text.slice(last, index))));
let url;
try {
url = new URL(match);
if (url.protocol === "javascript:") throw new Error();
} catch (e) {
url = null;
}
if (!url) {
nodes.push(...(await next(match)));
} else {
let s;
if (
url.origin == location.origin &&
url.pathname == "/" &&
url.hash.length > 1
) {
nodes.push(
Object.assign(document.createElement("a"), {
textContent: "Join Session",
className: "chip join-chip",
onclick: () => {
state().sessionId = url.hash.substring(1);
joinSession();
},
})
);
} else if (
url.hostname == "xiv.st" &&
(s = url.pathname.match(/(\d?\d).?(\d\d)/))
) {
if (s) {
const date = new Date();
date.setUTCSeconds(0);
date.setUTCMilliseconds(0);
date.setUTCHours(s[1]), date.setUTCMinutes(s[2]);
nodes.push(
Object.assign(document.createElement("a"), {
href: url.href,
textContent: date.toLocaleString([], {
hour: "2-digit",
minute: "2-digit",
}),
className: "chip time-chip",
target: "_blank",
})
);
}
} else {
nodes.push(
Object.assign(document.createElement("a"), {
href: url.href,
textContent: url.href,
target: "_blank",
})
);
}
}
last = index + match.length;
}))
);
await promise;
if (last < text.length) nodes.push(...(await next(text.slice(last))));
return nodes;
}
const emojis = {};
export const emojisLoaded = Promise.all([
fetch("/emojis")
.then((e) => e.json())
.then((a) => {
for (let e of a) {
const name = e.slice(0, -4),
lower = name.toLowerCase();
emojis[lower[0]] = emojis[lower[0]] || [];
emojis[lower[0]].push([name, ":" + name + ":", e.slice(-4), lower]);
}
}),
fetch("/emojis/unicode.json")
.then((e) => e.json())
.then((a) => {
for (let e of a) {
emojis[e[0][0]] = emojis[e[0][0]] || [];
emojis[e[0][0]].push([e[0], e[1], null, e[0]]);
}
}),
]);
export async function findEmojis(search) {
await emojisLoaded;
let groups = [[], []];
if (search.length < 1) {
for (let letter of Object.keys(emojis).sort())
for (let emoji of emojis[letter]) {
(emoji[1][0] === ":" ? groups[0] : groups[1]).push(emoji);
}
} else {
search = search.toLowerCase();
for (let emoji of emojis[search[0]]) {
if (search.length == 1 || emoji[3].startsWith(search)) {
(emoji[1][0] === ":" ? groups[0] : groups[1]).push(emoji);
}
}
}
return [...groups[0], ...groups[1]];
}

79
frontend/lib/pling.mjs Normal file
View File

@ -0,0 +1,79 @@
export const pling = () => {
const maxGain = 0.3;
const duration = 0.22;
const fadeDuration = 0.1;
const secondBeepOffset = 0.05;
const thirdBeepOffset = 2 * secondBeepOffset;
const ctx = new AudioContext();
const firstBeepGain = ctx.createGain();
firstBeepGain.connect(ctx.destination);
firstBeepGain.gain.setValueAtTime(0.01, ctx.currentTime);
firstBeepGain.gain.exponentialRampToValueAtTime(
maxGain,
ctx.currentTime + fadeDuration
);
firstBeepGain.gain.setValueAtTime(
maxGain,
ctx.currentTime + (duration - fadeDuration)
);
firstBeepGain.gain.exponentialRampToValueAtTime(
0.01,
ctx.currentTime + duration
);
const firstBeep = ctx.createOscillator();
firstBeep.connect(firstBeepGain);
firstBeep.frequency.value = 400;
firstBeep.type = "sine";
const secondBeepGain = ctx.createGain();
secondBeepGain.connect(ctx.destination);
secondBeepGain.gain.setValueAtTime(0.01, ctx.currentTime + secondBeepOffset);
secondBeepGain.gain.exponentialRampToValueAtTime(
maxGain,
ctx.currentTime + secondBeepOffset + fadeDuration
);
secondBeepGain.gain.setValueAtTime(
maxGain,
ctx.currentTime + secondBeepOffset + (duration - fadeDuration)
);
secondBeepGain.gain.exponentialRampToValueAtTime(
0.01,
ctx.currentTime + secondBeepOffset + duration
);
const secondBeep = ctx.createOscillator();
secondBeep.connect(secondBeepGain);
secondBeep.frequency.value = 600;
secondBeep.type = "sine";
const thirdBeepGain = ctx.createGain();
thirdBeepGain.connect(ctx.destination);
thirdBeepGain.gain.setValueAtTime(0.01, ctx.currentTime + thirdBeepOffset);
thirdBeepGain.gain.exponentialRampToValueAtTime(
maxGain,
ctx.currentTime + thirdBeepOffset + fadeDuration
);
thirdBeepGain.gain.setValueAtTime(
maxGain,
ctx.currentTime + thirdBeepOffset + (duration - fadeDuration)
);
thirdBeepGain.gain.exponentialRampToValueAtTime(
0.01,
ctx.currentTime + thirdBeepOffset + duration
);
const thirdBeep = ctx.createOscillator();
thirdBeep.connect(thirdBeepGain);
thirdBeep.frequency.value = 900;
thirdBeep.type = "sine";
firstBeep.start(ctx.currentTime);
firstBeep.stop(ctx.currentTime + duration);
secondBeep.start(ctx.currentTime + secondBeepOffset);
secondBeep.stop(ctx.currentTime + (secondBeepOffset + duration));
thirdBeep.start(ctx.currentTime + thirdBeepOffset);
thirdBeep.stop(ctx.currentTime + (thirdBeepOffset + duration));
};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1,65 +1,71 @@
export default class ReconnectingWebSocket { export default class ReconnectingWebSocket {
constructor(url) { constructor(url) {
if (url instanceof URL) { if (url instanceof URL) {
this.url = url; this.url = url;
} else { } else {
this.url = new URL(url); this.url = new URL(url);
} }
this.connected = false; this.connected = false;
this._eventTarget = new EventTarget(); this._eventTarget = new EventTarget();
this._backoff = 250; // milliseconds, doubled before use this._backoff = 250; // milliseconds, doubled before use
this._lastConnect = 0; this._lastConnect = 0;
this._socket = null; this._socket = null;
this._unsent = []; this._unsent = [];
this._connect(true); this._closing = false;
} this._connect(true);
_connect(first) { }
if (this._socket) _connect(first) {
try { if (this._socket)
this._socket.close(); try {
} catch (e) {} this._socket.close();
try { } catch (e) {}
this._socket = new WebSocket(this.url.href); try {
} catch (e) { this._socket = new WebSocket(this.url.href);
this._reconnecting = false; } catch (e) {
return this._reconnect(); this._reconnecting = false;
} return this._reconnect();
this._socket.addEventListener("close", () => this._reconnect()); }
this._socket.addEventListener("error", () => this._reconnect()); this._socket.addEventListener("close", () => this._reconnect());
this._socket.addEventListener("message", ({ data }) => this._socket.addEventListener("error", () => this._reconnect());
this._eventTarget.dispatchEvent(new MessageEvent("message", { data })) this._socket.addEventListener("message", ({ data }) => {
); this._eventTarget.dispatchEvent(new MessageEvent("message", { data }));
this._socket.addEventListener("open", (e) => { });
if (first) this._eventTarget.dispatchEvent(new Event("open")); this._socket.addEventListener("open", (e) => {
if (this._reconnecting) if (first) this._eventTarget.dispatchEvent(new Event("open"));
this._eventTarget.dispatchEvent(new Event("reconnected")); if (this._reconnecting)
this._reconnecting = false; this._eventTarget.dispatchEvent(new Event("reconnected"));
this._backoff = 250; this._reconnecting = false;
this.connected = true; this._backoff = 250;
while (this._unsent.length > 0) this._socket.send(this._unsent.shift()); this.connected = true;
}); while (this._unsent.length > 0) this._socket.send(this._unsent.shift());
} });
_reconnect() { }
if (this._reconnecting) return; _reconnect() {
this._eventTarget.dispatchEvent(new Event("reconnecting")); if (this._closing) return;
this._reconnecting = true; if (this._reconnecting) return;
this.connected = false; this._eventTarget.dispatchEvent(new Event("reconnecting"));
this._backoff *= 2; // exponential backoff this._reconnecting = true;
setTimeout(() => { this.connected = false;
this._connect(); this._backoff *= 2; // exponential backoff
}, Math.floor(this._backoff + Math.random() * this._backoff * 0.25 - this._backoff * 0.125)); setTimeout(() => {
} this._connect();
send(message) { }, Math.floor(this._backoff + Math.random() * this._backoff * 0.25 - this._backoff * 0.125));
if (this.connected) { }
this._socket.send(message); send(message) {
} else { if (this.connected) {
this._unsent.push(message); this._socket.send(message);
} } else {
} this._unsent.push(message);
addEventListener(...a) { }
return this._eventTarget.addEventListener(...a); }
} close() {
removeEventListener(...a) { this._closing = true;
return this._eventTarget.removeEventListener(...a); this._socket.close();
} }
} addEventListener(...a) {
return this._eventTarget.addEventListener(...a);
}
removeEventListener(...a) {
return this._eventTarget.removeEventListener(...a);
}
}

7
frontend/lib/state.mjs Normal file
View File

@ -0,0 +1,7 @@
let instance = null;
export const state = () => {
if (!instance) {
instance = {};
}
return instance;
};

View File

@ -1,158 +1,112 @@
const loadVolume = () => { import Plyr from "./plyr-3.7.3.min.esm.js";
try {
const savedVolume = localStorage.getItem("watch-party-volume"); /**
if (savedVolume != null && savedVolume != "") { * @param {string} videoUrl
return +savedVolume; * @param {{name: string, url: string}[]} subtitles
} */
} catch (_err) { const createVideoElement = (videoUrl, subtitles, created) => {
// Sometimes localStorage is blocked from use const oldVideo = document.getElementById(".plyr");
} if (oldVideo) {
// default oldVideo.remove();
return 0.5; }
}; const video = document.createElement("video");
video.id = "video";
/** video.crossOrigin = "anonymous";
* @param {number} volume
*/ const source = document.createElement("source");
const saveVolume = (volume) => { source.src = videoUrl;
try {
localStorage.setItem("watch-party-volume", volume); video.appendChild(source);
} catch (_err) {
// see loadVolume for (const { name, url } of subtitles) {
} const track = document.createElement("track");
}; track.label = name;
track.srclang = "xx-" + name.toLowerCase();
const loadCaptionTrack = () => { track.src = url;
try { track.kind = "captions";
const savedTrack = localStorage.getItem("watch-party-captions"); video.appendChild(track);
if (savedTrack != null && savedTrack != "") { }
return +savedTrack;
} const videoContainer = document.querySelector("#video-container");
} catch (_err) { videoContainer.style.display = "block";
// Sometimes localStorage is blocked from use videoContainer.appendChild(video);
}
// default const player = new Plyr(video, {
return -1; clickToPlay: false,
}; settings: ["captions", "quality"],
autopause: false,
/** });
* @param {number} track player.elements.controls.insertAdjacentHTML(
*/ "afterbegin",
const saveCaptionsTrack = (track) => { `<button type="button" aria-pressed="false" class="plyr__controls__item plyr__control lock-controls"><svg aria-hidden="true" focusable="false" viewBox="0 0 24 24"><path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zM9 8V6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9z"></path></svg><span class="label--pressed plyr__sr-only">Unlock controls</span><span class="label--not-pressed plyr__sr-only">Lock controls</span></button>`
try { );
localStorage.setItem("watch-party-captions", track); const lockButton = player.elements.controls.children[0];
} catch (_err) { let controlsEnabled = created;
// see loadCaptionsTrack const setControlsEnabled = (enabled) => {
} controlsEnabled = enabled;
}; lockButton.setAttribute("aria-pressed", enabled);
lockButton.classList.toggle("plyr__control--pressed", enabled);
/** player.elements.buttons.play[0].disabled =
* @param {string} videoUrl player.elements.buttons.play[1].disabled =
* @param {{name: string, url: string}[]} subtitles player.elements.inputs.seek.disabled =
*/ !enabled;
const createVideoElement = (videoUrl, subtitles) => { if (!enabled) {
const video = document.createElement("video"); // enable media button support
video.controls = true; navigator.mediaSession.setActionHandler("play", null);
video.autoplay = false; navigator.mediaSession.setActionHandler("pause", null);
video.volume = loadVolume(); navigator.mediaSession.setActionHandler("stop", null);
video.crossOrigin = "anonymous"; navigator.mediaSession.setActionHandler("seekbackward", null);
navigator.mediaSession.setActionHandler("seekforward", null);
video.addEventListener("volumechange", async () => { navigator.mediaSession.setActionHandler("seekto", null);
saveVolume(video.volume); navigator.mediaSession.setActionHandler("previoustrack", null);
}); navigator.mediaSession.setActionHandler("nexttrack", null);
} else {
const source = document.createElement("source"); // disable media button support by ignoring the events
source.src = videoUrl; navigator.mediaSession.setActionHandler("play", () => {});
navigator.mediaSession.setActionHandler("pause", () => {});
video.appendChild(source); navigator.mediaSession.setActionHandler("stop", () => {});
navigator.mediaSession.setActionHandler("seekbackward", () => {});
const storedTrack = loadCaptionTrack(); navigator.mediaSession.setActionHandler("seekforward", () => {});
let id = 0; navigator.mediaSession.setActionHandler("seekto", () => {});
for (const { name, url } of subtitles) { navigator.mediaSession.setActionHandler("previoustrack", () => {});
const track = document.createElement("track"); navigator.mediaSession.setActionHandler("nexttrack", () => {});
track.label = name; }
track.src = url; };
track.kind = "captions"; setControlsEnabled(controlsEnabled);
lockButton.addEventListener("click", () =>
if (id == storedTrack) { setControlsEnabled(!controlsEnabled)
track.default = true; );
} window.__plyr = player;
video.appendChild(track); return player;
id++; };
}
/**
video.textTracks.addEventListener("change", async () => { * @param {string} videoUrl
let id = 0; * @param {{name: string, url: string}[]} subtitles
for (const track of video.textTracks) { * @param {number} currentTime
if (track.mode != "disabled") { * @param {boolean} playing
saveCaptionsTrack(id); */
return; export const setupVideo = async (
} videoUrl,
id++; subtitles,
} currentTime,
saveCaptionsTrack(-1); playing,
}); created
) => {
// watch for attribute changes on the video object to detect hiding/showing of controls document.querySelector("#pre-join-controls").style["display"] = "none";
// as far as i can tell this is the least hacky solutions to get control visibility change events const player = createVideoElement(videoUrl, subtitles, created);
const observer = new MutationObserver(async (mutations) => { player.currentTime = currentTime / 1000.0;
for (const mutation of mutations) {
if (mutation.attributeName == "controls") { try {
if (video.controls) { if (playing) {
// enable media button support player.play();
navigator.mediaSession.setActionHandler("play", null); } else {
navigator.mediaSession.setActionHandler("pause", null); player.pause();
navigator.mediaSession.setActionHandler("stop", null); }
navigator.mediaSession.setActionHandler("seekbackward", null); } catch (err) {
navigator.mediaSession.setActionHandler("seekforward", null); // Auto-play is probably disabled, we should uhhhhhhh do something about it
navigator.mediaSession.setActionHandler("seekto", null); }
navigator.mediaSession.setActionHandler("previoustrack", null);
navigator.mediaSession.setActionHandler("nexttrack", null); return player;
} else { };
// disable media button support by ignoring the events
navigator.mediaSession.setActionHandler("play", () => {});
navigator.mediaSession.setActionHandler("pause", () => {});
navigator.mediaSession.setActionHandler("stop", () => {});
navigator.mediaSession.setActionHandler("seekbackward", () => {});
navigator.mediaSession.setActionHandler("seekforward", () => {});
navigator.mediaSession.setActionHandler("seekto", () => {});
navigator.mediaSession.setActionHandler("previoustrack", () => {});
navigator.mediaSession.setActionHandler("nexttrack", () => {});
}
return;
}
}
});
observer.observe(video, { attributes: true });
return video;
};
/**
* @param {string} videoUrl
* @param {{name: string, url: string}[]} subtitles
* @param {number} currentTime
* @param {boolean} playing
*/
export const setupVideo = async (videoUrl, subtitles, currentTime, playing) => {
document.querySelector("#pre-join-controls").style["display"] = "none";
const video = createVideoElement(videoUrl, subtitles);
const videoContainer = document.querySelector("#video-container");
videoContainer.style.display = "block";
videoContainer.appendChild(video);
video.currentTime = currentTime / 1000.0;
try {
if (playing) {
await video.play();
} else {
video.pause();
}
} catch (err) {
// Auto-play is probably disabled, we should uhhhhhhh do something about it
}
return video;
};

View File

@ -1,252 +1,270 @@
import { setupVideo } from "./video.mjs?v=048af96"; import { setupVideo } from "./video.mjs?v=4b61c4";
import { import {
setupChat, setupChat,
logEventToChat, logEventToChat,
updateViewerList, updateViewerList,
} from "./chat.mjs?v=048af96"; printChatMessage,
import ReconnectingWebSocket from "./reconnecting-web-socket.mjs"; } from "./chat.mjs?v=4b61c4";
import ReconnectingWebSocket from "./reconnecting-web-socket.mjs";
/** import { state } from "./state.mjs";
* @param {string} sessionId let player;
* @param {string} nickname /**
* @returns {ReconnectingWebSocket} * @param {string} sessionId
*/ * @param {string} nickname
const createWebSocket = (sessionId, nickname, colour) => { * @returns {ReconnectingWebSocket}
const wsUrl = new URL( */
`/sess/${sessionId}/subscribe` + const createWebSocket = () => {
`?nickname=${encodeURIComponent(nickname)}` + const wsUrl = new URL(
`&colour=${encodeURIComponent(colour)}`, `/sess/${state().sessionId}/subscribe` +
window.location.href `?nickname=${encodeURIComponent(state().nickname)}` +
); `&colour=${encodeURIComponent(state().colour)}`,
wsUrl.protocol = "ws" + window.location.protocol.slice(4); window.location.href
const socket = new ReconnectingWebSocket(wsUrl); );
wsUrl.protocol = "ws" + window.location.protocol.slice(4);
return socket; const socket = new ReconnectingWebSocket(wsUrl);
};
return socket;
let outgoingDebounce = false; };
let outgoingDebounceCallbackId = null;
let outgoingDebounce = false;
export const setDebounce = () => { let outgoingDebounceCallbackId = null;
outgoingDebounce = true;
export const setDebounce = () => {
if (outgoingDebounceCallbackId) { outgoingDebounce = true;
cancelIdleCallback(outgoingDebounceCallbackId);
outgoingDebounceCallbackId = null; if (outgoingDebounceCallbackId) {
} cancelIdleCallback(outgoingDebounceCallbackId);
outgoingDebounceCallbackId = null;
outgoingDebounceCallbackId = setTimeout(() => { }
outgoingDebounce = false;
}, 500); outgoingDebounceCallbackId = setTimeout(() => {
}; outgoingDebounce = false;
}, 500);
export const setVideoTime = (time, video = null) => { };
if (video == null) {
video = document.querySelector("video"); export const setVideoTime = (time) => {
} const timeSecs = time / 1000.0;
if (Math.abs(player.currentTime - timeSecs) > 0.5) {
const timeSecs = time / 1000.0; player.currentTime = timeSecs;
if (Math.abs(video.currentTime - timeSecs) > 0.5) { }
video.currentTime = timeSecs; };
}
}; export const setPlaying = async (playing) => {
if (playing) {
export const setPlaying = async (playing, video = null) => { await player.play();
if (video == null) { } else {
video = document.querySelector("video"); player.pause();
} }
};
if (playing) {
await video.play(); /**
} else { * @param {HTMLVideoElement} video
video.pause(); * @param {ReconnectingWebSocket} socket
} */
}; const setupIncomingEvents = (player, socket) => {
socket.addEventListener("message", async (messageEvent) => {
/** try {
* @param {HTMLVideoElement} video const event = JSON.parse(messageEvent.data);
* @param {ReconnectingWebSocket} socket if (!event.reflected) {
*/ switch (event.op) {
const setupIncomingEvents = (video, socket) => { case "SetPlaying":
socket.addEventListener("message", async (messageEvent) => { setDebounce();
try {
const event = JSON.parse(messageEvent.data); if (event.data.playing) {
await player.play();
if (!event.reflected) { } else {
switch (event.op) { player.pause();
case "SetPlaying": }
setDebounce();
setVideoTime(event.data.time);
if (event.data.playing) { break;
await video.play(); case "SetTime":
} else { setDebounce();
video.pause(); setVideoTime(event.data);
} break;
case "UpdateViewerList":
setVideoTime(event.data.time, video); updateViewerList(event.data);
break; break;
case "SetTime": }
setDebounce(); }
setVideoTime(event.data, video);
break; logEventToChat(event);
case "UpdateViewerList": } catch (_err) {}
updateViewerList(event.data); });
break; };
}
} /**
* @param {Plyr} player
logEventToChat(event); * @param {ReconnectingWebSocket} socket
} catch (_err) {} */
}); const setupOutgoingEvents = (player, socket) => {
}; const currentVideoTime = () => (player.currentTime * 1000) | 0;
/** player.on("pause", async () => {
* @param {HTMLVideoElement} video if (outgoingDebounce || player.elements.inputs.seek.disabled) {
* @param {ReconnectingWebSocket} socket return;
*/ }
const setupOutgoingEvents = (video, socket) => {
const currentVideoTime = () => (video.currentTime * 1000) | 0; // don't send a pause event for the video ending
if (player.currentTime == player.duration) {
video.addEventListener("pause", async (event) => { return;
if (outgoingDebounce || !video.controls) { }
return;
} socket.send(
JSON.stringify({
// don't send a pause event for the video ending op: "SetPlaying",
if (video.currentTime == video.duration) { data: {
return; playing: false,
} time: currentVideoTime(),
},
socket.send( })
JSON.stringify({ );
op: "SetPlaying", });
data: {
playing: false, player.on("play", () => {
time: currentVideoTime(), if (outgoingDebounce || player.elements.inputs.seek.disabled) {
}, return;
}) }
);
}); socket.send(
JSON.stringify({
video.addEventListener("play", (event) => { op: "SetPlaying",
if (outgoingDebounce || !video.controls) { data: {
return; playing: true,
} time: currentVideoTime(),
},
socket.send( })
JSON.stringify({ );
op: "SetPlaying", });
data: {
playing: true, let firstSeekComplete = false;
time: currentVideoTime(), player.on("seeked", async (event) => {
}, if (!firstSeekComplete) {
}) // The first seeked event is performed by the browser when the video is loading
); firstSeekComplete = true;
}); return;
}
let firstSeekComplete = false;
video.addEventListener("seeked", async (event) => { if (outgoingDebounce || player.elements.inputs.seek.disabled) {
if (!firstSeekComplete) { return;
// The first seeked event is performed by the browser when the video is loading }
firstSeekComplete = true;
return; socket.send(
} JSON.stringify({
op: "SetTime",
if (outgoingDebounce || !video.controls) { data: {
return; to: currentVideoTime(),
} },
})
socket.send( );
JSON.stringify({ });
op: "SetTime", };
data: {
to: currentVideoTime(), export const joinSession = async (created) => {
}, if (state().activeSession) {
}) if (state().activeSession === state().sessionId) {
); // we are already in this session, dont rejoin
}); return;
}; }
// we are joining a new session from an existing session
/** const messageContent = document.createElement("span");
* @param {string} nickname messageContent.appendChild(document.createTextNode("joining new session "));
* @param {string} sessionId messageContent.appendChild(document.createTextNode(state().sessionId));
*/
export const joinSession = async (nickname, sessionId, colour) => { printChatMessage("join-session", "watch-party", "#fffff", messageContent);
// try { // we are handling errors in the join form. }
const genericConnectionError = new Error( state().activeSession = state().sessionId;
"There was an issue getting the session information."
); // try { // we are handling errors in the join form.
window.location.hash = sessionId; const genericConnectionError = new Error(
let response, video_url, subtitle_tracks, current_time_ms, is_playing; "There was an issue getting the session information."
try { );
response = await fetch(`/sess/${sessionId}`); window.location.hash = state().sessionId;
} catch (e) { let response, video_url, subtitle_tracks, current_time_ms, is_playing;
console.error(e); try {
throw genericConnectionError; response = await fetch(`/sess/${state().sessionId}`);
} } catch (e) {
if (!response.ok) { console.error(e);
let error; throw genericConnectionError;
try { }
({ error } = await response.json()); if (!response.ok) {
if (!error) throw new Error(); let error;
} catch (e) { try {
console.error(e); ({ error } = await response.json());
throw genericConnectionError; if (!error) throw new Error();
} } catch (e) {
throw new Error(error); console.error(e);
} throw genericConnectionError;
try { }
({ video_url, subtitle_tracks, current_time_ms, is_playing } = throw new Error(error);
await response.json()); }
} catch (e) { try {
console.error(e); ({ video_url, subtitle_tracks, current_time_ms, is_playing } =
throw genericConnectionError; await response.json());
} } catch (e) {
console.error(e);
const socket = createWebSocket(sessionId, nickname, colour); throw genericConnectionError;
socket.addEventListener("open", async () => { }
const video = await setupVideo(
video_url, if (state().socket) {
subtitle_tracks, state().socket.close();
current_time_ms, state().socket = null;
is_playing }
); const socket = createWebSocket();
state().socket = socket;
// By default, we should disable video controls if the video is already playing. socket.addEventListener("open", async () => {
// This solves an issue where Safari users join and seek to 00:00:00 because of player = await setupVideo(
// outgoing events. video_url,
if (current_time_ms != 0) { subtitle_tracks,
video.controls = false; current_time_ms,
} is_playing,
created
setupOutgoingEvents(video, socket); );
setupIncomingEvents(video, socket);
setupChat(socket); player.on("canplay", () => {
}); sync();
socket.addEventListener("reconnecting", (e) => { });
console.log("Reconnecting...");
}); setupOutgoingEvents(player, socket);
socket.addEventListener("reconnected", (e) => { setupIncomingEvents(player, socket);
console.log("Reconnected."); setupChat(socket);
}); });
//} catch (e) { socket.addEventListener("reconnecting", (e) => {
// alert(e.message) console.log("Reconnecting...");
//} });
}; socket.addEventListener("reconnected", (e) => {
console.log("Reconnected.");
/** });
* @param {string} videoUrl //} catch (e) {
* @param {Array} subtitleTracks // alert(e.message)
*/ //}
export const createSession = async (videoUrl, subtitleTracks) => { };
const { id } = await fetch("/start_session", {
method: "POST", /**
headers: { "Content-Type": "application/json" }, * @param {string} videoUrl
body: JSON.stringify({ * @param {Array} subtitleTracks
video_url: videoUrl, */
subtitle_tracks: subtitleTracks, export const createSession = async (videoUrl, subtitleTracks) => {
}), const { id } = await fetch("/start_session", {
}).then((r) => r.json()); method: "POST",
headers: { "Content-Type": "application/json" },
window.location = `/?created=true#${id}`; body: JSON.stringify({
}; video_url: videoUrl,
subtitle_tracks: subtitleTracks,
}),
}).then((r) => r.json());
window.location = `/?created=true#${id}`;
};
export const sync = async () => {
setDebounce();
await setPlaying(false);
const { current_time_ms, is_playing } = await fetch(
`/sess/${state().sessionId}`
).then((r) => r.json());
setDebounce();
setVideoTime(current_time_ms);
if (is_playing) await setPlaying(is_playing);
};

View File

@ -1,11 +1,11 @@
import { setupJoinSessionForm } from "./lib/join-session.mjs?v=048af96"; import { setupJoinSessionForm } from "./lib/join-session.mjs?v=4b61c4";
const main = () => { const main = () => {
setupJoinSessionForm(); setupJoinSessionForm();
}; };
if (document.readyState === "complete") { if (document.readyState === "complete") {
main(); main();
} else { } else {
document.addEventListener("DOMContentLoaded", main); document.addEventListener("DOMContentLoaded", main);
} }

View File

@ -1,346 +1,435 @@
* { *,
box-sizing: border-box; *:before,
} *:after {
box-sizing: border-box;
:root { }
--bg-rgb: 28, 23, 36;
--fg-rgb: 234, 234, 248; :root {
--accent-rgb: 181, 127, 220; --bg-rgb: 28, 23, 36;
--fg: rgb(var(--fg-rgb)); --fg-rgb: 234, 234, 248;
--bg: rgb(var(--bg-rgb)); --accent-rgb: 181, 127, 220;
--default-user-color: rgb(126, 208, 255); --fg: rgb(var(--fg-rgb));
--accent: rgb(var(--accent-rgb)); --bg: rgb(var(--bg-rgb));
--fg-transparent: rgba(var(--fg-rgb), 0.25); --default-user-color: rgb(126, 208, 255);
--bg-transparent: rgba(var(--bg-rgb), 0.25); --accent: rgb(var(--accent-rgb));
--autocomplete-bg: linear-gradient( --fg-transparent: rgba(var(--fg-rgb), 0.25);
var(--fg-transparent), --bg-transparent: rgba(var(--bg-rgb), 0.25);
var(--fg-transparent) --autocomplete-bg: linear-gradient(
), var(--fg-transparent),
linear-gradient(var(--bg), var(--bg)); var(--fg-transparent)
} ),
linear-gradient(var(--bg), var(--bg));
html { --chip-bg: linear-gradient(
background-color: var(--bg); var(--accent-transparent),
color: var(--fg); var(--accent-transparent)
font-size: 1.125rem; ),
font-family: sans-serif; linear-gradient(var(--bg), var(--bg));
} --accent-transparent: rgba(var(--accent-rgb), 0.25);
--plyr-color-main: var(--accent);
html, --plyr-control-radius: 6px;
body { --plyr-menu-radius: 6px;
margin: 0; --plyr-menu-background: var(--autocomplete-bg);
padding: 0; --plyr-menu-color: var(--fg);
overflow: hidden; --plyr-menu-arrow-color: var(--fg);
overscroll-behavior: none; --plyr-menu-back-border-color: var(--fg-transparent);
width: 100%; --plyr-menu-back-border-shadow-color: transparent;
height: 100%; }
}
html {
body { background-color: var(--bg);
display: flex; color: var(--fg);
flex-direction: column; font-size: 1.125rem;
} font-family: sans-serif;
}
video {
display: block; html,
width: 100%; body {
height: 100%; margin: 0;
object-fit: contain; padding: 0;
} overflow: hidden;
overscroll-behavior: none;
#video-container { width: 100%;
flex-grow: 0; height: 100%;
flex-shrink: 1; }
display: none;
} body {
display: flex;
a { flex-direction: column;
color: var(--accent); }
}
.lock-controls.plyr__control--pressed svg {
label { opacity: 0.5;
display: block; }
}
.plyr {
input[type="url"], width: 100%;
input[type="text"] { height: 100%;
background: #fff; }
background-clip: padding-box;
border: 1px solid rgba(0, 0, 0, 0.12); .plyr__menu__container {
border-radius: 6px; --plyr-video-control-background-hover: var(--fg-transparent);
color: rgba(0, 0, 0, 0.8); --plyr-video-control-color-hover: var(--fg);
display: block; --plyr-control-radius: 4px;
--plyr-control-spacing: calc(0.25rem / 0.7);
margin: 0.5em 0; --plyr-font-size-menu: 0.75rem;
padding: 0.5em 1em; --plyr-menu-arrow-size: 0;
line-height: 1.5; margin-bottom: 0.48rem;
max-height: 27vmin;
font-family: sans-serif; clip-path: inset(0 0 0 0 round 4px);
font-size: 1em; scrollbar-width: thin;
width: 100%; }
resize: none; .plyr__menu__container .plyr__control[role="menuitemradio"]::after {
overflow-x: wrap; left: 10px;
overflow-y: scroll; }
}
.plyr__menu__container
button { .plyr__control[role="menuitemradio"][aria-checked="true"].plyr__tab-focus::before,
background-color: var(--accent); .plyr__menu__container
border: var(--accent); .plyr__control[role="menuitemradio"][aria-checked="true"]:hover::before {
border-radius: 6px; background: var(--accent);
color: #fff; }
padding: 0.5em 1em;
display: inline-block; [data-plyr="language"] .plyr__menu__value {
font-weight: 400; display: none;
text-align: center; }
white-space: nowrap;
vertical-align: middle; #video-container {
flex-grow: 0;
font-family: sans-serif; flex-shrink: 1;
font-size: 1em; display: none;
width: 100%; }
user-select: none; a {
border: 1px solid rgba(0, 0, 0, 0); color: var(--accent);
line-height: 1.5; }
cursor: pointer;
margin: 0.5em 0; .chip {
} color: var(--fg);
background: var(--chip-bg);
button:disabled { text-decoration: none;
filter: saturate(0.75); padding: 0 0.5rem 0 1.45rem;
opacity: 0.75; display: inline-flex;
cursor: default; position: relative;
} font-size: 0.9rem;
height: 1.125rem;
button.small-button { align-items: center;
font-size: 0.75em; border-radius: 2rem;
padding-top: 0; overflow: hidden;
padding-bottom: 0; }
}
.chip::before {
.subtitle-track-group { content: "";
display: flex; position: absolute;
} left: 0;
top: 0;
.subtitle-track-group > * { width: 1.125rem;
margin-top: 0 !important; height: 100%;
margin-bottom: 0 !important; display: flex;
margin-right: 1ch !important; align-items: center;
} justify-content: center;
text-align: center;
#pre-join-controls, background: var(--accent-transparent);
#create-controls { background-repeat: no-repeat;
margin: 0; background-size: 18px;
flex-grow: 1; background-position: center;
overflow-y: auto; }
display: flex;
flex-direction: column; .join-chip::before {
align-items: center; background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0iI2ZmZiI+PHBhdGggZD0iTTggNXYxNGwxMS03eiIvPjwvc3ZnPg==");
justify-content: center; }
}
.time-chip::before {
#join-session-form, background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0iI2ZmZiI+PHBhdGggZD0iTTExLjk5IDJDNi40NyAyIDIgNi40OCAyIDEyczQuNDcgMTAgOS45OSAxMEMxNy41MiAyMiAyMiAxNy41MiAyMiAxMlMxNy41MiAyIDExLjk5IDJ6TTEyIDIwYy00LjQyIDAtOC0zLjU4LTgtOHMzLjU4LTggOC04IDggMy41OCA4IDgtMy41OCA4LTggOHoiLz48cGF0aCBkPSJNMTIuNSA3SDExdjZsNS4yNSAzLjE1Ljc1LTEuMjMtNC41LTIuNjd6Ii8+PC9zdmc+");
#create-session-form { }
width: 500px;
max-width: 100%; label {
padding: 1rem; display: block;
} }
#join-session-form > *:first-child, input[type="url"],
#create-session-form > *:first-child { input[type="text"] {
margin-top: 0; background: #fff;
} background-clip: padding-box;
border: 1px solid rgba(0, 0, 0, 0.12);
#post-create-message { border-radius: 6px;
display: none; color: rgba(0, 0, 0, 0.8);
width: 100%; display: block;
font-size: 0.85em;
} margin: 0.5em 0;
padding: 0.5em 1em;
#chatbox-container { line-height: 1.5;
display: none;
} font-family: sans-serif;
font-size: 1em;
.chat-message { width: 100%;
overflow-wrap: break-word;
} resize: none;
overflow-x: wrap;
.chat-message > strong, overflow-y: scroll;
#viewer-list strong { }
color: var(--user-color, var(--default-user-color));
} button:not(.plyr button) {
background-color: var(--accent);
/* border: var(--accent);
@supports (-webkit-background-clip: text) { border-radius: 6px;
.chat-message > strong, color: #fff;
#viewer-list strong { padding: 0.5em 1em;
background: linear-gradient(var(--fg-transparent), var(--fg-transparent)), display: inline-block;
linear-gradient( font-weight: 400;
var(--user-color, var(--default-user-color)), text-align: center;
var(--user-color, var(--default-user-color)) white-space: nowrap;
); vertical-align: middle;
-webkit-background-clip: text;
color: transparent !important; font-family: sans-serif;
} font-size: 1em;
} width: 100%;
*/
user-select: none;
.chat-message.user-join, border: 1px solid rgba(0, 0, 0, 0);
.chat-message.user-leave, line-height: 1.5;
.chat-message.ping { cursor: pointer;
font-style: italic; margin: 0.5em 0;
} }
.chat-message.set-time, button:disabled {
.chat-message.set-playing { filter: saturate(0.75);
font-style: italic; opacity: 0.75;
text-align: right; cursor: default;
font-size: 0.85em; }
}
button.small-button {
.chat-message.command-message { font-size: 0.75em;
font-size: 0.85em; padding-top: 0;
} padding-bottom: 0;
}
.chat-message.set-time > strong,
.chat-message.set-playing > strong { .subtitle-track-group {
color: unset !important; display: flex;
} }
.emoji { .subtitle-track-group > * {
width: 2ch; margin-top: 0 !important;
height: 2ch; margin-bottom: 0 !important;
object-fit: contain; margin-right: 1ch !important;
margin-bottom: -0.35ch; }
}
#pre-join-controls,
#chatbox { #create-controls {
padding: 0.5em 1em; margin: 0;
overflow-y: scroll; flex-grow: 1;
flex-shrink: 1; overflow-y: auto;
flex-grow: 1; display: flex;
} flex-direction: column;
align-items: center;
#viewer-list { justify-content: center;
padding: 0.5em 1em; }
/* TODO: turn this into max-height instead of fixed height without breaking the chatbox height */
overflow-y: scroll; #join-session-form,
border-bottom: var(--fg-transparent); #create-session-form {
border-bottom-style: solid; width: 500px;
max-height: 4rem; max-width: 100%;
flex-shrink: 0; padding: 1rem;
} }
#chatbox-container { #join-session-form > *:first-child,
background-color: var(--bg); #create-session-form > *:first-child {
flex-direction: column; margin-top: 0;
flex-grow: 1; }
flex-shrink: 1;
flex-basis: 36ch; #post-create-message {
min-width: 36ch; display: none;
overflow: hidden; width: 100%;
} font-size: 0.85em;
}
#chatbox-send {
padding: 0 1em; #chatbox-container {
padding-bottom: 0.5em; display: none;
position: relative; }
}
.chat-message {
#chatbox-send > input { overflow-wrap: break-word;
font-size: 0.75em; margin-bottom: 0.125rem;
width: 100%; }
}
.chat-message > strong,
#emoji-autocomplete { #viewer-list strong {
position: absolute; color: var(--user-color, var(--default-user-color));
bottom: 3.25rem; }
background-image: var(--autocomplete-bg);
border-radius: 6px; .chat-message.user-join,
width: calc(100% - 2rem); .chat-message.user-leave,
max-height: 8.5rem; .chat-message.ping {
overflow-y: auto; font-style: italic;
clip-path: inset(0 0 0 0 round 8px); }
}
.chat-message.set-time,
#emoji-autocomplete:empty { .chat-message.set-playing,
display: none; .chat-message.join-session {
} font-style: italic;
text-align: right;
.emoji-option { font-size: 0.85em;
background: transparent; }
font-size: 0.75rem;
text-align: left; .chat-message.command-message {
margin: 0 0.25rem; font-size: 0.85em;
border-radius: 4px; }
width: calc(100% - 0.5rem);
display: flex; .chat-message.set-time > strong,
align-items: center; .chat-message.set-playing > strong,
padding: 0.25rem 0.5rem; .chat-message.join-session > strong {
scroll-margin: 0.25rem; color: unset !important;
} }
.emoji-option:first-child {
margin-top: 0.25rem; .emoji {
} width: 2ch;
.emoji-option:last-child { height: 2ch;
margin-bottom: 0.25rem; object-fit: contain;
} margin-bottom: -0.35ch;
}
.emoji-option .emoji {
width: 1.25rem; #chatbox {
height: 1.25rem; padding: 0.5em 1em;
margin: 0 0.5rem 0 0; overflow-y: scroll;
font-size: 2.25ch; flex-shrink: 1;
display: flex; flex-grow: 1;
align-items: center; }
justify-content: center;
overflow: hidden; #viewer-list {
flex-shrink: 0; padding: 0.5em 1em;
} /* TODO: turn this into max-height instead of fixed height without breaking the chatbox height */
overflow-y: scroll;
.emoji-option.selected { border-bottom: var(--fg-transparent);
background: var(--fg-transparent); border-bottom-style: solid;
} max-height: 4rem;
flex-shrink: 0;
#join-session-colour { }
-moz-appearance: none;
-webkit-appearance: none; #chatbox-container {
appearance: none; background-color: var(--bg);
border: none; flex-direction: column;
padding: 0; flex-grow: 1;
border-radius: 6px; flex-shrink: 1;
overflow: hidden; flex-basis: 36ch;
margin: 0.5em 0; min-width: 36ch;
height: 2rem; overflow: hidden;
width: 2.5rem; }
cursor: pointer;
} #chatbox-send {
padding: 0 1em;
input[type="color"]::-moz-color-swatch, padding-bottom: 0.5em;
input[type="color"]::-webkit-color-swatch, position: relative;
input[type="color"]::-webkit-color-swatch-wrapper { }
/* This *should* be working in Chrome, but it doesn't for reasons that are beyond me. */
border: none; #chatbox-send > input {
margin: 0; font-size: 0.75em;
padding: 0; width: 100%;
} }
@media (min-aspect-ratio: 4/3) { #emoji-autocomplete {
body { position: absolute;
flex-direction: row; bottom: 3.25rem;
} background-image: var(--autocomplete-bg);
border-radius: 6px;
#chatbox-container { width: calc(100% - 2rem);
height: 100vh !important; max-height: 8.5rem;
flex-grow: 0; overflow-y: auto;
} clip-path: inset(0 0 0 0 round 8px);
}
#video-container {
flex-grow: 1; #emoji-autocomplete:empty {
} display: none;
}
#chatbox {
height: calc(100vh - 5em - 4em) !important; .emoji-option:not(:root) {
} background: transparent;
} font-size: 0.75rem;
text-align: left;
margin: 0 0.25rem;
border-radius: 4px;
width: calc(100% - 0.5rem);
display: flex;
align-items: center;
padding: 0.25rem 0.5rem;
scroll-margin: 0.25rem;
}
.emoji-option:first-child {
margin-top: 0.25rem;
}
.emoji-option:last-child {
margin-bottom: 0.25rem;
}
.emoji-option .emoji {
width: 1.25rem;
height: 1.25rem;
margin: 0 0.5rem 0 0;
font-size: 2.25ch;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
flex-shrink: 0;
}
.emoji-name {
overflow: hidden;
text-overflow: ellipsis;
}
.emoji-option.selected {
background: var(--fg-transparent);
}
#join-session-colour {
-moz-appearance: none;
-webkit-appearance: none;
appearance: none;
border: none;
padding: 0;
border-radius: 6px;
overflow: hidden;
margin: 0.5em 0;
height: 2rem;
width: 2.5rem;
cursor: pointer;
}
input[type="color"]::-moz-color-swatch {
border: none;
margin: 0;
padding: 0;
}
input[type="color"]::-webkit-color-swatch {
border: none;
margin: 0;
padding: 0;
}
input[type="color"]::-webkit-color-swatch-wrapper {
border: none;
margin: 0;
padding: 0;
}
@media (min-aspect-ratio: 4/3) {
body {
flex-direction: row;
}
#chatbox-container {
height: 100vh !important;
flex-grow: 0;
}
#video-container {
flex-grow: 1;
}
#chatbox {
height: calc(100vh - 5em - 4em) !important;
}
}

View File

@ -1,52 +1,52 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize)] #[derive(Clone, Serialize, Deserialize)]
pub struct Viewer { pub struct Viewer {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub nickname: Option<String>, pub nickname: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub colour: Option<String>, pub colour: Option<String>,
} }
#[derive(Clone, Serialize, Deserialize)] #[derive(Clone, Serialize, Deserialize)]
#[serde(tag = "op", content = "data")] #[serde(tag = "op", content = "data")]
pub enum WatchEventData { pub enum WatchEventData {
SetPlaying { SetPlaying {
playing: bool, playing: bool,
time: u64, time: u64,
}, },
SetTime { SetTime {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
from: Option<u64>, from: Option<u64>,
to: u64, to: u64,
}, },
UserJoin, UserJoin,
UserLeave, UserLeave,
ChatMessage(String), ChatMessage(String),
Ping(String), Ping(String),
UpdateViewerList(Vec<Viewer>), UpdateViewerList(Vec<Viewer>),
} }
#[derive(Clone, Serialize, Deserialize)] #[derive(Clone, Serialize, Deserialize)]
pub struct WatchEvent { pub struct WatchEvent {
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub user: Option<String>, pub user: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub colour: Option<String>, pub colour: Option<String>,
#[serde(flatten)] #[serde(flatten)]
pub data: WatchEventData, pub data: WatchEventData,
#[serde(default)] #[serde(default)]
pub reflected: bool, pub reflected: bool,
} }
impl WatchEvent { impl WatchEvent {
pub fn new(user: String, colour: String, data: WatchEventData) -> Self { pub fn new(user: String, colour: String, data: WatchEventData) -> Self {
WatchEvent { WatchEvent {
user: Some(user), user: Some(user),
colour: Some(colour), colour: Some(colour),
data, data,
reflected: false, reflected: false,
} }
} }
} }

View File

@ -1,132 +1,132 @@
use serde_json::json; use serde_json::json;
use std::net::IpAddr; use std::net::IpAddr;
use uuid::Uuid; use uuid::Uuid;
use warb::{hyper::StatusCode, Filter, Reply}; use warb::{hyper::StatusCode, Filter, Reply};
use warp as warb; // i think it's funny use warp as warb; // i think it's funny
mod events; mod events;
mod utils; mod utils;
mod viewer_connection; mod viewer_connection;
mod watch_session; mod watch_session;
use serde::Deserialize; use serde::Deserialize;
use crate::{ use crate::{
viewer_connection::ws_subscribe, viewer_connection::ws_subscribe,
watch_session::{get_session, SubtitleTrack, WatchSession, SESSIONS}, watch_session::{get_session, SubtitleTrack, WatchSession, SESSIONS},
}; };
#[derive(Deserialize)] #[derive(Deserialize)]
struct StartSessionBody { struct StartSessionBody {
video_url: String, video_url: String,
#[serde(default = "Vec::new")] #[serde(default = "Vec::new")]
subtitle_tracks: Vec<SubtitleTrack>, subtitle_tracks: Vec<SubtitleTrack>,
} }
#[derive(Deserialize)] #[derive(Deserialize)]
struct SubscribeQuery { struct SubscribeQuery {
nickname: String, nickname: String,
colour: String, colour: String,
} }
async fn get_emoji_list() -> Result<impl warb::Reply, warb::Rejection> { async fn get_emoji_list() -> Result<impl warb::Reply, warb::Rejection> {
use tokio_stream::{wrappers::ReadDirStream, StreamExt}; use tokio_stream::{wrappers::ReadDirStream, StreamExt};
let dir = tokio::fs::read_dir("frontend/emojis") let dir = tokio::fs::read_dir("frontend/emojis")
.await .await
.expect("Couldn't read emojis directory!"); .expect("Couldn't read emojis directory!");
let files = ReadDirStream::new(dir) let files = ReadDirStream::new(dir)
.filter_map(|r| r.ok()) .filter_map(|r| r.ok())
.map(|e| e.file_name().to_string_lossy().to_string()) .map(|e| e.file_name().to_string_lossy().to_string())
.collect::<Vec<_>>() .collect::<Vec<_>>()
.await; .await;
Ok(warb::reply::json(&files)) Ok(warb::reply::json(&files))
} }
#[tokio::main] #[tokio::main]
async fn main() { async fn main() {
let start_session_route = warb::path!("start_session") let start_session_route = warb::path!("start_session")
.and(warb::path::end()) .and(warb::path::end())
.and(warb::post()) .and(warb::post())
.and(warb::body::json()) .and(warb::body::json())
.map(|body: StartSessionBody| { .map(|body: StartSessionBody| {
let mut sessions = SESSIONS.lock().unwrap(); let mut sessions = SESSIONS.lock().unwrap();
let session_uuid = Uuid::new_v4(); let session_uuid = Uuid::new_v4();
let session = WatchSession::new(body.video_url, body.subtitle_tracks); let session = WatchSession::new(body.video_url, body.subtitle_tracks);
let session_view = session.view(); let session_view = session.view();
sessions.insert(session_uuid, session); sessions.insert(session_uuid, session);
warb::reply::json(&json!({ "id": session_uuid.to_string(), "session": session_view })) warb::reply::json(&json!({ "id": session_uuid.to_string(), "session": session_view }))
}); });
let get_emoji_route = warb::path!("emojis").and_then(get_emoji_list); let get_emoji_route = warb::path!("emojos").and_then(get_emoji_list);
enum RequestedSession { enum RequestedSession {
Session(Uuid, WatchSession), Session(Uuid, WatchSession),
Error(warb::reply::WithStatus<warb::reply::Json>), Error(warb::reply::WithStatus<warb::reply::Json>),
} }
let get_running_session = warb::path::path("sess") let get_running_session = warb::path::path("sess")
.and(warb::path::param::<String>()) .and(warb::path::param::<String>())
.map(|session_id: String| { .map(|session_id: String| {
if let Ok(uuid) = Uuid::parse_str(&session_id) { if let Ok(uuid) = Uuid::parse_str(&session_id) {
get_session(uuid) get_session(uuid)
.map(|sess| RequestedSession::Session(uuid, sess)) .map(|sess| RequestedSession::Session(uuid, sess))
.unwrap_or_else(|| { .unwrap_or_else(|| {
RequestedSession::Error(warb::reply::with_status( RequestedSession::Error(warb::reply::with_status(
warb::reply::json(&json!({ "error": "session does not exist" })), warb::reply::json(&json!({ "error": "session does not exist" })),
StatusCode::NOT_FOUND, StatusCode::NOT_FOUND,
)) ))
}) })
} else { } else {
RequestedSession::Error(warb::reply::with_status( RequestedSession::Error(warb::reply::with_status(
warb::reply::json(&json!({ "error": "invalid session UUID" })), warb::reply::json(&json!({ "error": "invalid session UUID" })),
StatusCode::BAD_REQUEST, StatusCode::BAD_REQUEST,
)) ))
} }
}); });
let get_status_route = get_running_session let get_status_route = get_running_session
.and(warb::path::end()) .and(warb::path::end())
.map(|requested_session| match requested_session { .map(|requested_session| match requested_session {
RequestedSession::Session(_, sess) => { RequestedSession::Session(_, sess) => {
warb::reply::with_status(warb::reply::json(&sess.view()), StatusCode::OK) warb::reply::with_status(warb::reply::json(&sess.view()), StatusCode::OK)
} }
RequestedSession::Error(e) => e, RequestedSession::Error(e) => e,
}); });
let ws_subscribe_route = get_running_session let ws_subscribe_route = get_running_session
.and(warb::path!("subscribe")) .and(warb::path!("subscribe"))
.and(warb::query()) .and(warb::query())
.and(warb::ws()) .and(warb::ws())
.map( .map(
|requested_session, query: SubscribeQuery, ws: warb::ws::Ws| match requested_session { |requested_session, query: SubscribeQuery, ws: warb::ws::Ws| match requested_session {
RequestedSession::Session(uuid, _) => ws RequestedSession::Session(uuid, _) => ws
.on_upgrade(move |ws| ws_subscribe(uuid, query.nickname, query.colour, ws)) .on_upgrade(move |ws| ws_subscribe(uuid, query.nickname, query.colour, ws))
.into_response(), .into_response(),
RequestedSession::Error(error_response) => error_response.into_response(), RequestedSession::Error(error_response) => error_response.into_response(),
}, },
); );
let routes = start_session_route let routes = start_session_route
.or(get_status_route) .or(get_status_route)
.or(ws_subscribe_route) .or(ws_subscribe_route)
.or(get_emoji_route) .or(get_emoji_route)
.or(warb::path::end().and(warb::fs::file("frontend/index.html"))) .or(warb::path::end().and(warb::fs::file("frontend/index.html")))
.or(warb::fs::dir("frontend")); .or(warb::fs::dir("frontend"));
let ip = std::env::var("IP") let ip = std::env::var("IP")
.ok() .ok()
.and_then(|s| s.parse::<IpAddr>().ok()) .and_then(|s| s.parse::<IpAddr>().ok())
.unwrap_or_else(|| [127, 0, 0, 1].into()); .unwrap_or_else(|| [127, 0, 0, 1].into());
let port = std::env::var("PORT") let port = std::env::var("PORT")
.ok() .ok()
.and_then(|s| s.parse::<u16>().ok()) .and_then(|s| s.parse::<u16>().ok())
.unwrap_or(3000); .unwrap_or(3000);
println!("Listening at http://{}:{} ...", &ip, &port); println!("Listening at http://{}:{} ...", &ip, &port);
warb::serve(routes).run((ip, port)).await; warb::serve(routes).run((ip, port)).await;
} }

View File

@ -1,156 +1,156 @@
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use std::{ use std::{
collections::HashMap, collections::HashMap,
sync::atomic::{AtomicUsize, Ordering}, sync::atomic::{AtomicUsize, Ordering},
}; };
use futures::{SinkExt, StreamExt, TryFutureExt}; use futures::{SinkExt, StreamExt, TryFutureExt};
use tokio::sync::{ use tokio::sync::{
mpsc::{self, UnboundedSender}, mpsc::{self, UnboundedSender},
RwLock, RwLock,
}; };
use tokio_stream::wrappers::UnboundedReceiverStream; use tokio_stream::wrappers::UnboundedReceiverStream;
use uuid::Uuid; use uuid::Uuid;
use warp::ws::{Message, WebSocket}; use warp::ws::{Message, WebSocket};
use crate::{ use crate::{
events::{Viewer, WatchEvent, WatchEventData}, events::{Viewer, WatchEvent, WatchEventData},
utils::truncate_str, utils::truncate_str,
watch_session::{get_session, handle_watch_event_data}, watch_session::{get_session, handle_watch_event_data},
}; };
static CONNECTED_VIEWERS: Lazy<RwLock<HashMap<usize, ConnectedViewer>>> = static CONNECTED_VIEWERS: Lazy<RwLock<HashMap<usize, ConnectedViewer>>> =
Lazy::new(|| RwLock::new(HashMap::new())); Lazy::new(|| RwLock::new(HashMap::new()));
static NEXT_VIEWER_ID: AtomicUsize = AtomicUsize::new(1); static NEXT_VIEWER_ID: AtomicUsize = AtomicUsize::new(1);
pub struct ConnectedViewer { pub struct ConnectedViewer {
pub session: Uuid, pub session: Uuid,
pub viewer_id: usize, pub viewer_id: usize,
pub tx: UnboundedSender<WatchEvent>, pub tx: UnboundedSender<WatchEvent>,
pub nickname: Option<String>, pub nickname: Option<String>,
pub colour: Option<String>, pub colour: Option<String>,
} }
pub async fn ws_subscribe(session_uuid: Uuid, nickname: String, colour: String, ws: WebSocket) { pub async fn ws_subscribe(session_uuid: Uuid, nickname: String, colour: String, ws: WebSocket) {
let viewer_id = NEXT_VIEWER_ID.fetch_add(1, Ordering::Relaxed); let viewer_id = NEXT_VIEWER_ID.fetch_add(1, Ordering::Relaxed);
let (mut viewer_ws_tx, mut viewer_ws_rx) = ws.split(); let (mut viewer_ws_tx, mut viewer_ws_rx) = ws.split();
let (tx, rx) = mpsc::unbounded_channel::<WatchEvent>(); let (tx, rx) = mpsc::unbounded_channel::<WatchEvent>();
let mut rx = UnboundedReceiverStream::new(rx); let mut rx = UnboundedReceiverStream::new(rx);
tokio::task::spawn(async move { tokio::task::spawn(async move {
while let Some(event) = rx.next().await { while let Some(event) = rx.next().await {
viewer_ws_tx viewer_ws_tx
.send(Message::text( .send(Message::text(
serde_json::to_string(&event).expect("couldn't convert WatchEvent into JSON"), serde_json::to_string(&event).expect("couldn't convert WatchEvent into JSON"),
)) ))
.unwrap_or_else(|e| eprintln!("ws send error: {}", e)) .unwrap_or_else(|e| eprintln!("ws send error: {}", e))
.await; .await;
} }
}); });
let mut colour = colour; let mut colour = colour;
if colour.len() != 6 || !colour.chars().all(|x| x.is_ascii_hexdigit()) { if colour.len() != 6 || !colour.chars().all(|x| x.is_ascii_hexdigit()) {
colour = String::from("7ed0ff"); colour = String::from("7ed0ff");
} }
let nickname = truncate_str(&nickname, 50).to_string(); let nickname = truncate_str(&nickname, 50).to_string();
CONNECTED_VIEWERS.write().await.insert( CONNECTED_VIEWERS.write().await.insert(
viewer_id, viewer_id,
ConnectedViewer { ConnectedViewer {
viewer_id, viewer_id,
session: session_uuid, session: session_uuid,
tx, tx,
nickname: Some(nickname.clone()), nickname: Some(nickname.clone()),
colour: Some(colour.clone()), colour: Some(colour.clone()),
}, },
); );
ws_publish( ws_publish(
session_uuid, session_uuid,
None, None,
WatchEvent::new(nickname.clone(), colour.clone(), WatchEventData::UserJoin), WatchEvent::new(nickname.clone(), colour.clone(), WatchEventData::UserJoin),
) )
.await; .await;
update_viewer_list(session_uuid).await; update_viewer_list(session_uuid).await;
while let Some(Ok(message)) = viewer_ws_rx.next().await { while let Some(Ok(message)) = viewer_ws_rx.next().await {
let event: WatchEventData = match message let event: WatchEventData = match message
.to_str() .to_str()
.ok() .ok()
.and_then(|s| serde_json::from_str(s).ok()) .and_then(|s| serde_json::from_str(s).ok())
{ {
Some(e) => e, Some(e) => e,
None => continue, None => continue,
}; };
let session = &mut get_session(session_uuid).unwrap(); let session = &mut get_session(session_uuid).unwrap();
// server side event modification where neccessary // server side event modification where neccessary
let event: WatchEventData = match event { let event: WatchEventData = match event {
WatchEventData::SetTime { from: _, to } => WatchEventData::SetTime { WatchEventData::SetTime { from: _, to } => WatchEventData::SetTime {
from: Some(session.get_time_ms()), from: Some(session.get_time_ms()),
to, to,
}, },
_ => event, _ => event,
}; };
handle_watch_event_data(session_uuid, session, event.clone()); handle_watch_event_data(session_uuid, session, event.clone());
ws_publish( ws_publish(
session_uuid, session_uuid,
Some(viewer_id), Some(viewer_id),
WatchEvent::new(nickname.clone(), colour.clone(), event), WatchEvent::new(nickname.clone(), colour.clone(), event),
) )
.await; .await;
} }
ws_publish( ws_publish(
session_uuid, session_uuid,
None, None,
WatchEvent::new(nickname.clone(), colour.clone(), WatchEventData::UserLeave), WatchEvent::new(nickname.clone(), colour.clone(), WatchEventData::UserLeave),
) )
.await; .await;
CONNECTED_VIEWERS.write().await.remove(&viewer_id); CONNECTED_VIEWERS.write().await.remove(&viewer_id);
update_viewer_list(session_uuid).await; update_viewer_list(session_uuid).await;
} }
pub async fn ws_publish(session_uuid: Uuid, skip_viewer_id: Option<usize>, event: WatchEvent) { pub async fn ws_publish(session_uuid: Uuid, skip_viewer_id: Option<usize>, event: WatchEvent) {
for viewer in CONNECTED_VIEWERS.read().await.values() { for viewer in CONNECTED_VIEWERS.read().await.values() {
if viewer.session != session_uuid { if viewer.session != session_uuid {
continue; continue;
} }
let _ = viewer.tx.send(WatchEvent { let _ = viewer.tx.send(WatchEvent {
reflected: skip_viewer_id == Some(viewer.viewer_id), reflected: skip_viewer_id == Some(viewer.viewer_id),
..event.clone() ..event.clone()
}); });
} }
} }
async fn update_viewer_list(session_uuid: Uuid) { async fn update_viewer_list(session_uuid: Uuid) {
let mut viewers = Vec::new(); let mut viewers = Vec::new();
for viewer in CONNECTED_VIEWERS.read().await.values() { for viewer in CONNECTED_VIEWERS.read().await.values() {
if viewer.session == session_uuid { if viewer.session == session_uuid {
viewers.push(Viewer { viewers.push(Viewer {
nickname: viewer.nickname.clone(), nickname: viewer.nickname.clone(),
colour: viewer.colour.clone(), colour: viewer.colour.clone(),
}) })
} }
} }
ws_publish( ws_publish(
session_uuid, session_uuid,
None, None,
WatchEvent::new( WatchEvent::new(
String::from("server"), String::from("server"),
String::from(""), String::from(""),
WatchEventData::UpdateViewerList(viewers), WatchEventData::UpdateViewerList(viewers),
), ),
) )
.await; .await;
} }

View File

@ -1,96 +1,96 @@
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{collections::HashMap, sync::Mutex, time::Instant}; use std::{collections::HashMap, sync::Mutex, time::Instant};
use uuid::Uuid; use uuid::Uuid;
use crate::events::WatchEventData; use crate::events::WatchEventData;
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Deserialize, Clone)]
pub struct SubtitleTrack { pub struct SubtitleTrack {
pub url: String, pub url: String,
pub name: String, pub name: String,
} }
#[derive(Clone)] #[derive(Clone)]
pub struct WatchSession { pub struct WatchSession {
pub video_url: String, pub video_url: String,
pub subtitle_tracks: Vec<SubtitleTrack>, pub subtitle_tracks: Vec<SubtitleTrack>,
is_playing: bool, is_playing: bool,
playing_from_timestamp: u64, playing_from_timestamp: u64,
playing_from_instant: Instant, playing_from_instant: Instant,
} }
#[derive(Serialize)] #[derive(Serialize)]
pub struct WatchSessionView { pub struct WatchSessionView {
pub video_url: String, pub video_url: String,
pub subtitle_tracks: Vec<SubtitleTrack>, pub subtitle_tracks: Vec<SubtitleTrack>,
pub current_time_ms: u64, pub current_time_ms: u64,
pub is_playing: bool, pub is_playing: bool,
} }
impl WatchSession { impl WatchSession {
pub fn new(video_url: String, subtitle_tracks: Vec<SubtitleTrack>) -> Self { pub fn new(video_url: String, subtitle_tracks: Vec<SubtitleTrack>) -> Self {
WatchSession { WatchSession {
video_url, video_url,
subtitle_tracks, subtitle_tracks,
is_playing: false, is_playing: false,
playing_from_timestamp: 0, playing_from_timestamp: 0,
playing_from_instant: Instant::now(), playing_from_instant: Instant::now(),
} }
} }
pub fn view(&self) -> WatchSessionView { pub fn view(&self) -> WatchSessionView {
WatchSessionView { WatchSessionView {
video_url: self.video_url.clone(), video_url: self.video_url.clone(),
subtitle_tracks: self.subtitle_tracks.clone(), subtitle_tracks: self.subtitle_tracks.clone(),
current_time_ms: self.get_time_ms() as u64, current_time_ms: self.get_time_ms() as u64,
is_playing: self.is_playing, is_playing: self.is_playing,
} }
} }
pub fn get_time_ms(&self) -> u64 { pub fn get_time_ms(&self) -> u64 {
if !self.is_playing { if !self.is_playing {
return self.playing_from_timestamp; return self.playing_from_timestamp;
} }
self.playing_from_timestamp + self.playing_from_instant.elapsed().as_millis() as u64 self.playing_from_timestamp + self.playing_from_instant.elapsed().as_millis() as u64
} }
pub fn set_time_ms(&mut self, time_ms: u64) { pub fn set_time_ms(&mut self, time_ms: u64) {
self.playing_from_timestamp = time_ms; self.playing_from_timestamp = time_ms;
self.playing_from_instant = Instant::now(); self.playing_from_instant = Instant::now();
} }
pub fn set_playing(&mut self, playing: bool, time_ms: u64) { pub fn set_playing(&mut self, playing: bool, time_ms: u64) {
self.set_time_ms(time_ms); self.set_time_ms(time_ms);
self.is_playing = playing; self.is_playing = playing;
} }
} }
pub static SESSIONS: Lazy<Mutex<HashMap<Uuid, WatchSession>>> = pub static SESSIONS: Lazy<Mutex<HashMap<Uuid, WatchSession>>> =
Lazy::new(|| Mutex::new(HashMap::new())); Lazy::new(|| Mutex::new(HashMap::new()));
pub fn get_session(uuid: Uuid) -> Option<WatchSession> { pub fn get_session(uuid: Uuid) -> Option<WatchSession> {
SESSIONS.lock().unwrap().get(&uuid).cloned() SESSIONS.lock().unwrap().get(&uuid).cloned()
} }
pub fn handle_watch_event_data( pub fn handle_watch_event_data(
uuid: Uuid, uuid: Uuid,
watch_session: &mut WatchSession, watch_session: &mut WatchSession,
event: WatchEventData, event: WatchEventData,
) { ) {
match event { match event {
WatchEventData::SetPlaying { playing, time } => { WatchEventData::SetPlaying { playing, time } => {
watch_session.set_playing(playing, time); watch_session.set_playing(playing, time);
} }
WatchEventData::SetTime { from: _, to } => { WatchEventData::SetTime { from: _, to } => {
watch_session.set_time_ms(to); watch_session.set_time_ms(to);
} }
_ => {} _ => {}
}; };
let _ = SESSIONS.lock().unwrap().insert(uuid, watch_session.clone()); let _ = SESSIONS.lock().unwrap().insert(uuid, watch_session.clone());
} }