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();