Files

721 lines
13 KiB
JavaScript

// room-auth.js
window.Kronick =
window.Kronick || {};
Kronick.roomAuth = {
status:
null,
checkedRoomName:
'',
pendingResolve:
null,
pendingReject:
null,
statusTimer:
null
};
Kronick.normalizeRoomName =
function normalizeRoomName(value) {
return String(
value || ''
)
.trim()
.toLowerCase();
};
Kronick.getOwnerTokenStorageKey =
function getOwnerTokenStorageKey(
roomName
) {
return (
'kronickRoomOwner:'
+ Kronick.normalizeRoomName(
roomName
)
);
};
Kronick.getStoredRoomOwnerToken =
function getStoredRoomOwnerToken(
roomName
) {
return localStorage.getItem(
Kronick.getOwnerTokenStorageKey(
roomName
)
) || '';
};
Kronick.saveRoomOwnerToken =
function saveRoomOwnerToken(
roomName,
ownerToken
) {
if (
!roomName
|| !ownerToken
) {
return;
}
localStorage.setItem(
Kronick.getOwnerTokenStorageKey(
roomName
),
ownerToken
);
};
Kronick.removeRoomOwnerToken =
function removeRoomOwnerToken(
roomName
) {
localStorage.removeItem(
Kronick.getOwnerTokenStorageKey(
roomName
)
);
};
Kronick.formatCooldownTime =
function formatCooldownTime(seconds) {
const remaining =
Math.max(
0,
Number(seconds || 0)
);
const hours =
Math.floor(
remaining / 3600
);
const minutes =
Math.ceil(
(
remaining % 3600
) / 60
);
if (hours > 0) {
return (
`${hours}h ${minutes}m`
);
}
return `${minutes}m`;
};
Kronick.checkRoomStatus =
async function checkRoomStatus(
roomName
) {
const normalizedRoom =
Kronick.normalizeRoomName(
roomName
);
const statusElement =
document.getElementById(
'roomAvailabilityStatus'
);
if (
normalizedRoom.length < 3
) {
Kronick.roomAuth.status =
null;
Kronick.roomAuth
.checkedRoomName =
'';
if (statusElement) {
statusElement.textContent =
'Enter at least 3 characters.';
}
return null;
}
if (statusElement) {
statusElement.textContent =
'Checking room...';
}
try {
const response =
await fetch(
'/api/rooms/'
+ encodeURIComponent(
normalizedRoom
)
+ '/status',
{
cache:
'no-store'
}
);
const data =
await response.json();
if (!response.ok) {
throw new Error(
typeof data.detail
=== 'string'
? data.detail
: 'Could not check room.'
);
}
Kronick.roomAuth.status =
data;
Kronick.roomAuth
.checkedRoomName =
normalizedRoom;
if (statusElement) {
if (data.exists) {
statusElement.textContent =
'Room exists — enter its password.';
} else if (data.cooldown) {
statusElement.textContent =
'Room name unavailable for '
+ Kronick.formatCooldownTime(
data
.cooldownSecondsRemaining
)
+ '.';
} else {
statusElement.textContent =
'Room is available — you will create it.';
}
}
return data;
} catch (error) {
console.error(
'Room status check failed:',
error
);
Kronick.roomAuth.status =
null;
if (statusElement) {
statusElement.textContent =
'Could not check room status.';
}
return null;
}
};
Kronick.ensureCurrentRoomStatus =
async function ensureCurrentRoomStatus() {
const roomInput =
document.getElementById(
'roomName'
);
const roomName =
Kronick.normalizeRoomName(
roomInput?.value
);
if (!roomName) {
throw new Error(
'Enter a room name.'
);
}
if (
Kronick.roomAuth
.checkedRoomName
=== roomName
&& Kronick.roomAuth.status
) {
return Kronick.roomAuth.status;
}
const status =
await Kronick.checkRoomStatus(
roomName
);
if (!status) {
throw new Error(
'Room status could not be determined.'
);
}
return status;
};
Kronick.openRoomAuthModal =
async function openRoomAuthModal() {
const roomInput =
document.getElementById(
'roomName'
);
const roomName =
Kronick.normalizeRoomName(
roomInput?.value
);
const status =
await Kronick
.ensureCurrentRoomStatus();
if (status.cooldown) {
throw new Error(
'That room name is unavailable for '
+ Kronick.formatCooldownTime(
status
.cooldownSecondsRemaining
)
+ '.'
);
}
const modal =
document.getElementById(
'roomAuthModal'
);
const title =
document.getElementById(
'roomAuthTitle'
);
const message =
document.getElementById(
'roomAuthMessage'
);
const passwordInput =
document.getElementById(
'roomAuthPassword'
);
const confirmationInput =
document.getElementById(
'roomAuthPasswordConfirm'
);
const confirmationGroup =
document.getElementById(
'roomAuthConfirmGroup'
);
const submitButton =
document.getElementById(
'roomAuthSubmitBtn'
);
const error =
document.getElementById(
'roomAuthError'
);
if (
!modal
|| !title
|| !message
|| !passwordInput
|| !confirmationInput
|| !confirmationGroup
|| !submitButton
|| !error
) {
throw new Error(
'Room authentication modal is incomplete.'
);
}
passwordInput.value =
'';
confirmationInput.value =
'';
error.hidden =
true;
error.textContent =
'';
if (status.exists) {
title.textContent =
'Join Room';
message.textContent =
`Enter the password for "${roomName}".`;
confirmationGroup.hidden =
true;
submitButton.textContent =
'Join Room';
} else {
title.textContent =
'Create Room';
message.textContent =
`The room "${roomName}" does not exist. `
+ 'Choose its permanent entry password.';
confirmationGroup.hidden =
false;
submitButton.textContent =
'Create Room';
}
modal.hidden =
false;
requestAnimationFrame(
() => {
passwordInput.focus();
}
);
return new Promise(
(
resolve,
reject
) => {
Kronick.roomAuth
.pendingResolve =
resolve;
Kronick.roomAuth
.pendingReject =
reject;
}
);
};
Kronick.closeRoomAuthModal =
function closeRoomAuthModal() {
const modal =
document.getElementById(
'roomAuthModal'
);
if (modal) {
modal.hidden =
true;
}
if (
Kronick.roomAuth
.pendingReject
) {
Kronick.roomAuth
.pendingReject(
new Error(
'Room authentication cancelled.'
)
);
}
Kronick.roomAuth
.pendingResolve =
null;
Kronick.roomAuth
.pendingReject =
null;
};
Kronick.submitRoomAuthentication =
function submitRoomAuthentication() {
const status =
Kronick.roomAuth.status;
const modal =
document.getElementById(
'roomAuthModal'
);
const passwordInput =
document.getElementById(
'roomAuthPassword'
);
const confirmationInput =
document.getElementById(
'roomAuthPasswordConfirm'
);
const error =
document.getElementById(
'roomAuthError'
);
const password =
passwordInput?.value || '';
const confirmation =
confirmationInput?.value || '';
if (!password) {
error.textContent =
'Enter a room password.';
error.hidden =
false;
return;
}
if (
!status?.exists
&& password.length < 8
) {
error.textContent =
'New passwords must contain at least 8 characters.';
error.hidden =
false;
return;
}
if (
!status?.exists
&& password !== confirmation
) {
error.textContent =
'The passwords do not match.';
error.hidden =
false;
return;
}
const resolve =
Kronick.roomAuth
.pendingResolve;
Kronick.roomAuth
.pendingResolve =
null;
Kronick.roomAuth
.pendingReject =
null;
if (modal) {
modal.hidden =
true;
}
resolve?.({
password,
creating:
!status.exists
});
};
Kronick.updateDeleteRoomButton =
function updateDeleteRoomButton(
roomName,
isOwner
) {
const button =
document.getElementById(
'deleteRoomBtn'
);
if (!button) {
return;
}
const ownerToken =
Kronick
.getStoredRoomOwnerToken(
roomName
);
button.hidden =
!isOwner
|| !ownerToken;
};
Kronick.requestDeleteCurrentRoom =
async function requestDeleteCurrentRoom() {
const roomName =
Kronick.normalizeRoomName(
Kronick.state
.currentRoomName
);
const ownerToken =
Kronick
.getStoredRoomOwnerToken(
roomName
);
if (
!roomName
|| !ownerToken
) {
alert(
'Room-owner authorization is unavailable.'
);
return;
}
const confirmed =
window.confirm(
`Delete "${roomName}" permanently?\n\n`
+ 'Everyone will be disconnected and '
+ 'the room name will be locked for 24 hours.'
);
if (!confirmed) {
return;
}
const response =
await fetch(
'/api/rooms/'
+ encodeURIComponent(
roomName
),
{
method:
'DELETE',
headers: {
Authorization:
`Bearer ${ownerToken}`
}
}
);
const data =
await response.json();
if (!response.ok) {
const detail =
typeof data.detail
=== 'string'
? data.detail
: data.detail?.message
|| 'Room deletion failed.';
alert(detail);
return;
}
Kronick.removeRoomOwnerToken(
roomName
);
Kronick.disconnect();
await Kronick.checkRoomStatus(
roomName
);
alert(
'Room deleted. Its name is reserved for 24 hours.'
);
};
window.closeRoomAuthModal =
function closeRoomAuthModal() {
return Kronick
.closeRoomAuthModal();
};
window.submitRoomAuthentication =
function submitRoomAuthentication() {
return Kronick
.submitRoomAuthentication();
};
window.requestDeleteCurrentRoom =
function requestDeleteCurrentRoom() {
return Kronick
.requestDeleteCurrentRoom();
};
window.addEventListener(
'DOMContentLoaded',
() => {
const roomInput =
document.getElementById(
'roomName'
);
roomInput?.addEventListener(
'input',
() => {
clearTimeout(
Kronick.roomAuth
.statusTimer
);
Kronick.roomAuth
.statusTimer =
setTimeout(
() => {
Kronick.checkRoomStatus(
roomInput.value
);
},
450
);
}
);
document
.querySelectorAll(
'[data-room-auth-close]'
)
.forEach(element => {
element.addEventListener(
'click',
() => {
Kronick
.closeRoomAuthModal();
}
);
});
}
);