diff --git a/JS/app-config.js b/JS/app-config.js new file mode 100644 index 0000000..73c5207 --- /dev/null +++ b/JS/app-config.js @@ -0,0 +1,38 @@ +window.Kronick = window.Kronick || {}; + +const installConfig = + window.KRONICK_INSTALL_CONFIG || {}; + +Kronick.config = { + LIVEKIT_URL: + installConfig.LIVEKIT_URL, + + TOKEN_URL: + installConfig.TOKEN_URL || + `${window.location.origin}/get-token`, + + APP_ORIGIN: + window.location.origin, + + DATA_TOPIC_MEDIA: + 'kronick-media', + + MEDIA_ORIGIN: 'https://media.kronickrusaders.ca', + + DATA_TOPIC_CHAT: + 'kronick-chat' +}; + +Kronick.state = { + room: null, + currentRoomName: '', + nextTileX: 0, + nextTileY: 0, + giphyTargetMode: 'room', + highestWindowZIndex: 6000, + + participantStatsIntervals: new Map(), + participantLevels: new Map(), + participantRtts: new Map(), + participantAudioElements: new Map() +}; diff --git a/JS/app-init.js b/JS/app-init.js new file mode 100644 index 0000000..6804ff0 --- /dev/null +++ b/JS/app-init.js @@ -0,0 +1,434 @@ +window.Kronick = + window.Kronick || {}; + + +/* + * Initialize the page after all deferred scripts + * and HTML elements have loaded. + */ +window.addEventListener( + 'DOMContentLoaded', + () => { + /* + * Initialize per-device microphone, suppression and spatial audio controls. + */ + if ( + typeof Kronick.initAudioSettings + === 'function' + ) { + Kronick.initAudioSettings(); + } + + + /* + * Restore saved room, username and avatar + * values, then populate their datalists. + */ + if ( + typeof Kronick.loadSavedJoinInfo + === 'function' + ) { + Kronick.loadSavedJoinInfo(); + } + + if ( + typeof Kronick.populateSavedLists + === 'function' + ) { + Kronick.populateSavedLists(); + } + + + /* + * Display the empty-room placeholder before + * a LiveKit connection is established. + */ + if ( + typeof Kronick.showEmptyRoomMessage + === 'function' + ) { + Kronick.showEmptyRoomMessage(); + } + + + /* + * Initialize the disconnected button states. + */ + if ( + typeof Kronick.setConnectionControls + === 'function' + ) { + Kronick.setConnectionControls( + 'disconnected' + ); + } + + + if (typeof Kronick.initializeWindowManager === 'function') { + Kronick.initializeWindowManager(); + } + + + /* + * Music browser window. + */ + Kronick.initializeDraggableWindow( + 'musicFrameWrap', + 'musicFrameHeader', + 'musicFramePosition' + ); + + + /* + * Giphy browser window. + */ + Kronick.initializeDraggableWindow( + 'giphyFrameWrap', + 'giphyFrameHeader', + 'giphyFramePosition' + ); + + + /* + * Chat window. + */ + Kronick.initializeDraggableWindow( + 'chatFrameWrap', + 'chatFrameHeader', + 'chatFramePosition' + ); + + + /* + * Screen-share window. + */ + Kronick.initializeDraggableWindow( + 'screenShareFrameWrap', + 'screenShareFrameHeader', + 'screenShareFramePosition' + ); + + + /* + * Bring any clicked floating window to the + * front of the other tool windows. + */ + document + .querySelectorAll( + '.tool-frame-wrap, ' + + '.shared-media-wrap' + ) + .forEach(windowElement => { + windowElement.addEventListener( + 'mousedown', + () => { + if ( + typeof Kronick + .bringToolWindowToFront + === 'function' + ) { + Kronick + .bringToolWindowToFront( + windowElement + ); + } + } + ); + }); + + + /* + * Keep floating windows inside the browser + * viewport when the browser is resized. + */ + window.addEventListener( + 'resize', + () => { + if ( + typeof Kronick + .keepVisibleWindowsInViewport + === 'function' + ) { + Kronick + .keepVisibleWindowsInViewport(); + } + } + ); + + + /* + * Update the screen-share button for the + * initial disconnected state. + */ + if ( + typeof Kronick + .updateScreenShareControls + === 'function' + ) { + Kronick + .updateScreenShareControls(); + } + + + console.log( + 'Kronick application initialized.' + ); + } +); + + +/* + * Safely initialize one draggable tool window. + * + * Missing optional windows will be reported but will + * not prevent the rest of the application from loading. + */ +Kronick.initializeDraggableWindow = +function initializeDraggableWindow( + windowId, + headerId, + storageKey +) { + const windowElement = + document.getElementById( + windowId + ); + + const headerElement = + document.getElementById( + headerId + ); + + if ( + !windowElement + || !headerElement + ) { + console.debug( + 'Optional draggable window not found:', + { + windowId, + headerId + } + ); + + return; + } + + if ( + typeof Kronick.makeToolWindowDraggable + !== 'function' + ) { + console.error( + 'makeToolWindowDraggable() ' + + 'is unavailable.' + ); + + return; + } + + Kronick.makeToolWindowDraggable( + windowElement, + headerElement, + storageKey + ); +}; + + +/* + * Receive messages from the chat, Giphy and music + * iframes through the central message router. + */ +window.addEventListener( + 'message', + event => { + if ( + typeof Kronick.handleWindowMessage + !== 'function' + ) { + console.error( + 'Window message router ' + + 'is unavailable.' + ); + + return; + } + + Kronick.handleWindowMessage( + event + ); + } +); + + +/* + * Compatibility exports. + * + * These allow existing inline HTML handlers such as + * onclick="connect()" to continue working while the + * implementations remain organized under Kronick. + */ + + +/* + * LiveKit connection controls. + */ +window.connect = +function connect() { + return Kronick.connect(); +}; + +window.disconnect = +function disconnect() { + return Kronick.disconnect(); +}; + +window.toggleMute = +function toggleMute() { + return Kronick.toggleMute(); +}; + + +/* + * Music browser controls. + */ +window.openMusicBrowser = +function openMusicBrowser() { + return Kronick.openMusicBrowser(); +}; + +window.closeMusicBrowser = +function closeMusicBrowser() { + return Kronick.closeMusicBrowser(); +}; + + +/* + * Giphy browser controls. + */ +window.openGiphyBrowser = +function openGiphyBrowser( + targetMode = 'room' +) { + return Kronick.openGiphyBrowser( + targetMode + ); +}; + +window.closeGiphyBrowser = +function closeGiphyBrowser() { + return Kronick.closeGiphyBrowser(); +}; + + +/* + * Chat controls. + */ +window.openChatWindow = +function openChatWindow() { + return Kronick.openChatWindow(); +}; + +window.closeChatWindow = +function closeChatWindow() { + return Kronick.closeChatWindow(); +}; + + +/* + * Shared media controls. + */ +window.closeSharedMedia = +function closeSharedMedia( + sendStop = true +) { + return Kronick.closeSharedMedia( + sendStop + ); +}; + + +/* + * Participant controls. + */ +window.setParticipantVolume = +function setParticipantVolume( + sid, + participantKey, + value +) { + return Kronick.setParticipantVolume( + sid, + participantKey, + value + ); +}; + + +/* + * Screen-share controls. + */ +window.toggleScreenShare = +function toggleScreenShare() { + return Kronick.toggleScreenShare(); +}; + +window.stopScreenShare = +function stopScreenShare() { + return Kronick.stopScreenShare(); +}; + +window.openScreenShareWindow = +function openScreenShareWindow() { + return Kronick.openScreenShareWindow(); +}; + +window.closeScreenShareWindow = +function closeScreenShareWindow() { + return Kronick.closeScreenShareWindow(); +}; + +/* + * Mobile layout uses the existing connection/audio sidebar as a drawer. + * Desktop behavior is unchanged. + */ +Kronick.isMobileLayout = function isMobileLayout() { + return window.matchMedia('(max-width: 760px)').matches; +}; + +Kronick.setMobileSidebarOpen = function setMobileSidebarOpen(open) { + if (!Kronick.isMobileLayout()) { + open = false; + } + + document.body.classList.toggle('mobile-sidebar-open', Boolean(open)); + + const button = document.getElementById('mobileAudioMenuBtn'); + if (button) { + button.setAttribute('aria-expanded', open ? 'true' : 'false'); + button.title = open + ? 'Close connection and audio settings' + : 'Open connection and audio settings'; + } +}; + +Kronick.toggleMobileSidebar = function toggleMobileSidebar() { + Kronick.setMobileSidebarOpen( + !document.body.classList.contains('mobile-sidebar-open') + ); +}; + +Kronick.closeMobileSidebar = function closeMobileSidebar() { + Kronick.setMobileSidebarOpen(false); +}; + +window.addEventListener('keydown', event => { + if (event.key === 'Escape' && document.body.classList.contains('mobile-sidebar-open')) { + Kronick.closeMobileSidebar(); + } +}); + +window.addEventListener('resize', () => { + if (!Kronick.isMobileLayout()) { + Kronick.closeMobileSidebar(); + } +}); diff --git a/JS/media-controller.js b/JS/media-controller.js new file mode 100644 index 0000000..1ff6f91 --- /dev/null +++ b/JS/media-controller.js @@ -0,0 +1,124 @@ +// Kronic Media bridge: playback is owned by media.kronickrusaders.ca. +// Chat only broadcasts room events and hosts the external media window. +window.Kronick = window.Kronick || {}; + +Kronick.normalizePublicMediaUrl = function(raw) { + if (typeof raw !== 'string' || raw.length > 4096) return ''; + try { + const url = new URL(raw, Kronick.config.MEDIA_ORIGIN); + return ['https:', 'http:'].includes(url.protocol) ? url.href : ''; + } catch { return ''; } +}; + +Kronick.notifyMediaFrame = function(message) { + const frame = document.getElementById('musicFrame'); + if (!frame?.contentWindow) return; + frame.contentWindow.postMessage(message || { + type: 'KRONICK_CHAT_CONTEXT', + room: Kronick.state.currentRoomName || '', + connected: Boolean(Kronick.state.room?.localParticipant), + user: Kronick.account?.user?.username || '' + }, Kronick.config.MEDIA_ORIGIN); +}; + +// Set when a shared item arrives before the external iframe is ready. +Kronick.pendingMediaShare = null; +Kronick.flushMediaShare = function() { + if (!Kronick.pendingMediaShare) return; + Kronick.notifyMediaFrame({ + type: 'KRONICK_ROOM_MEDIA_OPEN', + room: Kronick.state.currentRoomName || '', + media: Kronick.pendingMediaShare + }); +}; + +Kronick.sendMediaToRoom = async function(data) { + const room = Kronick.state.room; + if (!room?.localParticipant) { + alert('Join a Kronic chat room before sharing media.'); + return; + } + // The media app should send a canonical item URL (or a media ID in a future API). + const url = Kronick.normalizePublicMediaUrl(data?.url); + if (!url) { + console.warn('Media share requires a valid URL.', data); + return; + } + const mediaType = String(data.mediaType || 'video').slice(0, 24); + const message = { + type: 'media', + mediaType, url, + title: String(data.title || '').slice(0, 300), + thumbnail: Kronick.normalizePublicMediaUrl(data.thumbnail || '') + }; + try { + await room.localParticipant.publishData( + new TextEncoder().encode(JSON.stringify(message)), + {reliable: true, topic: Kronick.config.DATA_TOPIC_MEDIA} + ); + Kronick.handleRoomMedia(message); + } catch(error) { + console.error('Failed to share media to room:', error); + } +}; + +Kronick.handleRoomMedia = function(message) { + if (!message || typeof message !== 'object') return; + if (message.type === 'media-stop') { + Kronick.pendingMediaShare = null; + Kronick.notifyMediaFrame({type: 'KRONICK_ROOM_MEDIA_STOP'}); + return; + } + if (message.type !== 'media') return; + const url = Kronick.normalizePublicMediaUrl(message.url); + if (!url) return; + if (String(message.mediaType).toLowerCase() === 'gif') { + Kronick.showSharedGif(url); + return; + } + Kronick.pendingMediaShare = { + url, + mediaType: String(message.mediaType || 'video').slice(0, 24), + title: String(message.title || '').slice(0, 300), + thumbnail: Kronick.normalizePublicMediaUrl(message.thumbnail || '') + }; + Kronick.openMusicBrowser(); + Kronick.flushMediaShare(); +}; + +// A local close should not end playback for other room members. +Kronick.closeSharedMedia = function(sendStop = false) { + Kronick.closeMusicBrowser(); + if (!sendStop) return; + const room = Kronick.state.room; + if (!room?.localParticipant) return; + room.localParticipant.publishData( + new TextEncoder().encode(JSON.stringify({type: 'media-stop'})), + {reliable: true, topic: Kronick.config.DATA_TOPIC_MEDIA} + ).catch(console.error); +}; +Kronick.stopSharedMediaForRoom = function() { + Kronick.closeSharedMedia(true); +}; + +Kronick.showSharedGif = function(url) { + const gif = document.getElementById('sharedGif'); + if (!gif) return; + gif.style.display = 'none'; + gif.onload = () => { gif.style.display = 'block'; }; + gif.onerror = () => { gif.style.display = 'none'; }; + gif.src = url; + clearTimeout(Kronick.state.sharedGifTimeout); + Kronick.state.sharedGifTimeout = setTimeout(() => { + gif.style.display = 'none'; + gif.removeAttribute('src'); + }, 8000); +}; + +window.addEventListener('DOMContentLoaded', () => { + const frame = document.getElementById('musicFrame'); + frame?.addEventListener('load', () => { + Kronick.notifyMediaFrame(); + Kronick.flushMediaShare(); + }); +}); diff --git a/JS/message-router.js b/JS/message-router.js new file mode 100644 index 0000000..98e632d --- /dev/null +++ b/JS/message-router.js @@ -0,0 +1,625 @@ +// message-router.js + +window.Kronick = + window.Kronick || {}; + + +/* + * Central message router for the music, Giphy and + * chat iframes. + */ +Kronick.handleWindowMessage = +function handleWindowMessage(event) { + const fromKronicMedia = event.origin === 'https://media.kronickrusaders.ca'; + if (event.origin !== Kronick.config.APP_ORIGIN && !fromKronicMedia) { + 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( + fromKronicMedia && musicFrame?.contentWindow && + event.source === musicFrame.contentWindow + ); + + const fromGiphyFrame = + Boolean( + giphyFrame?.contentWindow + && event.source + === giphyFrame.contentWindow + ); + + const fromChatFrame = + Boolean( + chatFrame?.contentWindow + && event.source + === chatFrame.contentWindow + ); + + + // Never accept cross-origin messages from anything except our media iframe. + if (fromKronicMedia && !fromMusicFrame) return; + if (fromKronicMedia && !['KRONICK_MEDIA_READY', 'KRONICK_MEDIA_SHARE', 'KRONICK_MUSIC_CLOSE'].includes(data.type)) return; + + switch (data.type) { + case 'KRONICK_MEDIA_READY': + if (fromMusicFrame) Kronick.notifyMediaFrame(); + return; + 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) return; + Kronick.sendMediaToRoom(data); + 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(); +}; diff --git a/JS/room_sync.js b/JS/room_sync.js new file mode 100644 index 0000000..b738b5d --- /dev/null +++ b/JS/room_sync.js @@ -0,0 +1,258 @@ +/* Kronic Media <-> embedded Kronic Chat <-> LiveKit room playback. + * Only references to media are synchronized; streams remain local to Media. + */ +(() => { + 'use strict'; + const FRAME_ID = 'borgChatFrame'; + const PREFIX = 'KRONIC_ROOM_SYNC'; + // Per-browser preference; do not publish switch state to LiveKit. + const SHARE_SETTING = 'kronic.room.mediaShareEnabled'; + const shareInput = document.getElementById('borgMediaShareToggle'); + const shareStatus = document.getElementById('borgMediaShareStatus'); + let shareEnabled = true; // Preserve existing sharing behavior on first visit. + try { shareEnabled = localStorage.getItem(SHARE_SETTING) !== 'false'; } + catch (error) { console.debug('[Kronic room sync] Share preference not persisted', error); } + function updateShareControl() { + if (shareInput) shareInput.checked = shareEnabled; + if (shareStatus) shareStatus.textContent = shareEnabled ? 'On' : 'Off'; + if (shareInput) shareInput.closest('.borg-media-share-toggle')?.classList.toggle('is-off', !shareEnabled); + } + updateShareControl(); + shareInput?.addEventListener('change', () => { + shareEnabled = shareInput.checked; + updateShareControl(); + try { localStorage.setItem(SHARE_SETTING, String(shareEnabled)); } + catch (error) { console.debug('[Kronic room sync] Share preference not persisted', error); } + }); + let remoteDepth = 0; + let localOpening = 0; + let suppressUntil = 0; + let lastActionKey = ''; + let lastActionAt = 0; + // Stable room identifiers; per-user database IDs cannot be shared between accounts. + function stableIptvId(channel) { + const text=String(channel?.tvg_id || channel?.name || '').trim().toLowerCase(); + let h=2166136261; + for(const char of text){h^=char.charCodeAt(0);h=Math.imul(h,16777619);} + return 'iptv'+(h>>>0).toString(16); + } + const sameMedia = (a, b) => a && b && a.kind === b.kind && String(a.id) === String(b.id); + let active = null; + let incomingQueue = Promise.resolve(); + + function inRemote() { return remoteDepth > 0 || Date.now() < suppressUntil; } + function position(kind) { + if (kind === 'iptv') return 0; + if (kind === 'library') return typeof getAbsolutePlaybackPosition === 'function' ? getAbsolutePlaybackPosition() : 0; + if (kind === 'youtube') return typeof getYouTubeAbsolutePosition === 'function' ? getYouTubeAbsolutePosition() : 0; + if (kind === 'twitch') return Number(twitchVideoElement?.currentTime) || 0; + if (kind === 'music') return Number(musicPlayer?.audio?.currentTime) || 0; + return 0; + } + function current(kind) { + if (kind === 'iptv' && activeIptvChannel?.id) return {kind, id:stableIptvId(activeIptvChannel), title:String(activeIptvChannel.name||'Live TV'), tvg_id:String(activeIptvChannel.tvg_id||'')}; + if (kind === 'library' && activeMediaId) return {kind, id:Number(activeMediaId), title:String(activeMediaTitle||'Media')}; + if (kind === 'youtube' && youtubeActiveItem?.id) { + const item = youtubeActiveItem; + return {kind, id:String(item.id), title:String(item.title||'Tube'), artist:String(item.artist||''), thumbnail:String(item.thumbnail||''), duration:Number(item.duration)||null, live:Boolean(item.is_live)}; + } + if (kind === 'twitch' && twitchActiveChannel?.id) return {kind, id:String(twitchActiveChannel.channel_name||'').trim().toLowerCase(), title:String(twitchActiveChannel.title||twitchActiveChannel.channel_name||'Twitch'), channel_name:String(twitchActiveChannel.channel_name||'')}; + if (kind === 'music' && musicPlayer?.root?.classList.contains('active') && musicQueue[musicQueueIndex]) { + const track=musicQueue[musicQueueIndex]; + return {kind, id:Number(track.id), title:String(track.title||'Music'),artist:String(track.artist||''),album:String(track.album||''),cover_url:String(track.cover_url||'')}; + } + return null; + } + function emit(action, detail, throttle = false) { + // Off means this browser plays locally, without sending open/play/pause/seek to peers. + // Receiving other participants' room events remains allowed. + if (!shareEnabled || inRemote() || localOpening || !detail) return; + const frame = document.getElementById(FRAME_ID)?.contentWindow; + if (!frame) return; + const payload = {...detail, action, position: action === 'open' && ['youtube','twitch','iptv','music'].includes(detail.kind) ? 0 : Math.max(0, Number(position(detail.kind))||0), v:1}; + const key = `${action}:${detail.kind}:${detail.id}:${Math.round(payload.position)}`; + if (throttle && key === lastActionKey && Date.now() - lastActionAt < 350) return; + lastActionKey = key; lastActionAt = Date.now(); + frame.postMessage({type:PREFIX+'_OUTGOING',payload}, location.origin); + } + function activeVideo(kind) { + if (kind === 'library' || kind === 'iptv') return mediaPlayer; + if (kind === 'youtube') return youtubeVideoElement; + if (kind === 'twitch') return twitchVideoElement; + if (kind === 'music') return musicPlayer?.audio; + return null; + } + async function withRemote(work) { + remoteDepth++; + try { await work(); } + finally { remoteDepth--; suppressUntil = Date.now() + 1500; } + } + async function applySeek(kind, seconds, playAfter = false) { + const target = Math.max(0, Number(seconds)||0); + const video = activeVideo(kind); + if (!video) return; + if (kind === 'iptv' || kind === 'twitch') return; + if (kind === 'library' && playbackSeekMode === 'server') await beginPlayback(target); + else if (kind === 'youtube' && youtubeSeekMode === 'server' && youtubeActiveItem) { + await openYouTubePlayer({...youtubeActiveItem},{cast:true,startPosition:target}); + } else { + try { video.currentTime = target; } catch (e) { console.debug('[Kronic room sync] Seek deferred',e); } + } + if (playAfter) video.play().catch(error => console.debug('[Kronic room sync] Playback deferred',error)); + else video.pause(); + } + async function resolveChannel(kind, payload) { + const data=await api(kind === 'twitch' ? '/api/twitch/overview' : '/api/iptv/overview'); + const channels=Array.isArray(data?.channels) ? data.channels : []; + // IDs may belong to different account databases. Never trust a remote numeric ID. + const name=String(payload.channel_name || payload.title || '').trim().toLowerCase(); + const tvg=String(payload.tvg_id || '').trim().toLowerCase(); + const matches=channels.filter(c => { + if (kind === 'twitch') return String(c.channel_name||'').trim().toLowerCase() === (name || String(payload.title||'').toLowerCase()); + return (tvg && String(c.tvg_id||'').trim().toLowerCase()===tvg) || + String(c.name||'').trim().toLowerCase()===name; + }); + if (!matches.length) { + console.warn(`[Kronic room sync] ${kind} not accessible to receiving user`, {name,tvg}); + return null; + } + if (matches.length > 1) console.warn(`[Kronic room sync] Ambiguous ${kind} channel`,name); + return matches[0]; + } + async function receive(payload) { + if (!payload || payload.v !== 1 || !['library','youtube','twitch','music','iptv'].includes(payload.kind) || !['open','play','pause','seek'].includes(payload.action)) return; + const id = ['library','music'].includes(payload.kind) ? Number(payload.id) : String(payload.id||''); + if (!id || (['library','music'].includes(payload.kind) && !Number.isSafeInteger(id))) return; + const item = {kind:payload.kind,id,title:String(payload.title||'Shared media').slice(0,240)}; + try { + await withRemote(async () => { + if (payload.action === 'open' || !sameMedia(active,item)) { + // Remote watchers never receive the local user's progress/resume dialog. + if (payload.kind === 'library') { + if (youtubeActiveItem) await closeYouTubePlayer(false); + if (twitchActiveChannel) closeTwitchPlayer(); + // openPlayer may prompt for local progress, so replace that logic on the receiving side. + await openPlayer(id,item.title,{roomSync:true,startPosition:Number(payload.position)||0}); + } else if (payload.kind === 'youtube') { + if (activeMediaId) await closePlayer(); + if (twitchActiveChannel) closeTwitchPlayer(); + await openYouTubePlayer({id:String(id),title:item.title,artist:String(payload.artist||''),thumbnail:String(payload.thumbnail||''),duration:Number(payload.duration)||null,is_live:!!payload.live},{cast:true,startPosition:Number(payload.position)||0}); + } else if (payload.kind === 'iptv') { + const channel=await resolveChannel('iptv',payload); + if (!channel) return; + await openIptvChannel(channel); + } else if (payload.kind === 'music') { + // Same authenticated Media service exposes the track by ID to both users. + const track={id:Number(id),title:item.title,artist:String(payload.artist||''),album:String(payload.album||''),cover_url:String(payload.cover_url||'')}; + await playMusicTrack(track,[track],0); + const audio=musicPlayer?.audio; + if (audio && Number(payload.position)>0) { + const seek=()=>{try{audio.currentTime=Number(payload.position)||0;}catch{}}; + if (audio.readyState>=1) seek(); else audio.addEventListener('loadedmetadata',seek,{once:true}); + } + } else { + if (activeMediaId) await closePlayer(); + if (youtubeActiveItem) await closeYouTubePlayer(false); + const slug=String(payload.channel_name||id).trim().toLowerCase(); + if (!/^[a-z0-9_]{1,25}$/.test(slug)) throw new Error('Invalid shared Twitch channel'); + await openTwitchPlayer({id:slug,channel_name:slug,title:item.title,roomSyncLive:true}); + } + active = item; + if (payload.action === 'pause') activeVideo(item.kind)?.pause(); + return; + } + if (payload.action === 'seek') await applySeek(item.kind,payload.position,!!payload.playing); + else if (payload.action === 'pause') { + const video = activeVideo(item.kind); + if (Math.abs(position(item.kind)-(Number(payload.position)||0)) > 2) await applySeek(item.kind,payload.position,false); + else video?.pause(); + } else if (payload.action === 'play') { + const video = activeVideo(item.kind); + if (Math.abs(position(item.kind)-(Number(payload.position)||0)) > 3) await applySeek(item.kind,payload.position,true); + else video?.play()?.catch(error => console.debug('[Kronic room sync] Autoplay deferred',error)); + } + }); + } catch (error) { console.error('[Kronic room sync] Could not apply remote media event',error,payload); } + } + + // Only accept sync messages from the actual Chat iframe on our origin. + window.addEventListener('message',event=>{ + if (event.origin !== location.origin || event.source !== document.getElementById(FRAME_ID)?.contentWindow) return; + if (event.data?.type === PREFIX+'_INCOMING') { + const payload = event.data.payload; + incomingQueue = incomingQueue.then(() => receive(payload)).catch(error => console.error('[Kronic room sync] Queue error', error)); + } + if (event.data?.type === PREFIX+'_STATUS' && !event.data.connected) console.info('[Kronic room sync] Join voice to share media with the room'); + }); + + // Wrap the existing player entrypoints: do not replace Kronic Media's playback logic. + const originalOpenLibrary = openPlayer; + openPlayer = async function(id,title,options={}) { + // The native player accepts room-sync options to bypass per-user resume prompts. + localOpening++; + try { await originalOpenLibrary(id,title,options); } + finally { localOpening--; } + active = current('library'); + if (!options.roomSync) emit('open',active); + }; + const originalOpenYouTube = openYouTubePlayer; + openYouTubePlayer = async function(item,options={}) { + // Announce the new selection immediately; do not wait for YouTube metadata, + // progress requests, or buffering. Receiver begins resolving concurrently. + if (!options.cast && item?.id) emit('open', { + kind:'youtube',id:String(item.id),title:String(item.title||'Tube'), + artist:String(item.artist||''),thumbnail:String(item.thumbnail||''), + duration:Number(item.duration)||null,live:Boolean(item.is_live) + }); + localOpening++; + try { await originalOpenYouTube(item,options); } + finally { localOpening--; } + active = current('youtube'); + }; + const originalOpenTwitch = openTwitchPlayer; + openTwitchPlayer = async function(item) { + localOpening++; + try { await originalOpenTwitch(item); } + finally { localOpening--; } + active = current('twitch'); + emit('open',active); + }; + const originalPlayMusicTrack=playMusicTrack; + playMusicTrack=function(track,queue=null,index=null){ + // This player's native function is async but doesn't await loading media. + // Send the OPEN before browser autoplay promises can delay another client's event. + if (!inRemote() && !localOpening && track?.id) { + emit('open',{kind:'music',id:Number(track.id),title:String(track.title||'Music'), + artist:String(track.artist||''),album:String(track.album||''),cover_url:String(track.cover_url||'')}); + } + const result=originalPlayMusicTrack(track,queue,index); + active={kind:'music',id:Number(track.id),title:String(track.title||'Music')}; + return result; + }; + const originalOpenIptv=openIptvChannel; + openIptvChannel=async function(channel){ + if (!inRemote() && !localOpening && channel?.id) { + emit('open',{kind:'iptv',id:stableIptvId(channel),title:String(channel.name||'Live TV'), + channel_name:String(channel.name||''),tvg_id:String(channel.tvg_id||'')}); + } + localOpening++; + try { await originalOpenIptv(channel); } + finally { localOpening--; } + active=current('iptv'); + }; + + + // Use capturing listeners because native players are sometimes dynamically recreated. + document.addEventListener('play',event=>{ + const kind = event.target?.id === 'mediaPlayerFrame' ? (activeIptvChannel ? 'iptv' : 'library') : event.target?.id === 'youtubeVideoElement' ? 'youtube' : event.target?.id === 'twitchVideoElement' ? 'twitch' : event.target?.id === 'musicAudio' ? 'music' : null; + if (kind) emit('play',current(kind),true); + },true); + document.addEventListener('pause',event=>{ + const kind = event.target?.id === 'mediaPlayerFrame' ? (activeIptvChannel ? 'iptv' : 'library') : event.target?.id === 'youtubeVideoElement' ? 'youtube' : event.target?.id === 'twitchVideoElement' ? 'twitch' : event.target?.id === 'musicAudio' ? 'music' : null; + if (kind) emit('pause',current(kind),true); + },true); + document.addEventListener('seeked',event=>{ + const kind = event.target?.id === 'mediaPlayerFrame' ? (activeIptvChannel ? 'iptv' : 'library') : event.target?.id === 'youtubeVideoElement' ? 'youtube' : event.target?.id === 'twitchVideoElement' ? 'twitch' : event.target?.id === 'musicAudio' ? 'music' : null; + if (kind) emit('seek',{...current(kind),playing:!event.target.paused},true); + },true); +})();