From 9ad6c44a84df8a6d4e0bd4fa788094160fbdcf22 Mon Sep 17 00:00:00 2001 From: admin Date: Wed, 25 Nov 2026 20:26:26 -0600 Subject: [PATCH] Upload files to "kronic-chat/js" --- kronic-chat/js/music-browser.js | 1675 ++++++++++++++++++++++++++++ kronic-chat/js/rnnoise-worklet.js | 116 ++ kronic-chat/js/room-auth.js | 721 ++++++++++++ kronic-chat/js/room-layout.js | 80 ++ kronic-chat/js/room-sync-bridge.js | 55 + 5 files changed, 2647 insertions(+) create mode 100644 kronic-chat/js/music-browser.js create mode 100644 kronic-chat/js/rnnoise-worklet.js create mode 100644 kronic-chat/js/room-auth.js create mode 100644 kronic-chat/js/room-layout.js create mode 100644 kronic-chat/js/room-sync-bridge.js diff --git a/kronic-chat/js/music-browser.js b/kronic-chat/js/music-browser.js new file mode 100644 index 0000000..e68054d --- /dev/null +++ b/kronic-chat/js/music-browser.js @@ -0,0 +1,1675 @@ +const API_BASE_URL = + '/media'; + +const PARENT_ORIGIN = + window.location.origin; + +const HISTORY_STORAGE_KEY = + 'kronickMediaHistory'; + +const QUEUE_STORAGE_KEY = + 'kronickMediaQueue'; + +const MAX_HISTORY_ITEMS = + 100; + + +let searchTimer = + null; + +let currentRequestId = + 0; + + +// ======================================================== +// DOM +// ======================================================== + +const list = + document.getElementById( + 'list' + ); + +const status = + document.getElementById( + 'status' + ); + +const nav = + document.getElementById( + 'nav' + ); + +const searchInput = + document.getElementById( + 'searchInput' + ); + +const closeButton = + document.getElementById( + 'musicBrowserClose' + ); + +const historyList = + document.getElementById( + 'historyList' + ); + +const historyCount = + document.getElementById( + 'historyCount' + ); + +const clearHistoryBtn = + document.getElementById( + 'clearHistoryBtn' + ); + +const queueList = + document.getElementById( + 'queueList' + ); + +const queueCount = + document.getElementById( + 'queueCount' + ); + +const clearQueueBtn = + document.getElementById( + 'clearQueueBtn' + ); + +const playNextBtn = + document.getElementById( + 'playNextBtn' + ); + + +// ======================================================== +// Utility +// ======================================================== + +function setStatus( + message = '' +) { + status.textContent = + message; +} + + +function formatDuration( + duration +) { + const seconds = + Number( + duration || 0 + ); + + if ( + !Number.isFinite( + seconds + ) + || seconds <= 0 + ) { + return ''; + } + + const minutes = + Math.floor( + seconds / 60 + ); + + const remainder = + Math.floor( + seconds % 60 + ); + + return ( + `${minutes}:` + + String( + remainder + ).padStart( + 2, + '0' + ) + ); +} + + +function normalizeMediaUrl( + rawUrl +) { + if ( + typeof rawUrl !== 'string' + || !rawUrl.trim() + ) { + return ''; + } + + let url = + rawUrl.trim() + .replace( + /&/g, + '&' + ); + + if ( + url.startsWith( + '//' + ) + ) { + url = + `https:${url}`; + } + + try { + const parsed = + new URL( + url, + window.location.origin + ); + + /* + * Old Kronic media API URLs: + * + * https://kronickrusaders.ca/api/video/... + * + * become: + * + * https://kronickrusaders.ca/media/api/video/... + */ + if ( + parsed.origin + === window.location.origin + && parsed.pathname.startsWith( + '/api/' + ) + ) { + parsed.pathname = + `/media${parsed.pathname}`; + } + + /* + * Return same-origin URLs as relative paths. + * External HTTPS URLs such as i.ytimg.com + * remain absolute. + */ + if ( + parsed.origin + === window.location.origin + ) { + return ( + parsed.pathname + + parsed.search + + parsed.hash + ); + } + + return parsed.href; + + } catch ( + error + ) { + console.warn( + 'Invalid media URL:', + rawUrl, + error + ); + + return ''; + } +} + + +// ======================================================== +// API helper +// ======================================================== + +async function api( + path +) { + const response = + await fetch( + API_BASE_URL + path, + { + cache: + 'no-store' + } + ); + + if ( + !response.ok + ) { + const body = + await response.text(); + + throw new Error( + `${response.url} failed: ` + + `${response.status}: ` + + body + ); + } + + return await response.json(); +} + + +// ======================================================== +// Media objects +// ======================================================== + +function createMediaItem({ + id = '', + source = 'invidious', + mediaType = 'video', + url = '', + title = '', + artist = '', + thumbnail = '', + duration = 0, +}) { + return { + queueId: + crypto.randomUUID(), + + id: + String( + id || '' + ), + + source, + + mediaType, + + url, + + title: + title || 'Unknown', + + artist, + + thumbnail, + + duration: + Number( + duration || 0 + ), + + addedAt: + Date.now() + }; +} + + +// ======================================================== +// Search +// ======================================================== + +async function performSearch( + query +) { + const cleanQuery = + String( + query || '' + ).trim(); + + if ( + !cleanQuery + ) { + list.innerHTML = + ''; + + setStatus( + '' + ); + + return; + } + + const requestId = + ++currentRequestId; + + setStatus( + 'Searching Invidious...' + ); + + list.innerHTML = + ''; + + try { + const formattedQuery = + encodeURIComponent( + cleanQuery + ).replace( + /%20/g, + '+' + ); + + const data = + await api( + '/api/video/search?q=' + + formattedQuery + ); + + if ( + requestId + !== currentRequestId + ) { + return; + } + + const items = + Array.isArray( + data + ) + ? data + : ( + data.items + || [] + ); + + if ( + items.length === 0 + ) { + setStatus( + 'No results.' + ); + + return; + } + + setStatus( + `${items.length} result` + + ( + items.length === 1 + ? '' + : 's' + ) + ); + + for ( + const item + of items + ) { + list.appendChild( + videoResultRow( + item + ) + ); + } + + } catch ( + error + ) { + console.error( + 'Search failed:', + error + ); + + setStatus( + error.message + || 'Search failed.' + ); + } +} + + +// ======================================================== +// Result rows +// ======================================================== + +function createRowBase( + thumbnail, + title, + subtitle +) { + const row = + document.createElement( + 'div' + ); + + row.className = + 'row'; + + + const image = + document.createElement( + 'img' + ); + + image.className = + 'thumb'; + + + if ( + thumbnail + ) { + image.src = + thumbnail; + + } else { + image.style.display = + 'none'; + } + + + image.onerror = + () => { + image.style.display = + 'none'; + }; + + + const info = + document.createElement( + 'div' + ); + + info.className = + 'info'; + + + const titleElement = + document.createElement( + 'div' + ); + + titleElement.className = + 'title'; + + titleElement.textContent = + title + || 'Unknown'; + + + const subtitleElement = + document.createElement( + 'div' + ); + + subtitleElement.className = + 'meta'; + + subtitleElement.textContent = + subtitle || ''; + + + info.append( + titleElement, + subtitleElement + ); + + + const action = + document.createElement( + 'div' + ); + + action.className = + 'action'; + + + row.append( + image, + info, + action + ); + + + return row; +} + + +// ======================================================== +// Invidious results +// ======================================================== + +function videoResultRow( + item +) { + const subtitle = [ + item.artist || '', + formatDuration( + item.duration + ) + ] + .filter( + Boolean + ) + .join( + ' — ' + ); + + + const row = + createRowBase( + item.thumbnail || '', + item.title + || 'Unknown Video', + subtitle + ); + + + // ==================================================== + // Audio-only item + // ==================================================== + + const audioItem = + createMediaItem({ + id: + item.id, + + source: + 'invidious', + + mediaType: + 'audio', + + url: + item.audioUrl + || '', + + title: + item.title + || 'Unknown', + + artist: + item.artist + || '', + + thumbnail: + item.thumbnail + || '', + + duration: + item.duration, + }); + + + // ==================================================== + // Video + audio item + // ==================================================== + + const videoItem = + createMediaItem({ + id: + item.id, + + source: + 'invidious', + + mediaType: + 'video', + + url: + item.videoUrl + || item.url + || '', + + title: + item.title + || 'Unknown Video', + + artist: + item.artist + || '', + + thumbnail: + item.thumbnail + || '', + + duration: + item.duration, + }); + + + const action = + row.querySelector( + '.action' + ); + + + // ---------------------------------------------------- + // Audio controls + // ---------------------------------------------------- + + const audioPlay = + createPlaybackButton( + '♫ Audio', + audioItem + ); + + + const audioQueue = + createQueueButton( + '+ Audio', + audioItem + ); + + + // ---------------------------------------------------- + // Video controls + // ---------------------------------------------------- + + const videoPlay = + createPlaybackButton( + '▶ Video', + videoItem + ); + + + const videoQueue = + createQueueButton( + '+ Video', + videoItem + ); + + + // ---------------------------------------------------- + // Disable audio controls if backend search result + // does not contain audioUrl. + // ---------------------------------------------------- + + if ( + !audioItem.url + ) { + audioPlay.disabled = + true; + + audioQueue.disabled = + true; + } + + + if ( + !videoItem.url + ) { + videoPlay.disabled = + true; + + videoQueue.disabled = + true; + } + + + action.append( + audioPlay, + audioQueue, + videoPlay, + videoQueue + ); + + + return row; +} + + +// ======================================================== +// Playback buttons +// ======================================================== + +function createPlaybackButton( + label, + item +) { + const button = + document.createElement( + 'button' + ); + + button.type = + 'button'; + + button.className = + 'send-btn play-btn'; + + button.textContent = + label; + + + button.onclick = + event => { + event.stopPropagation(); + + sendMediaItemToRoom( + item, + button + ); + }; + + + return button; +} + + +function createQueueButton( + label, + item +) { + const button = + document.createElement( + 'button' + ); + + button.type = + 'button'; + + button.className = + 'send-btn queue-btn'; + + button.textContent = + label; + + + button.onclick = + event => { + event.stopPropagation(); + + addToQueue( + item + ); + + button.textContent = + 'Added'; + + setTimeout( + () => { + button.textContent = + label; + }, + 800 + ); + }; + + + return button; +} + + +// ======================================================== +// Parent messaging +// ======================================================== + +async function sendMediaItemToRoom( + item, + button = null +) { + return sendToChatRoom( + item.url, + button, + item.mediaType, + item.title, + item.thumbnail, + item + ); +} + + +async function sendToChatRoom( + url, + button, + mediaType = 'video', + title = '', + thumbnail = '', + mediaItem = null +) { + const originalText = + button + ? button.textContent + : 'Play'; + + + const normalizedUrl = + normalizeMediaUrl( + url + ); + + + const normalizedThumbnail = + normalizeMediaUrl( + thumbnail + ); + + + if ( + !normalizedUrl + ) { + setStatus( + 'Invalid media URL.' + ); + + return false; + } + + + if ( + button + ) { + button.disabled = + true; + + button.textContent = + 'Sending...'; + } + + + try { + console.log( + 'SENDING MEDIA TO PARENT:', + { + mediaType, + + originalUrl: + url, + + normalizedUrl, + + title, + + iframeOrigin: + window.location.origin, + + parentOrigin: + PARENT_ORIGIN + } + ); + + + window.parent.postMessage( + { + type: + 'KRONICK_MEDIA_SHARE', + + mediaType, + + url: + normalizedUrl, + + title, + + thumbnail: + normalizedThumbnail + }, + + PARENT_ORIGIN + ); + + + const historyItem = + mediaItem + ? { + ...mediaItem, + + url: + normalizedUrl, + + thumbnail: + normalizedThumbnail, + } + + : createMediaItem({ + mediaType, + + url: + normalizedUrl, + + title, + + thumbnail: + normalizedThumbnail, + }); + + + addToHistory( + historyItem + ); + + + setStatus( + `Playing "${title || 'media'}"` + ); + + + if ( + button + ) { + button.textContent = + 'Sent'; + + setTimeout( + () => { + button.disabled = + false; + + button.textContent = + originalText; + }, + 800 + ); + } + + + return true; + + } catch ( + error + ) { + console.error( + 'Could not send media:', + error + ); + + + setStatus( + error.message + || 'Could not send media.' + ); + + + if ( + button + ) { + button.disabled = + false; + + button.textContent = + originalText; + } + + + return false; + } +} + + +// ======================================================== +// History +// ======================================================== + +function loadHistory() { + try { + return JSON.parse( + localStorage.getItem( + HISTORY_STORAGE_KEY + ) + || '[]' + ); + + } catch ( + error + ) { + return []; + } +} + + +function saveHistory( + history +) { + localStorage.setItem( + HISTORY_STORAGE_KEY, + JSON.stringify( + history + ) + ); +} + + +function addToHistory( + item +) { + const history = + loadHistory(); + + + history.unshift({ + ...item, + + addedAt: + Date.now(), + }); + + + if ( + history.length + > MAX_HISTORY_ITEMS + ) { + history.length = + MAX_HISTORY_ITEMS; + } + + + saveHistory( + history + ); + + renderHistory(); +} + + +function renderHistory() { + const history = + loadHistory(); + + + historyCount.textContent = + String( + history.length + ); + + + historyList.innerHTML = + ''; + + + if ( + history.length === 0 + ) { + const empty = + document.createElement( + 'div' + ); + + empty.className = + 'side-panel-empty'; + + empty.textContent = + 'No playback history.'; + + historyList.appendChild( + empty + ); + + return; + } + + + for ( + const item + of history + ) { + const row = + createSidePanelItem( + item, + () => { + sendMediaItemToRoom( + item + ); + } + ); + + + historyList.appendChild( + row + ); + } +} + + +// ======================================================== +// Queue +// ======================================================== + +function loadQueue() { + try { + return JSON.parse( + localStorage.getItem( + QUEUE_STORAGE_KEY + ) + || '[]' + ); + + } catch ( + error + ) { + return []; + } +} + + +function saveQueue( + queue +) { + localStorage.setItem( + QUEUE_STORAGE_KEY, + JSON.stringify( + queue + ) + ); +} + + +function addToQueue( + item +) { + const queue = + loadQueue(); + + + queue.push({ + ...item, + + queueId: + crypto.randomUUID(), + + addedAt: + Date.now(), + }); + + + saveQueue( + queue + ); + + renderQueue(); + + setStatus( + `Queued "${item.title}"` + ); +} + + +function removeQueueItem( + queueId +) { + const queue = + loadQueue() + .filter( + item => + item.queueId + !== queueId + ); + + + saveQueue( + queue + ); + + renderQueue(); +} + + +async function playNextQueueItem() { + const queue = + loadQueue(); + + + if ( + queue.length === 0 + ) { + return; + } + + + const item = + queue.shift(); + + + saveQueue( + queue + ); + + renderQueue(); + + + await sendMediaItemToRoom( + item + ); +} + + +function renderQueue() { + const queue = + loadQueue(); + + + queueCount.textContent = + String( + queue.length + ); + + + playNextBtn.disabled = + queue.length === 0; + + + queueList.innerHTML = + ''; + + + if ( + queue.length === 0 + ) { + const empty = + document.createElement( + 'div' + ); + + empty.className = + 'side-panel-empty'; + + empty.textContent = + 'Queue is empty.'; + + queueList.appendChild( + empty + ); + + return; + } + + + for ( + const item + of queue + ) { + const row = + createSidePanelItem( + item, + + () => { + sendMediaItemToRoom( + item + ); + }, + + () => { + removeQueueItem( + item.queueId + ); + } + ); + + + queueList.appendChild( + row + ); + } +} + + +// ======================================================== +// Side panel rows +// ======================================================== + +function createSidePanelItem( + item, + onPlay, + onRemove = null +) { + const row = + document.createElement( + 'div' + ); + + row.className = + 'side-media-item'; + + + const thumbnail = + document.createElement( + 'img' + ); + + thumbnail.className = + 'side-media-thumb'; + + + if ( + item.thumbnail + ) { + thumbnail.src = + item.thumbnail; + + } else { + thumbnail.style.display = + 'none'; + } + + + thumbnail.onerror = + () => { + thumbnail.style.display = + 'none'; + }; + + + const info = + document.createElement( + 'div' + ); + + info.className = + 'side-media-info'; + + + const title = + document.createElement( + 'div' + ); + + title.className = + 'side-media-title'; + + title.textContent = + item.title + || 'Unknown'; + + + const meta = + document.createElement( + 'div' + ); + + meta.className = + 'side-media-meta'; + + + const mediaLabel = + item.mediaType === 'audio' + ? 'Audio' + : 'Video'; + + + meta.textContent = [ + mediaLabel, + item.artist || '', + ] + .filter( + Boolean + ) + .join( + ' — ' + ); + + + info.append( + title, + meta + ); + + + const controls = + document.createElement( + 'div' + ); + + controls.className = + 'side-media-actions'; + + + const play = + document.createElement( + 'button' + ); + + play.type = + 'button'; + + play.className = + 'side-action-button'; + + play.textContent = + item.mediaType === 'audio' + ? '♫' + : '▶'; + + play.title = + item.mediaType === 'audio' + ? 'Play audio' + : 'Play video'; + + + play.onclick = + event => { + event.stopPropagation(); + + onPlay(); + }; + + + controls.appendChild( + play + ); + + + if ( + onRemove + ) { + const remove = + document.createElement( + 'button' + ); + + remove.type = + 'button'; + + remove.className = + 'side-action-button'; + + remove.textContent = + '×'; + + remove.title = + 'Remove'; + + + remove.onclick = + event => { + event.stopPropagation(); + + onRemove(); + }; + + + controls.appendChild( + remove + ); + } + + + row.append( + thumbnail, + info, + controls + ); + + + return row; +} + + +// ======================================================== +// Events +// ======================================================== + +searchInput.addEventListener( + 'input', + () => { + clearTimeout( + searchTimer + ); + + + const query = + searchInput.value.trim(); + + + if ( + !query + ) { + list.innerHTML = + ''; + + setStatus( + '' + ); + + return; + } + + + searchTimer = + setTimeout( + () => { + performSearch( + query + ); + }, + 350 + ); + } +); + + +searchInput.addEventListener( + 'keydown', + event => { + if ( + event.key + !== 'Enter' + ) { + return; + } + + + clearTimeout( + searchTimer + ); + + + performSearch( + searchInput.value + ); + } +); + + +closeButton.addEventListener( + 'click', + () => { + window.parent.postMessage( + { + type: + 'KRONICK_MUSIC_CLOSE' + }, + + PARENT_ORIGIN + ); + } +); + + +clearHistoryBtn.addEventListener( + 'click', + () => { + localStorage.removeItem( + HISTORY_STORAGE_KEY + ); + + renderHistory(); + + setStatus( + 'History cleared.' + ); + } +); + + +clearQueueBtn.addEventListener( + 'click', + () => { + localStorage.removeItem( + QUEUE_STORAGE_KEY + ); + + renderQueue(); + + setStatus( + 'Queue cleared.' + ); + } +); + + +playNextBtn.addEventListener( + 'click', + () => { + playNextQueueItem(); + } +); + + +// ======================================================== +// Messages from parent +// ======================================================== + +window.addEventListener( + 'message', + event => { + if ( + event.origin + !== PARENT_ORIGIN + ) { + return; + } + + + if ( + event.data?.type + === 'KRONICK_MEDIA_ENDED' + ) { + playNextQueueItem(); + + return; + } + } +); + + +// ======================================================== +// Startup +// ======================================================== + +function initializeMusicBrowser() { + renderHistory(); + + renderQueue(); + + searchInput.placeholder = + 'Search videos or music...'; + + nav.textContent = + ''; + + setStatus( + 'Search Invidious.' + ); + + searchInput.focus(); + + + console.log( + 'Kronick media browser initialized', + { + origin: + window.location.origin, + + parentOrigin: + PARENT_ORIGIN, + + videoAPI: + `${API_BASE_URL}/api/video/search`, + + audioPattern: + `${API_BASE_URL}/api/audio/{video_id}`, + + videoPattern: + `${API_BASE_URL}/api/video/{video_id}` + } + ); +} + + +initializeMusicBrowser(); diff --git a/kronic-chat/js/rnnoise-worklet.js b/kronic-chat/js/rnnoise-worklet.js new file mode 100644 index 0000000..76d1280 --- /dev/null +++ b/kronic-chat/js/rnnoise-worklet.js @@ -0,0 +1,116 @@ +/* + * RNNoise AudioWorklet Processor + * Handles frame chunking (480 samples / 10ms frame size required by RNNoise) + * and bridges PCM audio buffers with the WebAssembly RNNoise engine. + */ + +class RNNoiseWorkletProcessor extends AudioWorkletProcessor { + constructor() { + super(); + this.FRAME_SIZE = 480; // 10ms at 48kHz + this.inputBuffer = new Float32Array(0); + this.outputBuffer = new Float32Array(0); + this.isWasmReady = false; + + // Listen for WASM binary or module initialization from the main thread + this.port.onmessage = (event) => { + if (event.data.type === 'INIT_WASM') { + this.initWasm(event.data.wasmBytes); + } + }; + } + + initWasm(wasmBytes) { + // Instantiate WASM module directly inside the AudioWorklet scope + WebAssembly.instantiate(wasmBytes, { + env: { + memory: new WebAssembly.Memory({ initial: 256 }), + abort: () => console.error('RNNoise WASM Aborted') + } + }).then(result => { + this.wasmInstance = result.instance; + this.denoiseState = this.wasmInstance.exports.rnnoise_create(null); + this.wasmInputPtr = this.wasmInstance.exports.malloc(this.FRAME_SIZE * 4); + this.wasmOutputPtr = this.wasmInstance.exports.malloc(this.FRAME_SIZE * 4); + this.isWasmReady = true; + }).catch(err => { + console.error('Failed to initialize RNNoise WASM in AudioWorklet:', err); + }); + } + + process(inputs, outputs, parameters) { + const input = inputs[0]; + const output = outputs[0]; + + if (!input || !input[0]) return true; + + const inputChannel = input[0]; + const outputChannel = output[0]; + + // Append incoming Web Audio rendering quantum (typically 128 samples) to buffer + this.inputBuffer = this.concatFloat32(this.inputBuffer, inputChannel); + + // Process full 480-sample frames when available + while (this.inputBuffer.length >= this.FRAME_SIZE) { + const frame = this.inputBuffer.subarray(0, this.FRAME_SIZE); + this.inputBuffer = this.inputBuffer.subarray(this.FRAME_SIZE); + + if (this.isWasmReady && this.denoiseState) { + // Copy frame to WASM heap + const heapF32 = new Float32Array( + this.wasmInstance.exports.memory.buffer, + this.wasmInputPtr, + this.FRAME_SIZE + ); + heapF32.set(frame); + + // Run RNNoise frame processing + this.wasmInstance.exports.rnnoise_process_frame( + this.denoiseState, + this.wasmOutputPtr, + this.wasmInputPtr + ); + + // Extract processed frame from WASM heap + const processedFrame = new Float32Array( + this.wasmInstance.exports.memory.buffer, + this.wasmOutputPtr, + this.FRAME_SIZE + ); + + this.outputBuffer = this.concatFloat32(this.outputBuffer, processedFrame); + } else { + // Pass-through fallback until WASM module is fully loaded + this.outputBuffer = this.concatFloat32(this.outputBuffer, frame); + } + } + + // Deliver processed audio back to Web Audio graph (128 samples at a time) + if (this.outputBuffer.length >= outputChannel.length) { + outputChannel.set(this.outputBuffer.subarray(0, outputChannel.length)); + this.outputBuffer = this.outputBuffer.subarray(outputChannel.length); + } else { + // Silence padding if buffer is temporarily underrun + outputChannel.fill(0); + } + + return true; + } + + concatFloat32(a, b) { + const c = new Float32Array(a.length + b.length); + c.set(a, 0); + c.set(b, a.length); + return c; + } + + destroy() { + if (this.isWasmReady && this.wasmInstance) { + this.wasmInstance.exports.rnnoise_destroy(this.denoiseState); + this.wasmInstance.exports.free(this.wasmInputPtr); + this.wasmInstance.exports.free(this.wasmOutputPtr); + } + } +} + +registerProcessor('rnnoise-worklet', RNNoiseWorkletProcessor); \ No newline at end of file diff --git a/kronic-chat/js/room-auth.js b/kronic-chat/js/room-auth.js new file mode 100644 index 0000000..b3deb63 --- /dev/null +++ b/kronic-chat/js/room-auth.js @@ -0,0 +1,721 @@ +// 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(); + } + ); + }); + } +); \ No newline at end of file diff --git a/kronic-chat/js/room-layout.js b/kronic-chat/js/room-layout.js new file mode 100644 index 0000000..b23e0d8 --- /dev/null +++ b/kronic-chat/js/room-layout.js @@ -0,0 +1,80 @@ +/* Kronic compact room layout. Retain every existing audio control and listener. */ +(() => { + function init() { + const sidebar = document.getElementById('connectionPanel'); + const header = document.querySelector('.topbar'); + if (!sidebar || !header || document.getElementById('kronicVoiceTop')) return; + + const connection = sidebar.querySelector('.panel-section:not(.audio-settings-section)'); + const top = document.createElement('div'); + top.id = 'kronicVoiceTop'; + top.className = 'kronic-voice-top'; + header.insertBefore(top, header.querySelector('.topbar-tools') || null); + if (connection) top.append(connection); + + // Three independent popups use the original details elements, not clones. + const names = ['voice', 'noise', 'spatial']; + const groups = [...sidebar.querySelectorAll('.audio-setting-group.audio-collapsible')]; + const popups = {}; + for (let i = 0; i < names.length; i++) { + const panel = document.createElement('section'); + panel.className = 'kronic-audio-popup'; + panel.dataset.audioPopup = names[i]; + panel.hidden = true; + panel.setAttribute('role', 'dialog'); + panel.setAttribute('aria-label', names[i] + ' audio settings'); + const close = document.createElement('button'); + close.className = 'kronic-audio-close'; + close.type = 'button'; + close.textContent = '×'; + close.setAttribute('aria-label', 'Close audio settings'); + close.addEventListener('click', () => hideAll()); + panel.append(close); + if (groups[i]) { + groups[i].open = true; + panel.append(groups[i]); + } + // Noise suppression has Apply and restart-hint elements in the same source section. + if (names[i] === 'noise') { + const section = sidebar.querySelector('.audio-settings-section'); + // Keep external controls that are siblings of the noise group near their original section. + // Existing handlers remain attached to the original DOM nodes. + } + document.body.append(panel); + popups[names[i]] = panel; + } + sidebar.classList.add('kronic-parked-sidebar'); + document.body.append(sidebar); + + function hideAll() { + Object.values(popups).forEach(panel => panel.hidden = true); + window.parent?.postMessage({type:'KRONIC_ROOM_UI_PANEL', action:'closed'}, location.origin); + } + window.addEventListener('message', event => { + if (event.origin !== location.origin || event.source !== window.parent) return; + const message = event.data; + if (message?.type !== 'KRONIC_ROOM_UI') return; + if (message.action === 'close-audio') hideAll(); + else if (typeof message.action === 'string' && message.action.startsWith('open-audio-')) { + const target = message.action.slice('open-audio-'.length); + Object.entries(popups).forEach(([name,panel]) => panel.hidden = name !== target); + if (popups[target]) popups[target].scrollTop = 0; + } else if (message.action === 'mute') { + document.getElementById('muteBtn')?.click(); + } else if (message.action === 'leave') { + document.getElementById('leaveBtn')?.click(); + } + }); + document.addEventListener('keydown', event => { if (event.key === 'Escape') hideAll(); }); + const state = document.getElementById('statusBar'); + const publish = () => { + if (window.parent !== window) window.parent.postMessage({ + type:'KRONIC_ROOM_UI_STATUS',label:state?.textContent?.trim() || 'Not connected' + },location.origin); + }; + if (state) new MutationObserver(publish).observe(state, {childList:true,subtree:true,characterData:true}); + publish(); + } + if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init, {once:true}); + else init(); +})(); diff --git a/kronic-chat/js/room-sync-bridge.js b/kronic-chat/js/room-sync-bridge.js new file mode 100644 index 0000000..a789147 --- /dev/null +++ b/kronic-chat/js/room-sync-bridge.js @@ -0,0 +1,55 @@ +/* Kronic room playback bridge: LiveKit is the ONLY transport between peers. + * Parent and embedded Chat share the same origin through /borg-chat/app. + * No URLs, passwords, or media bytes are sent to other participants. + */ +(() => { + 'use strict'; + const PREFIX = 'KRONIC_ROOM_SYNC'; + const TOPIC = 'kronic-room-playback-v1'; + const VALID_KINDS = new Set(['library', 'youtube', 'twitch', 'music', 'iptv']); + const VALID_ACTIONS = new Set(['open', 'play', 'pause', 'seek']); + let sequence = 0; + + const parentIsSameOrigin = () => window.parent !== window && (() => { + try { return window.parent.location.origin === location.origin; } + catch { return false; } + })(); + + function valid(message) { + if (!message || message.v !== 1 || !VALID_KINDS.has(message.kind) || !VALID_ACTIONS.has(message.action)) return false; + if (message.kind === 'library' || message.kind === 'music') { + if (!Number.isSafeInteger(Number(message.id)) || Number(message.id) <= 0) return false; + } else if (typeof message.id !== 'string' || message.id.length < 1 || message.id.length > 100 || !/^[\w-]+$/.test(message.id)) return false; + if (message.title !== undefined && (typeof message.title !== 'string' || message.title.length > 240)) return false; + if (message.position !== undefined && (!Number.isFinite(message.position) || message.position < 0 || message.position > 864000)) return false; + return true; + } + + function toParent(payload) { + if (parentIsSameOrigin()) window.parent.postMessage({type: PREFIX + '_INCOMING', payload}, location.origin); + } + + // Do not use the legacy "media" URL player: these messages target Media's native players. + window.Kronick = window.Kronick || {}; + Kronick.handleNativeRoomPlayback = function (payload, participant) { + if (!participant || !valid(payload)) return; + toParent(payload); + }; + + window.addEventListener('message', (event) => { + if (!parentIsSameOrigin() || event.origin !== location.origin || event.source !== window.parent) return; + const message = event.data; + if (message?.type !== PREFIX + '_OUTGOING' || !valid(message.payload)) return; + const room = Kronick.state?.room; + if (!room?.localParticipant || room.state !== 'connected') { + window.parent.postMessage({type: PREFIX + '_STATUS', connected: false}, location.origin); + return; + } + const payload = {...message.payload, v: 1, seq: ++sequence}; + room.localParticipant.publishData(new TextEncoder().encode(JSON.stringify(payload)), { + reliable: true, topic: TOPIC, + }).catch(error => console.warn('[Kronic room sync] LiveKit publish failed:', error)); + }); + + Kronick.roomPlaybackTopic = TOPIC; +})();