Upload files to "kronic-chat/js"

This commit is contained in:
2026-11-25 20:26:02 -06:00
parent 2615897782
commit 159e5137ab
5 changed files with 2301 additions and 0 deletions
+640
View File
@@ -0,0 +1,640 @@
const $ = id => document.getElementById(id);
let state = {
users: [],
groups: [],
memberships: [],
rooms: []
};
async function api(url, opts = {}) {
opts.credentials = 'same-origin';
if (
opts.body
&& typeof opts.body !== 'string'
) {
opts.headers = {
...(opts.headers || {}),
'Content-Type': 'application/json'
};
opts.body =
JSON.stringify(
opts.body
);
}
const r =
await fetch(
url,
opts
);
const d =
await r.json()
.catch(
() => ({})
);
/*
* No valid login session at all.
*
* Send the user to the admin login flow.
*/
if (
r.status === 401
) {
location.replace(
'/login?admin=1'
);
throw new Error(
'Login required'
);
}
/*
* Authenticated, but not authorized for admin.
*
* Do NOT redirect back to /app.
* Stay on the admin page and report the problem.
*/
if (
r.status === 403
) {
throw new Error(
typeof d.detail === 'string'
? d.detail
: 'Administrator access required.'
);
}
if (
!r.ok
) {
throw new Error(
typeof d.detail === 'string'
? d.detail
: 'Request failed'
);
}
return d;
}
function msg(t) {
$('status').textContent =
t;
setTimeout(
() => {
if (
$('status').textContent
=== t
) {
$('status').textContent =
'';
}
},
3500
);
}
async function load() {
try {
state =
await api(
'/api/admin/overview'
);
render();
} catch (e) {
/*
* Important:
*
* Do NOT redirect to /app here.
*
* If the user already has a valid login session,
* redirecting to /app creates the exact behavior
* we don't want.
*/
msg(
e.message
);
console.error(
'Admin overview failed:',
e
);
}
}
function render() {
const pending =
state.users.filter(
u => u.status === 'pending'
);
$('pendingUsers').innerHTML =
pending.length
? pending.map(
u => `
<div class="row">
<div>
<b>${esc(u.username)}</b>
<div class="muted">
${esc(u.email)}
</div>
</div>
<div>
<button
class="approve"
onclick="setStatus(${u.id}, 'active')"
>
Approve
</button>
<button
class="deny"
onclick="setStatus(${u.id}, 'denied')"
>
Deny
</button>
</div>
</div>
`
).join('')
: '<div class="muted">No pending accounts.</div>';
$('users').innerHTML =
state.users.map(
u => `
<div class="row">
<div>
<b>${esc(u.username)}</b>
<span class="pill">
${u.status}
</span>
${
u.isPlatformAdmin
? '<span class="pill">platform admin</span>'
: ''
}
<div class="muted">
${esc(u.email)}
</div>
</div>
<div>
${
u.status === 'active'
? `
<button
onclick="setStatus(${u.id}, 'disabled')"
>
Disable
</button>
`
: `
<button
onclick="setStatus(${u.id}, 'active')"
>
Activate
</button>
`
}
${u.isPlatformAdmin ? '' : `<button class="danger" onclick="deleteAccount(${u.id})">Delete Account</button>`}
</div>
</div>
`
).join('');
$('groups').innerHTML =
'<div class="grid">'
+ state.groups.map(
g => `
<div class="card">
<b>${esc(g.name)}</b>
<div class="muted">
${esc(g.slug)}
· ${g.user_count}/${g.max_users} users
· ${g.room_count}/${g.max_rooms} rooms
</div>
<div class="muted">
subscription:
${esc(g.subscription_status)}
· media:
${g.media_enabled ? 'on' : 'off'}
</div>
</div>
`
).join('')
+ '</div>';
$('memberships').innerHTML =
state.memberships.map(
m => `
<div class="row">
<div>
<b>${esc(m.username)}</b>
→
${esc(m.group_name)}
</div>
<span class="pill">
${m.role}
</span>
</div>
`
).join('')
|| '<div class="muted">No memberships.</div>';
$('rooms').innerHTML =
state.rooms.map(
r => `
<div class="row">
<div>
<b>
${esc(
r.display_name
|| r.room_name
)}
</b>
<div class="muted">
${esc(r.group_name)}
·
${esc(r.room_name)}
</div>
</div>
<button
class="danger"
onclick="deleteRoom(${r.id})"
>
Delete
</button>
</div>
`
).join('')
|| '<div class="muted">No managed rooms.</div>';
fill(
$('memberGroup'),
state.groups,
'id',
'name'
);
fill(
$('roomGroup'),
state.groups,
'id',
'name'
);
renderRegistrationRooms();
fill($('roomRoleRoom'), state.rooms, 'id', 'display_name');
fill($('roomRoleUser'), state.users.filter(u => u.status === 'active'), 'id', 'username');
fill(
$('memberUser'),
state.users.filter(
u => u.status === 'active'
),
'id',
'username'
);
}
function fill(
el,
items,
val,
label
) {
const old =
el.value;
el.innerHTML =
items.map(
x => `
<option value="${x[val]}">
${esc(x[label])}
</option>
`
).join('');
if (
[...el.options].some(
o => o.value === old
)
) {
el.value =
old;
}
}
function esc(v) {
return String(
v ?? ''
).replace(
/[&<>"']/g,
c => ({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
}[c])
);
}
window.setStatus =
async (
id,
status
) => {
try {
await api(
`/api/admin/users/${id}/status`,
{
method:
'PATCH',
body: {
status
}
}
);
await load();
msg(
`User ${status}.`
);
} catch (e) {
msg(
e.message
);
}
};
window.deleteAccount = async id => {
const user = state.users.find(u => u.id === id);
if (!user || user.isPlatformAdmin) return;
const typed = prompt(`PERMANENTLY delete ${user.username} and release ${user.email}?\nType the exact username to confirm:`);
if (typed !== user.username) return;
try {
await api(`/api/admin/users/${id}`, {method: 'DELETE'});
await load();
msg('Account permanently deleted.');
} catch (e) { msg(e.message); }
};
window.deleteRoom =
async id => {
if (
!confirm(
'Delete this managed room?'
)
) {
return;
}
try {
await api(
`/api/admin/rooms/${id}`,
{
method:
'DELETE'
}
);
await load();
msg(
'Room deleted.'
);
} catch (e) {
msg(
e.message
);
}
};
$('groupForm').onsubmit =
async e => {
e.preventDefault();
try {
await api(
'/api/admin/groups',
{
method:
'POST',
body: {
name:
$('groupName').value,
slug:
$('groupSlug').value,
max_users:
+$('groupMaxUsers').value,
max_rooms:
+$('groupMaxRooms').value
}
}
);
e.target.reset();
$('groupMaxUsers').value =
10;
$('groupMaxRooms').value =
10;
await load();
msg(
'Group created.'
);
} catch (e) {
msg(
e.message
);
}
};
$('memberForm').onsubmit =
async e => {
e.preventDefault();
try {
await api(
`/api/admin/groups/${$('memberGroup').value}/members`,
{
method:
'POST',
body: {
user_id:
+$('memberUser').value,
role:
$('memberRole').value
}
}
);
await load();
msg(
'Membership saved.'
);
} catch (e) {
msg(
e.message
);
}
};
$('roomForm').onsubmit =
async e => {
e.preventDefault();
try {
await api(
`/api/admin/groups/${$('roomGroup').value}/rooms`,
{
method:
'POST',
body: {
room_name:
$('roomName').value,
display_name:
$('roomDisplay').value
}
}
);
$('roomName').value =
'';
$('roomDisplay').value =
'';
await load();
msg(
'Room created.'
);
} catch (e) {
msg(
e.message
);
}
};
$('logoutBtn').onclick =
async () => {
await api(
'/api/auth/logout',
{
method:
'POST'
}
).catch(
() => {}
);
location.replace(
'/login?admin=1'
);
};
load();
// Instance administrators can appoint room owners without joining the room.
$('roomRoleForm').addEventListener('submit', async event => {
event.preventDefault();
const room = Number($('roomRoleRoom').value);
const user = Number($('roomRoleUser').value);
try {
await api(`/api/room-admin/${room}/members`, {
method: 'PUT', body: {user_id:user, role:$('roomRoleRole').value}
});
msg('Room role assigned.');
await load();
} catch (error) {msg(error.message);}
});
let signupPolicy = {mode:'manual',defaultRoomIds:[]};
function renderRegistrationRooms() {
const root=$('registrationRooms');
if(!root) return;
root.replaceChildren();
for(const room of state.rooms){
const label=document.createElement('label');
label.style.display='inline-flex';label.style.alignItems='center';label.style.margin='7px';
const input=document.createElement('input');input.type='checkbox';input.value=room.id;
input.className='registration-room';
input.checked=signupPolicy.defaultRoomIds.includes(room.id);
label.append(input,document.createTextNode(' '+(room.group_name||'')+' / '+(room.display_name||room.room_name)));
root.append(label);
}
}
async function loadRegistration(){
try{
signupPolicy=await api('/api/admin/registration');
$('registrationMode').value=signupPolicy.mode;
renderRegistrationRooms();
}catch(e){msg(e.message);}
}
$('registrationForm').addEventListener('submit',async event=>{
event.preventDefault();
try{
const ids=[...document.querySelectorAll('.registration-room:checked')].map(x=>Number(x.value));
await api('/api/admin/registration',{method:'PUT',body:{mode:$('registrationMode').value,default_room_ids:ids}});
msg('Registration policy saved.');await loadRegistration();
}catch(e){msg(e.message);}
});
document.addEventListener('DOMContentLoaded',loadRegistration);
+448
View File
@@ -0,0 +1,448 @@
window.Kronick =
window.Kronick || {};
/*
* Initialize the page after all deferred scripts
* and HTML elements have loaded.
*/
window.addEventListener(
'DOMContentLoaded',
() => {
/*
* Initialize per-device microphone, suppression and spatial audio controls.
*/
if (
typeof Kronick.initAudioSettings
=== 'function'
) {
Kronick.initAudioSettings();
}
/*
* Restore saved room, username and avatar
* values, then populate their datalists.
*/
if (
typeof Kronick.loadSavedJoinInfo
=== 'function'
) {
Kronick.loadSavedJoinInfo();
}
if (
typeof Kronick.populateSavedLists
=== 'function'
) {
Kronick.populateSavedLists();
}
/*
* Display the empty-room placeholder before
* a LiveKit connection is established.
*/
if (
typeof Kronick.showEmptyRoomMessage
=== 'function'
) {
Kronick.showEmptyRoomMessage();
}
/*
* Initialize the disconnected button states.
*/
if (
typeof Kronick.setConnectionControls
=== 'function'
) {
Kronick.setConnectionControls(
'disconnected'
);
}
if (typeof Kronick.initializeWindowManager === 'function') {
Kronick.initializeWindowManager();
}
/*
* Shared audio/video player window.
*/
Kronick.initializeDraggableWindow(
'sharedMediaWrap',
'sharedMediaHeader',
'sharedMediaPosition'
);
/*
* Music browser window.
*/
Kronick.initializeDraggableWindow(
'musicFrameWrap',
'musicFrameHeader',
'musicFramePosition'
);
/*
* Giphy browser window.
*/
Kronick.initializeDraggableWindow(
'giphyFrameWrap',
'giphyFrameHeader',
'giphyFramePosition'
);
/*
* Chat window.
*/
Kronick.initializeDraggableWindow(
'chatFrameWrap',
'chatFrameHeader',
'chatFramePosition'
);
Kronick.initializeDraggableWindow(
'roomAdminFrameWrap', 'roomAdminFrameHeader', 'roomAdminFramePosition'
);
/*
* Screen-share window.
*/
Kronick.initializeDraggableWindow(
'screenShareFrameWrap',
'screenShareFrameHeader',
'screenShareFramePosition'
);
/*
* Bring any clicked floating window to the
* front of the other tool windows.
*/
document
.querySelectorAll(
'.tool-frame-wrap, '
+ '.shared-media-wrap'
)
.forEach(windowElement => {
windowElement.addEventListener(
'mousedown',
() => {
if (
typeof Kronick
.bringToolWindowToFront
=== 'function'
) {
Kronick
.bringToolWindowToFront(
windowElement
);
}
}
);
});
/*
* Keep floating windows inside the browser
* viewport when the browser is resized.
*/
window.addEventListener(
'resize',
() => {
if (
typeof Kronick
.keepVisibleWindowsInViewport
=== 'function'
) {
Kronick
.keepVisibleWindowsInViewport();
}
}
);
/*
* Update the screen-share button for the
* initial disconnected state.
*/
if (
typeof Kronick
.updateScreenShareControls
=== 'function'
) {
Kronick
.updateScreenShareControls();
}
console.log(
'Kronick application initialized.'
);
}
);
/*
* Safely initialize one draggable tool window.
*
* Missing optional windows will be reported but will
* not prevent the rest of the application from loading.
*/
Kronick.initializeDraggableWindow =
function initializeDraggableWindow(
windowId,
headerId,
storageKey
) {
const windowElement =
document.getElementById(
windowId
);
const headerElement =
document.getElementById(
headerId
);
if (
!windowElement
|| !headerElement
) {
console.debug(
'Optional draggable window not found:',
{
windowId,
headerId
}
);
return;
}
if (
typeof Kronick.makeToolWindowDraggable
!== 'function'
) {
console.error(
'makeToolWindowDraggable() '
+ 'is unavailable.'
);
return;
}
Kronick.makeToolWindowDraggable(
windowElement,
headerElement,
storageKey
);
};
/*
* Receive messages from the chat, Giphy and music
* iframes through the central message router.
*/
window.addEventListener(
'message',
event => {
if (
typeof Kronick.handleWindowMessage
!== 'function'
) {
console.error(
'Window message router '
+ 'is unavailable.'
);
return;
}
Kronick.handleWindowMessage(
event
);
}
);
/*
* Compatibility exports.
*
* These allow existing inline HTML handlers such as
* onclick="connect()" to continue working while the
* implementations remain organized under Kronick.
*/
/*
* LiveKit connection controls.
*/
window.connect =
function connect() {
return Kronick.connect();
};
window.disconnect =
function disconnect() {
return Kronick.disconnect();
};
window.toggleMute =
function toggleMute() {
return Kronick.toggleMute();
};
/*
* Music browser controls.
*/
window.openMusicBrowser =
function openMusicBrowser() {
return Kronick.openMusicBrowser();
};
window.closeMusicBrowser =
function closeMusicBrowser() {
return Kronick.closeMusicBrowser();
};
/*
* Giphy browser controls.
*/
window.openGiphyBrowser =
function openGiphyBrowser(
targetMode = 'room'
) {
return Kronick.openGiphyBrowser(
targetMode
);
};
window.closeGiphyBrowser =
function closeGiphyBrowser() {
return Kronick.closeGiphyBrowser();
};
/*
* Chat controls.
*/
window.openChatWindow =
function openChatWindow() {
return Kronick.openChatWindow();
};
window.closeChatWindow =
function closeChatWindow() {
return Kronick.closeChatWindow();
};
/*
* Shared media controls.
*/
window.closeSharedMedia =
function closeSharedMedia(
sendStop = true
) {
return Kronick.closeSharedMedia(
sendStop
);
};
/*
* Participant controls.
*/
window.setParticipantVolume =
function setParticipantVolume(
sid,
participantKey,
value
) {
return Kronick.setParticipantVolume(
sid,
participantKey,
value
);
};
/*
* Screen-share controls.
*/
window.toggleScreenShare =
function toggleScreenShare() {
return Kronick.toggleScreenShare();
};
window.stopScreenShare =
function stopScreenShare() {
return Kronick.stopScreenShare();
};
window.openScreenShareWindow =
function openScreenShareWindow() {
return Kronick.openScreenShareWindow();
};
window.closeScreenShareWindow =
function closeScreenShareWindow() {
return Kronick.closeScreenShareWindow();
};
/*
* Mobile layout uses the existing connection/audio sidebar as a drawer.
* Desktop behavior is unchanged.
*/
Kronick.isMobileLayout = function isMobileLayout() {
return window.matchMedia('(max-width: 760px)').matches;
};
Kronick.setMobileSidebarOpen = function setMobileSidebarOpen(open) {
if (!Kronick.isMobileLayout()) {
open = false;
}
document.body.classList.toggle('mobile-sidebar-open', Boolean(open));
const button = document.getElementById('mobileAudioMenuBtn');
if (button) {
button.setAttribute('aria-expanded', open ? 'true' : 'false');
button.title = open
? 'Close connection and audio settings'
: 'Open connection and audio settings';
}
};
Kronick.toggleMobileSidebar = function toggleMobileSidebar() {
Kronick.setMobileSidebarOpen(
!document.body.classList.contains('mobile-sidebar-open')
);
};
Kronick.closeMobileSidebar = function closeMobileSidebar() {
Kronick.setMobileSidebarOpen(false);
};
window.addEventListener('keydown', event => {
if (event.key === 'Escape' && document.body.classList.contains('mobile-sidebar-open')) {
Kronick.closeMobileSidebar();
}
});
window.addEventListener('resize', () => {
if (!Kronick.isMobileLayout()) {
Kronick.closeMobileSidebar();
}
});
+965
View File
@@ -0,0 +1,965 @@
// chat.js
document.addEventListener(
'DOMContentLoaded',
() => {
const messagesContainer =
document.getElementById(
'chat-messages'
);
const messageInput =
document.getElementById(
'messageInput'
);
const sendBtn =
document.getElementById(
'sendBtn'
);
const gifBtn =
document.getElementById(
'gifBtn'
);
const fileBtn =
document.getElementById(
'fileBtn'
);
const fileInput =
document.getElementById(
'fileInput'
);
const chatStatus =
document.getElementById(
'chatStatus'
);
const renderedMessages =
new Set();
bindEvents();
setChatStatus('Room messages');
requestChatHistory();
function bindEvents() {
messageInput.addEventListener(
'keydown',
event => {
if (
event.key === 'Enter'
&& !event.shiftKey
) {
event.preventDefault();
handleOutboundMessage();
}
}
);
sendBtn.addEventListener(
'click',
handleOutboundMessage
);
gifBtn.addEventListener(
'click',
() => {
window.parent.postMessage(
{
type:
'KRONICK_CHAT_GIF_PICK'
},
window.location.origin
);
}
);
if (fileBtn && fileInput) {
fileBtn.addEventListener(
'click',
() => {
fileInput.click();
}
);
fileInput.addEventListener(
'change',
handleFileSelection
);
}
window.addEventListener(
'message',
handleParentMessage
);
}
function requestChatHistory() {
window.parent.postMessage(
{
type:
'KRONICK_CHAT_HISTORY_REQUEST'
},
window.location.origin
);
}
function handleParentMessage(event) {
if (
event.origin
!== window.location.origin
) {
return;
}
const data =
event.data;
if (
!data
|| typeof data !== 'object'
) {
return;
}
if (
data.type === 'CHAT_HISTORY'
|| data.type === 'KRONICK_CHAT_HISTORY'
) {
handleChatHistory(
data.messages
|| data.payload
);
return;
}
if (
data.type === 'CHAT_MESSAGE'
|| data.type === 'CHAT_RECEIVE'
|| data.type === 'KRONICK_CHAT_MESSAGE'
|| data.type === 'KRONICK_CHAT_RECEIVE'
) {
const message =
data.message
|| data.payload;
if (message) {
removeEmptyMessage();
displayMessage(message);
}
return;
}
if (
data.type
=== 'CHAT_INSERT_AND_SEND_URL'
) {
messageInput.value =
data.url || '';
handleOutboundMessage();
return;
}
}
function handleChatHistory(history) {
clearMessages();
const messages =
Array.isArray(history)
? history
: [];
if (!messages.length) {
renderEmptyMessage();
return;
}
messages.forEach(
message => {
displayMessage(
message,
false
);
}
);
scrollToBottom();
}
function handleOutboundMessage() {
const rawText =
messageInput.value.trim();
if (!rawText) {
return;
}
const mediaInfo =
detectMedia(rawText);
const chatPayload = {
id:
createMessageId(),
sender:
'You',
text:
mediaInfo
? ''
: rawText,
gifUrl:
mediaInfo?.type
=== 'gif'
? mediaInfo.url
: null,
imageUrl:
mediaInfo?.type
=== 'image'
? mediaInfo.url
: null,
createdAt:
Date.now()
};
/*
* Render locally right away.
*
* If the parent sends the same message back,
* renderedMessages prevents a duplicate.
*/
removeEmptyMessage();
displayMessage(chatPayload);
window.parent.postMessage(
{
type:
'KRONICK_CHAT_SEND',
payload:
chatPayload
},
window.location.origin
);
messageInput.value = '';
messageInput.focus();
setChatStatus(
'Message sent'
);
setTimeout(
() => {
setChatStatus(
'Room messages'
);
},
1000
);
}
async function handleFileSelection(event) {
const file = event.target.files?.[0];
if (!file) {
return;
}
// Clear input so selecting the same file consecutively works properly
fileInput.value = '';
const formData = new FormData();
formData.append('file', file);
// Attempt to infer room name from the active context, window globals, or URL search params
const urlParams = new URLSearchParams(window.location.search);
const activeRoom =
urlParams.get('room')
|| window.parent?.Kronick?.state?.room?.name
|| window.Kronick?.state?.room?.name
|| window.parent?.Kronick?.state?.roomID
|| window.Kronick?.state?.roomID
|| 'kronic';
formData.append('room', activeRoom);
// Add the sender field required by your FastAPI backend
const senderName =
window.parent?.Kronick?.state?.room?.localParticipant?.identity
|| window.Kronick?.state?.room?.localParticipant?.identity
|| localStorage.getItem('kronick_username')
|| 'You';
formData.append('sender', senderName);
setChatStatus('Uploading file...');
try {
const response = await fetch('/api/chat/files', {
method: 'POST',
body: formData
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
// Safely extract string message whether detail is a string or object
let errorMessage = 'File upload failed.';
if (typeof errorData.detail === 'string') {
errorMessage = errorData.detail;
} else if (errorData.detail && typeof errorData.detail === 'object') {
errorMessage = JSON.stringify(errorData.detail);
} else if (errorData.message) {
errorMessage = errorData.message;
}
throw new Error(errorMessage);
}
const fileMeta = await response.json();
const chatPayload = {
id: fileMeta.id || createMessageId(),
sender: 'You',
text: fileMeta.text || `Shared a file: ${fileMeta.filename}`,
fileId: fileMeta.id,
filename: fileMeta.filename,
fileSize: fileMeta.fileSize,
fileUrl: fileMeta.fileUrl,
createdAt: Date.now()
};
removeEmptyMessage();
displayMessage(chatPayload);
window.parent.postMessage(
{
type: 'KRONICK_CHAT_SEND',
payload: chatPayload
},
window.location.origin
);
setChatStatus('File sent');
} catch (error) {
console.error('File upload error:', error);
setChatStatus(`Upload failed: ${error.message}`);
} finally {
setTimeout(() => {
setChatStatus('Room messages');
}, 2000);
}
}
function detectMedia(text) {
const clean =
text.trim();
if (!clean) {
return null;
}
if (
/\.(gif)(\?.*)?$/i
.test(clean)
|| clean.includes(
'giphy.com'
)
|| clean.includes(
'media.giphy.com'
)
) {
return {
type: 'gif',
url: clean
};
}
if (
/\.(jpeg|jpg|png|webp)(\?.*)?$/i
.test(clean)
) {
return {
type: 'image',
url: clean
};
}
return null;
}
function displayMessage(
message,
shouldScroll = true
) {
if (
!message
|| typeof message !== 'object'
) {
return;
}
const normalizedMessage =
normalizeMessage(message);
const messageId =
getMessageId(
normalizedMessage
);
if (
renderedMessages.has(
messageId
)
) {
return;
}
renderedMessages.add(
messageId
);
removeEmptyMessage();
const messageDiv =
document.createElement(
'article'
);
messageDiv.className =
'chat-message';
messageDiv.dataset.messageId =
messageId;
const avatar =
createAvatar(
normalizedMessage.sender
);
const messageBody =
document.createElement(
'div'
);
messageBody.className =
'chat-message-body';
const headerDiv =
document.createElement(
'div'
);
headerDiv.className =
'chat-message-header';
const senderSpan =
document.createElement(
'span'
);
senderSpan.className =
'chat-username';
senderSpan.textContent =
normalizedMessage.sender;
const timeSpan =
document.createElement(
'time'
);
timeSpan.className =
'chat-timestamp';
const timestampDate =
new Date(
normalizedMessage.createdAt
);
if (
!Number.isNaN(
timestampDate.getTime()
)
) {
timeSpan.dateTime =
timestampDate.toISOString();
}
timeSpan.textContent =
formatTime(
normalizedMessage.createdAt
);
headerDiv.append(
senderSpan,
timeSpan
);
messageBody.appendChild(
headerDiv
);
if (normalizedMessage.text) {
const bodyDiv =
document.createElement(
'div'
);
bodyDiv.className =
'chat-message-text';
bodyDiv.textContent =
normalizedMessage.text;
messageBody.appendChild(
bodyDiv
);
}
const mediaUrl =
normalizedMessage.gifUrl
|| normalizedMessage.imageUrl;
if (mediaUrl) {
appendMedia(
messageBody,
mediaUrl,
Boolean(
normalizedMessage.gifUrl
)
);
}
// Handle file attachments if present
if (normalizedMessage.fileUrl || normalizedMessage.fileId) {
appendFileAttachment(messageBody, normalizedMessage);
}
messageDiv.append(
avatar,
messageBody
);
messagesContainer.appendChild(
messageDiv
);
if (shouldScroll) {
scrollToBottom();
}
}
function normalizeMessage(message) {
const sender =
message.sender
|| message.username
|| message.participantName
|| message.identity
|| 'Unknown';
const text =
message.text
|| message.message
|| '';
const gifUrl =
message.gifUrl
|| message.gif_url
|| null;
const imageUrl =
message.imageUrl
|| message.image_url
|| null;
const fileUrl =
message.fileUrl
|| message.file_url
|| (message.fileId ? `/api/chat/files/${message.fileId}` : null);
const filename =
message.filename
|| message.file_name
|| null;
const fileSize =
message.fileSize
|| message.file_size
|| null;
const createdAt =
message.createdAt
|| message.created_at
|| message.timestamp
|| Date.now();
return {
id:
message.id
|| message.messageId
|| message.message_id
|| null,
sender:
String(sender),
text:
String(text),
gifUrl:
gifUrl
? String(gifUrl)
: null,
imageUrl:
imageUrl
? String(imageUrl)
: null,
fileUrl:
fileUrl
? String(fileUrl)
: null,
filename:
filename
? String(filename)
: null,
fileSize:
fileSize,
createdAt:
normalizeTimestamp(
createdAt
)
};
}
function normalizeTimestamp(timestamp) {
if (
typeof timestamp === 'number'
) {
/*
* Convert Unix seconds to milliseconds.
*/
if (
timestamp > 0
&& timestamp < 100000000000
) {
return timestamp * 1000;
}
return timestamp;
}
const parsed =
new Date(timestamp).getTime();
if (
Number.isNaN(parsed)
) {
return Date.now();
}
return parsed;
}
function appendMedia(
messageBody,
mediaUrl,
isGif
) {
const image =
document.createElement(
'img'
);
image.className =
isGif
? 'chat-gif'
: 'chat-message-image';
image.src =
mediaUrl;
image.alt =
isGif
? 'Shared GIF'
: 'Shared image';
image.loading =
'lazy';
image.referrerPolicy =
'no-referrer';
image.addEventListener(
'load',
scrollToBottom
);
image.addEventListener(
'error',
() => {
image.remove();
const error =
document.createElement(
'div'
);
error.className =
'message-error';
error.textContent =
'Image failed to load.';
messageBody.appendChild(
error
);
scrollToBottom();
}
);
messageBody.appendChild(
image
);
}
function appendFileAttachment(messageBody, message) {
const fileCard = document.createElement('div');
fileCard.className = 'chat-file-card';
const iconSpan = document.createElement('span');
iconSpan.className = 'chat-file-icon';
iconSpan.textContent = '📄';
const infoDiv = document.createElement('div');
infoDiv.className = 'chat-file-info';
const link = document.createElement('a');
link.className = 'chat-file-link';
const rawUrl = String(message.fileUrl || (message.fileId ? `/api/chat/files/${encodeURIComponent(message.fileId)}` : ''));
const url = new URL(rawUrl, window.location.href);
if (!['https:', 'http:'].includes(url.protocol) || url.origin !== window.location.origin || !url.pathname.includes('/api/chat/files/')) {
link.textContent = 'Attachment unavailable';
infoDiv.appendChild(link);
fileCard.append(iconSpan, infoDiv);
messageBody.appendChild(fileCard);
return;
}
link.href = url.href;
link.textContent = message.filename || 'Download Attachment';
link.target = '_blank';
link.rel = 'noopener noreferrer';
infoDiv.appendChild(link);
if (message.fileSize) {
const sizeSpan = document.createElement('span');
sizeSpan.className = 'chat-file-size';
sizeSpan.textContent = formatFileSize(message.fileSize);
infoDiv.appendChild(sizeSpan);
}
fileCard.append(iconSpan, infoDiv);
messageBody.appendChild(fileCard);
}
function formatFileSize(bytes) {
if (!bytes || isNaN(bytes)) return '';
if (bytes < 1024) return bytes + ' B';
if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
}
function createAvatar(sender) {
const avatar =
document.createElement(
'div'
);
avatar.className =
'chat-avatar';
const initial =
String(sender)
.trim()
.charAt(0)
.toUpperCase();
avatar.textContent =
initial || '?';
return avatar;
}
function createMessageId() {
if (
window.crypto
&& typeof crypto.randomUUID
=== 'function'
) {
return crypto.randomUUID();
}
return [
Date.now(),
Math.random()
.toString(36)
.slice(2)
].join('-');
}
function getMessageId(message) {
if (message.id) {
return String(
message.id
);
}
return [
message.sender
|| 'unknown',
message.createdAt
|| Date.now(),
message.text
|| message.gifUrl
|| message.imageUrl
|| message.fileUrl
|| ''
].join('-');
}
function clearMessages() {
renderedMessages.clear();
messagesContainer.innerHTML =
'';
}
function renderEmptyMessage() {
messagesContainer.innerHTML =
'';
const emptyMessage =
document.createElement(
'div'
);
emptyMessage.className =
'chat-empty';
emptyMessage.textContent =
'No messages yet.';
messagesContainer.appendChild(
emptyMessage
);
}
function removeEmptyMessage() {
const emptyMessage =
messagesContainer
.querySelector(
'.chat-empty'
);
emptyMessage?.remove();
}
function scrollToBottom() {
requestAnimationFrame(
() => {
messagesContainer.scrollTop =
messagesContainer.scrollHeight;
}
);
}
function setChatStatus(text) {
if (chatStatus) {
chatStatus.textContent =
text;
}
}
function formatTime(timestamp) {
const date =
new Date(timestamp);
if (
Number.isNaN(
date.getTime()
)
) {
return '';
}
return date.toLocaleTimeString(
[],
{
hour:
'2-digit',
minute:
'2-digit'
}
);
}
}
);
+57
View File
@@ -0,0 +1,57 @@
const $=id=>document.getElementById(id);function tab(name){$('loginForm').hidden=name!=='login';$('signupForm').hidden=name!=='signup';$('loginTab').hidden=name==='login';$('signupTab').hidden=name!=='login';$('authMessage').textContent=''}
$('loginTab').onclick=()=>tab('login');$('signupTab').onclick=()=>tab('signup');
$('loginForm').onsubmit=async e=>{e.preventDefault();const r=await fetch('/api/auth/login',{method:'POST',headers:{'Content-Type':'application/json'},credentials:'same-origin',body:JSON.stringify({login:$('loginName').value,password:$('loginPassword').value})});const d=await r.json().catch(()=>({}));if(r.ok&&d.requiresPasswordChange){window.kronicPasswordResetToken=d.resetToken;$('loginForm').hidden=true;$('signupForm').hidden=true;$('passwordChangeForm').hidden=false;$('loginTab').hidden=false;$('signupTab').hidden=true;$('authMessage').textContent='Choose a new password to continue.';return}if(!r.ok){$('authMessage').className='message error';$('authMessage').textContent=d.detail||'Login failed.';return}location.replace(d.user?.isPlatformAdmin&&new URLSearchParams(location.search).get('admin')==='1'?'/admin':'/app')};
$('signupForm').onsubmit=async e=>{e.preventDefault();const code=normalizeInvite($('signupInvite').value);const r=await fetch('/api/auth/signup',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:$('signupName').value,email:$('signupEmail').value,password:$('signupPassword').value,invite_code:code,requested_room:$('signupRoom').value.trim()})});const d=await r.json().catch(()=>({}));$('authMessage').className='message '+(r.ok?'ok':'error');$('authMessage').textContent=r.ok?d.message:(d.detail||'Signup failed.');if(r.ok)e.target.reset()};
// Accept a complete invitation URL or the code alone.
function normalizeInvite(raw) {
const value=(raw||'').trim();
if(!value)return '';
try { const u=new URL(value);return u.searchParams.get('invite')||''; }
catch(_) { return value; }
}
let inviteRequest=0;
async function previewInvite() {
const seq=++inviteRequest;
const code=normalizeInvite($('signupInvite').value);
const room=$('signupRoom');
if(!code){room.readOnly=false;room.required=true;return;}
room.readOnly=true;
try {
const response=await fetch('/api/invites/preview?code='+encodeURIComponent(code),{cache:'no-store'});
const data=await response.json().catch(()=>({}));
if(seq!==inviteRequest)return;
if(!response.ok)throw new Error(data.detail||'Invitation invalid or expired.');
room.value=data.room;
room.readOnly=true;
$('authMessage').className='message ok';
$('authMessage').textContent='Invitation for '+data.displayName+'. Create an account to request approval.';
} catch(error) {
if(seq!==inviteRequest)return;
room.value='';room.readOnly=false;
$('authMessage').className='message error';
$('authMessage').textContent=error.message;
}
}
$('signupInvite').addEventListener('change',previewInvite);
$('signupInvite').addEventListener('paste',()=>setTimeout(previewInvite,0));
(() => {
const invite=new URLSearchParams(location.search).get('invite');
if(invite){
$('signupInvite').value=invite;
tab('signup');
history.replaceState(null,'',location.pathname);
previewInvite();
}
})();
$('passwordChangeForm').onsubmit=async event=>{
event.preventDefault();
if($('newRequiredPassword').value!==$('confirmRequiredPassword').value){$('authMessage').textContent='Passwords do not match.';return;}
const response=await fetch('/api/auth/change-required-password',{method:'POST',headers:{'Content-Type':'application/json'},credentials:'same-origin',body:JSON.stringify({reset_token:window.kronicPasswordResetToken,new_password:$('newRequiredPassword').value})});
const data=await response.json().catch(()=>({}));
$('authMessage').className='message '+(response.ok?'ok':'error');
$('authMessage').textContent=response.ok?'Password changed. Sign in with your new password.':(data.detail||'Could not change password.');
if(response.ok){window.kronicPasswordResetToken=null;$('passwordChangeForm').hidden=true;tab('login');$('authMessage').textContent='Password changed. Sign in with your new password.';}
};
$('loginTab').addEventListener('click',()=>{if(!$('passwordChangeForm').hidden){$('passwordChangeForm').hidden=true;window.kronicPasswordResetToken=null;}tab('login');});
+191
View File
@@ -0,0 +1,191 @@
/* Kronic room-owner controls. All actions verified again by the backend. */
(() => {
const K = window.Kronick = window.Kronick || {};
const byId = id => document.getElementById(id);
let allowed = [];
let currentRoom = null;
const api = async (path, options={}) => {
const headers = {'Accept':'application/json'};
if (options.body) headers['Content-Type']='application/json';
const res = await fetch(path, {...options,headers,credentials:'same-origin',cache:'no-store'});
const data=await res.json().catch(()=>({}));
if (!res.ok) throw new Error(data.detail || `Request failed (${res.status})`);
return data;
};
const status = message => { if (byId('roomAdminStatus')) byId('roomAdminStatus').textContent=message; };
const element = (tag,text) => {const el=document.createElement(tag); if(text!==undefined) el.textContent=String(text); return el;};
const button = (label,handler) => {const b=element('button',label);b.type='button';b.addEventListener('click',handler);return b;};
const formatTime = unix => new Date(unix*1000).toLocaleString();
async function refreshAvailable() {
const data=await api('/api/my/room-admin');
allowed=data.rooms || [];
const gear=byId('roomAdminButton');
if(gear) gear.hidden=allowed.length===0;
const select=byId('roomAdminSelect');
if(!select) return;
const previous=select.value;
select.replaceChildren();
for(const room of allowed){const option=element('option',room.display_name||room.room_name);option.value=room.id;select.append(option);}
const matching=allowed.find(room=>String(room.id)===previous);
const chosen=matching || allowed.find(room=>room.room_name===(K.state?.currentRoomName || byId('roomName')?.value)) || allowed[0];
if(chosen)select.value=String(chosen.id);
if(!allowed.length && byId('roomAdminFrameWrap')?.style.display==='flex') K.hideToolWindow('roomAdminFrameWrap');
}
async function loadRoom() {
const id=Number(byId('roomAdminSelect')?.value);
if(!id)return;
status('Loading room…');
try {
const data=await api(`/api/room-admin/${id}`);
currentRoom=data;
renderMembers(data);
renderInvites(data);
const inviteBox=byId('roomInviteCreate')?.closest('section');
if(inviteBox) inviteBox.hidden=!data.capabilities?.room_permissions;
if(data.capabilities?.account_approvals) await renderRequests(data);
else byId('roomAdminRequests')?.replaceChildren();
status('');
}catch(error){status(error.message);}
}
function renderMembers(data){
const root=byId('roomAdminMembers');root.replaceChildren();
const can=data.capabilities || {};
for(const member of data.members){
const row=element('div');row.className='room-admin-row room-admin-member';
const name=element('div');name.className='room-admin-member-name';name.append(element('strong',member.username),element('small',member.status));row.append(name);
const actions=element('div');actions.className='room-admin-actions';
const select=element('select');select.setAttribute('aria-label',`Role for ${member.username}`);
['member','moderator','admin','owner'].forEach(role=>{const opt=element('option',role);opt.value=role;select.append(opt);});
select.value=member.role;
select.disabled=(member.role==='owner' && data.myRole!=='owner') || (member.isPlatformAdmin && member.id!==K.account?.user?.id);
const save=button('Save',async()=>{
try{await api(`/api/room-admin/${data.room.id}/members`,{method:'PUT',body:JSON.stringify({user_id:member.id,role:select.value})});await loadRoom();status('Role updated.');}
catch(error){status(error.message);}
});
save.disabled=select.disabled || !can.user_permissions;
const remove=button('Remove',async()=>{
if(!confirm(`Remove ${member.username} from ${data.room.display_name || data.room.room_name}?`))return;
try{await api(`/api/room-admin/${data.room.id}/members/${member.id}`,{method:'DELETE'});await loadRoom();status('Member removed.');}
catch(error){status(error.message);}
});
remove.disabled=!can.user_permissions || select.disabled || member.isPlatformAdmin || member.id===K.account?.user?.id;
const permanent=button('Delete account',async()=>{
const typed=prompt(`PERMANENTLY delete ${member.username} and their login? This affects the entire instance, not just ${data.room.room_name}.\nType the exact username to confirm:`);
if(typed!==member.username)return;
try { await api(`/api/room-admin/${data.room.id}/users/${member.id}`,{method:'DELETE'});await loadRoom();status('Account permanently deleted.'); }
catch(error){status(error.message);}
});
permanent.disabled=!can.user_permissions || member.id===K.account?.user?.id || (member.role==='owner' && data.myRole!=='owner') || !!member.isPlatformAdmin;
const reset=button('Require new password',async()=>{
if(!confirm(`Require ${member.username} to set a new password on next login? Current sessions will be ended.`))return;
try{await api(`/api/room-admin/${data.room.id}/users/${member.id}/require-password-change`,{method:'POST'});status('Password change required on next sign-in.');}
catch(error){status(error.message);}
});
reset.disabled=!can.password_resets || member.id===K.account?.user?.id;
const media=document.createElement('details');media.className='room-admin-media';
const summary=element('summary','Media access');media.append(summary);
const grants={};
const saved=data.mediaPermissions?.[member.id] || {};
for(const key of data.mediaKeys || ['movies','tv','music','iptv','tube','twitch']){
const entry=element('label');const check=element('input');check.type='checkbox';
check.checked=saved[key]!==false;grants[key]=check;entry.append(check,document.createTextNode(' '+({'tv':'TV Shows','tube':'YouTube'}[key]||key.charAt(0).toUpperCase()+key.slice(1))));media.append(entry);
}
media.append(button('Save media access',async()=>{
const libraries=Object.fromEntries(Object.entries(grants).map(([key,value])=>[key,value.checked]));
try{await api(`/api/room-admin/${data.room.id}/users/${member.id}/media`,{method:'PUT',body:JSON.stringify({libraries})});status('Media access saved.');}
catch(error){status(error.message);}
}));
actions.append(select,save,remove,permanent);
if(!can.user_permissions){select.hidden=true;save.hidden=true;remove.hidden=true;permanent.hidden=true;}
if(!can.password_resets)reset.hidden=true;
if(!can.media_access || member.canEditMedia===false)media.hidden=true;
const extras=element('div');extras.className='room-admin-member-extras';extras.append(reset,media);
row.append(actions,extras);root.append(row);
}
if(!data.members.length)root.append(element('p','No members assigned.'));
}
async function renderRequests(data){
const root=byId('roomAdminRequests');if(!root)return;
root.replaceChildren();
const response=await api(`/api/room-admin/${data.room.id}/requests`);
for(const user of response.requests){
const row=element('div');row.className='room-admin-row';
const name=element('div');name.append(element('strong',user.username),element('small',user.email));
row.append(name);
for(const [label,approve] of [['Approve',true],['Deny',false]]){
row.append(button(label,async()=>{
if(!confirm(`${label} account ${user.username} for this room?`))return;
try{await api(`/api/room-admin/${data.room.id}/requests/decision`,{
method:'POST',body:JSON.stringify({user_id:user.id,approve})});
await loadRoom();status(`Request ${approve?'approved':'denied'}.`);
}catch(error){status(error.message);}
}));
}
root.append(row);
}
if(!response.requests.length)root.append(element('p','No pending room requests.'));
}
function renderInvites(data){
const root=byId('roomAdminInvites');root.replaceChildren();
for(const invite of data.invites){
const row=element('div');row.className='room-admin-row';
const info=element('div');info.append(element('strong',`Invite #${invite.id}`),
element('small',`${invite.uses}/${invite.max_uses} uses · expires ${formatTime(invite.expires_at)}`),
element('small',invite.revoked?'Revoked':(invite.expires_at*1000 < Date.now()?'Expired':'Active')));
row.append(info);
if(!invite.revoked){row.append(button('Revoke',async()=>{
if(!confirm('Revoke this invitation?'))return;
try{await api(`/api/room-admin/${data.room.id}/invites/${invite.id}`,{method:'DELETE'});await loadRoom();status('Invitation revoked.');}
catch(error){status(error.message);}
}));}
root.append(row);
}
if(!data.invites.length)root.append(element('p','No invitations yet.'));
}
K.redeemInvitePrompt=async function redeemInvitePrompt(){
const code=prompt('Enter your room invitation code (or paste an invitation URL):');
if(!code)return;
let token=code.trim();
try {const url=new URL(token);token=url.searchParams.get('invite')||token;}catch(_){/* plain code */}
try{
await api('/api/my/redeem-invite',{method:'POST',body:JSON.stringify({code:token})});
alert('Room added to your account. Reloading your room list.');
window.location.reload();
}catch(error){alert(error.message);}
};
K.openRoomAdmin=async function openRoomAdmin(){
try{await refreshAvailable();if(!allowed.length){status('You do not manage any rooms.');return;}
K.showToolWindow('roomAdminFrameWrap');await loadRoom();}
catch(error){status(error.message);}
};
document.addEventListener('DOMContentLoaded',()=>{
byId('roomAdminSelect')?.addEventListener('change',loadRoom);
byId('roomAdminRefresh')?.addEventListener('click',async()=>{await refreshAvailable();await loadRoom();});
byId('roomInviteCreate')?.addEventListener('click',async()=>{
const id=Number(byId('roomAdminSelect')?.value);
try{
const result=await api(`/api/room-admin/${id}/invites`,{method:'POST',body:JSON.stringify({hours:Number(byId('roomInviteHours').value),max_uses:Number(byId('roomInviteUses').value)})});
// Generate a link to Chat signup, not the legacy Media signup screen.
const roomAdminScript=[...document.scripts].find(s=>/\/js\/room-admin\.js(?:\?|$)/.test(s.src));
const scriptPath=roomAdminScript?new URL(roomAdminScript.src).pathname:'';
const prefix=scriptPath.includes('/borg-chat/')?'/borg-chat':'';
const url=new URL(`${prefix}/login`,location.origin);
url.searchParams.set('invite',result.code);
byId('roomInviteLink').value=url.toString();byId('roomInviteResult').hidden=false;
await loadRoom();status('Invite created; copy the link now.');
}catch(error){status(error.message);}
});
byId('roomInviteCopy')?.addEventListener('click',async()=>{
try{await navigator.clipboard.writeText(byId('roomInviteLink').value);status('Invitation link copied.');}
catch(error){byId('roomInviteLink').focus();byId('roomInviteLink').select();status('Select and copy the link.');}
});
refreshAvailable().catch(error=>console.warn('Room administration unavailable:',error));
// Re-check on focus so the gear disappears soon after a role change.
let lastCheck=Date.now();
window.addEventListener('focus',()=>{
if(Date.now()-lastCheck<30000)return;
lastCheck=Date.now();
refreshAvailable().catch(()=>{});
});
});
})();