From e3157104a49ae321f7cd102ba852c9f1b44dc3a5 Mon Sep 17 00:00:00 2001 From: admin Date: Wed, 25 Nov 2026 20:26:42 -0600 Subject: [PATCH] Upload files to "kronic-chat/js" --- kronic-chat/js/chat-notifications.js | 397 +++++++++ kronic-chat/js/giphy.js | 1178 +++++++++++++++++++++++++ kronic-chat/js/install-config.js | 15 + kronic-chat/js/media-controller.js | 1205 ++++++++++++++++++++++++++ kronic-chat/js/message-router.js | 735 ++++++++++++++++ 5 files changed, 3530 insertions(+) create mode 100644 kronic-chat/js/chat-notifications.js create mode 100644 kronic-chat/js/giphy.js create mode 100644 kronic-chat/js/install-config.js create mode 100644 kronic-chat/js/media-controller.js create mode 100644 kronic-chat/js/message-router.js diff --git a/kronic-chat/js/chat-notifications.js b/kronic-chat/js/chat-notifications.js new file mode 100644 index 0000000..f19165d --- /dev/null +++ b/kronic-chat/js/chat-notifications.js @@ -0,0 +1,397 @@ +// chat-notifications.js +// +// Reliable parent-level unread notification handling. +// Incoming LiveKit chat is observed directly in the host app instead +// of depending on the chat iframe to echo a notification back. + +window.Kronick = + window.Kronick || {}; + +(() => { + const seenMessageKeys = + new Map(); + + const MESSAGE_DEDUPE_MS = + 15000; + + let unreadCount = + 0; + + function getChatButton() { + return document.getElementById( + 'chatToolButton' + ); + } + + function getUnreadBadge() { + return document.getElementById( + 'chatUnreadCount' + ); + } + + function getChatWindow() { + return document.getElementById( + 'chatFrameWrap' + ); + } + + function getMessageKey(message) { + if (!message) { + return ''; + } + + if (message.id) { + return String( + message.id + ); + } + + return [ + message.sender || '', + message.createdAt || '', + message.text || '', + message.gifUrl || '', + message.imageUrl || '' + ].join('|'); + } + + function pruneSeenMessages() { + const cutoff = + Date.now() + - MESSAGE_DEDUPE_MS; + + for ( + const [key, timestamp] + of seenMessageKeys + ) { + if (timestamp < cutoff) { + seenMessageKeys.delete( + key + ); + } + } + } + + function markMessageSeen(message) { + const key = + getMessageKey( + message + ); + + if (!key) { + return false; + } + + pruneSeenMessages(); + + if ( + seenMessageKeys.has( + key + ) + ) { + return false; + } + + seenMessageKeys.set( + key, + Date.now() + ); + + return true; + } + + function chatIsVisible() { + const chatWindow = + getChatWindow(); + + if (!chatWindow) { + return false; + } + + if ( + chatWindow.classList.contains( + 'window-minimized' + ) + ) { + return false; + } + + const style = + window.getComputedStyle( + chatWindow + ); + + return ( + style.display !== 'none' + && style.visibility !== 'hidden' + && style.opacity !== '0' + ); + } + + function isOwnMessage(message) { + const localIdentity = + Kronick.state + ?.room + ?.localParticipant + ?.identity + || ''; + + if (!localIdentity) { + return false; + } + + return ( + String( + message?.sender + || '' + ) + === String( + localIdentity + ) + ); + } + + function renderUnreadState() { + const button = + getChatButton(); + + const badge = + getUnreadBadge(); + + if (!button || !badge) { + return; + } + + const hasUnread = + unreadCount > 0; + + button.classList.toggle( + 'chat-alert', + hasUnread + ); + + badge.dataset.count = + String( + unreadCount + ); + + badge.textContent = + unreadCount > 99 + ? '99+' + : String( + unreadCount + ); + + badge.hidden = + !hasUnread; + + button.setAttribute( + 'aria-label', + hasUnread + ? `Open chat, ${unreadCount} unread message${ + unreadCount === 1 + ? '' + : 's' + }` + : 'Open chat' + ); + } + + function clearUnread() { + unreadCount = + 0; + + renderUnreadState(); + } + + function notifyForMessage( + message + ) { + if (!message) { + return; + } + + if ( + isOwnMessage( + message + ) + ) { + return; + } + + if ( + !markMessageSeen( + message + ) + ) { + return; + } + + if ( + chatIsVisible() + ) { + clearUnread(); + return; + } + + unreadCount += + 1; + + renderUnreadState(); + } + + function installReceiveHook() { + const originalReceive = + Kronick.receiveChatMessage; + + if ( + typeof originalReceive + !== 'function' + ) { + return false; + } + + if ( + originalReceive + .__kronickUnreadWrapped + ) { + return true; + } + + const wrappedReceive = + function wrappedReceiveChatMessage( + message + ) { + const result = + originalReceive.apply( + this, + arguments + ); + + notifyForMessage( + message + ); + + return result; + }; + + wrappedReceive + .__kronickUnreadWrapped = + true; + + Kronick.receiveChatMessage = + wrappedReceive; + + return true; + } + + function installUiHooks() { + const chatButton = + getChatButton(); + + const chatWindow = + getChatWindow(); + + chatButton?.addEventListener( + 'click', + () => { + window.setTimeout( + () => { + if ( + chatIsVisible() + ) { + clearUnread(); + } + }, + 0 + ); + } + ); + + if (chatWindow) { + const observer = + new MutationObserver( + () => { + if ( + chatIsVisible() + ) { + clearUnread(); + } + } + ); + + observer.observe( + chatWindow, + { + attributes: + true, + + attributeFilter: + [ + 'class', + 'style', + 'hidden' + ] + } + ); + } + + window.addEventListener( + 'focus', + () => { + if ( + chatIsVisible() + ) { + clearUnread(); + } + } + ); + } + + // Keep old iframe notification calls compatible, + // but funnel them through the same deduped handler. + Kronick + .handleIncomingChatNotification = + notifyForMessage; + + Kronick + .clearChatNotification = + clearUnread; + + function init() { + installReceiveHook(); + installUiHooks(); + renderUnreadState(); + + if ( + typeof Kronick.receiveChatMessage + !== 'function' + ) { + window.setTimeout( + installReceiveHook, + 0 + ); + + window.setTimeout( + installReceiveHook, + 250 + ); + } + } + + if ( + document.readyState + === 'loading' + ) { + document.addEventListener( + 'DOMContentLoaded', + init, + { + once: + true + } + ); + } else { + init(); + } +})(); diff --git a/kronic-chat/js/giphy.js b/kronic-chat/js/giphy.js new file mode 100644 index 0000000..e4e1dc5 --- /dev/null +++ b/kronic-chat/js/giphy.js @@ -0,0 +1,1178 @@ +// ===================================================== +// Kronick GIPHY Browser +// ===================================================== + +const GIPHY_SEARCH_ENDPOINT = + window.location.pathname.startsWith('/borg-chat/') + ? '/borg-chat/api/giphy/search' + : '/api/giphy/search'; + +const PARENT_ORIGIN = + window.location.origin; + +const GIPHY_HISTORY_STORAGE_KEY = + 'kronickGiphyHistory'; + +const MAX_GIPHY_HISTORY_ITEMS = 75; + + +// ===================================================== +// DOM elements +// ===================================================== + +const searchInput = + document.getElementById( + 'giphySearchInput' + ); + +const searchBtn = + document.getElementById( + 'giphySearchBtn' + ); + +const results = + document.getElementById( + 'giphyResults' + ); + +const statusBox = + document.getElementById( + 'giphyStatus' + ); + +const closeBtn = + document.getElementById( + 'giphyCloseBtn' + ); + +const historyList = + document.getElementById( + 'giphyHistoryList' + ); + +const historyCount = + document.getElementById( + 'giphyHistoryCount' + ); + +const clearHistoryBtn = + document.getElementById( + 'clearGiphyHistoryBtn' + ); + + +// ===================================================== +// State +// ===================================================== + +let giphyAbortController = null; +let giphySearchSeq = 0; + +let giphyHistory = + loadGiphyHistory(); + + +// ===================================================== +// Startup +// ===================================================== + +init(); + + +function init() { + bindEvents(); + renderGiphyHistory(); + renderInitialResults(); + + searchInput?.focus(); + + console.log( + 'Kronick GIPHY browser initialized', + { + origin: + window.location.origin, + + parentAvailable: + window.parent !== window + } + ); +} + + +// ===================================================== +// Event bindings +// ===================================================== + +function bindEvents() { + searchBtn?.addEventListener( + 'click', + () => { + searchGiphy(false); + } + ); + + searchInput?.addEventListener( + 'keydown', + event => { + if (event.key !== 'Enter') { + return; + } + + event.preventDefault(); + + searchGiphy(false); + } + ); + + closeBtn?.addEventListener( + 'click', + () => { + postToParent({ + type: + 'KRONICK_GIPHY_CLOSE' + }); + } + ); + + clearHistoryBtn?.addEventListener( + 'click', + clearGiphyHistory + ); +} + + +// ===================================================== +// GIPHY search +// ===================================================== + +async function searchGiphy( + refresh = false +) { + const query = + searchInput?.value + .trim() + || ''; + + if (!query) { + setStatus( + 'Type something to search.' + ); + + renderEmptyResults( + 'Enter a search above to browse results.' + ); + + searchInput?.focus(); + + return; + } + + if (giphyAbortController) { + giphyAbortController.abort(); + } + + giphyAbortController = + new AbortController(); + + const requestSequence = + ++giphySearchSeq; + + setStatus('Searching...'); + + if (results) { + results.innerHTML = ''; + } + + if (searchBtn) { + searchBtn.disabled = true; + searchBtn.textContent = + 'Searching...'; + } + + try { + const url = + GIPHY_SEARCH_ENDPOINT + + '?q=' + + encodeURIComponent(query) + + '&refresh=' + + String(refresh); + + const response = + await fetch( + url, + { + signal: + giphyAbortController + .signal + } + ); + + if (!response.ok) { + let detail = ''; + + try { + const responseText = + await response.text(); + + if (responseText) { + detail = + ': ' + + responseText; + } + } catch { + // Ignore unreadable response bodies. + } + + throw new Error( + 'GIPHY search returned ' + + response.status + + detail + ); + } + + const data = + await response.json(); + + /* + * Ignore an older response if a newer + * search has already started. + */ + if ( + requestSequence + !== giphySearchSeq + ) { + return; + } + + // Embedded Chat backend returns { items: [...] }. + // Keep compatibility with the original GIPHY { data: [...] } shape. + const gifs = + Array.isArray(data?.items) + ? data.items + : Array.isArray(data?.data) + ? data.data + : []; + + if (results) { + results.innerHTML = ''; + } + + if (!gifs.length) { + setStatus( + 'No GIFs found.' + ); + + renderEmptyResults( + 'Try a different search.' + ); + + return; + } + + setStatus( + `${gifs.length} GIFs found` + ); + + const fragment = + document.createDocumentFragment(); + + gifs.forEach(gif => { + fragment.appendChild( + createGifResultCard(gif) + ); + }); + + results?.appendChild( + fragment + ); + } catch (error) { + if ( + error?.name + === 'AbortError' + ) { + return; + } + + console.error( + 'GIPHY SEARCH ERROR:', + error + ); + + setStatus( + 'GIPHY search failed.' + ); + + renderEmptyResults( + 'The GIF service could not complete the search.' + ); + } finally { + if ( + requestSequence + === giphySearchSeq + ) { + if (searchBtn) { + searchBtn.disabled = false; + searchBtn.textContent = + 'Search'; + } + } + } +} + + +// ===================================================== +// Result cards +// ===================================================== + +function createGifResultCard(gif) { + const normalizedGif = + normalizeGif(gif); + + const itemWrap = + document.createElement( + 'article' + ); + + itemWrap.className = + 'gif-item-wrap'; + + itemWrap.dataset.gifId = + normalizedGif.id; + + + const imageButton = + document.createElement( + 'button' + ); + + imageButton.type = + 'button'; + + imageButton.className = + 'giphy-image-button'; + + imageButton.title = + 'Send GIF'; + + imageButton.setAttribute( + 'aria-label', + 'Send ' + + normalizedGif.title + ); + + + const image = + document.createElement( + 'img' + ); + + image.src = + normalizedGif.thumb + || normalizedGif.url; + + image.alt = + normalizedGif.title + || 'GIPHY result'; + + image.title = + normalizedGif.title + || 'GIPHY result'; + + image.className = + 'giphy-result'; + + image.loading = + 'lazy'; + + image.addEventListener( + 'error', + () => { + image.style.visibility = + 'hidden'; + + itemWrap.classList.add( + 'gif-load-error' + ); + } + ); + + + imageButton.appendChild( + image + ); + + imageButton.addEventListener( + 'click', + () => { + sendGif( + normalizedGif + ); + } + ); + + + const title = + document.createElement( + 'div' + ); + + title.className = + 'giphy-result-title'; + + title.textContent = + normalizedGif.title + || 'GIPHY'; + + + const actions = + document.createElement( + 'div' + ); + + actions.className = + 'giphy-result-actions'; + + + const sendButton = + createActionButton( + 'Send', + 'send-gif-btn', + () => { + sendGif( + normalizedGif + ); + } + ); + + + const avatarButton = + createActionButton( + 'Set Avatar', + 'set-avatar-btn', + () => { + setGifAsAvatar( + normalizedGif + ); + } + ); + + + actions.append( + sendButton, + avatarButton + ); + + itemWrap.append( + imageButton, + title, + actions + ); + + return itemWrap; +} + + +function createActionButton( + text, + className, + handler +) { + const button = + document.createElement( + 'button' + ); + + button.type = + 'button'; + + button.className = + 'giphy-action-button ' + + className; + + button.textContent = + text; + + button.addEventListener( + 'click', + event => { + event.stopPropagation(); + + handler(); + } + ); + + return button; +} + + +// ===================================================== +// Sending GIFs +// ===================================================== + +function sendGif(gif) { + const normalizedGif = + normalizeGif(gif); + + if (!normalizedGif.url) { + setStatus( + 'GIF has no usable URL.' + ); + + return; + } + + const message = { + type: + 'KRONICK_GIPHY_SELECTED', + + url: + normalizedGif.url, + + title: + normalizedGif.title + || 'GIPHY', + + gif: { + id: + normalizedGif.id, + + title: + normalizedGif.title, + + url: + normalizedGif.url, + + thumb: + normalizedGif.thumb + } + }; + + console.log( + 'Sending selected GIF to parent:', + message + ); + + const sent = + postToParent(message); + + if (!sent) { + setStatus( + 'Could not send GIF. Open this from the main window.' + ); + + return; + } + + addGifToHistory( + normalizedGif, + 'sent' + ); + + setStatus( + 'GIF selected.' + ); + + // Auto-dismiss floating frame/modal in the host application + postToParent({ + type: + 'KRONICK_GIPHY_CLOSE' + }); +} + + +/* + * Compatibility alias for older code that may + * still call sendGifToChatRoom(). + */ +function sendGifToChatRoom(gif) { + sendGif(gif); +} + + +// ===================================================== +// Avatar selection +// ===================================================== + +function setGifAsAvatar(gif) { + const normalizedGif = + normalizeGif(gif); + + if (!normalizedGif.url) { + setStatus( + 'GIF has no usable URL.' + ); + + return; + } + + const message = { + type: + 'KRONICK_GIPHY_AVATAR_SET', + + url: + normalizedGif.url, + + title: + normalizedGif.title + || 'GIPHY', + + gif: { + id: + normalizedGif.id, + + title: + normalizedGif.title, + + url: + normalizedGif.url, + + thumb: + normalizedGif.thumb + } + }; + + console.log( + 'Sending avatar GIF to parent:', + message + ); + + const sent = + postToParent(message); + + if (!sent) { + setStatus( + 'Could not set avatar from a standalone window.' + ); + + return; + } + + addGifToHistory( + normalizedGif, + 'avatar' + ); + + setStatus( + 'Avatar updated!' + ); + + // Auto-dismiss floating frame/modal in the host application + postToParent({ + type: + 'KRONICK_GIPHY_CLOSE' + }); +} + + +// ===================================================== +// Parent communication +// ===================================================== + +function postToParent(message) { + if ( + !window.parent + || window.parent === window + ) { + console.warn( + 'Cannot post GIPHY message: no parent window.', + message + ); + + return false; + } + + try { + window.parent.postMessage( + message, + PARENT_ORIGIN + ); + + return true; + } catch (error) { + console.error( + 'Failed to post GIPHY message:', + error + ); + + return false; + } +} + + +// ===================================================== +// GIF normalization +// ===================================================== + +function normalizeGif(gif) { + const rawId = + gif?.id + || gif?.url + || gif?.images?.original?.url + || ''; + + const fullUrl = + gif?.url + || gif?.images?.original?.url + || gif?.images?.downsized?.url + || ''; + + const thumbnailUrl = + gif?.thumb + || gif?.thumbnail + || gif?.images?.fixed_width_small?.url + || gif?.images?.fixed_width?.url + || fullUrl; + + return { + id: + String( + rawId + || crypto.randomUUID() + ), + + title: + String( + gif?.title + || 'GIPHY' + ), + + url: + String( + fullUrl + || '' + ), + + thumb: + String( + thumbnailUrl + || '' + ) + }; +} + + +// ===================================================== +// History storage +// ===================================================== + +function loadGiphyHistory() { + try { + const storedValue = + localStorage.getItem( + GIPHY_HISTORY_STORAGE_KEY + ); + + if (!storedValue) { + return []; + } + + const parsed = + JSON.parse( + storedValue + ); + + return Array.isArray(parsed) + ? parsed + : []; + } catch (error) { + console.warn( + 'Could not load GIPHY history:', + error + ); + + return []; + } +} + + +function saveGiphyHistory() { + try { + localStorage.setItem( + GIPHY_HISTORY_STORAGE_KEY, + JSON.stringify( + giphyHistory + ) + ); + } catch (error) { + console.warn( + 'Could not save GIPHY history:', + error + ); + } +} + + +function addGifToHistory( + gif, + action +) { + const normalizedGif = + normalizeGif(gif); + + /* + * Remove an older occurrence of the same GIF, + * then place the newest use at the top. + */ + giphyHistory = + giphyHistory.filter( + item => + item.url + !== normalizedGif.url + ); + + giphyHistory.unshift({ + historyId: + crypto.randomUUID(), + + ...normalizedGif, + + action: + action === 'avatar' + ? 'avatar' + : 'sent', + + usedAt: + Date.now() + }); + + giphyHistory = + giphyHistory.slice( + 0, + MAX_GIPHY_HISTORY_ITEMS + ); + + saveGiphyHistory(); + renderGiphyHistory(); +} + + +function clearGiphyHistory() { + giphyHistory = []; + + saveGiphyHistory(); + renderGiphyHistory(); + + setStatus( + 'GIF history cleared.' + ); +} + + +function removeGiphyHistoryItem( + historyId +) { + giphyHistory = + giphyHistory.filter( + item => + item.historyId + !== historyId + ); + + saveGiphyHistory(); + renderGiphyHistory(); +} + + +// ===================================================== +// History rendering +// ===================================================== + +function renderGiphyHistory() { + if (!historyList) { + return; + } + + historyList.innerHTML = ''; + + if (historyCount) { + historyCount.textContent = + String( + giphyHistory.length + ); + } + + if (!giphyHistory.length) { + historyList.innerHTML = ` +
+ GIFs you send or use as avatars + will appear here. +
+ `; + + return; + } + + const fragment = + document.createDocumentFragment(); + + giphyHistory.forEach(item => { + fragment.appendChild( + createHistoryCard(item) + ); + }); + + historyList.appendChild( + fragment + ); +} + + +function createHistoryCard(item) { + const normalizedGif = + normalizeGif(item); + + const card = + document.createElement( + 'article' + ); + + card.className = + 'giphy-history-item'; + + + const image = + document.createElement( + 'img' + ); + + image.className = + 'giphy-history-image'; + + image.src = + normalizedGif.thumb + || normalizedGif.url; + + image.alt = + normalizedGif.title + || 'GIF history'; + + image.title = + 'Send again'; + + image.loading = + 'lazy'; + + image.addEventListener( + 'error', + () => { + image.style.visibility = + 'hidden'; + } + ); + + image.addEventListener( + 'click', + () => { + sendGif(item); + } + ); + + + const info = + document.createElement( + 'div' + ); + + info.className = + 'giphy-history-info'; + + + const title = + document.createElement( + 'div' + ); + + title.className = + 'giphy-history-item-title'; + + title.textContent = + normalizedGif.title + || 'GIPHY'; + + + const meta = + document.createElement( + 'div' + ); + + meta.className = + 'giphy-history-meta'; + + meta.textContent = + item.action === 'avatar' + ? 'Used as avatar' + : 'Sent'; + + + info.append( + title, + meta + ); + + + const actions = + document.createElement( + 'div' + ); + + actions.className = + 'giphy-history-actions'; + + + actions.append( + createHistoryButton( + '▶', + 'Send again', + () => { + sendGif(item); + } + ), + + createHistoryButton( + 'A', + 'Set as avatar', + () => { + setGifAsAvatar(item); + } + ), + + createHistoryButton( + '×', + 'Remove from history', + () => { + removeGiphyHistoryItem( + item.historyId + ); + } + ) + ); + + + card.append( + image, + info, + actions + ); + + return card; +} + + +function createHistoryButton( + text, + title, + handler +) { + const button = + document.createElement( + 'button' + ); + + button.type = + 'button'; + + button.className = + 'giphy-history-action'; + + button.textContent = + text; + + button.title = + title; + + button.setAttribute( + 'aria-label', + title + ); + + button.addEventListener( + 'click', + event => { + event.stopPropagation(); + + handler(); + } + ); + + return button; +} + + +// ===================================================== +// Empty states and status +// ===================================================== + +function renderInitialResults() { + if ( + !results + || results.children.length + ) { + return; + } + + renderEmptyResults( + 'Enter a search above to browse results.' + ); +} + + +function renderEmptyResults(message) { + if (!results) { + return; + } + + results.innerHTML = ` +
+
+ GIF +
+ +
+ No GIFs loaded +
+ +
+ ${escapeHtml(message)} +
+
+ `; +} + + +function setStatus(text) { + if (!statusBox) { + return; + } + + statusBox.textContent = + text || ''; +} + + +// ===================================================== +// Escaping +// ===================================================== + +function escapeHtml(value) { + return String(value || '') + .replaceAll( + '&', + '&' + ) + .replaceAll( + '<', + '<' + ) + .replaceAll( + '>', + '>' + ) + .replaceAll( + '"', + '"' + ) + .replaceAll( + "'", + ''' + ); +} diff --git a/kronic-chat/js/install-config.js b/kronic-chat/js/install-config.js new file mode 100644 index 0000000..b0835a9 --- /dev/null +++ b/kronic-chat/js/install-config.js @@ -0,0 +1,15 @@ +// --------------------------------------------------------- +// Kronic Krusaders browser installation configuration +// +// Generated automatically by setup.sh. +// +// PUBLIC VALUES ONLY. +// Never place passwords, API secrets, session secrets, +// admin credentials, or other private values in this file. +// --------------------------------------------------------- + +window.KRONICK_INSTALL_CONFIG = { + PUBLIC_BASE_URL: "https://kronickrusaders.ca", + LIVEKIT_URL: "wss://lvkt.kronickrusaders.ca", + TOKEN_URL: "https://kronickrusaders.ca/get-token" +}; diff --git a/kronic-chat/js/media-controller.js b/kronic-chat/js/media-controller.js new file mode 100644 index 0000000..8915f84 --- /dev/null +++ b/kronic-chat/js/media-controller.js @@ -0,0 +1,1205 @@ +// media-controller.js + +window.Kronick = + window.Kronick || {}; + + +/* + * Convert internal, insecure or outdated media URLs + * into URLs that browsers can access from the HTTPS + * Kronick Chat page. + */ +Kronick.normalizePublicMediaUrl = +function normalizePublicMediaUrl(rawUrl) { + if ( + typeof rawUrl !== 'string' + || !rawUrl.trim() + ) { + return ''; + } + + let normalized = + rawUrl.trim(); + + /* + * Remove HTML-escaped ampersands that may have + * come through an API response. + */ + normalized = normalized.replace( + /&/g, + '&' + ); + + /* + * Convert internal or insecure Kronick service + * addresses to their public HTTPS equivalents. + */ + normalized = normalized.replace( + /^http:\/\/tube\.kronickrusaders\.ca:3000(?=\/|$)/i, + 'https://tube.kronickrusaders.ca' + ); + + normalized = normalized.replace( + /^https:\/\/tube\.kronickrusaders\.ca:3000(?=\/|$)/i, + 'https://tube.kronickrusaders.ca' + ); + + normalized = normalized.replace( + /^http:\/\/tube\.kronickrusaders\.ca(?=\/|$)/i, + 'https://tube.kronickrusaders.ca' + ); + + normalized = normalized.replace( + /^http:\/\/music\.kronickrusaders\.ca(?=\/|$)/i, + 'https://music.kronickrusaders.ca' + ); + + normalized = normalized.replace( + /^http:\/\/discord\.kronickrusaders\.ca(?=\/|$)/i, + 'https://discord.kronickrusaders.ca' + ); + + /* + * Convert protocol-relative URLs to HTTPS. + */ + if (normalized.startsWith('//')) { + normalized = + `https:${normalized}`; + } + + /* + * Resolve relative media paths against the music + * service rather than the parent Discord app. + */ + try { + normalized = + new URL( + normalized, + 'https://music.kronickrusaders.ca' + ).href; + } catch (err) { + console.warn( + 'Invalid media URL:', + { + rawUrl, + error: + err.message + } + ); + + return ''; + } + + return normalized; +}; + + +/* + * Return a readable explanation for an HTMLMediaElement + * error code. + */ +Kronick.getMediaErrorMessage = +function getMediaErrorMessage(mediaError) { + const errorMessages = { + 1: + 'Playback was aborted.', + + 2: + 'A network error prevented ' + + 'the media from loading.', + + 3: + 'The media downloaded, but ' + + 'the browser could not decode it.', + + 4: + 'The URL did not provide a ' + + 'supported media format.' + }; + + return ( + errorMessages[ + mediaError?.code + ] + || mediaError?.message + || 'Unknown media playback error.' + ); +}; + + +/* + * Remove the previous media source and event handlers. + */ +Kronick.resetMediaElement = +function resetMediaElement(mediaElement) { + if (!mediaElement) { + return; + } + + mediaElement.pause(); + + mediaElement.onerror = null; + mediaElement.onloadstart = null; + mediaElement.onloadedmetadata = null; + mediaElement.oncanplay = null; + mediaElement.onplaying = null; + mediaElement.onwaiting = null; + mediaElement.onstalled = null; + mediaElement.onabort = null; + mediaElement.onemptied = null; + + mediaElement.removeAttribute( + 'src' + ); + + if ( + mediaElement.tagName + === 'VIDEO' + ) { + mediaElement.removeAttribute( + 'poster' + ); + } + + mediaElement.load(); +}; + + +/* + * Publish a media selection to the LiveKit room. + */ +Kronick.sendMediaToRoom = +function sendMediaToRoom(data) { + const room = + Kronick.state.room; + + if (!room?.localParticipant) { + alert( + 'Join a room first.' + ); + + return; + } + + if ( + !data + || typeof data !== 'object' + || typeof data.url !== 'string' + || !data.url.trim() + ) { + console.warn( + 'Media share has no valid URL:', + data + ); + + return; + } + + const normalizedUrl = + Kronick.normalizePublicMediaUrl( + data.url + ); + + const normalizedThumbnail = + data.thumbnail + ? Kronick + .normalizePublicMediaUrl( + data.thumbnail + ) + : ''; + + if (!normalizedUrl) { + console.warn( + 'Media URL could not be normalized:', + data.url + ); + + return; + } + + const message = { + type: + 'media', + + mediaType: + data.mediaType + || 'video', + + url: + normalizedUrl, + + title: + data.title + || '', + + thumbnail: + normalizedThumbnail + }; + + console.log( + 'SENDING MEDIA TO LIVEKIT ROOM:', + message + ); + + const payload = + new TextEncoder().encode( + JSON.stringify(message) + ); + + room.localParticipant + .publishData( + payload, + { + reliable: true, + + topic: + Kronick.config + .DATA_TOPIC_MEDIA + } + ) + .catch(err => { + console.error( + 'Could not publish media message:', + err + ); + }); + + + /* + * Display it immediately for the sender. + * LiveKit does not normally echo the sender's + * data packet back to the same participant. + */ + Kronick.handleRoomMedia( + message + ); +}; + + +/* + * Handle a media message received from LiveKit or + * generated locally. + */ +Kronick.handleRoomMedia = +function handleRoomMedia(message) { + if ( + !message + || typeof message !== 'object' + ) { + return; + } + + if (message.type === 'media-stop') { + Kronick.closeSharedMedia( + false + ); + + return; + } + + const normalizedUrl = + Kronick.normalizePublicMediaUrl( + message.url + ); + + if (!normalizedUrl) { + console.warn( + 'Received media message ' + + 'without a usable URL:', + message + ); + + return; + } + + const mediaType = + String( + message.mediaType + || 'video' + ).toLowerCase(); + + const normalizedThumbnail = + message.thumbnail + ? Kronick + .normalizePublicMediaUrl( + message.thumbnail + ) + : ''; + + console.log( + 'HANDLING ROOM MEDIA:', + { + ...message, + + url: + normalizedUrl, + + thumbnail: + normalizedThumbnail + } + ); + + + /* + * A room GIF is shown in the temporary overlay, + * rather than the audio/video player. + */ + if (mediaType === 'gif') { + Kronick.showSharedGif( + normalizedUrl + ); + + return; + } + + Kronick.playSharedMedia({ + url: + normalizedUrl, + + mediaType, + + title: + message.title + || 'Shared Media', + + thumbnail: + normalizedThumbnail + }); +}; + + +/* + * Display and play shared audio or video. + */ +Kronick.playSharedMedia = +function playSharedMedia({ + url, + mediaType = 'video', + title = '', + thumbnail = '' +}) { + const wrap = + document.getElementById( + 'sharedMediaWrap' + ); + + const titleEl = + document.getElementById( + 'sharedMediaTitle' + ); + + const video = + document.getElementById( + 'sharedMediaVideo' + ); + + const audio = + document.getElementById( + 'sharedMediaAudio' + ); + + const thumb = + document.getElementById( + 'sharedMediaThumb' + ); + + const error = + document.getElementById( + 'sharedMediaError' + ); + + if ( + !wrap + || !titleEl + || !video + || !audio + || !thumb + || !error + ) { + console.error( + 'Shared media HTML elements ' + + 'could not be found.' + ); + + return; + } + + const normalizedUrl = + Kronick.normalizePublicMediaUrl( + url + ); + + const normalizedThumbnail = + thumbnail + ? Kronick + .normalizePublicMediaUrl( + thumbnail + ) + : ''; + + if (!normalizedUrl) { + error.textContent = + 'The shared media URL is invalid.'; + + error.style.display = + 'block'; + + console.error( + 'Cannot play invalid media URL:', + url + ); + + return; + } + + + /* + * Stop and clear any previous playback. + */ + Kronick.resetMediaElement( + video + ); + + Kronick.resetMediaElement( + audio + ); + + thumb.removeAttribute( + 'src' + ); + + video.style.display = + 'none'; + + audio.style.display = + 'none'; + + thumb.style.display = + 'none'; + + error.style.display = + 'none'; + + error.textContent = + ''; + + titleEl.textContent = + title || 'Shared Media'; + + wrap.style.display = + 'flex'; + + Kronick.bringToolWindowToFront( + wrap + ); + + requestAnimationFrame(() => { + Kronick.keepWindowInViewport( + wrap + ); + }); + + const normalizedMediaType = + String(mediaType) + .toLowerCase(); + + + /* + * Audio playback. + */ + if ( + normalizedMediaType === 'audio' + || normalizedMediaType === 'music' + ) { + wrap.classList.add( + 'audio-mode' + ); + + if (normalizedThumbnail) { + thumb.src = + normalizedThumbnail; + + thumb.style.display = + 'block'; + + thumb.onerror = () => { + console.warn( + 'Shared audio thumbnail ' + + 'failed to load:', + normalizedThumbnail + ); + + thumb.style.display = + 'none'; + + thumb.removeAttribute( + 'src' + ); + }; + } + + console.log( + 'LOADING SHARED AUDIO:', + { + originalUrl: + url, + + normalizedUrl, + + thumbnail: + normalizedThumbnail, + + mediaType: + normalizedMediaType, + + pageOrigin: + window.location.origin, + + browserSupport: { + mp3: + audio.canPlayType( + 'audio/mpeg' + ), + + m4a: + audio.canPlayType( + 'audio/mp4' + ), + + aac: + audio.canPlayType( + 'audio/aac' + ), + + webmOpus: + audio.canPlayType( + 'audio/webm; ' + + 'codecs="opus"' + ), + + oggOpus: + audio.canPlayType( + 'audio/ogg; ' + + 'codecs="opus"' + ) + } + } + ); + + + audio.onerror = () => { + const mediaError = + audio.error; + + const detail = + Kronick + .getMediaErrorMessage( + mediaError + ); + + console.error( + 'SHARED AUDIO ERROR:', + { + code: + mediaError?.code, + + detail, + + originalUrl: + url, + + normalizedUrl, + + currentSrc: + audio.currentSrc, + + networkState: + audio.networkState, + + readyState: + audio.readyState + } + ); + + error.textContent = + `Audio playback failed: ` + + detail; + + error.style.display = + 'block'; + }; + + audio.onloadstart = () => { + console.log( + 'SHARED AUDIO LOAD STARTED:', + normalizedUrl + ); + }; + + audio.onloadedmetadata = () => { + console.log( + 'SHARED AUDIO METADATA LOADED:', + { + currentSrc: + audio.currentSrc, + + duration: + audio.duration, + + readyState: + audio.readyState, + + networkState: + audio.networkState + } + ); + }; + + audio.oncanplay = () => { + console.log( + 'SHARED AUDIO CAN PLAY:', + audio.currentSrc + ); + }; + + audio.onplaying = () => { + console.log( + 'SHARED AUDIO PLAYING:', + audio.currentSrc + ); + + error.style.display = + 'none'; + + error.textContent = + ''; + }; + + audio.onwaiting = () => { + console.debug( + 'Shared audio is buffering:', + audio.currentSrc + ); + }; + + audio.onstalled = () => { + console.warn( + 'Shared audio request stalled:', + audio.currentSrc + ); + }; + + audio.preload = + 'metadata'; + + audio.controls = + true; + + audio.src = + normalizedUrl; + + audio.volume = + 0.5; + + audio.style.display = + 'block'; + + audio.load(); + + audio.play() + .catch(playError => { + console.error( + 'SHARED AUDIO PLAY REJECTED:', + { + name: + playError.name, + + message: + playError.message, + + src: + audio.currentSrc + } + ); + + if ( + playError.name + === 'NotAllowedError' + ) { + error.textContent = + 'Press Play to start ' + + 'the audio.'; + + error.style.display = + 'block'; + } else if ( + playError.name + === 'NotSupportedError' + ) { + error.textContent = + 'The audio endpoint did ' + + 'not return a supported ' + + 'audio stream.'; + + error.style.display = + 'block'; + } + }); + + return; + } + + + /* + * Video playback. + */ + wrap.classList.remove( + 'audio-mode' + ); + + if (normalizedThumbnail) { + video.poster = + normalizedThumbnail; + } + + console.log( + 'LOADING SHARED VIDEO:', + { + originalUrl: + url, + + normalizedUrl, + + thumbnail: + normalizedThumbnail, + + mediaType: + normalizedMediaType, + + pageOrigin: + window.location.origin, + + browserSupport: { + mp4H264: + video.canPlayType( + 'video/mp4; ' + + 'codecs="avc1.42E01E"' + ), + + mp4: + video.canPlayType( + 'video/mp4' + ), + + webmVp8: + video.canPlayType( + 'video/webm; ' + + 'codecs="vp8, vorbis"' + ), + + webmVp9: + video.canPlayType( + 'video/webm; ' + + 'codecs="vp9, opus"' + ), + + ogg: + video.canPlayType( + 'video/ogg' + ) + } + } + ); + + + video.onerror = () => { + const mediaError = + video.error; + + const detail = + Kronick + .getMediaErrorMessage( + mediaError + ); + + console.error( + 'SHARED VIDEO ERROR:', + { + code: + mediaError?.code, + + detail, + + originalUrl: + url, + + normalizedUrl, + + currentSrc: + video.currentSrc, + + networkState: + video.networkState, + + readyState: + video.readyState, + + videoWidth: + video.videoWidth, + + videoHeight: + video.videoHeight + } + ); + + error.textContent = + `Video playback failed: ` + + detail; + + error.style.display = + 'block'; + }; + + video.onloadstart = () => { + console.log( + 'SHARED VIDEO LOAD STARTED:', + normalizedUrl + ); + }; + + video.onloadedmetadata = () => { + console.log( + 'SHARED VIDEO METADATA LOADED:', + { + currentSrc: + video.currentSrc, + + duration: + video.duration, + + videoWidth: + video.videoWidth, + + videoHeight: + video.videoHeight, + + readyState: + video.readyState, + + networkState: + video.networkState + } + ); + }; + + video.oncanplay = () => { + console.log( + 'SHARED VIDEO CAN PLAY:', + video.currentSrc + ); + }; + + video.onplaying = () => { + console.log( + 'SHARED VIDEO PLAYING:', + video.currentSrc + ); + + error.style.display = + 'none'; + + error.textContent = + ''; + }; + + video.onwaiting = () => { + console.debug( + 'Shared video is buffering:', + video.currentSrc + ); + }; + + video.onstalled = () => { + console.warn( + 'Shared video request stalled:', + video.currentSrc + ); + }; + + video.preload = + 'metadata'; + + video.controls = + true; + + video.playsInline = + true; + + video.src = + normalizedUrl; + + video.volume = + 0.5; + + video.style.display = + 'block'; + + video.load(); + + video.play() + .catch(playError => { + console.error( + 'SHARED VIDEO PLAY REJECTED:', + { + name: + playError.name, + + message: + playError.message, + + src: + video.currentSrc + } + ); + + if ( + playError.name + === 'NotAllowedError' + ) { + error.textContent = + 'Press Play to start ' + + 'the video.'; + + error.style.display = + 'block'; + } else if ( + playError.name + === 'NotSupportedError' + ) { + error.textContent = + 'The video endpoint did ' + + 'not return a supported ' + + 'video stream.'; + + error.style.display = + 'block'; + } + }); +}; + + +/* + * Close the shared media player. + * + * sendStop=false is used when another participant's + * stop message is being handled, preventing a loop. + */ +Kronick.closeSharedMedia = +function closeSharedMedia( + sendStop = false +) { + const wrap = + document.getElementById( + 'sharedMediaWrap' + ); + + const video = + document.getElementById( + 'sharedMediaVideo' + ); + + const audio = + document.getElementById( + 'sharedMediaAudio' + ); + + const thumb = + document.getElementById( + 'sharedMediaThumb' + ); + + const error = + document.getElementById( + 'sharedMediaError' + ); + + if ( + !wrap + || !video + || !audio + || !thumb + || !error + ) { + return; + } + + Kronick.resetMediaElement( + video + ); + + Kronick.resetMediaElement( + audio + ); + + thumb.onerror = null; + + thumb.removeAttribute( + 'src' + ); + + video.style.display = + 'none'; + + audio.style.display = + 'none'; + + thumb.style.display = + 'none'; + + error.style.display = + 'none'; + + error.textContent = + ''; + + wrap.style.display = + 'none'; + + wrap.classList.remove( + 'audio-mode' + ); + + const room = + Kronick.state.room; + + if ( + sendStop + && room?.localParticipant + ) { + const payload = + new TextEncoder().encode( + JSON.stringify({ + type: + 'media-stop' + }) + ); + + room.localParticipant + .publishData( + payload, + { + reliable: + true, + + topic: + Kronick.config + .DATA_TOPIC_MEDIA + } + ) + .catch(err => { + console.warn( + 'Could not publish ' + + 'media stop message:', + err + ); + }); + } +}; + + +/* + * Explicit room-wide stop. + * + * Normal window close is local-only. Call this function only + * from a deliberate "Stop for everyone" control. + */ +Kronick.stopSharedMediaForRoom = +function stopSharedMediaForRoom() { + Kronick.closeSharedMedia( + true + ); +}; + + +/* + * Display a temporary room-wide GIF overlay. + */ +Kronick.showSharedGif = +function showSharedGif(url) { + const gif = + document.getElementById( + 'sharedGif' + ); + + if (!gif) { + return; + } + + const normalizedUrl = + Kronick.normalizePublicMediaUrl( + url + ); + + if (!normalizedUrl) { + console.warn( + 'Cannot display invalid GIF URL:', + url + ); + + return; + } + + /* + * Clear a previous GIF before assigning the + * new source, allowing the same GIF to restart. + */ + gif.removeAttribute( + 'src' + ); + + gif.style.display = + 'none'; + + gif.onload = () => { + gif.style.display = + 'block'; + }; + + gif.onerror = () => { + console.error( + 'Shared GIF failed to load:', + normalizedUrl + ); + + gif.style.display = + 'none'; + + gif.removeAttribute( + 'src' + ); + }; + + gif.src = + normalizedUrl; + + clearTimeout( + Kronick.state + .sharedGifTimeout + ); + + Kronick.state.sharedGifTimeout = + setTimeout( + () => { + gif.style.display = + 'none'; + + gif.removeAttribute( + 'src' + ); + + gif.onload = null; + gif.onerror = null; + }, + 8000 + ); +}; diff --git a/kronic-chat/js/message-router.js b/kronic-chat/js/message-router.js new file mode 100644 index 0000000..dc08bcb --- /dev/null +++ b/kronic-chat/js/message-router.js @@ -0,0 +1,735 @@ +// message-router.js + +window.Kronick = + window.Kronick || {}; + + +/* + * Central message router for the music, Giphy and + * chat iframes. + */ +Kronick.handleWindowMessage = +function handleWindowMessage(event) { + if ( + event.origin + !== Kronick.config.APP_ORIGIN + ) { + console.warn( + 'Rejected cross-origin ' + + 'window message:', + event.origin + ); + + return; + } + + const data = + event.data; + + if ( + !data + || typeof data !== 'object' + ) { + return; + } + + const musicFrame = + document.getElementById( + 'musicFrame' + ); + + const giphyFrame = + document.getElementById( + 'giphyFrame' + ); + + const chatFrame = + document.getElementById( + 'chatFrame' + ); + + const fromMusicFrame = + Boolean( + musicFrame?.contentWindow + && event.source + === musicFrame.contentWindow + ); + + const fromGiphyFrame = + Boolean( + giphyFrame?.contentWindow + && event.source + === giphyFrame.contentWindow + ); + + const fromChatFrame = + Boolean( + chatFrame?.contentWindow + && event.source + === chatFrame.contentWindow + ); + + + switch (data.type) { + case 'KRONICK_CHAT_HISTORY_REQUEST': + if (!fromChatFrame) { + return; + } + + Kronick.sendChatHistoryToFrame(); + + return; + + + case 'KRONICK_CHAT_NEW_MESSAGE': + if (!fromChatFrame) { + return; + } + + Kronick + .handleIncomingChatNotification( + data.message + ); + + return; + + + case 'KRONICK_MUSIC_CLOSE': + if (!fromMusicFrame) { + return; + } + + Kronick.closeMusicBrowser(); + + return; + + + case 'KRONICK_GIPHY_CLOSE': + if (!fromGiphyFrame) { + return; + } + + Kronick.closeGiphyBrowser(); + + return; + + + case 'KRONICK_CHAT_GIF_PICK': + if (!fromChatFrame) { + return; + } + + Kronick.openGiphyBrowser( + 'chat' + ); + + return; + + + case 'KRONICK_GIPHY_SELECTED': + if ( + !fromGiphyFrame + ) { + console.warn( + 'Rejected GIPHY selection: ' + + 'message did not come from ' + + 'the GIPHY frame.' + ); + + return; + } + + { + const gifUrl = + Kronick.getGiphyMessageUrl( + data + ); + + if (!gifUrl) { + console.warn( + 'Rejected GIPHY selection: ' + + 'no usable GIF URL.', + data + ); + + return; + } + + if ( + Kronick.state + .giphyTargetMode + === 'chat' + ) { + chatFrame?.contentWindow + ?.postMessage( + { + type: + 'CHAT_INSERT_AND_SEND_URL', + + url: + gifUrl + }, + Kronick.config + .APP_ORIGIN + ); + + Kronick.state + .giphyTargetMode = + 'room'; + + Kronick.closeGiphyBrowser(); + + return; + } + + if ( + typeof Kronick.sendMediaToRoom + !== 'function' + ) { + console.error( + 'Kronick.sendMediaToRoom ' + + 'is not available.' + ); + + return; + } + + Kronick.sendMediaToRoom({ + mediaType: + 'gif', + + url: + gifUrl, + + title: + data.title || 'GIF' + }); + + Kronick.closeGiphyBrowser(); + + return; + } + + + case 'KRONICK_GIPHY_AVATAR_SET': + if (!fromGiphyFrame) { + console.warn( + 'Rejected GIPHY avatar: ' + + 'message did not come from ' + + 'the GIPHY frame.' + ); + + return; + } + + { + const avatarUrl = + Kronick.getGiphyMessageUrl( + data + ); + + if (!avatarUrl) { + console.warn( + 'Rejected GIPHY avatar: ' + + 'no usable GIF URL.', + data + ); + + return; + } + + console.log( + 'GIPHY AVATAR RECEIVED:', + { + url: + avatarUrl, + + title: + data.title + || data.gif?.title + || '' + } + ); + + Kronick + .setLocalAvatar( + avatarUrl + ) + .catch( + err => { + console.error( + 'Could not set ' + + 'GIPHY avatar:', + err + ); + } + ); + + return; + } + + + case 'KRONICK_MEDIA_SHARE': + if ( + !fromMusicFrame + || typeof data.url + !== 'string' + || !data.url + ) { + console.warn( + 'Rejected media share:', + { + fromMusicFrame, + url: + data.url + } + ); + + return; + } + + console.log( + 'MEDIA SHARE RECEIVED ' + + 'FROM MUSIC BROWSER:', + { + mediaType: + data.mediaType, + + url: + data.url, + + title: + data.title, + + thumbnail: + data.thumbnail + } + ); + + /* + * Do NOT close the music browser here. + * + * Keeping it open lets the user continue + * searching, adding tracks to the queue, + * and selecting additional media while the + * shared player is active. + */ + + if ( + typeof Kronick.sendMediaToRoom + !== 'function' + ) { + console.error( + 'Kronick.sendMediaToRoom ' + + 'is not available. ' + + 'Check media-controller.js ' + + 'for syntax/load errors.' + ); + + return; + } + + /* + * Send the media selection to LiveKit + * and play it locally. + */ + Kronick.sendMediaToRoom( + data + ); + + /* + * Bring the shared media window above + * the other floating tool windows. + */ + requestAnimationFrame( + () => { + const sharedMediaWrap = + document.getElementById( + 'sharedMediaWrap' + ); + + if (!sharedMediaWrap) { + console.warn( + 'sharedMediaWrap ' + + 'was not found.' + ); + + return; + } + + sharedMediaWrap.style.display = + 'flex'; + + if ( + typeof Kronick + .bringToolWindowToFront + === 'function' + ) { + Kronick + .bringToolWindowToFront( + sharedMediaWrap + ); + } + + if ( + typeof Kronick + .keepWindowInViewport + === 'function' + ) { + Kronick + .keepWindowInViewport( + sharedMediaWrap + ); + } + } + ); + + return; + + + case 'KRONICK_CHAT_SEND': + if ( + !fromChatFrame + || !data.payload + || typeof data.payload + !== 'object' + ) { + return; + } + + Kronick.sendChatToRoom( + data.payload + ); + + return; + + + default: + console.warn( + 'Unhandled window message:', + data.type + ); + } +}; + + +/* + * Extract a usable GIF URL from a GIPHY iframe message. + * + * Current giphy.js sends both data.url and data.gif.url. + * Prefer the nested GIF URL first so this remains compatible + * if the outer message structure changes again later. + */ +Kronick.getGiphyMessageUrl = +function getGiphyMessageUrl(data) { + const candidates = [ + data?.gif?.url, + data?.url, + data?.gif?.thumb + ]; + + for ( + const candidate + of candidates + ) { + if ( + typeof candidate + !== 'string' + ) { + continue; + } + + const url = + candidate.trim(); + + if (!url) { + continue; + } + + /* + * The avatar must be an actual image/media URL, + * not a GIPHY landing page. + */ + try { + const parsed = + new URL( + url, + window.location.origin + ); + + if ( + parsed.hostname + === 'giphy.com' + || parsed.hostname + === 'www.giphy.com' + ) { + console.warn( + 'Ignoring GIPHY page URL ' + + 'instead of media URL:', + url + ); + + continue; + } + + return parsed.href; + + } catch ( + error + ) { + console.warn( + 'Ignoring invalid GIPHY URL:', + { + url, + error: + error?.message + || String(error) + } + ); + } + } + + return ''; +}; + + +/* + * Set the selected Giphy image as the local avatar. + * + * This updates: + * 1. the avatar input + * 2. localStorage + * 3. LiveKit participant metadata + * 4. the local participant tile immediately + * + * The GIPHY browser is only closed after the local update + * has been attempted. + */ +Kronick.setLocalAvatar = +async function setLocalAvatar(url) { + if ( + typeof url !== 'string' + || !url.trim() + ) { + throw new Error( + 'Avatar URL is empty.' + ); + } + + const avatarUrl = + url.trim(); + + /* + * Reject a normal giphy.com landing page. Those URLs + * cannot be used directly as an avatar. + */ + try { + const parsed = + new URL( + avatarUrl, + window.location.origin + ); + + if ( + parsed.hostname + === 'giphy.com' + || parsed.hostname + === 'www.giphy.com' + ) { + throw new Error( + 'Received a GIPHY page URL ' + + 'instead of an image URL.' + ); + } + } catch ( + error + ) { + console.error( + 'Invalid avatar URL:', + { + url: + avatarUrl, + + error: + error?.message + || String(error) + } + ); + + throw error; + } + + + const avatarInput = + document.getElementById( + 'avatarUrl' + ); + + if (avatarInput) { + avatarInput.value = + avatarUrl; + + /* + * Notify any code listening to the avatar field. + */ + avatarInput.dispatchEvent( + new Event( + 'input', + { + bubbles: + true + } + ) + ); + + avatarInput.dispatchEvent( + new Event( + 'change', + { + bubbles: + true + } + ) + ); + } + + + localStorage.setItem( + 'lastAvatarUrl', + avatarUrl + ); + + + const room = + Kronick.state?.room; + + const participant = + room?.localParticipant; + + + if (!participant) { + console.log( + 'Avatar saved locally. ' + + 'No active LiveKit participant ' + + 'is connected yet.', + avatarUrl + ); + + Kronick.closeGiphyBrowser(); + + return; + } + + + let metaObj = {}; + + try { + metaObj = + participant.metadata + ? JSON.parse( + participant.metadata + ) + : {}; + + if ( + !metaObj + || typeof metaObj + !== 'object' + || Array.isArray( + metaObj + ) + ) { + metaObj = {}; + } + + } catch ( + error + ) { + console.warn( + 'Could not parse existing ' + + 'participant metadata. ' + + 'Starting with a new object.', + { + metadata: + participant.metadata, + + error: + error?.message + || String(error) + } + ); + + metaObj = {}; + } + + + metaObj.avatar = + avatarUrl; + + const newMetadata = + JSON.stringify( + metaObj + ); + + + console.log( + 'UPDATING LOCAL AVATAR METADATA:', + { + identity: + participant.identity, + + avatar: + avatarUrl, + + metadata: + newMetadata + } + ); + + + /* + * LiveKit publishes the new metadata to the room. + */ + await participant + .setMetadata( + newMetadata + ); + + + console.log( + 'LOCAL AVATAR METADATA UPDATED:', + { + identity: + participant.identity, + + avatar: + avatarUrl, + + metadata: + participant.metadata + } + ); + + + /* + * Do not wait for ParticipantMetadataChanged to redraw + * our own tile. Update it immediately as well. + */ + if ( + typeof Kronick + .updateParticipantAvatar + === 'function' + ) { + Kronick.updateParticipantAvatar( + participant + ); + } else { + console.warn( + 'Kronick.updateParticipantAvatar ' + + 'is not available.' + ); + } + + + Kronick.closeGiphyBrowser(); +};