Compare commits
1 Commits
main
...
chat-popou
Author | SHA1 | Date |
---|---|---|
maia arson crimew | 4885e5b747 |
|
@ -3,7 +3,7 @@ root = true
|
||||||
[*]
|
[*]
|
||||||
indent_style = space
|
indent_style = space
|
||||||
indent_size = 2
|
indent_size = 2
|
||||||
end_of_line = lf
|
end_of_line = crlf
|
||||||
charset = utf-8
|
charset = utf-8
|
||||||
trim_trailing_whitespace = false
|
trim_trailing_whitespace = false
|
||||||
insert_final_newline = true
|
insert_final_newline = true
|
||||||
|
|
|
@ -1,2 +1 @@
|
||||||
/target
|
/target
|
||||||
/frontend/emojis/*
|
|
||||||
|
|
|
@ -10,6 +10,6 @@ once_cell = "1.8.0"
|
||||||
serde = { version = "1.0.130", features = ["derive"] }
|
serde = { version = "1.0.130", features = ["derive"] }
|
||||||
serde_json = "1.0.68"
|
serde_json = "1.0.68"
|
||||||
tokio = { version = "1.12.0", features = ["full"] }
|
tokio = { version = "1.12.0", features = ["full"] }
|
||||||
tokio-stream = { version = "0.1.7", features = ["fs"] }
|
tokio-stream = "0.1.7"
|
||||||
uuid = { version = "0.8.2", features = ["v4"] }
|
uuid = { version = "0.8.2", features = ["v4"] }
|
||||||
warp = "0.3.1"
|
warp = "0.3.1"
|
||||||
|
|
|
@ -0,0 +1,22 @@
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<title>watch party chat <3</title>
|
||||||
|
<link rel="stylesheet" href="/styles.css?v=3" />
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
<noscript>
|
||||||
|
This site will <em>not</em> work without JavaScript, and there's not
|
||||||
|
really any way around that :(
|
||||||
|
</noscript>
|
||||||
|
|
||||||
|
<div id="chatbox-container" class="popped-out">
|
||||||
|
<div id="chatbox"></div>
|
||||||
|
<form id="chatbox-send">
|
||||||
|
<input type="text" placeholder="Message..." />
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
|
@ -1,52 +0,0 @@
|
||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<title>watch party :D</title>
|
|
||||||
<link rel="stylesheet" href="/styles.css?v=4b61c4" />
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
<noscript>
|
|
||||||
This site will <em>not</em> work without JavaScript, and there's not
|
|
||||||
really any way around that :(
|
|
||||||
</noscript>
|
|
||||||
|
|
||||||
<div id="create-controls">
|
|
||||||
<form id="create-session-form">
|
|
||||||
<h2>Create a session</h2>
|
|
||||||
|
|
||||||
<label for="create-session-video">Video:</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
id="create-session-video"
|
|
||||||
placeholder="https://video.example.com/example.mp4"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
|
|
||||||
<!-- TODO: Ability to add multiple subtitles for different languages -->
|
|
||||||
<label for="create-session-subs">Subtitles:</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
id="create-session-subs"
|
|
||||||
placeholder="https://video.example.com/example.vtt"
|
|
||||||
/>
|
|
||||||
|
|
||||||
<label for="create-session-subs-name">Subtitle track name:</label>
|
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
id="create-session-subs-name"
|
|
||||||
placeholder="English"
|
|
||||||
/>
|
|
||||||
<button>Create</button>
|
|
||||||
|
|
||||||
<p>
|
|
||||||
Already have a session?
|
|
||||||
<a href="/">Join your session</a> instead.
|
|
||||||
</p>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<script type="module" src="/create.mjs?v=4b61c4"></script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
|
@ -1,11 +0,0 @@
|
||||||
import { setupCreateSessionForm } from "./lib/create-session.mjs?v=4b61c4";
|
|
||||||
|
|
||||||
const main = () => {
|
|
||||||
setupCreateSessionForm();
|
|
||||||
};
|
|
||||||
|
|
||||||
if (document.readyState === "complete") {
|
|
||||||
main();
|
|
||||||
} else {
|
|
||||||
document.addEventListener("DOMContentLoaded", main);
|
|
||||||
}
|
|
|
@ -3,8 +3,7 @@
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<title>watch party :D</title>
|
<title>watch party :D</title>
|
||||||
<link rel="stylesheet" href="/lib/plyr-3.7.3.css" />
|
<link rel="stylesheet" href="/styles.css?v=3" />
|
||||||
<link rel="stylesheet" href="/styles.css?v=4b61c4" />
|
|
||||||
</head>
|
</head>
|
||||||
|
|
||||||
<body>
|
<body>
|
||||||
|
@ -17,69 +16,38 @@
|
||||||
<form id="join-session-form">
|
<form id="join-session-form">
|
||||||
<h2>Join a session</h2>
|
<h2>Join a session</h2>
|
||||||
|
|
||||||
<p id="post-create-message">
|
<label for="nickname">Nickname:</label>
|
||||||
Your session has been created successfully. Copy the current url or
|
|
||||||
the Session ID below and share it with your friends. :)
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<label for="join-session-nickname">Nickname:</label>
|
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
id="join-session-nickname"
|
id="join-session-nickname"
|
||||||
placeholder="Nickname"
|
placeholder="Nickname"
|
||||||
maxlength="50"
|
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<label id="join-session-colour-label" for="join-session-colour">
|
<label for="session-id">Session ID:</label>
|
||||||
Personal Colour:
|
|
||||||
</label>
|
|
||||||
<input type="color" id="join-session-colour" value="#ffffff" required />
|
|
||||||
|
|
||||||
<label for="join-session-id">Session ID:</label>
|
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
id="join-session-id"
|
id="join-session-id"
|
||||||
placeholder="123e4567-e89b-12d3-a456-426614174000"
|
placeholder="123e4567-e89b-12d3-a456-426614174000"
|
||||||
required
|
required
|
||||||
/>
|
/>
|
||||||
<button id="join-session-button">Join</button>
|
<button>Join</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
<p>
|
<p>
|
||||||
No session to join?
|
No session to join? <a href="/create.html">Create a session</a> instead.
|
||||||
<a href="/create.html">Create a session</a> instead.
|
|
||||||
</p>
|
</p>
|
||||||
</form>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div id="video-container"></div>
|
<div id="video-container"></div>
|
||||||
<div id="chatbox-container">
|
<div id="chatbox-container">
|
||||||
<div id="viewer-list"></div>
|
|
||||||
<div id="chatbox"></div>
|
<div id="chatbox"></div>
|
||||||
<form id="chatbox-send">
|
<form id="chatbox-send">
|
||||||
<input
|
<input type="text" id="message-box" placeholder="Message..." />
|
||||||
type="text"
|
<input type="button" id="pop-chat" value="Pop out chat" />
|
||||||
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 -->
|
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script type="module" src="/main.mjs?v=4b61c4"></script>
|
<script type="module" src="/main.mjs?v=2"></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>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
|
@ -1,453 +1,164 @@
|
||||||
import {
|
var win = window;
|
||||||
setDebounce,
|
var poppedOut = false;
|
||||||
setVideoTime,
|
|
||||||
setPlaying,
|
|
||||||
sync,
|
|
||||||
} from "./watch-session.mjs?v=4b61c4";
|
|
||||||
import { emojify, findEmojis } from "./emojis.mjs?v=4b61c4";
|
|
||||||
import { linkify } from "./links.mjs?v=4b61c4";
|
|
||||||
import { joinSession } from "./watch-session.mjs?v=4b61c4";
|
|
||||||
import { pling } from "./pling.mjs?v=4b61c4";
|
|
||||||
import { state } from "./state.mjs";
|
|
||||||
|
|
||||||
function setCaretPosition(elem, caretPos) {
|
|
||||||
if (elem.createTextRange) {
|
|
||||||
var range = elem.createTextRange();
|
|
||||||
range.move("character", caretPos);
|
|
||||||
range.select();
|
|
||||||
} else {
|
|
||||||
if (elem.selectionStart) {
|
|
||||||
elem.focus();
|
|
||||||
elem.setSelectionRange(caretPos, caretPos);
|
|
||||||
} else elem.focus();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const setupChatboxEvents = (socket) => {
|
const setupChatboxEvents = (socket) => {
|
||||||
// clear events by just reconstructing the form
|
// clear events by just reconstructing the form
|
||||||
const oldChatForm = document.querySelector("#chatbox-send");
|
const oldChatForm = win.document.querySelector("#chatbox-send");
|
||||||
const chatForm = oldChatForm.cloneNode(true);
|
const chatForm = oldChatForm.cloneNode(true);
|
||||||
const messageInput = chatForm.querySelector("input");
|
|
||||||
const emojiAutocomplete = chatForm.querySelector("#emoji-autocomplete");
|
|
||||||
oldChatForm.replaceWith(chatForm);
|
oldChatForm.replaceWith(chatForm);
|
||||||
|
if (!poppedOut) {
|
||||||
|
setupPopoutEvent(socket);
|
||||||
|
}
|
||||||
|
|
||||||
let autocompleting = false,
|
chatForm.addEventListener("submit", (e) => {
|
||||||
showListTimer;
|
|
||||||
|
|
||||||
const replaceMessage = (message) => () => {
|
|
||||||
messageInput.value = message;
|
|
||||||
autocomplete();
|
|
||||||
};
|
|
||||||
async function autocomplete(fromListTimeout) {
|
|
||||||
if (autocompleting) return;
|
|
||||||
try {
|
|
||||||
clearInterval(showListTimer);
|
|
||||||
emojiAutocomplete.textContent = "";
|
|
||||||
autocompleting = true;
|
|
||||||
let text = messageInput.value.slice(0, messageInput.selectionStart);
|
|
||||||
const match = text.match(/(:[^\s:]+)?:([^\s:]{2,})$/);
|
|
||||||
if (!match || match[1]) return (autocompleting = false); // We don't need to autocomplete.
|
|
||||||
const prefix = text.slice(0, match.index);
|
|
||||||
const search = text.slice(match.index + 1);
|
|
||||||
if (search.length < 1 && !fromListTimeout) {
|
|
||||||
autocompleting = false;
|
|
||||||
showListTimer = setTimeout(() => autocomplete(true), 500);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
const suffix = messageInput.value.slice(messageInput.selectionStart);
|
|
||||||
let selected;
|
|
||||||
const select = (button) => {
|
|
||||||
if (selected) selected.classList.remove("selected");
|
|
||||||
selected = button;
|
|
||||||
button.classList.add("selected");
|
|
||||||
};
|
|
||||||
let results = await findEmojis(search);
|
|
||||||
let yieldAt = performance.now() + 13;
|
|
||||||
for (let i = 0; i < results.length; i += 100) {
|
|
||||||
emojiAutocomplete.append.apply(
|
|
||||||
emojiAutocomplete,
|
|
||||||
results.slice(i, i + 100).map(([name, replaceWith, ext], i) => {
|
|
||||||
const button = Object.assign(document.createElement("button"), {
|
|
||||||
className: "emoji-option",
|
|
||||||
onmousedown: (e) => e.preventDefault(),
|
|
||||||
onclick: () => {
|
|
||||||
messageInput.value = prefix + replaceWith + " " + suffix;
|
|
||||||
setCaretPosition(
|
|
||||||
messageInput,
|
|
||||||
(prefix + " " + replaceWith).length
|
|
||||||
);
|
|
||||||
},
|
|
||||||
onmouseover: () => select(button),
|
|
||||||
onfocus: () => select(button),
|
|
||||||
type: "button",
|
|
||||||
title: name,
|
|
||||||
});
|
|
||||||
button.append(
|
|
||||||
replaceWith[0] !== ":"
|
|
||||||
? Object.assign(document.createElement("span"), {
|
|
||||||
textContent: replaceWith,
|
|
||||||
className: "emoji",
|
|
||||||
})
|
|
||||||
: Object.assign(new Image(), {
|
|
||||||
loading: "lazy",
|
|
||||||
src: `/emojis/${name}${ext}`,
|
|
||||||
className: "emoji",
|
|
||||||
}),
|
|
||||||
Object.assign(document.createElement("span"), {
|
|
||||||
textContent: name,
|
|
||||||
className: "emoji-name",
|
|
||||||
})
|
|
||||||
);
|
|
||||||
return button;
|
|
||||||
})
|
|
||||||
);
|
|
||||||
if (i == 0 && emojiAutocomplete.children[0]) {
|
|
||||||
emojiAutocomplete.children[0].scrollIntoView();
|
|
||||||
select(emojiAutocomplete.children[0]);
|
|
||||||
}
|
|
||||||
const now = performance.now();
|
|
||||||
if (now > yieldAt) {
|
|
||||||
yieldAt = now + 13;
|
|
||||||
await new Promise((cb) => setTimeout(cb, 0));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
autocompleting = false;
|
|
||||||
} catch (e) {
|
|
||||||
autocompleting = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
messageInput.addEventListener("input", () => autocomplete());
|
|
||||||
messageInput.addEventListener("selectionchange", () => autocomplete());
|
|
||||||
messageInput.addEventListener("keydown", (event) => {
|
|
||||||
if (event.key == "ArrowUp" || event.key == "ArrowDown") {
|
|
||||||
let selected = document.querySelector(".emoji-option.selected");
|
|
||||||
if (!selected) return;
|
|
||||||
event.preventDefault();
|
|
||||||
selected.classList.remove("selected");
|
|
||||||
selected =
|
|
||||||
event.key == "ArrowDown"
|
|
||||||
? selected.nextElementSibling || selected.parentElement.children[0]
|
|
||||||
: selected.previousElementSibling ||
|
|
||||||
selected.parentElement.children[
|
|
||||||
selected.parentElement.children.length - 1
|
|
||||||
];
|
|
||||||
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 (!selected) return;
|
|
||||||
event.preventDefault();
|
|
||||||
selected.onclick();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
chatForm.addEventListener("submit", async (e) => {
|
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
const content = messageInput.value;
|
|
||||||
|
const input = chatForm.querySelector("input");
|
||||||
|
const content = input.value;
|
||||||
if (content.trim().length) {
|
if (content.trim().length) {
|
||||||
messageInput.value = "";
|
input.value = "";
|
||||||
|
|
||||||
// handle commands
|
|
||||||
if (content.startsWith("/")) {
|
|
||||||
const command = content.toLowerCase().match(/^\/\S+/)[0];
|
|
||||||
const args = content.slice(command.length).trim();
|
|
||||||
|
|
||||||
let handled = false;
|
|
||||||
switch (command) {
|
|
||||||
case "/ping":
|
|
||||||
socket.send(
|
|
||||||
JSON.stringify({
|
|
||||||
op: "Ping",
|
|
||||||
data: args,
|
|
||||||
})
|
|
||||||
);
|
|
||||||
handled = true;
|
|
||||||
break;
|
|
||||||
case "/sync":
|
|
||||||
await sync();
|
|
||||||
|
|
||||||
const syncMessageContent = document.createElement("span");
|
|
||||||
syncMessageContent.appendChild(
|
|
||||||
document.createTextNode("resynced you to ")
|
|
||||||
);
|
|
||||||
syncMessageContent.appendChild(
|
|
||||||
document.createTextNode(formatTime(current_time_ms))
|
|
||||||
);
|
|
||||||
printChatMessage("set-time", "/sync", "b57fdc", syncMessageContent);
|
|
||||||
handled = true;
|
|
||||||
break;
|
|
||||||
case "/shrug":
|
|
||||||
socket.send(
|
socket.send(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
op: "ChatMessage",
|
op: "ChatMessage",
|
||||||
data: `${args} ¯\\_(ツ)_/¯`.trim(),
|
data: {
|
||||||
})
|
message: content,
|
||||||
);
|
},
|
||||||
handled = true;
|
|
||||||
break;
|
|
||||||
case "/join":
|
|
||||||
state().sessionId = args;
|
|
||||||
joinSession();
|
|
||||||
handled = true;
|
|
||||||
break;
|
|
||||||
case "/help":
|
|
||||||
const helpMessageContent = document.createElement("span");
|
|
||||||
helpMessageContent.innerHTML =
|
|
||||||
"Available commands:<br>" +
|
|
||||||
" <code>/help</code> - display this help message<br>" +
|
|
||||||
" <code>/ping [message]</code> - ping all viewers<br>" +
|
|
||||||
" <code>/sync</code> - resyncs you with other viewers<br>" +
|
|
||||||
" <code>/shrug</code> - appends ¯\\_(ツ)_/¯ to your message<br>" +
|
|
||||||
" <code>/join [session id]</code> - joins another session";
|
|
||||||
|
|
||||||
printChatMessage(
|
|
||||||
"command-message",
|
|
||||||
"/help",
|
|
||||||
"b57fdc",
|
|
||||||
helpMessageContent
|
|
||||||
);
|
|
||||||
handled = true;
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (handled) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// handle regular chat messages
|
|
||||||
socket.send(
|
|
||||||
JSON.stringify({
|
|
||||||
op: "ChatMessage",
|
|
||||||
data: content,
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const setupPopoutEvent = (socket) => {
|
||||||
|
const button = document.querySelector("#pop-chat");
|
||||||
|
button.addEventListener("click", () => {
|
||||||
|
openPopout(socket);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const fixChatSize = () => {
|
||||||
|
const video = document.querySelector("video");
|
||||||
|
const chatbox = document.querySelector("#chatbox");
|
||||||
|
const chatboxContainer = document.querySelector("#chatbox-container");
|
||||||
|
|
||||||
|
if (video && chatbox && chatboxContainer) {
|
||||||
|
const delta = chatboxContainer.clientHeight - chatbox.clientHeight;
|
||||||
|
|
||||||
|
chatbox.style["height"] = `calc(${
|
||||||
|
window.innerHeight - video.clientHeight
|
||||||
|
}px - ${delta}px - 1em)`;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// TODO: transfer chat history to popout and back?
|
||||||
|
const openPopout = async (socket) => {
|
||||||
|
win.document.querySelector("#chatbox-container").style["display"] = "none";
|
||||||
|
const popout = window.open("/chat.html", "popout", "width=800,height=1000");
|
||||||
|
win = popout;
|
||||||
|
poppedOut = true;
|
||||||
|
|
||||||
|
// I am aware of the fact that this is incredibly cursed,
|
||||||
|
// but apparently this is the only way to wait for a child window to load....
|
||||||
|
// I love browsers :)
|
||||||
|
function defer(callback) {
|
||||||
|
var channel = new MessageChannel();
|
||||||
|
channel.port1.onmessage = function (e) {
|
||||||
|
callback();
|
||||||
|
};
|
||||||
|
channel.port2.postMessage(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
win.addEventListener("unload", () => {
|
||||||
|
defer(() => {
|
||||||
|
if (popout.document.readyState === "complete") {
|
||||||
|
setupChat(socket);
|
||||||
|
// pop the chat back into the parent window on close
|
||||||
|
win.addEventListener("unload", () => {
|
||||||
|
popBackChat(socket);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
win.document.addEventListener("DOMContentLoaded", () => {
|
||||||
|
setupChat(socket);
|
||||||
|
// pop the chat back into the parent window on close
|
||||||
|
win.addEventListener("unload", () => {
|
||||||
|
popBackChat(socket);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const popBackChat = async (socket) => {
|
||||||
|
win = window;
|
||||||
|
poppedOut = false;
|
||||||
|
setupChat(socket);
|
||||||
|
};
|
||||||
|
|
||||||
|
const resizeCallback = () => {
|
||||||
|
fixChatSize();
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {WebSocket} socket
|
* @param {WebSocket} socket
|
||||||
*/
|
*/
|
||||||
export const setupChat = async (socket) => {
|
export const setupChat = async (socket) => {
|
||||||
document.querySelector("#chatbox-container").style["display"] = "flex";
|
win.document.querySelector("#chatbox-container").style["display"] = "block";
|
||||||
setupChatboxEvents(socket);
|
setupChatboxEvents(socket);
|
||||||
|
|
||||||
|
if (!poppedOut) {
|
||||||
|
fixChatSize();
|
||||||
|
window.addEventListener("resize", resizeCallback);
|
||||||
|
} else {
|
||||||
|
window.removeEventListener("resize", resizeCallback);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const addToChat = (node) => {
|
const printToChat = (elem) => {
|
||||||
const chatbox = document.querySelector("#chatbox");
|
const chatbox = win.document.querySelector("#chatbox");
|
||||||
chatbox.appendChild(node);
|
chatbox.appendChild(elem);
|
||||||
chatbox.scrollTop = chatbox.scrollHeight;
|
chatbox.scrollTop = chatbox.scrollHeight;
|
||||||
};
|
};
|
||||||
|
|
||||||
let lastTimeMs = null;
|
export const handleChatEvent = (event) => {
|
||||||
let lastPlaying = false;
|
|
||||||
|
|
||||||
const checkDebounce = (event) => {
|
|
||||||
let timeMs = null;
|
|
||||||
let playing = null;
|
|
||||||
if (event.op == "SetTime") {
|
|
||||||
timeMs = event.data;
|
|
||||||
} else if (event.op == "SetPlaying") {
|
|
||||||
timeMs = event.data.time;
|
|
||||||
playing = event.data.playing;
|
|
||||||
}
|
|
||||||
|
|
||||||
let shouldIgnore = false;
|
|
||||||
|
|
||||||
if (timeMs != null) {
|
|
||||||
if (lastTimeMs && Math.abs(lastTimeMs - timeMs) < 500) {
|
|
||||||
shouldIgnore = true;
|
|
||||||
}
|
|
||||||
lastTimeMs = timeMs;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (playing != null) {
|
|
||||||
if (lastPlaying != playing) {
|
|
||||||
shouldIgnore = false;
|
|
||||||
}
|
|
||||||
lastPlaying = playing;
|
|
||||||
}
|
|
||||||
|
|
||||||
return shouldIgnore;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
const getCurrentTimestamp = () => {
|
|
||||||
const t = new Date();
|
|
||||||
return `${matpad(t.getHours())}:${matpad(t.getMinutes())}:${matpad(
|
|
||||||
t.getSeconds()
|
|
||||||
)}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* https://media.discordapp.net/attachments/834541919568527361/931678814751301632/66d2c68c48daa414c96951381665ec2e.png
|
|
||||||
*/
|
|
||||||
const matpad = (n) => {
|
|
||||||
return ("00" + n).slice(-2);
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {string} eventType
|
|
||||||
* @param {string?} user
|
|
||||||
* @param {Node?} content
|
|
||||||
*/
|
|
||||||
export const printChatMessage = (eventType, user, colour, content) => {
|
|
||||||
const chatMessage = document.createElement("div");
|
|
||||||
chatMessage.classList.add("chat-message");
|
|
||||||
chatMessage.classList.add(eventType);
|
|
||||||
chatMessage.title = getCurrentTimestamp();
|
|
||||||
|
|
||||||
if (user != null) {
|
|
||||||
const userName = document.createElement("strong");
|
|
||||||
userName.style = `--user-color: #${colour}`;
|
|
||||||
userName.textContent = user + " ";
|
|
||||||
chatMessage.appendChild(userName);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (content != null) {
|
|
||||||
chatMessage.appendChild(content);
|
|
||||||
}
|
|
||||||
|
|
||||||
addToChat(chatMessage);
|
|
||||||
|
|
||||||
return chatMessage;
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatTime = (ms) => {
|
|
||||||
const seconds = Math.floor((ms / 1000) % 60);
|
|
||||||
const minutes = Math.floor((ms / (60 * 1000)) % 60);
|
|
||||||
const hours = Math.floor((ms / (3600 * 1000)) % 3600);
|
|
||||||
return `${hours < 10 ? "0" + hours : hours}:${
|
|
||||||
minutes < 10 ? "0" + minutes : minutes
|
|
||||||
}:${seconds < 10 ? "0" + seconds : seconds}`;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const logEventToChat = async (event) => {
|
|
||||||
if (checkDebounce(event)) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
switch (event.op) {
|
switch (event.op) {
|
||||||
case "UserJoin": {
|
case "UserJoin": {
|
||||||
printChatMessage(
|
// print something to the chat
|
||||||
"user-join",
|
const chatMessage = win.document.createElement("div");
|
||||||
event.user,
|
chatMessage.classList.add("chat-message");
|
||||||
event.colour,
|
chatMessage.classList.add("user-join");
|
||||||
document.createTextNode("joined")
|
const userName = win.document.createElement("strong");
|
||||||
);
|
userName.textContent = event.data;
|
||||||
|
chatMessage.appendChild(userName);
|
||||||
|
chatMessage.appendChild(win.document.createTextNode(" joined"));
|
||||||
|
printToChat(chatMessage);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "UserLeave": {
|
case "UserLeave": {
|
||||||
printChatMessage(
|
const chatMessage = win.document.createElement("div");
|
||||||
"user-leave",
|
chatMessage.classList.add("chat-message");
|
||||||
event.user,
|
chatMessage.classList.add("user-leave");
|
||||||
event.colour,
|
const userName = win.document.createElement("strong");
|
||||||
document.createTextNode("left")
|
userName.textContent = event.data;
|
||||||
);
|
chatMessage.appendChild(userName);
|
||||||
|
chatMessage.appendChild(win.document.createTextNode(" left"));
|
||||||
|
printToChat(chatMessage);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "ChatMessage": {
|
case "ChatMessage": {
|
||||||
const messageContent = document.createElement("span");
|
const chatMessage = win.document.createElement("div");
|
||||||
|
chatMessage.classList.add("chat-message");
|
||||||
|
const userName = win.document.createElement("strong");
|
||||||
|
userName.innerText = event.data.user;
|
||||||
|
chatMessage.appendChild(userName);
|
||||||
|
chatMessage.appendChild(win.document.createTextNode(" "));
|
||||||
|
const messageContent = win.document.createElement("span");
|
||||||
messageContent.classList.add("message-content");
|
messageContent.classList.add("message-content");
|
||||||
messageContent.append(...(await linkify(event.data, emojify)));
|
messageContent.textContent = event.data.message;
|
||||||
printChatMessage(
|
chatMessage.appendChild(messageContent);
|
||||||
"chat-message",
|
printToChat(chatMessage);
|
||||||
event.user,
|
|
||||||
event.colour,
|
|
||||||
messageContent
|
|
||||||
);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "SetTime": {
|
|
||||||
const messageContent = document.createElement("span");
|
|
||||||
if (event.data.from != undefined) {
|
|
||||||
messageContent.appendChild(
|
|
||||||
document.createTextNode("set the time from ")
|
|
||||||
);
|
|
||||||
|
|
||||||
messageContent.appendChild(
|
|
||||||
document.createTextNode(formatTime(event.data.from))
|
|
||||||
);
|
|
||||||
|
|
||||||
messageContent.appendChild(document.createTextNode(" to "));
|
|
||||||
} else {
|
|
||||||
messageContent.appendChild(document.createTextNode("set the time to "));
|
|
||||||
}
|
|
||||||
|
|
||||||
messageContent.appendChild(
|
|
||||||
document.createTextNode(formatTime(event.data.to))
|
|
||||||
);
|
|
||||||
|
|
||||||
printChatMessage("set-time", event.user, event.colour, messageContent);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "SetPlaying": {
|
|
||||||
const messageContent = document.createElement("span");
|
|
||||||
messageContent.appendChild(
|
|
||||||
document.createTextNode(
|
|
||||||
event.data.playing ? "started playing" : "paused"
|
|
||||||
)
|
|
||||||
);
|
|
||||||
messageContent.appendChild(document.createTextNode(" at "));
|
|
||||||
messageContent.appendChild(
|
|
||||||
document.createTextNode(formatTime(event.data.time))
|
|
||||||
);
|
|
||||||
|
|
||||||
printChatMessage("set-playing", event.user, event.colour, messageContent);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "Ping": {
|
|
||||||
const messageContent = document.createElement("span");
|
|
||||||
if (event.data) {
|
|
||||||
messageContent.appendChild(document.createTextNode("pinged saying: "));
|
|
||||||
messageContent.appendChild(document.createTextNode(event.data));
|
|
||||||
} else {
|
|
||||||
messageContent.appendChild(document.createTextNode("pinged"));
|
|
||||||
}
|
|
||||||
|
|
||||||
printChatMessage("ping", event.user, event.colour, messageContent);
|
|
||||||
pling();
|
|
||||||
if ("Notification" in window) {
|
|
||||||
const title = "watch party :)";
|
|
||||||
const options = {
|
|
||||||
body: event.data
|
|
||||||
? `${event.user} pinged saying: ${event.data}`
|
|
||||||
: `${event.user} pinged`,
|
|
||||||
};
|
|
||||||
if (Notification.permission === "granted") {
|
|
||||||
new Notification(title, options);
|
|
||||||
} else if (Notification.permission !== "denied") {
|
|
||||||
Notification.requestPermission().then(function (permission) {
|
|
||||||
if (permission === "granted") {
|
|
||||||
new Notification(title, options);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const updateViewerList = (viewers) => {
|
|
||||||
const listContainer = document.querySelector("#viewer-list");
|
|
||||||
|
|
||||||
// empty out the current list
|
|
||||||
listContainer.innerHTML = "";
|
|
||||||
|
|
||||||
// display the updated list
|
|
||||||
for (const viewer of viewers) {
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
|
@ -1,18 +0,0 @@
|
||||||
import { createSession } from "./watch-session.mjs?v=4b61c4";
|
|
||||||
|
|
||||||
export const setupCreateSessionForm = () => {
|
|
||||||
const form = document.querySelector("#create-session-form");
|
|
||||||
const videoUrl = form.querySelector("#create-session-video");
|
|
||||||
const subsUrl = form.querySelector("#create-session-subs");
|
|
||||||
const subsName = form.querySelector("#create-session-subs-name");
|
|
||||||
|
|
||||||
form.addEventListener("submit", (event) => {
|
|
||||||
event.preventDefault();
|
|
||||||
|
|
||||||
let subs = [];
|
|
||||||
if (subsUrl.value) {
|
|
||||||
subs.push({ url: subsUrl.value, name: subsName.value || "default" });
|
|
||||||
}
|
|
||||||
createSession(videoUrl.value, subs);
|
|
||||||
});
|
|
||||||
};
|
|
|
@ -1,72 +0,0 @@
|
||||||
export async function emojify(text) {
|
|
||||||
await emojisLoaded;
|
|
||||||
let last = 0;
|
|
||||||
let nodes = [];
|
|
||||||
text.replace(/:([^\s:]+):/g, (match, name, index) => {
|
|
||||||
if (last <= index)
|
|
||||||
nodes.push(document.createTextNode(text.slice(last, index)));
|
|
||||||
let emoji;
|
|
||||||
try {
|
|
||||||
emoji = emojis[name.toLowerCase()[0]].find((e) => e[0] == name);
|
|
||||||
} catch (e) {}
|
|
||||||
if (!emoji) {
|
|
||||||
nodes.push(document.createTextNode(match));
|
|
||||||
} else {
|
|
||||||
if (emoji[1][0] !== ":") {
|
|
||||||
nodes.push(document.createTextNode(emoji[1]));
|
|
||||||
} else {
|
|
||||||
nodes.push(
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
const emojis = {};
|
|
||||||
|
|
||||||
export const emojisLoaded = Promise.all([
|
|
||||||
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]]);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
fetch("/emojos")
|
|
||||||
.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]);
|
|
||||||
}
|
|
||||||
}),
|
|
||||||
]);
|
|
||||||
|
|
||||||
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[1], ...groups[0]];
|
|
||||||
}
|
|
|
@ -1,5 +1,4 @@
|
||||||
import { joinSession } from "./watch-session.mjs?v=4b61c4";
|
import { joinSession } from "./watch-session.mjs";
|
||||||
import { state } from "./state.mjs";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {HTMLInputElement} field
|
* @param {HTMLInputElement} field
|
||||||
|
@ -24,72 +23,23 @@ const saveNickname = (field) => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {HTMLInputElement} field
|
|
||||||
*/
|
|
||||||
const loadColour = (field) => {
|
|
||||||
try {
|
|
||||||
const savedColour = localStorage.getItem("watch-party-colour");
|
|
||||||
if (savedColour != null && savedColour != "") {
|
|
||||||
field.value = savedColour;
|
|
||||||
}
|
|
||||||
} catch (_err) {
|
|
||||||
// Sometimes localStorage is blocked from use
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {HTMLInputElement} field
|
|
||||||
*/
|
|
||||||
const saveColour = (field) => {
|
|
||||||
try {
|
|
||||||
localStorage.setItem("watch-party-colour", field.value);
|
|
||||||
} catch (_err) {
|
|
||||||
// see loadColour
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const displayPostCreateMessage = () => {
|
|
||||||
const params = new URLSearchParams(window.location.search);
|
|
||||||
if (params.get("created") == "true") {
|
|
||||||
document.querySelector("#post-create-message").style["display"] = "block";
|
|
||||||
window.history.replaceState({}, document.title, `/${window.location.hash}`);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const setupJoinSessionForm = () => {
|
export const setupJoinSessionForm = () => {
|
||||||
const created = displayPostCreateMessage();
|
|
||||||
|
|
||||||
const form = document.querySelector("#join-session-form");
|
const form = document.querySelector("#join-session-form");
|
||||||
const nickname = form.querySelector("#join-session-nickname");
|
const nickname = form.querySelector("#join-session-nickname");
|
||||||
const colour = form.querySelector("#join-session-colour");
|
|
||||||
const sessionId = form.querySelector("#join-session-id");
|
const sessionId = form.querySelector("#join-session-id");
|
||||||
const button = form.querySelector("#join-session-button");
|
|
||||||
|
|
||||||
loadNickname(nickname);
|
loadNickname(nickname);
|
||||||
loadColour(colour);
|
|
||||||
|
|
||||||
if (window.location.hash.match(/#[0-9a-f\-]+/)) {
|
if (window.location.hash.match(/#[0-9a-f\-]+/)) {
|
||||||
sessionId.value = window.location.hash.substring(1);
|
sessionId.value = window.location.hash.substring(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
form.addEventListener("submit", async (event) => {
|
document
|
||||||
|
.querySelector("#join-session-form")
|
||||||
|
.addEventListener("submit", (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
|
||||||
button.disabled = true;
|
|
||||||
|
|
||||||
saveNickname(nickname);
|
saveNickname(nickname);
|
||||||
saveColour(colour);
|
joinSession(nickname.value, sessionId.value);
|
||||||
try {
|
|
||||||
state().nickname = nickname.value;
|
|
||||||
state().sessionId = sessionId.value;
|
|
||||||
state().colour = colour.value.replace(/^#/, "");
|
|
||||||
await joinSession(created);
|
|
||||||
} catch (e) {
|
|
||||||
alert(e.message);
|
|
||||||
button.disabled = false;
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
|
@ -1,121 +0,0 @@
|
||||||
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]];
|
|
||||||
}
|
|
|
@ -1,79 +0,0 @@
|
||||||
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
|
@ -1,71 +0,0 @@
|
||||||
export default class ReconnectingWebSocket {
|
|
||||||
constructor(url) {
|
|
||||||
if (url instanceof URL) {
|
|
||||||
this.url = url;
|
|
||||||
} else {
|
|
||||||
this.url = new URL(url);
|
|
||||||
}
|
|
||||||
this.connected = false;
|
|
||||||
this._eventTarget = new EventTarget();
|
|
||||||
this._backoff = 250; // milliseconds, doubled before use
|
|
||||||
this._lastConnect = 0;
|
|
||||||
this._socket = null;
|
|
||||||
this._unsent = [];
|
|
||||||
this._closing = false;
|
|
||||||
this._connect(true);
|
|
||||||
}
|
|
||||||
_connect(first) {
|
|
||||||
if (this._socket)
|
|
||||||
try {
|
|
||||||
this._socket.close();
|
|
||||||
} catch (e) {}
|
|
||||||
try {
|
|
||||||
this._socket = new WebSocket(this.url.href);
|
|
||||||
} catch (e) {
|
|
||||||
this._reconnecting = false;
|
|
||||||
return this._reconnect();
|
|
||||||
}
|
|
||||||
this._socket.addEventListener("close", () => this._reconnect());
|
|
||||||
this._socket.addEventListener("error", () => this._reconnect());
|
|
||||||
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"));
|
|
||||||
if (this._reconnecting)
|
|
||||||
this._eventTarget.dispatchEvent(new Event("reconnected"));
|
|
||||||
this._reconnecting = false;
|
|
||||||
this._backoff = 250;
|
|
||||||
this.connected = true;
|
|
||||||
while (this._unsent.length > 0) this._socket.send(this._unsent.shift());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
_reconnect() {
|
|
||||||
if (this._closing) return;
|
|
||||||
if (this._reconnecting) return;
|
|
||||||
this._eventTarget.dispatchEvent(new Event("reconnecting"));
|
|
||||||
this._reconnecting = true;
|
|
||||||
this.connected = false;
|
|
||||||
this._backoff *= 2; // exponential backoff
|
|
||||||
setTimeout(() => {
|
|
||||||
this._connect();
|
|
||||||
}, Math.floor(this._backoff + Math.random() * this._backoff * 0.25 - this._backoff * 0.125));
|
|
||||||
}
|
|
||||||
send(message) {
|
|
||||||
if (this.connected) {
|
|
||||||
this._socket.send(message);
|
|
||||||
} else {
|
|
||||||
this._unsent.push(message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
close() {
|
|
||||||
this._closing = true;
|
|
||||||
this._socket.close();
|
|
||||||
}
|
|
||||||
addEventListener(...a) {
|
|
||||||
return this._eventTarget.addEventListener(...a);
|
|
||||||
}
|
|
||||||
removeEventListener(...a) {
|
|
||||||
return this._eventTarget.removeEventListener(...a);
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -1,7 +0,0 @@
|
||||||
let instance = null;
|
|
||||||
export const state = () => {
|
|
||||||
if (!instance) {
|
|
||||||
instance = {};
|
|
||||||
}
|
|
||||||
return instance;
|
|
||||||
};
|
|
|
@ -1,16 +1,11 @@
|
||||||
import Plyr from "./plyr-3.7.3.min.esm.js";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {string} videoUrl
|
* @param {string} videoUrl
|
||||||
* @param {{name: string, url: string}[]} subtitles
|
* @param {{name: string, url: string}[]} subtitles
|
||||||
*/
|
*/
|
||||||
const createVideoElement = (videoUrl, subtitles, created) => {
|
const createVideoElement = (videoUrl, subtitles) => {
|
||||||
const oldVideo = document.getElementById(".plyr");
|
|
||||||
if (oldVideo) {
|
|
||||||
oldVideo.remove();
|
|
||||||
}
|
|
||||||
const video = document.createElement("video");
|
const video = document.createElement("video");
|
||||||
video.id = "video";
|
video.controls = true;
|
||||||
|
video.autoplay = false;
|
||||||
video.crossOrigin = "anonymous";
|
video.crossOrigin = "anonymous";
|
||||||
|
|
||||||
const source = document.createElement("source");
|
const source = document.createElement("source");
|
||||||
|
@ -18,67 +13,22 @@ const createVideoElement = (videoUrl, subtitles, created) => {
|
||||||
|
|
||||||
video.appendChild(source);
|
video.appendChild(source);
|
||||||
|
|
||||||
|
let first = true;
|
||||||
for (const { name, url } of subtitles) {
|
for (const { name, url } of subtitles) {
|
||||||
const track = document.createElement("track");
|
const track = document.createElement("track");
|
||||||
track.label = name;
|
track.label = name;
|
||||||
track.srclang = "xx-" + name.toLowerCase();
|
|
||||||
track.src = url;
|
track.src = url;
|
||||||
track.kind = "captions";
|
track.kind = "captions";
|
||||||
|
|
||||||
|
if (first) {
|
||||||
|
track.default = true;
|
||||||
|
first = false;
|
||||||
|
}
|
||||||
|
|
||||||
video.appendChild(track);
|
video.appendChild(track);
|
||||||
}
|
}
|
||||||
|
|
||||||
const videoContainer = document.querySelector("#video-container");
|
return video;
|
||||||
videoContainer.style.display = "block";
|
|
||||||
videoContainer.appendChild(video);
|
|
||||||
|
|
||||||
const player = new Plyr(video, {
|
|
||||||
clickToPlay: false,
|
|
||||||
settings: ["captions", "quality"],
|
|
||||||
autopause: false,
|
|
||||||
});
|
|
||||||
player.elements.controls.insertAdjacentHTML(
|
|
||||||
"afterbegin",
|
|
||||||
`<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>`
|
|
||||||
);
|
|
||||||
const lockButton = player.elements.controls.children[0];
|
|
||||||
let controlsEnabled = created;
|
|
||||||
const setControlsEnabled = (enabled) => {
|
|
||||||
controlsEnabled = enabled;
|
|
||||||
lockButton.setAttribute("aria-pressed", enabled);
|
|
||||||
lockButton.classList.toggle("plyr__control--pressed", enabled);
|
|
||||||
player.elements.buttons.play[0].disabled =
|
|
||||||
player.elements.buttons.play[1].disabled =
|
|
||||||
player.elements.inputs.seek.disabled =
|
|
||||||
!enabled;
|
|
||||||
if (!enabled) {
|
|
||||||
// enable media button support
|
|
||||||
navigator.mediaSession.setActionHandler("play", null);
|
|
||||||
navigator.mediaSession.setActionHandler("pause", null);
|
|
||||||
navigator.mediaSession.setActionHandler("stop", null);
|
|
||||||
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", () => {});
|
|
||||||
}
|
|
||||||
};
|
|
||||||
setControlsEnabled(controlsEnabled);
|
|
||||||
lockButton.addEventListener("click", () =>
|
|
||||||
setControlsEnabled(!controlsEnabled)
|
|
||||||
);
|
|
||||||
window.__plyr = player;
|
|
||||||
|
|
||||||
return player;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -87,26 +37,22 @@ const createVideoElement = (videoUrl, subtitles, created) => {
|
||||||
* @param {number} currentTime
|
* @param {number} currentTime
|
||||||
* @param {boolean} playing
|
* @param {boolean} playing
|
||||||
*/
|
*/
|
||||||
export const setupVideo = async (
|
export const setupVideo = async (videoUrl, subtitles, currentTime, playing) => {
|
||||||
videoUrl,
|
|
||||||
subtitles,
|
|
||||||
currentTime,
|
|
||||||
playing,
|
|
||||||
created
|
|
||||||
) => {
|
|
||||||
document.querySelector("#pre-join-controls").style["display"] = "none";
|
document.querySelector("#pre-join-controls").style["display"] = "none";
|
||||||
const player = createVideoElement(videoUrl, subtitles, created);
|
const video = createVideoElement(videoUrl, subtitles);
|
||||||
player.currentTime = currentTime / 1000.0;
|
document.querySelector("#video-container").appendChild(video);
|
||||||
|
|
||||||
|
video.currentTime = currentTime / 1000.0;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
if (playing) {
|
if (playing) {
|
||||||
player.play();
|
await video.play();
|
||||||
} else {
|
} else {
|
||||||
player.pause();
|
video.pause();
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Auto-play is probably disabled, we should uhhhhhhh do something about it
|
// Auto-play is probably disabled, we should uhhhhhhh do something about it
|
||||||
}
|
}
|
||||||
|
|
||||||
return player;
|
return video;
|
||||||
};
|
};
|
||||||
|
|
|
@ -1,27 +1,19 @@
|
||||||
import { setupVideo } from "./video.mjs?v=4b61c4";
|
import { setupVideo } from "./video.mjs";
|
||||||
import {
|
import { setupChat, handleChatEvent } from "./chat.mjs";
|
||||||
setupChat,
|
|
||||||
logEventToChat,
|
|
||||||
updateViewerList,
|
|
||||||
printChatMessage,
|
|
||||||
} from "./chat.mjs?v=4b61c4";
|
|
||||||
import ReconnectingWebSocket from "./reconnecting-web-socket.mjs";
|
|
||||||
import { state } from "./state.mjs";
|
|
||||||
let player;
|
|
||||||
/**
|
/**
|
||||||
* @param {string} sessionId
|
* @param {string} sessionId
|
||||||
* @param {string} nickname
|
* @param {string} nickname
|
||||||
* @returns {ReconnectingWebSocket}
|
* @returns {WebSocket}
|
||||||
*/
|
*/
|
||||||
const createWebSocket = () => {
|
const createWebSocket = (sessionId, nickname) => {
|
||||||
const wsUrl = new URL(
|
const wsUrl = new URL(
|
||||||
`/sess/${state().sessionId}/subscribe` +
|
`/sess/${sessionId}/subscribe` +
|
||||||
`?nickname=${encodeURIComponent(state().nickname)}` +
|
`?nickname=${encodeURIComponent(nickname)}`,
|
||||||
`&colour=${encodeURIComponent(state().colour)}`,
|
|
||||||
window.location.href
|
window.location.href
|
||||||
);
|
);
|
||||||
wsUrl.protocol = "ws" + window.location.protocol.slice(4);
|
wsUrl.protocol = { "http:": "ws:", "https:": "wss:" }[wsUrl.protocol];
|
||||||
const socket = new ReconnectingWebSocket(wsUrl);
|
const socket = new WebSocket(wsUrl.toString());
|
||||||
|
|
||||||
return socket;
|
return socket;
|
||||||
};
|
};
|
||||||
|
@ -29,7 +21,7 @@ const createWebSocket = () => {
|
||||||
let outgoingDebounce = false;
|
let outgoingDebounce = false;
|
||||||
let outgoingDebounceCallbackId = null;
|
let outgoingDebounceCallbackId = null;
|
||||||
|
|
||||||
export const setDebounce = () => {
|
const setDebounce = () => {
|
||||||
outgoingDebounce = true;
|
outgoingDebounce = true;
|
||||||
|
|
||||||
if (outgoingDebounceCallbackId) {
|
if (outgoingDebounceCallbackId) {
|
||||||
|
@ -42,71 +34,60 @@ export const setDebounce = () => {
|
||||||
}, 500);
|
}, 500);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const setVideoTime = (time) => {
|
|
||||||
const timeSecs = time / 1000.0;
|
|
||||||
if (Math.abs(player.currentTime - timeSecs) > 0.5) {
|
|
||||||
player.currentTime = timeSecs;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const setPlaying = async (playing) => {
|
|
||||||
if (playing) {
|
|
||||||
await player.play();
|
|
||||||
} else {
|
|
||||||
player.pause();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {HTMLVideoElement} video
|
* @param {HTMLVideoElement} video
|
||||||
* @param {ReconnectingWebSocket} socket
|
* @param {WebSocket} socket
|
||||||
*/
|
*/
|
||||||
const setupIncomingEvents = (player, socket) => {
|
const setupIncomingEvents = (video, socket) => {
|
||||||
|
const setVideoTime = (time) => {
|
||||||
|
const timeSecs = time / 1000.0;
|
||||||
|
|
||||||
|
if (Math.abs(video.currentTime - timeSecs) > 0.5) {
|
||||||
|
video.currentTime = timeSecs;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
socket.addEventListener("message", async (messageEvent) => {
|
socket.addEventListener("message", async (messageEvent) => {
|
||||||
try {
|
try {
|
||||||
const event = JSON.parse(messageEvent.data);
|
const event = JSON.parse(messageEvent.data);
|
||||||
if (!event.reflected) {
|
// console.log(event);
|
||||||
|
|
||||||
switch (event.op) {
|
switch (event.op) {
|
||||||
case "SetPlaying":
|
case "SetPlaying":
|
||||||
setDebounce();
|
setDebounce();
|
||||||
|
|
||||||
if (event.data.playing) {
|
if (event.data.playing) {
|
||||||
await player.play();
|
await video.play();
|
||||||
} else {
|
} else {
|
||||||
player.pause();
|
video.pause();
|
||||||
}
|
}
|
||||||
|
|
||||||
setVideoTime(event.data.time);
|
setVideoTime(event.data.time);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
case "SetTime":
|
case "SetTime":
|
||||||
setDebounce();
|
setDebounce();
|
||||||
setVideoTime(event.data);
|
setVideoTime(event.data);
|
||||||
break;
|
break;
|
||||||
case "UpdateViewerList":
|
case "UserJoin":
|
||||||
updateViewerList(event.data);
|
case "UserLeave":
|
||||||
|
case "ChatMessage":
|
||||||
|
handleChatEvent(event);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
logEventToChat(event);
|
|
||||||
} catch (_err) {}
|
} catch (_err) {}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {Plyr} player
|
* @param {HTMLVideoElement} video
|
||||||
* @param {ReconnectingWebSocket} socket
|
* @param {WebSocket} socket
|
||||||
*/
|
*/
|
||||||
const setupOutgoingEvents = (player, socket) => {
|
const setupOutgoingEvents = (video, socket) => {
|
||||||
const currentVideoTime = () => (player.currentTime * 1000) | 0;
|
const currentVideoTime = () => (video.currentTime * 1000) | 0;
|
||||||
|
|
||||||
player.on("pause", async () => {
|
video.addEventListener("pause", async (event) => {
|
||||||
if (outgoingDebounce || player.elements.inputs.seek.disabled) {
|
if (outgoingDebounce) {
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// don't send a pause event for the video ending
|
|
||||||
if (player.currentTime == player.duration) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -121,8 +102,8 @@ const setupOutgoingEvents = (player, socket) => {
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
player.on("play", () => {
|
video.addEventListener("play", (event) => {
|
||||||
if (outgoingDebounce || player.elements.inputs.seek.disabled) {
|
if (outgoingDebounce) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -138,133 +119,53 @@ const setupOutgoingEvents = (player, socket) => {
|
||||||
});
|
});
|
||||||
|
|
||||||
let firstSeekComplete = false;
|
let firstSeekComplete = false;
|
||||||
player.on("seeked", async (event) => {
|
video.addEventListener("seeked", async (event) => {
|
||||||
if (!firstSeekComplete) {
|
if (!firstSeekComplete) {
|
||||||
// The first seeked event is performed by the browser when the video is loading
|
// The first seeked event is performed by the browser when the video is loading
|
||||||
firstSeekComplete = true;
|
firstSeekComplete = true;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (outgoingDebounce || player.elements.inputs.seek.disabled) {
|
if (outgoingDebounce) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.send(
|
socket.send(
|
||||||
JSON.stringify({
|
JSON.stringify({
|
||||||
op: "SetTime",
|
op: "SetTime",
|
||||||
data: {
|
data: currentVideoTime(),
|
||||||
to: currentVideoTime(),
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const joinSession = async (created) => {
|
/**
|
||||||
if (state().activeSession) {
|
* @param {string} nickname
|
||||||
if (state().activeSession === state().sessionId) {
|
* @param {string} sessionId
|
||||||
// we are already in this session, dont rejoin
|
*/
|
||||||
return;
|
export const joinSession = async (nickname, sessionId) => {
|
||||||
}
|
|
||||||
// we are joining a new session from an existing session
|
|
||||||
const messageContent = document.createElement("span");
|
|
||||||
messageContent.appendChild(document.createTextNode("joining new session "));
|
|
||||||
messageContent.appendChild(document.createTextNode(state().sessionId));
|
|
||||||
|
|
||||||
printChatMessage("join-session", "watch-party", "#fffff", messageContent);
|
|
||||||
}
|
|
||||||
state().activeSession = state().sessionId;
|
|
||||||
|
|
||||||
// try { // we are handling errors in the join form.
|
|
||||||
const genericConnectionError = new Error(
|
|
||||||
"There was an issue getting the session information."
|
|
||||||
);
|
|
||||||
window.location.hash = state().sessionId;
|
|
||||||
let response, video_url, subtitle_tracks, current_time_ms, is_playing;
|
|
||||||
try {
|
try {
|
||||||
response = await fetch(`/sess/${state().sessionId}`);
|
window.location.hash = sessionId;
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
throw genericConnectionError;
|
|
||||||
}
|
|
||||||
if (!response.ok) {
|
|
||||||
let error;
|
|
||||||
try {
|
|
||||||
({ error } = await response.json());
|
|
||||||
if (!error) throw new Error();
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
throw genericConnectionError;
|
|
||||||
}
|
|
||||||
throw new Error(error);
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
({ video_url, subtitle_tracks, current_time_ms, is_playing } =
|
|
||||||
await response.json());
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e);
|
|
||||||
throw genericConnectionError;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state().socket) {
|
const { video_url, subtitle_tracks, current_time_ms, is_playing } =
|
||||||
state().socket.close();
|
await fetch(`/sess/${sessionId}`).then((r) => r.json());
|
||||||
state().socket = null;
|
|
||||||
}
|
const socket = createWebSocket(sessionId, nickname);
|
||||||
const socket = createWebSocket();
|
|
||||||
state().socket = socket;
|
|
||||||
socket.addEventListener("open", async () => {
|
socket.addEventListener("open", async () => {
|
||||||
player = await setupVideo(
|
const video = await setupVideo(
|
||||||
video_url,
|
video_url,
|
||||||
subtitle_tracks,
|
subtitle_tracks,
|
||||||
current_time_ms,
|
current_time_ms,
|
||||||
is_playing,
|
is_playing
|
||||||
created
|
|
||||||
);
|
);
|
||||||
|
|
||||||
player.on("canplay", () => {
|
setupOutgoingEvents(video, socket);
|
||||||
sync();
|
setupIncomingEvents(video, socket);
|
||||||
});
|
|
||||||
|
|
||||||
setupOutgoingEvents(player, socket);
|
|
||||||
setupIncomingEvents(player, socket);
|
|
||||||
setupChat(socket);
|
setupChat(socket);
|
||||||
});
|
});
|
||||||
socket.addEventListener("reconnecting", (e) => {
|
// TODO: Close listener ?
|
||||||
console.log("Reconnecting...");
|
} catch (err) {
|
||||||
});
|
// TODO: Show an error on the screen
|
||||||
socket.addEventListener("reconnected", (e) => {
|
console.error(err);
|
||||||
console.log("Reconnected.");
|
}
|
||||||
});
|
|
||||||
//} catch (e) {
|
|
||||||
// alert(e.message)
|
|
||||||
//}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* @param {string} videoUrl
|
|
||||||
* @param {Array} subtitleTracks
|
|
||||||
*/
|
|
||||||
export const createSession = async (videoUrl, subtitleTracks) => {
|
|
||||||
const { id } = await fetch("/start_session", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
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);
|
|
||||||
};
|
};
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
import { setupJoinSessionForm } from "./lib/join-session.mjs?v=4b61c4";
|
import { setupJoinSessionForm } from "./lib/join-session.mjs";
|
||||||
|
|
||||||
const main = () => {
|
const main = () => {
|
||||||
setupJoinSessionForm();
|
setupJoinSessionForm();
|
||||||
|
|
|
@ -1,38 +1,7 @@
|
||||||
*,
|
|
||||||
*:before,
|
|
||||||
*:after {
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
|
||||||
|
|
||||||
:root {
|
:root {
|
||||||
--bg-rgb: 28, 23, 36;
|
--bg: rgb(28, 23, 36);
|
||||||
--fg-rgb: 234, 234, 248;
|
--fg: rgb(234, 234, 248);
|
||||||
--accent-rgb: 181, 127, 220;
|
--accent: hsl(275, 57%, 68%);
|
||||||
--fg: rgb(var(--fg-rgb));
|
|
||||||
--bg: rgb(var(--bg-rgb));
|
|
||||||
--default-user-color: rgb(126, 208, 255);
|
|
||||||
--accent: rgb(var(--accent-rgb));
|
|
||||||
--fg-transparent: rgba(var(--fg-rgb), 0.25);
|
|
||||||
--bg-transparent: rgba(var(--bg-rgb), 0.25);
|
|
||||||
--autocomplete-bg: linear-gradient(
|
|
||||||
var(--fg-transparent),
|
|
||||||
var(--fg-transparent)
|
|
||||||
),
|
|
||||||
linear-gradient(var(--bg), var(--bg));
|
|
||||||
--chip-bg: linear-gradient(
|
|
||||||
var(--accent-transparent),
|
|
||||||
var(--accent-transparent)
|
|
||||||
),
|
|
||||||
linear-gradient(var(--bg), var(--bg));
|
|
||||||
--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 {
|
||||||
|
@ -40,115 +9,45 @@ html {
|
||||||
color: var(--fg);
|
color: var(--fg);
|
||||||
font-size: 1.125rem;
|
font-size: 1.125rem;
|
||||||
font-family: sans-serif;
|
font-family: sans-serif;
|
||||||
|
|
||||||
|
overflow-y: scroll;
|
||||||
|
scrollbar-width: none;
|
||||||
|
-ms-overflow-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar {
|
||||||
|
width: 0;
|
||||||
|
background: transparent;
|
||||||
}
|
}
|
||||||
|
|
||||||
html,
|
html,
|
||||||
body {
|
body {
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0;
|
|
||||||
overflow: hidden;
|
|
||||||
overscroll-behavior: none;
|
|
||||||
width: 100%;
|
|
||||||
height: 100%;
|
height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
video {
|
||||||
display: flex;
|
display: block;
|
||||||
flex-direction: column;
|
|
||||||
}
|
|
||||||
|
|
||||||
.lock-controls.plyr__control--pressed svg {
|
width: 100vw;
|
||||||
opacity: 0.5;
|
height: auto;
|
||||||
}
|
|
||||||
|
|
||||||
.plyr {
|
max-width: auto;
|
||||||
width: 100%;
|
max-height: 100vh;
|
||||||
height: 100%;
|
|
||||||
}
|
|
||||||
|
|
||||||
.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 {
|
|
||||||
flex-grow: 0;
|
|
||||||
flex-shrink: 1;
|
|
||||||
display: none;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
a {
|
a {
|
||||||
color: var(--accent);
|
color: var(--accent);
|
||||||
}
|
}
|
||||||
|
|
||||||
.chip {
|
|
||||||
color: var(--fg);
|
|
||||||
background: var(--chip-bg);
|
|
||||||
text-decoration: none;
|
|
||||||
padding: 0 0.5rem 0 1.45rem;
|
|
||||||
display: inline-flex;
|
|
||||||
position: relative;
|
|
||||||
font-size: 0.9rem;
|
|
||||||
height: 1.125rem;
|
|
||||||
align-items: center;
|
|
||||||
border-radius: 2rem;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chip::before {
|
|
||||||
content: "";
|
|
||||||
position: absolute;
|
|
||||||
left: 0;
|
|
||||||
top: 0;
|
|
||||||
width: 1.125rem;
|
|
||||||
height: 100%;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
text-align: center;
|
|
||||||
background: var(--accent-transparent);
|
|
||||||
background-repeat: no-repeat;
|
|
||||||
background-size: 18px;
|
|
||||||
background-position: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
.join-chip::before {
|
|
||||||
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0iI2ZmZiI+PHBhdGggZD0iTTggNXYxNGwxMS03eiIvPjwvc3ZnPg==");
|
|
||||||
}
|
|
||||||
|
|
||||||
.time-chip::before {
|
|
||||||
background-image: url("data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0iI2ZmZiI+PHBhdGggZD0iTTExLjk5IDJDNi40NyAyIDIgNi40OCAyIDEyczQuNDcgMTAgOS45OSAxMEMxNy41MiAyMiAyMiAxNy41MiAyMiAxMlMxNy41MiAyIDExLjk5IDJ6TTEyIDIwYy00LjQyIDAtOC0zLjU4LTgtOHMzLjU4LTggOC04IDggMy41OCA4IDgtMy41OCA4LTggOHoiLz48cGF0aCBkPSJNMTIuNSA3SDExdjZsNS4yNSAzLjE1Ljc1LTEuMjMtNC41LTIuNjd6Ii8+PC9zdmc+");
|
|
||||||
}
|
|
||||||
|
|
||||||
label {
|
label {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
input[type="url"],
|
input[type="url"],
|
||||||
input[type="text"] {
|
input[type="text"] {
|
||||||
|
box-sizing: border-box;
|
||||||
|
|
||||||
background: #fff;
|
background: #fff;
|
||||||
background-clip: padding-box;
|
background-clip: padding-box;
|
||||||
border: 1px solid rgba(0, 0, 0, 0.12);
|
border: 1px solid rgba(0, 0, 0, 0.12);
|
||||||
|
@ -162,14 +61,15 @@ input[type="text"] {
|
||||||
|
|
||||||
font-family: sans-serif;
|
font-family: sans-serif;
|
||||||
font-size: 1em;
|
font-size: 1em;
|
||||||
width: 100%;
|
width: 500px;
|
||||||
|
|
||||||
resize: none;
|
resize: none;
|
||||||
overflow-x: wrap;
|
overflow-x: wrap;
|
||||||
overflow-y: scroll;
|
overflow-y: scroll;
|
||||||
}
|
}
|
||||||
|
|
||||||
button:not(.plyr button) {
|
button,
|
||||||
|
input[type="button"] {
|
||||||
background-color: var(--accent);
|
background-color: var(--accent);
|
||||||
border: var(--accent);
|
border: var(--accent);
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
|
@ -183,19 +83,11 @@ button:not(.plyr button) {
|
||||||
|
|
||||||
font-family: sans-serif;
|
font-family: sans-serif;
|
||||||
font-size: 1em;
|
font-size: 1em;
|
||||||
width: 100%;
|
width: 500px;
|
||||||
|
|
||||||
user-select: none;
|
user-select: none;
|
||||||
border: 1px solid rgba(0, 0, 0, 0);
|
border: 1px solid rgba(0, 0, 0, 0);
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
cursor: pointer;
|
|
||||||
margin: 0.5em 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
button:disabled {
|
|
||||||
filter: saturate(0.75);
|
|
||||||
opacity: 0.75;
|
|
||||||
cursor: default;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
button.small-button {
|
button.small-button {
|
||||||
|
@ -214,222 +106,62 @@ button.small-button {
|
||||||
margin-right: 1ch !important;
|
margin-right: 1ch !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
#pre-join-controls,
|
#pre-join-controls {
|
||||||
#create-controls {
|
width: 60%;
|
||||||
margin: 0;
|
margin: 0 auto;
|
||||||
flex-grow: 1;
|
margin-top: 4em;
|
||||||
overflow-y: auto;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
align-items: center;
|
|
||||||
justify-content: center;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#join-session-form,
|
#join-session-form {
|
||||||
#create-session-form {
|
margin-bottom: 4em;
|
||||||
width: 500px;
|
|
||||||
max-width: 100%;
|
|
||||||
padding: 1rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
#join-session-form > *:first-child,
|
|
||||||
#create-session-form > *:first-child {
|
|
||||||
margin-top: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
#post-create-message {
|
|
||||||
display: none;
|
|
||||||
width: 100%;
|
|
||||||
font-size: 0.85em;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#chatbox-container {
|
#chatbox-container {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.chat-message {
|
#chatbox-container.popped-out {
|
||||||
overflow-wrap: break-word;
|
width: 100%;
|
||||||
margin-bottom: 0.125rem;
|
height: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.chat-message > strong,
|
#chatbox-container.popped-out > #chatbox {
|
||||||
#viewer-list strong {
|
height: calc(100vh - 5em);
|
||||||
color: var(--user-color, var(--default-user-color));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.chat-message.user-join,
|
.user-join,
|
||||||
.chat-message.user-leave,
|
.user-leave {
|
||||||
.chat-message.ping {
|
|
||||||
font-style: italic;
|
font-style: italic;
|
||||||
}
|
}
|
||||||
|
|
||||||
.chat-message.set-time,
|
.chat-message > strong {
|
||||||
.chat-message.set-playing,
|
color: rgb(126, 208, 255);
|
||||||
.chat-message.join-session {
|
|
||||||
font-style: italic;
|
|
||||||
text-align: right;
|
|
||||||
font-size: 0.85em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chat-message.command-message {
|
|
||||||
font-size: 0.85em;
|
|
||||||
}
|
|
||||||
|
|
||||||
.chat-message.set-time > strong,
|
|
||||||
.chat-message.set-playing > strong,
|
|
||||||
.chat-message.join-session > strong {
|
|
||||||
color: unset !important;
|
|
||||||
}
|
|
||||||
|
|
||||||
.emoji {
|
|
||||||
width: 2ch;
|
|
||||||
height: 2ch;
|
|
||||||
object-fit: contain;
|
|
||||||
margin-bottom: -0.35ch;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#chatbox {
|
#chatbox {
|
||||||
padding: 0.5em 1em;
|
padding: 0.5em 2em;
|
||||||
|
min-height: 8em;
|
||||||
overflow-y: scroll;
|
overflow-y: scroll;
|
||||||
flex-shrink: 1;
|
|
||||||
flex-grow: 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
#viewer-list {
|
|
||||||
padding: 0.5em 1em;
|
|
||||||
/* TODO: turn this into max-height instead of fixed height without breaking the chatbox height */
|
|
||||||
overflow-y: scroll;
|
|
||||||
border-bottom: var(--fg-transparent);
|
|
||||||
border-bottom-style: solid;
|
|
||||||
max-height: 4rem;
|
|
||||||
flex-shrink: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#chatbox-container {
|
#chatbox-container {
|
||||||
background-color: var(--bg);
|
background-color: #222;
|
||||||
flex-direction: column;
|
|
||||||
flex-grow: 1;
|
|
||||||
flex-shrink: 1;
|
|
||||||
flex-basis: 36ch;
|
|
||||||
min-width: 36ch;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#chatbox-send {
|
#chatbox-send {
|
||||||
padding: 0 1em;
|
padding: 0 2em;
|
||||||
padding-bottom: 0.5em;
|
padding-bottom: 0.5em;
|
||||||
position: relative;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#chatbox-send > input {
|
#chatbox-send > input {
|
||||||
font-size: 0.75em;
|
font-size: 0.75em;
|
||||||
width: 100%;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#emoji-autocomplete {
|
#message-box {
|
||||||
position: absolute;
|
display: inline-block;
|
||||||
bottom: 3.25rem;
|
|
||||||
background-image: var(--autocomplete-bg);
|
|
||||||
border-radius: 6px;
|
|
||||||
width: calc(100% - 2rem);
|
|
||||||
max-height: 8.5rem;
|
|
||||||
overflow-y: auto;
|
|
||||||
clip-path: inset(0 0 0 0 round 8px);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#emoji-autocomplete:empty {
|
#pop-chat {
|
||||||
display: none;
|
width: auto;
|
||||||
}
|
float: right;
|
||||||
|
|
||||||
.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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,23 +0,0 @@
|
||||||
#!/bin/sh
|
|
||||||
set -eu
|
|
||||||
|
|
||||||
# Get guild ID
|
|
||||||
if [ ! "$1" ];then
|
|
||||||
echo "You need to provide a Discord Guild ID."
|
|
||||||
exit 1
|
|
||||||
else
|
|
||||||
guild="$1"
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Get emoji folder
|
|
||||||
emojiFolder="$(readlink -f "$(dirname $0)/../frontend/emojis/")"
|
|
||||||
|
|
||||||
# Get Discord token
|
|
||||||
printf "Token: " 1>&2
|
|
||||||
trap 'stty echo' INT EXIT
|
|
||||||
stty -echo
|
|
||||||
read token
|
|
||||||
printf "\n" 1>&2
|
|
||||||
stty echo
|
|
||||||
|
|
||||||
curl "https://discord.com/api/v9/guilds/${guild}/emojis" -H "Authorization: $token" | jq --raw-output 'map((if .animated then ".gif" else ".png" end) as $ext | "curl '"'"'https://cdn.discordapp.com/emojis/" + .id + $ext + "?size=48&quality=lossless'"'"' -o '"'${emojiFolder}/"'" + .name + $ext + "'"'"'") | join("\n")' | sh
|
|
|
@ -1,6 +0,0 @@
|
||||||
#!/bin/sh
|
|
||||||
|
|
||||||
# Get emoji folder
|
|
||||||
emojiFolder="$(readlink -f "$(dirname $0)/../frontend/emojis/")"
|
|
||||||
|
|
||||||
curl 'https://raw.githubusercontent.com/iamcal/emoji-data/master/emoji.json' | jq '. | map(. as $emoji | .short_names | map([., ($emoji.unified | split("-") | map(. | split("") | map(. as $nibble | (["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"] | index($nibble))) | reduce .[] as $item (0; (. * 16) + $item)) | map(if (. < 65536) then (.) else [55296 - 64 + (. / 1024 | floor), 56320 + (((. / 1024) - (. / 1024 | floor)) * 1024)] end) | flatten(1) | map(("\\u" + ("0000" + ({"str": "", "num": .} | until(.num < 1; {"str": (["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"][((.num / 16) - (.num / 16 | floor)) * 16] + .str), "num": (.num / 16) | floor})).str)[-4:])) | join("") | "\"" + . + "\"" | fromjson)])) | flatten(1)' --raw-output >"$emojiFolder/unicode.json"
|
|
|
@ -1,52 +1,19 @@
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Deserialize)]
|
|
||||||
pub struct Viewer {
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub nickname: Option<String>,
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
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 WatchEvent {
|
||||||
SetPlaying {
|
SetPlaying {
|
||||||
playing: bool,
|
playing: bool,
|
||||||
time: u64,
|
time: u64,
|
||||||
},
|
},
|
||||||
SetTime {
|
SetTime(u64),
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
from: Option<u64>,
|
UserJoin(String),
|
||||||
to: u64,
|
UserLeave(String),
|
||||||
|
ChatMessage {
|
||||||
|
#[serde(default = "String::new")]
|
||||||
|
user: String,
|
||||||
|
message: String,
|
||||||
},
|
},
|
||||||
|
|
||||||
UserJoin,
|
|
||||||
UserLeave,
|
|
||||||
ChatMessage(String),
|
|
||||||
Ping(String),
|
|
||||||
UpdateViewerList(Vec<Viewer>),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Deserialize)]
|
|
||||||
pub struct WatchEvent {
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub user: Option<String>,
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub colour: Option<String>,
|
|
||||||
#[serde(flatten)]
|
|
||||||
pub data: WatchEventData,
|
|
||||||
#[serde(default)]
|
|
||||||
pub reflected: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WatchEvent {
|
|
||||||
pub fn new(user: String, colour: String, data: WatchEventData) -> Self {
|
|
||||||
WatchEvent {
|
|
||||||
user: Some(user),
|
|
||||||
colour: Some(colour),
|
|
||||||
data,
|
|
||||||
reflected: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
67
src/main.rs
67
src/main.rs
|
@ -6,15 +6,15 @@ 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 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,
|
events::WatchEvent,
|
||||||
watch_session::{get_session, SubtitleTrack, WatchSession, SESSIONS},
|
viewer_connection::{ws_publish, ws_subscribe},
|
||||||
|
watch_session::{get_session, handle_watch_event, SubtitleTrack, WatchSession, SESSIONS},
|
||||||
};
|
};
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
|
@ -27,23 +27,6 @@ struct StartSessionBody {
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct SubscribeQuery {
|
struct SubscribeQuery {
|
||||||
nickname: String,
|
nickname: String,
|
||||||
colour: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn get_emoji_list() -> Result<impl warb::Reply, warb::Rejection> {
|
|
||||||
use tokio_stream::{wrappers::ReadDirStream, StreamExt};
|
|
||||||
|
|
||||||
let dir = tokio::fs::read_dir("frontend/emojis")
|
|
||||||
.await
|
|
||||||
.expect("Couldn't read emojis directory!");
|
|
||||||
|
|
||||||
let files = ReadDirStream::new(dir)
|
|
||||||
.filter_map(|r| r.ok())
|
|
||||||
.map(|e| e.file_name().to_string_lossy().to_string())
|
|
||||||
.collect::<Vec<_>>()
|
|
||||||
.await;
|
|
||||||
|
|
||||||
Ok(warb::reply::json(&files))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
|
@ -62,8 +45,6 @@ async fn main() {
|
||||||
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!("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>),
|
||||||
|
@ -98,6 +79,43 @@ async fn main() {
|
||||||
RequestedSession::Error(e) => e,
|
RequestedSession::Error(e) => e,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let set_playing_route = get_running_session
|
||||||
|
.and(warb::path!("playing"))
|
||||||
|
.and(warb::put())
|
||||||
|
.and(warb::body::json())
|
||||||
|
.map(|requested_session, playing: bool| match requested_session {
|
||||||
|
RequestedSession::Session(uuid, mut sess) => {
|
||||||
|
let event = WatchEvent::SetPlaying {
|
||||||
|
playing,
|
||||||
|
time: sess.get_time_ms(),
|
||||||
|
};
|
||||||
|
|
||||||
|
handle_watch_event(uuid, &mut sess, event.clone());
|
||||||
|
tokio::spawn(ws_publish(uuid, None, event));
|
||||||
|
|
||||||
|
warb::reply::with_status(warb::reply::json(&sess.view()), StatusCode::OK)
|
||||||
|
}
|
||||||
|
RequestedSession::Error(e) => e,
|
||||||
|
});
|
||||||
|
|
||||||
|
let set_timestamp_route = get_running_session
|
||||||
|
.and(warb::path!("current_time"))
|
||||||
|
.and(warb::put())
|
||||||
|
.and(warb::body::json())
|
||||||
|
.map(
|
||||||
|
|requested_session, current_time_ms: u64| match requested_session {
|
||||||
|
RequestedSession::Session(uuid, mut sess) => {
|
||||||
|
let event = WatchEvent::SetTime(current_time_ms);
|
||||||
|
|
||||||
|
handle_watch_event(uuid, &mut sess, event.clone());
|
||||||
|
tokio::spawn(ws_publish(uuid, None, event));
|
||||||
|
|
||||||
|
warb::reply::with_status(warb::reply::json(&sess.view()), StatusCode::OK)
|
||||||
|
}
|
||||||
|
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())
|
||||||
|
@ -105,7 +123,7 @@ async fn main() {
|
||||||
.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, ws))
|
||||||
.into_response(),
|
.into_response(),
|
||||||
RequestedSession::Error(error_response) => error_response.into_response(),
|
RequestedSession::Error(error_response) => error_response.into_response(),
|
||||||
},
|
},
|
||||||
|
@ -113,8 +131,9 @@ async fn main() {
|
||||||
|
|
||||||
let routes = start_session_route
|
let routes = start_session_route
|
||||||
.or(get_status_route)
|
.or(get_status_route)
|
||||||
|
.or(set_playing_route)
|
||||||
|
.or(set_timestamp_route)
|
||||||
.or(ws_subscribe_route)
|
.or(ws_subscribe_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"));
|
||||||
|
|
||||||
|
|
|
@ -1,6 +0,0 @@
|
||||||
pub fn truncate_str(s: &str, max_chars: usize) -> &str {
|
|
||||||
match s.char_indices().nth(max_chars) {
|
|
||||||
None => s,
|
|
||||||
Some((idx, _)) => &s[..idx],
|
|
||||||
}
|
|
||||||
}
|
|
|
@ -15,9 +15,8 @@ use uuid::Uuid;
|
||||||
use warp::ws::{Message, WebSocket};
|
use warp::ws::{Message, WebSocket};
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
events::{Viewer, WatchEvent, WatchEventData},
|
events::WatchEvent,
|
||||||
utils::truncate_str,
|
watch_session::{get_session, handle_watch_event},
|
||||||
watch_session::{get_session, handle_watch_event_data},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
static CONNECTED_VIEWERS: Lazy<RwLock<HashMap<usize, ConnectedViewer>>> =
|
static CONNECTED_VIEWERS: Lazy<RwLock<HashMap<usize, ConnectedViewer>>> =
|
||||||
|
@ -28,11 +27,9 @@ 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 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, 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();
|
||||||
|
|
||||||
|
@ -50,34 +47,19 @@ pub async fn ws_subscribe(session_uuid: Uuid, nickname: String, colour: String,
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut colour = colour;
|
|
||||||
if colour.len() != 6 || !colour.chars().all(|x| x.is_ascii_hexdigit()) {
|
|
||||||
colour = String::from("7ed0ff");
|
|
||||||
}
|
|
||||||
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()),
|
|
||||||
colour: Some(colour.clone()),
|
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
ws_publish(
|
ws_publish(session_uuid, None, WatchEvent::UserJoin(nickname.clone())).await;
|
||||||
session_uuid,
|
|
||||||
None,
|
|
||||||
WatchEvent::new(nickname.clone(), colour.clone(), WatchEventData::UserJoin),
|
|
||||||
)
|
|
||||||
.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 mut event: WatchEvent = 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())
|
||||||
|
@ -86,71 +68,47 @@ pub async fn ws_subscribe(session_uuid: Uuid, nickname: String, colour: String,
|
||||||
None => continue,
|
None => continue,
|
||||||
};
|
};
|
||||||
|
|
||||||
let session = &mut get_session(session_uuid).unwrap();
|
// Make sure people don't spoof their nicknames to pretend to be others
|
||||||
|
// If a nickname change is required, I guess reconnect idk
|
||||||
// server side event modification where neccessary
|
if let WatchEvent::ChatMessage { user: _, message } = event {
|
||||||
let event: WatchEventData = match event {
|
event = WatchEvent::ChatMessage {
|
||||||
WatchEventData::SetTime { from: _, to } => WatchEventData::SetTime {
|
user: nickname.clone(),
|
||||||
from: Some(session.get_time_ms()),
|
message,
|
||||||
to,
|
|
||||||
},
|
|
||||||
_ => event,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
handle_watch_event_data(session_uuid, session, event.clone());
|
// Don't pass through the viewer_id because we want the chat message
|
||||||
|
// to be reflected to the user.
|
||||||
|
ws_publish(session_uuid, None, event).await;
|
||||||
|
|
||||||
ws_publish(
|
// We don't need to handle() chat messages,
|
||||||
session_uuid,
|
// and we are already publishing them ourselves.
|
||||||
Some(viewer_id),
|
continue;
|
||||||
WatchEvent::new(nickname.clone(), colour.clone(), event),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ws_publish(
|
handle_watch_event(
|
||||||
session_uuid,
|
session_uuid,
|
||||||
None,
|
&mut get_session(session_uuid).unwrap(),
|
||||||
WatchEvent::new(nickname.clone(), colour.clone(), WatchEventData::UserLeave),
|
event.clone(),
|
||||||
)
|
);
|
||||||
.await;
|
|
||||||
|
ws_publish(session_uuid, Some(viewer_id), event).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
ws_publish(session_uuid, None, WatchEvent::UserLeave(nickname.clone())).await;
|
||||||
|
|
||||||
CONNECTED_VIEWERS.write().await.remove(&viewer_id);
|
CONNECTED_VIEWERS.write().await.remove(&viewer_id);
|
||||||
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, viewer_id: Option<usize>, event: WatchEvent) {
|
||||||
for viewer in CONNECTED_VIEWERS.read().await.values() {
|
for viewer in CONNECTED_VIEWERS.read().await.values() {
|
||||||
|
if viewer_id == Some(viewer.viewer_id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if viewer.session != session_uuid {
|
if viewer.session != session_uuid {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let _ = viewer.tx.send(WatchEvent {
|
let _ = viewer.tx.send(event.clone());
|
||||||
reflected: skip_viewer_id == Some(viewer.viewer_id),
|
|
||||||
..event.clone()
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn update_viewer_list(session_uuid: Uuid) {
|
|
||||||
let mut viewers = Vec::new();
|
|
||||||
|
|
||||||
for viewer in CONNECTED_VIEWERS.read().await.values() {
|
|
||||||
if viewer.session == session_uuid {
|
|
||||||
viewers.push(Viewer {
|
|
||||||
nickname: viewer.nickname.clone(),
|
|
||||||
colour: viewer.colour.clone(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
ws_publish(
|
|
||||||
session_uuid,
|
|
||||||
None,
|
|
||||||
WatchEvent::new(
|
|
||||||
String::from("server"),
|
|
||||||
String::from(""),
|
|
||||||
WatchEventData::UpdateViewerList(viewers),
|
|
||||||
),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
|
|
|
@ -3,7 +3,7 @@ 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::WatchEvent;
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Clone)]
|
#[derive(Serialize, Deserialize, Clone)]
|
||||||
pub struct SubtitleTrack {
|
pub struct SubtitleTrack {
|
||||||
|
@ -75,18 +75,14 @@ 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(uuid: Uuid, watch_session: &mut WatchSession, event: WatchEvent) {
|
||||||
uuid: Uuid,
|
|
||||||
watch_session: &mut WatchSession,
|
|
||||||
event: WatchEventData,
|
|
||||||
) {
|
|
||||||
match event {
|
match event {
|
||||||
WatchEventData::SetPlaying { playing, time } => {
|
WatchEvent::SetPlaying { playing, time } => {
|
||||||
watch_session.set_playing(playing, time);
|
watch_session.set_playing(playing, time);
|
||||||
}
|
}
|
||||||
|
|
||||||
WatchEventData::SetTime { from: _, to } => {
|
WatchEvent::SetTime(time) => {
|
||||||
watch_session.set_time_ms(to);
|
watch_session.set_time_ms(time);
|
||||||
}
|
}
|
||||||
|
|
||||||
_ => {}
|
_ => {}
|
||||||
|
|
Loading…
Reference in New Issue