watch-party/frontend/lib/create-session.mjs

49 lines
1.6 KiB
JavaScript

import { createSession } from "./watch-session.mjs?v=bfdcf21";
const getFreeSessionId = async () => {
// fetch /random_unused_session
const response = await fetch("/random_unused_session");
const json = await response.json();
return json.id;
}
const checkIfSessionExists = async (sessionId) => {
// fetch /check_if_session_exists/:sessionId
const response = await fetch(`/check_if_session_exists/${sessionId}`);
const json = await response.json();
return json.exists;
}
export const setupCreateSessionForm = async () => {
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");
const sessionId = form.querySelector("#create-session-id");
// get free session id
const freeSessionId = await getFreeSessionId();
// set session id to free session id
sessionId.placeholder = freeSessionId;
// sessionId.value = freeSessionId;
form.addEventListener("submit", async (event) => {
event.preventDefault();
const realSessionId = sessionId.value || sessionId.placeholder;
// check if session exists
const exists = await checkIfSessionExists(realSessionId);
if (exists) {
alert("Session already exists");
return;
}
let subs = [];
if (subsUrl.value) {
subs.push({ url: subsUrl.value, name: subsName.value || "default" });
}
createSession(realSessionId, videoUrl.value, subs);
});
}