use plyr for video controls

easrng 2023-02-01 20:18:46 -05:00
parent e43184ab49
commit 1bd7071cec
16 changed files with 1416 additions and 1437 deletions

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=bfdcf2" /> <link rel="stylesheet" href="/styles.css?v=bfdcf2" />
</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=bfdcf2"></script> <script type="module" src="/create.mjs?v=bfdcf2"></script>
</body> </body>
</html> </html>

View File

@ -1,11 +1,11 @@
import { setupCreateSessionForm } from "./lib/create-session.mjs?v=bfdcf2"; import { setupCreateSessionForm } from "./lib/create-session.mjs?v=bfdcf2";
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);
} }

View File

@ -1,84 +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=bfdcf2" /> <link rel="stylesheet" href="/lib/plyr-3.7.3.css" />
</head> <link rel="stylesheet" href="/styles.css?v=bfdcf2" />
</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 id="join-session-colour-label" for="join-session-colour">
Personal Colour: <label id="join-session-colour-label" for="join-session-colour">
</label> Personal Colour:
<input type="color" id="join-session-colour" value="#ffffff" required /> </label>
<input type="color" id="join-session-colour" value="#ffffff" required />
<label for="join-session-id">Session ID:</label>
<input <label for="join-session-id">Session ID:</label>
type="text" <input
id="join-session-id" type="text"
placeholder="123e4567-e89b-12d3-a456-426614174000" id="join-session-id"
required placeholder="123e4567-e89b-12d3-a456-426614174000"
/> required
<button id="join-session-button">Join</button> />
<button id="join-session-button">Join</button>
<p>
No session to join? <p>
<a href="/create.html">Create a session</a> instead. No session to join?
</p> <a href="/create.html">Create a session</a> instead.
</form> </p>
</div> </form>
</div>
<div id="video-container"></div>
<div id="chatbox-container"> <div id="video-container"></div>
<div id="viewer-list"></div> <div id="chatbox-container">
<div id="chatbox"></div> <div id="viewer-list"></div>
<form id="chatbox-send"> <div id="chatbox"></div>
<input <form id="chatbox-send">
type="text" <input
placeholder="Message... (/help for commands)" type="text"
list="emoji-autocomplete" placeholder="Message... (/help for commands)"
/> list="emoji-autocomplete"
<div id="emoji-autocomplete"></div> />
<!-- DO NOT ADD SPACING INSIDE THE TAG IT WILL BREAK THE CSS kthxbye --> <div id="emoji-autocomplete"></div>
</form> <!-- DO NOT ADD SPACING INSIDE THE TAG IT WILL BREAK THE CSS kthxbye -->
</div> </form>
</div>
<script type="module" src="/main.mjs?v=bfdcf2"></script>
<script> <script type="module" src="/main.mjs?v=bfdcf2"></script>
const updateColourLabel = () => { <script>
const colour = document.querySelector("#join-session-colour").value; const updateColourLabel = () => {
document.querySelector( const colour = document.querySelector("#join-session-colour").value;
"#join-session-colour-label" document.querySelector(
).textContent = `Personal Colour: ${colour}`; "#join-session-colour-label"
}; ).textContent = `Personal Colour: ${colour}`;
};
document
.querySelector("#join-session-colour") document
.addEventListener("input", updateColourLabel); .querySelector("#join-session-colour")
updateColourLabel(); .addEventListener("input", updateColourLabel);
</script> updateColourLabel();
</body> </script>
</html> </body>
</html>

View File

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

View File

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

View File

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

View File

@ -77,4 +77,3 @@ export const pling = () => {
thirdBeep.start(ctx.currentTime + thirdBeepOffset); thirdBeep.start(ctx.currentTime + thirdBeepOffset);
thirdBeep.stop(ctx.currentTime + (thirdBeepOffset + duration)); 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,71 +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._closing = false; this._closing = false;
this._connect(true); this._connect(true);
} }
_connect(first) { _connect(first) {
if (this._socket) if (this._socket)
try { try {
this._socket.close(); this._socket.close();
} catch (e) {} } catch (e) {}
try { try {
this._socket = new WebSocket(this.url.href); this._socket = new WebSocket(this.url.href);
} catch (e) { } catch (e) {
this._reconnecting = false; this._reconnecting = false;
return this._reconnect(); return this._reconnect();
} }
this._socket.addEventListener("close", () => this._reconnect()); this._socket.addEventListener("close", () => this._reconnect());
this._socket.addEventListener("error", () => this._reconnect()); this._socket.addEventListener("error", () => this._reconnect());
this._socket.addEventListener("message", ({ data }) => { this._socket.addEventListener("message", ({ data }) => {
this._eventTarget.dispatchEvent(new MessageEvent("message", { data })); this._eventTarget.dispatchEvent(new MessageEvent("message", { data }));
}); });
this._socket.addEventListener("open", (e) => { this._socket.addEventListener("open", (e) => {
if (first) this._eventTarget.dispatchEvent(new Event("open")); if (first) this._eventTarget.dispatchEvent(new Event("open"));
if (this._reconnecting) if (this._reconnecting)
this._eventTarget.dispatchEvent(new Event("reconnected")); this._eventTarget.dispatchEvent(new Event("reconnected"));
this._reconnecting = false; this._reconnecting = false;
this._backoff = 250; this._backoff = 250;
this.connected = true; this.connected = true;
while (this._unsent.length > 0) this._socket.send(this._unsent.shift()); while (this._unsent.length > 0) this._socket.send(this._unsent.shift());
}); });
} }
_reconnect() { _reconnect() {
if (this._closing) return; if (this._closing) return;
if (this._reconnecting) return; if (this._reconnecting) return;
this._eventTarget.dispatchEvent(new Event("reconnecting")); this._eventTarget.dispatchEvent(new Event("reconnecting"));
this._reconnecting = true; this._reconnecting = true;
this.connected = false; this.connected = false;
this._backoff *= 2; // exponential backoff this._backoff *= 2; // exponential backoff
setTimeout(() => { setTimeout(() => {
this._connect(); this._connect();
}, Math.floor(this._backoff + Math.random() * this._backoff * 0.25 - this._backoff * 0.125)); }, Math.floor(this._backoff + Math.random() * this._backoff * 0.25 - this._backoff * 0.125));
} }
send(message) { send(message) {
if (this.connected) { if (this.connected) {
this._socket.send(message); this._socket.send(message);
} else { } else {
this._unsent.push(message); this._unsent.push(message);
} }
} }
close() { close() {
this._closing = true; this._closing = true;
this._socket.close(); this._socket.close();
} }
addEventListener(...a) { addEventListener(...a) {
return this._eventTarget.addEventListener(...a); return this._eventTarget.addEventListener(...a);
} }
removeEventListener(...a) { removeEventListener(...a) {
return this._eventTarget.removeEventListener(...a); return this._eventTarget.removeEventListener(...a);
} }
} }

View File

@ -1,163 +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 oldVideo = document.getElementById("video"); // enable media button support
if (oldVideo) { navigator.mediaSession.setActionHandler("play", null);
oldVideo.remove(); navigator.mediaSession.setActionHandler("pause", null);
} navigator.mediaSession.setActionHandler("stop", null);
const video = document.createElement("video"); navigator.mediaSession.setActionHandler("seekbackward", null);
video.id = "video"; navigator.mediaSession.setActionHandler("seekforward", null);
video.controls = true; navigator.mediaSession.setActionHandler("seekto", null);
video.autoplay = false; navigator.mediaSession.setActionHandler("previoustrack", null);
video.volume = loadVolume(); navigator.mediaSession.setActionHandler("nexttrack", null);
video.crossOrigin = "anonymous"; } else {
// disable media button support by ignoring the events
video.addEventListener("volumechange", async () => { navigator.mediaSession.setActionHandler("play", () => {});
saveVolume(video.volume); navigator.mediaSession.setActionHandler("pause", () => {});
}); navigator.mediaSession.setActionHandler("stop", () => {});
navigator.mediaSession.setActionHandler("seekbackward", () => {});
const source = document.createElement("source"); navigator.mediaSession.setActionHandler("seekforward", () => {});
source.src = videoUrl; navigator.mediaSession.setActionHandler("seekto", () => {});
navigator.mediaSession.setActionHandler("previoustrack", () => {});
video.appendChild(source); navigator.mediaSession.setActionHandler("nexttrack", () => {});
}
const storedTrack = loadCaptionTrack(); };
let id = 0; setControlsEnabled(controlsEnabled);
for (const { name, url } of subtitles) { lockButton.addEventListener("click", () =>
const track = document.createElement("track"); setControlsEnabled(!controlsEnabled)
track.label = name; );
track.src = url; window.__plyr = player;
track.kind = "captions";
return player;
if (id == storedTrack || storedTrack == -1) { };
track.default = true;
} /**
* @param {string} videoUrl
video.appendChild(track); * @param {{name: string, url: string}[]} subtitles
id++; * @param {number} currentTime
} * @param {boolean} playing
*/
video.textTracks.addEventListener("change", async () => { export const setupVideo = async (
let id = 0; videoUrl,
for (const track of video.textTracks) { subtitles,
if (track.mode != "disabled") { currentTime,
saveCaptionsTrack(id); playing,
return; created
} ) => {
id++; document.querySelector("#pre-join-controls").style["display"] = "none";
} const player = createVideoElement(videoUrl, subtitles, created);
saveCaptionsTrack(-1); player.currentTime = currentTime / 1000.0;
});
try {
// watch for attribute changes on the video object to detect hiding/showing of controls if (playing) {
// as far as i can tell this is the least hacky solutions to get control visibility change events player.play();
const observer = new MutationObserver(async (mutations) => { } else {
for (const mutation of mutations) { player.pause();
if (mutation.attributeName == "controls") { }
if (video.controls) { } catch (err) {
// enable media button support // Auto-play is probably disabled, we should uhhhhhhh do something about it
navigator.mediaSession.setActionHandler("play", null); }
navigator.mediaSession.setActionHandler("pause", null);
navigator.mediaSession.setActionHandler("stop", null); return player;
navigator.mediaSession.setActionHandler("seekbackward", null); };
navigator.mediaSession.setActionHandler("seekforward", null);
navigator.mediaSession.setActionHandler("seekto", null);
navigator.mediaSession.setActionHandler("previoustrack", null);
navigator.mediaSession.setActionHandler("nexttrack", null);
} 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,276 +1,270 @@
import { setupVideo } from "./video.mjs?v=bfdcf2"; import { setupVideo } from "./video.mjs?v=bfdcf2";
import { import {
setupChat, setupChat,
logEventToChat, logEventToChat,
updateViewerList, updateViewerList,
printChatMessage, printChatMessage,
} from "./chat.mjs?v=bfdcf2"; } from "./chat.mjs?v=bfdcf2";
import ReconnectingWebSocket from "./reconnecting-web-socket.mjs"; import ReconnectingWebSocket from "./reconnecting-web-socket.mjs";
import { state } from "./state.mjs"; import { state } from "./state.mjs";
let player;
/** /**
* @param {string} sessionId * @param {string} sessionId
* @param {string} nickname * @param {string} nickname
* @returns {ReconnectingWebSocket} * @returns {ReconnectingWebSocket}
*/ */
const createWebSocket = () => { const createWebSocket = () => {
const wsUrl = new URL( const wsUrl = new URL(
`/sess/${state().sessionId}/subscribe` + `/sess/${state().sessionId}/subscribe` +
`?nickname=${encodeURIComponent(state().nickname)}` + `?nickname=${encodeURIComponent(state().nickname)}` +
`&colour=${encodeURIComponent(state().colour)}`, `&colour=${encodeURIComponent(state().colour)}`,
window.location.href window.location.href
); );
wsUrl.protocol = "ws" + window.location.protocol.slice(4); wsUrl.protocol = "ws" + window.location.protocol.slice(4);
const socket = new ReconnectingWebSocket(wsUrl); const socket = new ReconnectingWebSocket(wsUrl);
return socket; return socket;
}; };
let outgoingDebounce = false; let outgoingDebounce = false;
let outgoingDebounceCallbackId = null; let outgoingDebounceCallbackId = null;
export const setDebounce = () => { export const setDebounce = () => {
outgoingDebounce = true; outgoingDebounce = true;
if (outgoingDebounceCallbackId) { if (outgoingDebounceCallbackId) {
cancelIdleCallback(outgoingDebounceCallbackId); cancelIdleCallback(outgoingDebounceCallbackId);
outgoingDebounceCallbackId = null; outgoingDebounceCallbackId = null;
} }
outgoingDebounceCallbackId = setTimeout(() => { outgoingDebounceCallbackId = setTimeout(() => {
outgoingDebounce = false; outgoingDebounce = false;
}, 500); }, 500);
}; };
export const setVideoTime = (time, video = null) => { export const setVideoTime = (time) => {
if (video == null) { const timeSecs = time / 1000.0;
video = document.querySelector("video"); if (Math.abs(player.currentTime - timeSecs) > 0.5) {
} player.currentTime = timeSecs;
}
const timeSecs = time / 1000.0; };
if (Math.abs(video.currentTime - timeSecs) > 0.5) {
video.currentTime = timeSecs; export const setPlaying = async (playing) => {
} if (playing) {
}; await player.play();
} else {
export const setPlaying = async (playing, video = null) => { player.pause();
if (video == null) { }
video = document.querySelector("video"); };
}
/**
if (playing) { * @param {HTMLVideoElement} video
await video.play(); * @param {ReconnectingWebSocket} socket
} else { */
video.pause(); const setupIncomingEvents = (player, socket) => {
} socket.addEventListener("message", async (messageEvent) => {
}; try {
const event = JSON.parse(messageEvent.data);
/** if (!event.reflected) {
* @param {HTMLVideoElement} video switch (event.op) {
* @param {ReconnectingWebSocket} socket case "SetPlaying":
*/ setDebounce();
const setupIncomingEvents = (video, socket) => {
socket.addEventListener("message", async (messageEvent) => { if (event.data.playing) {
try { await player.play();
const event = JSON.parse(messageEvent.data); } else {
if (!event.reflected) { player.pause();
switch (event.op) { }
case "SetPlaying":
setDebounce(); setVideoTime(event.data.time);
break;
if (event.data.playing) { case "SetTime":
await video.play(); setDebounce();
} else { setVideoTime(event.data);
video.pause(); break;
} case "UpdateViewerList":
updateViewerList(event.data);
setVideoTime(event.data.time, video); break;
break; }
case "SetTime": }
setDebounce();
setVideoTime(event.data, video); logEventToChat(event);
break; } catch (_err) {}
case "UpdateViewerList": });
updateViewerList(event.data); };
break;
} /**
} * @param {Plyr} player
* @param {ReconnectingWebSocket} socket
logEventToChat(event); */
} catch (_err) {} const setupOutgoingEvents = (player, socket) => {
}); const currentVideoTime = () => (player.currentTime * 1000) | 0;
};
player.on("pause", async () => {
/** if (outgoingDebounce || player.elements.inputs.seek.disabled) {
* @param {HTMLVideoElement} video return;
* @param {ReconnectingWebSocket} socket }
*/
const setupOutgoingEvents = (video, socket) => { // don't send a pause event for the video ending
const currentVideoTime = () => (video.currentTime * 1000) | 0; if (player.currentTime == player.duration) {
return;
video.addEventListener("pause", async (event) => { }
if (outgoingDebounce || !video.controls) {
return; socket.send(
} JSON.stringify({
op: "SetPlaying",
// don't send a pause event for the video ending data: {
if (video.currentTime == video.duration) { playing: false,
return; time: currentVideoTime(),
} },
})
socket.send( );
JSON.stringify({ });
op: "SetPlaying",
data: { player.on("play", () => {
playing: false, if (outgoingDebounce || player.elements.inputs.seek.disabled) {
time: currentVideoTime(), return;
}, }
})
); socket.send(
}); JSON.stringify({
op: "SetPlaying",
video.addEventListener("play", (event) => { data: {
if (outgoingDebounce || !video.controls) { playing: true,
return; time: currentVideoTime(),
} },
})
socket.send( );
JSON.stringify({ });
op: "SetPlaying",
data: { let firstSeekComplete = false;
playing: true, player.on("seeked", async (event) => {
time: currentVideoTime(), if (!firstSeekComplete) {
}, // The first seeked event is performed by the browser when the video is loading
}) firstSeekComplete = true;
); return;
}); }
let firstSeekComplete = false; if (outgoingDebounce || player.elements.inputs.seek.disabled) {
video.addEventListener("seeked", async (event) => { return;
if (!firstSeekComplete) { }
// The first seeked event is performed by the browser when the video is loading
firstSeekComplete = true; socket.send(
return; JSON.stringify({
} op: "SetTime",
data: {
if (outgoingDebounce || !video.controls) { to: currentVideoTime(),
return; },
} })
);
socket.send( });
JSON.stringify({ };
op: "SetTime",
data: { export const joinSession = async (created) => {
to: currentVideoTime(), 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");
export const joinSession = async () => { messageContent.appendChild(document.createTextNode("joining new session "));
if (state().activeSession) { messageContent.appendChild(document.createTextNode(state().sessionId));
if (state().activeSession === state().sessionId) {
// we are already in this session, dont rejoin printChatMessage("join-session", "watch-party", "#fffff", messageContent);
return; }
} state().activeSession = state().sessionId;
// we are joining a new session from an existing session
const messageContent = document.createElement("span"); // try { // we are handling errors in the join form.
messageContent.appendChild(document.createTextNode("joining new session ")); const genericConnectionError = new Error(
messageContent.appendChild(document.createTextNode(state().sessionId)); "There was an issue getting the session information."
);
printChatMessage("join-session", "watch-party", "#fffff", messageContent); window.location.hash = state().sessionId;
} let response, video_url, subtitle_tracks, current_time_ms, is_playing;
state().activeSession = state().sessionId; try {
response = await fetch(`/sess/${state().sessionId}`);
// try { // we are handling errors in the join form. } catch (e) {
const genericConnectionError = new Error( console.error(e);
"There was an issue getting the session information." throw genericConnectionError;
); }
window.location.hash = state().sessionId; if (!response.ok) {
let response, video_url, subtitle_tracks, current_time_ms, is_playing; let error;
try { try {
response = await fetch(`/sess/${state().sessionId}`); ({ error } = await response.json());
} catch (e) { if (!error) throw new Error();
console.error(e); } catch (e) {
throw genericConnectionError; console.error(e);
} throw genericConnectionError;
if (!response.ok) { }
let error; throw new Error(error);
try { }
({ error } = await response.json()); try {
if (!error) throw new Error(); ({ video_url, subtitle_tracks, current_time_ms, is_playing } =
} catch (e) { await response.json());
console.error(e); } catch (e) {
throw genericConnectionError; console.error(e);
} throw genericConnectionError;
throw new Error(error); }
}
try { if (state().socket) {
({ video_url, subtitle_tracks, current_time_ms, is_playing } = state().socket.close();
await response.json()); state().socket = null;
} catch (e) { }
console.error(e); const socket = createWebSocket();
throw genericConnectionError; state().socket = socket;
} socket.addEventListener("open", async () => {
player = await setupVideo(
if (state().socket) { video_url,
state().socket.close(); subtitle_tracks,
state().socket = null; current_time_ms,
} is_playing,
const socket = createWebSocket(); created
state().socket = socket; );
socket.addEventListener("open", async () => {
const video = await setupVideo( player.on("canplay", () => {
video_url, sync();
subtitle_tracks, });
current_time_ms,
is_playing setupOutgoingEvents(player, socket);
); setupIncomingEvents(player, socket);
setupChat(socket);
// TODO: Allow the user to set this somewhere });
let defaultAllowControls = false; socket.addEventListener("reconnecting", (e) => {
try { console.log("Reconnecting...");
defaultAllowControls = localStorage.getItem( });
"watch-party-default-allow-controls" socket.addEventListener("reconnected", (e) => {
); console.log("Reconnected.");
} catch (_err) {} });
//} catch (e) {
// By default, we should disable video controls if the video is already playing. // alert(e.message)
// This solves an issue where Safari users join and seek to 00:00:00 because of //}
// outgoing events. };
if (current_time_ms != 0 || !defaultAllowControls) {
video.controls = false; /**
} * @param {string} videoUrl
* @param {Array} subtitleTracks
setupOutgoingEvents(video, socket); */
setupIncomingEvents(video, socket); export const createSession = async (videoUrl, subtitleTracks) => {
setupChat(socket); const { id } = await fetch("/start_session", {
}); method: "POST",
socket.addEventListener("reconnecting", (e) => { headers: { "Content-Type": "application/json" },
console.log("Reconnecting..."); body: JSON.stringify({
}); video_url: videoUrl,
socket.addEventListener("reconnected", (e) => { subtitle_tracks: subtitleTracks,
console.log("Reconnected."); }),
}); }).then((r) => r.json());
//} catch (e) {
// alert(e.message) window.location = `/?created=true#${id}`;
//} };
};
export const sync = async () => {
/** setDebounce();
* @param {string} videoUrl await setPlaying(false);
* @param {Array} subtitleTracks const { current_time_ms, is_playing } = await fetch(
*/ `/sess/${state().sessionId}`
export const createSession = async (videoUrl, subtitleTracks) => { ).then((r) => r.json());
const { id } = await fetch("/start_session", {
method: "POST", setDebounce();
headers: { "Content-Type": "application/json" }, setVideoTime(current_time_ms);
body: JSON.stringify({ if (is_playing) await setPlaying(is_playing);
video_url: videoUrl, };
subtitle_tracks: subtitleTracks,
}),
}).then((r) => r.json());
window.location = `/?created=true#${id}`;
};

View File

@ -1,11 +1,11 @@
import { setupJoinSessionForm } from "./lib/join-session.mjs?v=bfdcf2"; import { setupJoinSessionForm } from "./lib/join-session.mjs?v=bfdcf2";
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

@ -25,6 +25,14 @@
), ),
linear-gradient(var(--bg), var(--bg)); linear-gradient(var(--bg), var(--bg));
--accent-transparent: rgba(var(--accent-rgb), 0.25); --accent-transparent: rgba(var(--accent-rgb), 0.25);
--plyr-color-main: var(--accent);
--plyr-control-radius: 6px;
--plyr-menu-radius: 6px;
--plyr-menu-background: var(--autocomplete-bg);
--plyr-menu-color: var(--fg);
--plyr-menu-arrow-color: var(--fg);
--plyr-menu-back-border-color: var(--fg-transparent);
--plyr-menu-back-border-shadow-color: transparent;
} }
html { html {
@ -49,11 +57,41 @@ body {
flex-direction: column; flex-direction: column;
} }
video { .lock-controls.plyr__control--pressed svg {
display: block; opacity: 0.5;
}
.plyr {
width: 100%; width: 100%;
height: 100%; height: 100%;
object-fit: contain; }
.plyr__menu__container {
--plyr-video-control-background-hover: var(--fg-transparent);
--plyr-video-control-color-hover: var(--fg);
--plyr-control-radius: 4px;
--plyr-control-spacing: calc(0.25rem / 0.7);
--plyr-font-size-menu: 0.75rem;
--plyr-menu-arrow-size: 0;
margin-bottom: 0.48rem;
max-height: 27vmin;
clip-path: inset(0 0 0 0 round 4px);
scrollbar-width: thin;
}
.plyr__menu__container .plyr__control[role="menuitemradio"]::after {
left: 10px;
}
.plyr__menu__container
.plyr__control[role="menuitemradio"][aria-checked="true"].plyr__tab-focus::before,
.plyr__menu__container
.plyr__control[role="menuitemradio"][aria-checked="true"]:hover::before {
background: var(--accent);
}
[data-plyr="language"] .plyr__menu__value {
display: none;
} }
#video-container { #video-container {
@ -131,7 +169,7 @@ input[type="text"] {
overflow-y: scroll; overflow-y: scroll;
} }
button { button:not(.plyr button) {
background-color: var(--accent); background-color: var(--accent);
border: var(--accent); border: var(--accent);
border-radius: 6px; border-radius: 6px;
@ -303,7 +341,7 @@ button.small-button {
display: none; display: none;
} }
.emoji-option { .emoji-option:not(:root) {
background: transparent; background: transparent;
font-size: 0.75rem; font-size: 0.75rem;
text-align: left; text-align: left;