Files
Kronic-Krusaders/JS/borg_shell.js
T
2026-11-25 20:21:57 -06:00

443 lines
23 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Borg stage 2.1: route sidebar through existing Kronic Media functions. */
(() => {
const wrap = document.getElementById('borgWindowWrap');
const header = document.getElementById('borgWindowHeader');
const title = document.getElementById('borgWindowTitle');
if (!wrap || !header || !title) return;
let pos = null;
let currentSection = 'room';
let previousSection = 'libraries';
let navigationBusy = false;
// This is presentation only. The server independently enforces media permissions
// on authenticated API requests and playback routes.
const libraryKind = {movies:'movies',shows:'tv',music:'music',iptv:'iptv',youtube:'tube',twitch:'twitch'};
let permittedLibraries = null;
function applyLibraryVisibility() {
const allowed = permittedLibraries;
if (!allowed) return;
document.querySelectorAll('[data-borg]').forEach(button => {
const kind = button.dataset.borg;
const key = libraryKind[kind];
const isAllowed = !key || allowed[key] !== false;
if (key) { button.hidden = !isAllowed; button.style.display = isAllowed ? '' : 'none'; }
else if (kind === 'libraries') {
const someAllowed = Object.values(libraryKind).some(k => allowed[k] !== false);
button.hidden = !someAllowed;
button.style.display = someAllowed ? '' : 'none';
}
});
// A category revoked while the page was open must not stay visible.
if (libraryKind[currentSection] && allowed[libraryKind[currentSection]] === false) {
currentSection='room';
mark('room');
close();
}
}
async function refreshLibraryPermissions() {
try {
const response = await fetch('/api/auth/media-context', {credentials:'same-origin',cache:'no-store',headers:{'X-Kronic-Room':document.body.dataset.roomId}});
if (!response.ok) throw new Error('Media permissions unavailable ('+response.status+')');
const context = await response.json();
permittedLibraries = context.allowedLibraries || null;
applyLibraryVisibility();
} catch(error) {
console.warn('[Kronic] Permission check failed:',error);
// Fail closed in navigation until the session/permissions can be verified.
permittedLibraries = Object.fromEntries(Object.values(libraryKind).map(k=>[k,false]));
applyLibraryVisibility();
}
}
window.addEventListener('focus', refreshLibraryPermissions);
window.addEventListener('pageshow', refreshLibraryPermissions);
window.addEventListener('kronic:permissions-changed', refreshLibraryPermissions);
refreshLibraryPermissions();
const room = document.querySelector('.borg-room-background');
const chatFrame = document.getElementById('borgChatFrame');
// Resize only the room's horizontal width; keep the room-height and bottom controls stable.
if (room && !room.querySelector('.borg-room-resize-grip')) {
const grip = document.createElement('div');
grip.className = 'borg-room-resize-grip';
grip.setAttribute('role', 'separator');
grip.setAttribute('aria-label', 'Resize Chat panel');
grip.setAttribute('aria-orientation', 'vertical');
grip.tabIndex = 0;
room.append(grip);
let dragging = false, startX = 0, startWidth = 0;
const limit = width => Math.max(Math.min(340, room.parentElement.clientWidth),
Math.min(room.parentElement.clientWidth - 10, width));
grip.addEventListener('pointerdown', e => {
if (!document.body.classList.contains('borg-split-layout')) return;
dragging = true; startX = e.clientX; startWidth = room.getBoundingClientRect().width;
grip.setPointerCapture(e.pointerId); e.preventDefault();
});
grip.addEventListener('pointermove', e => {
if (!dragging) return;
room.style.setProperty('--borg-chat-width', `${limit(startWidth + e.clientX - startX)}px`);
});
const stop = () => { dragging = false; };
grip.addEventListener('pointerup', stop);
grip.addEventListener('pointercancel', stop);
grip.addEventListener('keydown', e => {
if (!['ArrowLeft','ArrowRight'].includes(e.key)) return;
if (!document.body.classList.contains('borg-split-layout')) return;
room.style.setProperty('--borg-chat-width', `${limit(room.getBoundingClientRect().width + (e.key === 'ArrowRight' ? 28 : -28))}px`);
e.preventDefault();
});
}
// Compact mobile bottom dock: keep the existing voice-setting handlers intact.
const mobileAudioToggle = document.getElementById('borgMobileAudioToggle');
const closeMobileAudio = () => {
document.body.classList.remove('borg-mobile-audio-open');
mobileAudioToggle?.setAttribute('aria-expanded','false');
};
mobileAudioToggle?.addEventListener('click', () => {
const opening = !document.body.classList.contains('borg-mobile-audio-open');
document.body.classList.toggle('borg-mobile-audio-open', opening);
mobileAudioToggle.setAttribute('aria-expanded',String(opening));
});
document.addEventListener('keydown', e => {
if(e.key==='Escape') {closeMobileAudio();document.body.classList.remove('borg-mobile-navigation-open');document.getElementById('borgMobileNavigation')?.setAttribute('aria-expanded','false');}
});
window.addEventListener('resize', () => {
if(window.innerWidth>700) closeMobileAudio();
});
const mobileNavButton=document.getElementById('borgMobileNavigation');
const mobileRail=document.querySelector('.borg-rail');
const mobileMediaQuick=document.getElementById('borgMobileMediaQuick');
// Close the drawer after a destination is selected; keep all library navigation
// routed through the existing navigate() function below.
// The mobile drawer is the access point for all media libraries and account actions.
// Use the existing authenticated Account dropdown and Logout endpoint; never duplicate auth.
const mobileAccount=document.getElementById('borgMobileAccount');
const mobileLogout=document.getElementById('borgMobileLogout');
const closeMobileNavigation=()=>{
document.body.classList.remove('borg-mobile-navigation-open');
mobileNavButton?.setAttribute('aria-expanded','false');
};
mobileAccount?.addEventListener('click',()=>{
closeMobileNavigation();
const account=document.querySelector('#mediaAccountNav details');
if(account) account.open=true;
else window.location.assign('/login');
});
mobileLogout?.addEventListener('click',async()=>{
closeMobileNavigation();
mobileLogout.disabled=true;
try {
const res=await fetch('/api/auth/logout',{method:'POST',credentials:'same-origin'});
if(!res.ok) throw new Error('Logout failed ('+res.status+')');
window.location.assign('/login');
} catch(err) {
console.error('[Kronic] Logout failed',err);
mobileLogout.disabled=false;
alert('Could not log out. Please try again.');
}
});
mobileNavButton?.addEventListener('click',()=>{
const open=document.body.classList.toggle('borg-mobile-navigation-open');
mobileNavButton.setAttribute('aria-expanded',String(open));
});
mobileRail?.addEventListener('click',event=>{
if(event.target.closest('[data-borg]')) {
document.body.classList.remove('borg-mobile-navigation-open');
mobileNavButton?.setAttribute('aria-expanded','false');
}
});
const navigateTrail = [];
let currentRoot = 'libraries';
const pushRoomCommand = action => chatFrame?.contentWindow?.postMessage({type:'KRONIC_ROOM_UI',action}, location.origin);
document.querySelectorAll('[data-audio-panel]').forEach(button => {
button.addEventListener('click', () => {
const active = button.getAttribute('aria-expanded') === 'true';
document.querySelectorAll('[data-audio-panel]').forEach(other => {
other.setAttribute('aria-expanded', String(!active && other === button));
});
pushRoomCommand(active ? 'close-audio' : `open-audio-${button.dataset.audioPanel}`);
});
});
document.addEventListener('pointerdown', event => {
if(event.target.closest('.borg-audio-group')) return;
if(event.target.closest('.borg-room-quick-actions')) return;
if(event.target.closest('.borg-call-strip')) {
document.querySelectorAll('[data-audio-panel]').forEach(button => button.setAttribute('aria-expanded','false'));
pushRoomCommand('close-audio');
}
});
document.getElementById('borgRoomMute')?.addEventListener('click',()=>pushRoomCommand('mute'));
document.getElementById('borgRoomLeave')?.addEventListener('click',()=>pushRoomCommand('leave'));
window.addEventListener('message',event=>{
if(event.origin!==location.origin || event.source!==chatFrame?.contentWindow) return;
if(event.data?.type==='KRONIC_ROOM_UI_PANEL' && event.data.action==='closed') {
document.querySelectorAll('[data-audio-panel]').forEach(button => button.setAttribute('aria-expanded','false'));
}
if(event.data?.type==='KRONIC_ROOM_UI_STATUS') {
const state=document.getElementById('borgRoomVoiceState');
if(state) state.textContent=event.data.label || 'Voice controls';
}
});
// Keep the media window beside the room (never over the chat top-bar icons).
const sizeShare = {small:0.35, wide:0.65};
const desktop = () => window.matchMedia('(min-width:901px)').matches;
const layoutWindow = () => {
if (!wrap || !room || wrap.hidden) return;
const free = !wrap.classList.contains('borg-max') && !wrap.dataset.moved
&& document.body.classList.contains('borg-split-layout') && desktop();
if (!free) {
['left','right','width','height'].forEach(k => { if (!wrap.dataset.moved && !wrap.classList.contains('borg-max')) wrap.style.removeProperty(k); });
return;
}
const r = room.getBoundingClientRect();
const left = Math.round(r.right + 8);
wrap.style.left = left + 'px';
wrap.style.right = '8px';
wrap.style.width = Math.max(320, window.innerWidth - left - 8) + 'px';
wrap.style.top = Math.round(Math.max(r.top, 0)) + 'px';
wrap.style.height = Math.max(240, window.innerHeight - Math.round(Math.max(r.top, 0)) - 8) + 'px';
};
const setRoomShare = () => {
const parent = room && room.parentElement;
if (!parent || !desktop()) return;
const windowShare = sizeShare[wrap.dataset.size] || 0.5;
room.style.setProperty('--borg-chat-width', Math.round(parent.clientWidth * (1 - windowShare)) + 'px');
};
if (window.ResizeObserver && room) new ResizeObserver(() => layoutWindow()).observe(room);
window.addEventListener('resize', () => { if (!wrap.dataset.size) setRoomShare(); layoutWindow(); });
const setSplit = active => {
const wasSplit = document.body.classList.contains('borg-split-layout');
document.body.classList.toggle('borg-split-layout',active);
if (!active && room) room.style.removeProperty('--borg-chat-width');
if (active && room && !wasSplit) setRoomShare();
if (active && wrap && !wrap.classList.contains('borg-max') && !wrap.dataset.moved) {
wrap.style.left='';wrap.style.top='';
}
requestAnimationFrame(layoutWindow);
};
document.querySelectorAll('[data-borg-size]').forEach(button=>button.addEventListener('click',()=>{
wrap.classList.remove('borg-max');
wrap.dataset.size=button.dataset.borgSize;
wrap.style.width='';wrap.style.height='';wrap.style.left='';wrap.style.top='';
delete wrap.dataset.moved;
setSplit(true);
setRoomShare();
requestAnimationFrame(layoutWindow);
}));
const labels = {libraries:'Libraries',movies:'Movies',shows:'TV Shows',music:'Music',iptv:'IPTV',youtube:'Tube',twitch:'Twitch',settings:'Manage Libraries'};
const showWindow = name => { wrap.hidden = false; title.textContent = name; setSplit(true); document.body.classList.add('borg-mobile-media-view'); };
const hasOpenPlayer = () => Boolean(document.querySelector(
'.youtube-player-overlay.active:not(.minimized), .twitch-player-overlay.open:not(.minimized), #playerOverlay.active, .player-overlay.active, .music-player:not([hidden])'
));
const close = () => { wrap.hidden = true; document.body.classList.remove('borg-mobile-media-view'); setSplit(hasOpenPlayer()); };
const mark = kind => document.querySelectorAll('[data-borg]').forEach(b => b.classList.toggle('borg-selected',b.dataset.borg===kind));
const back = document.createElement('button');
back.id = 'borgWindowBack';
back.type = 'button';
back.textContent = '← Back';
back.title = 'Go back within media';
back.setAttribute('aria-label','Go back');
const labelEl = document.getElementById('borgWindowTitle');
labelEl.before(back);
back.addEventListener('click', async () => {
if(navigationBusy) return;
const bc=document.getElementById('breadcrumb')?.textContent?.trim() || '';
// Native library navigation handles nested movie/show/episode breadcrumbs.
// Every category owns its history: never fall through to the global Libraries screen.
// We use the existing library functions so filters, sorting and selection remain intact.
const crumbs=bc.split('›').map(part=>part.trim()).filter(Boolean);
if(currentSection==='movies' || currentSection==='shows' ||
(currentSection==='libraries' && typeof currentSourceId!=='undefined' && currentSourceId)) {
if(crumbs.length>=4 && typeof openShow==='function') {
await openShow(currentShowName || crumbs[2]); return;
}
if(crumbs.length>=3 && typeof showLibrary==='function') {
await showLibrary(currentSourceId,currentSourceName,currentSourceType); return;
}
// At the selected library's root, remain in its category's selection view.
if(crumbs.length>=2 && typeof showCategory==='function') {
await showCategory(currentSourceType==='shows'?'shows':'movies'); return;
}
return;
}
// Music, IPTV, Twitch and Tube are their own roots, not shortcuts to Libraries.
if(currentSection==='music'||currentSection==='iptv'||currentSection==='youtube'||currentSection==='twitch') return;
if(currentSection==='libraries' && navigateTrail.length) {
await navigate(navigateTrail.pop(),true); return;
}
if(currentSection==='libraries') return;
await navigate('libraries');
});
async function showCategory(type) {
const sources = await api('/api/sources');
const matches = sources.filter(s => s.library_type === type && s.enabled !== false && s.enabled !== 0);
if (matches.length === 1) return showLibrary(matches[0].id,matches[0].name,matches[0].library_type);
// Multiple libraries: use the existing library homepage and select a category
// using its existing card click handlers, rather than inventing a separate renderer.
await showLibraries();
const content = document.getElementById('content');
const section = document.createElement('div');
section.className = 'borg-category-picks';
const heading = document.createElement('h2');
heading.textContent = type === 'movies' ? 'Movie Libraries' : 'TV Show Libraries';
section.appendChild(heading);
if (!matches.length) {
const empty = document.createElement('p');
empty.textContent = 'No enabled libraries in this category.';
section.appendChild(empty);
} else {
for (const source of matches) {
const button=document.createElement('button');
button.type='button'; button.className='borg-category-choice';
button.textContent=source.name;
button.addEventListener('click',()=>showLibrary(source.id,source.name,source.library_type));
section.appendChild(button);
}
}
content.replaceChildren(section);
}
mobileMediaQuick?.addEventListener('click',()=>{closeMobileNavigation(); void navigate('libraries');});
async function navigate(kind, fromHistory=false) {
if (navigationBusy) return;
// Revalidate permission on navigation, not just when the sidebar is rendered.
if (kind !== 'room' && kind !== 'settings') {
await refreshLibraryPermissions();
const key=libraryKind[kind];
if ((key && permittedLibraries?.[key] === false) ||
(kind==='libraries' && !Object.values(libraryKind).some(k=>permittedLibraries?.[k] !== false))) {
console.warn('[Kronic] Library access denied:',kind);
return;
}
}
if (kind === 'room') { previousSection=currentSection; currentSection='room'; mark(kind); close(); return; }
navigationBusy = true;
const old = currentSection;
showWindow(labels[kind] || 'Media Library');
mark(kind);
try {
if (kind === 'libraries') await showLibraries();
else if (kind === 'movies') await showCategory('movies');
else if (kind === 'shows') await showCategory('shows');
else if (kind === 'music') await showMusicLibrary();
else if (kind === 'iptv') await showIptvLibrary('library');
else if (kind === 'youtube') await showYouTubeLibrary();
else if (kind === 'twitch') await showTwitchLibrary();
else if (kind === 'settings') await showManageLibraries();
if(!fromHistory && old !== kind && old !== 'room') navigateTrail.push(old);
previousSection=old;
currentSection=kind;
currentRoot=kind;
} catch (error) {
console.error('[BORG] Navigation failed:',kind,error);
const content=document.getElementById('content');
if (content) content.textContent = `Could not open ${labels[kind] || kind}: ${error.message}`;
} finally { navigationBusy=false; }
}
window.addEventListener('kronic:preferred-start-view', event => {
const section = event.detail?.section;
// A full-window library is an individual preference, never a room-wide action.
if (section === 'libraries') navigate('libraries').then(() => { wrap.classList.add('borg-max'); document.body.classList.remove('borg-split-layout'); });
else if (section === 'room') {mark('room'); close();}
});
// The app may finish authentication before or after this bridge is initialized.
const preferredKey = 'kronic.start-view.v1.' + String(document.querySelector('.media-account-name')?.textContent || 'guest').toLowerCase();
if (localStorage.getItem(preferredKey) === 'libraries') {
window.addEventListener('load', () => { if(wrap.hidden) navigate('libraries').then(() => {wrap.classList.add('borg-max'); document.body.classList.remove('borg-split-layout');}); }, {once:true});
}
// AI Command must use the SAME navigation function as the sidebar, otherwise
// search results render into a hidden media library instead of opening a window.
window.addEventListener('kronic:ai-media-navigate', async event => {
const detail=event.detail||{};
const finish=typeof detail.finish==='function'?detail.finish:()=>{};
try {
if(!['youtube','music','iptv','movies','shows','twitch'].includes(detail.kind))throw Error('Unsupported media window');
await navigate(detail.kind);
if(wrap.hidden)throw Error('Media window was not opened (permission or navigation blocked)');
finish();
} catch(error) { finish(error); }
});
window.addEventListener('kronic:ai-open-library', async event => {
const d=event.detail||{};
try {
const sources=await api('/api/sources');
const source=sources.find(x=>Number(x.id)===Number(d.source_id) && String(x.library_type)===String(d.kind) && x.enabled!==false && x.enabled!==0);
if(!source)throw Error('Requested media library unavailable');
await refreshLibraryPermissions();
const key=d.kind==='shows'?'tv':'movies';
if(permittedLibraries?.[key]===false)throw Error('Library access denied');
await showLibrary(source.id,source.name,source.library_type);
if(d.show_name){
// Only navigate into an actual series displayed by this library.
const media=await api('/api/media?source_id='+encodeURIComponent(source.id));
const names=[...new Set(media.map(i=>getShowName(i)))];
const show=names.find(x=>x.toLowerCase()===String(d.show_name).toLowerCase());
if(show){
await openShow(show);
if(d.season!==undefined && d.season!==null){
const exists=media.some(i=>getShowName(i)===show && Number(getSeasonNumber(i))===Number(d.season));
if(exists)await openSeason(show,'Season '+Number(d.season));
}
}
}
d.finish?.();
} catch(error){d.finish?.(error);}
});
document.querySelectorAll('[data-borg]').forEach(btn => btn.addEventListener('click', () => navigate(btn.dataset.borg)));
document.getElementById('borgClose')?.addEventListener('click', () => { previousSection=currentSection; currentSection='room'; mark('room'); close(); });
document.getElementById('borgMinimize')?.addEventListener('click', () => { previousSection=currentSection; currentSection='room'; mark('room'); close(); });
document.getElementById('borgMaximize')?.addEventListener('click', () => { wrap.classList.toggle('borg-max'); setSplit(!wrap.hidden); });
header.addEventListener('pointerdown',e=>{
if(e.target.closest('button') || wrap.classList.contains('borg-max') || matchMedia('(max-width:700px)').matches) return;
pos={x:e.clientX,y:e.clientY,left:wrap.offsetLeft,top:wrap.offsetTop};
wrap.dataset.moved='1';
header.setPointerCapture(e.pointerId);
});
header.addEventListener('pointermove',e=>{
if(!pos) return;
wrap.style.left=Math.max(0,Math.min(window.innerWidth-90,pos.left+e.clientX-pos.x))+'px';
wrap.style.top=Math.max(0,Math.min(window.innerHeight-90,pos.top+e.clientY-pos.y))+'px';
});
const stop=()=>{pos=null;};
header.addEventListener('pointerup',stop);
header.addEventListener('pointercancel',stop);
// Give standalone floating players their own optional sizing controls.
// Never move their DOM nodes or touch playback state/events.
const addPlayerSizing = () => {
document.querySelectorAll('#playerWindow, .youtube-player-window').forEach(player => {
if (player.dataset.borgSizing === '1') return;
const header = player.querySelector('.player-header, .youtube-player-header');
if (!header) return;
player.dataset.borgSizing = '1';
const buttons = document.createElement('span');
buttons.className = 'borg-player-size-tools';
for (const [label, width] of [['¼','420px'],['½','760px'],['▭','1100px']]) {
const button=document.createElement('button');
button.type='button'; button.textContent=label;
button.title=`Size player to ${width}`;
button.addEventListener('click', event => {
event.stopPropagation();
if (matchMedia('(max-width:700px)').matches) return;
player.style.width=`min(${width}, 90vw)`;
player.style.maxWidth='90vw';
player.style.height='auto';
});
buttons.appendChild(button);
}
const controls=header.querySelector('.player-controls, .youtube-player-controls');
(controls || header).prepend(buttons);
});
};
addPlayerSizing();
const sizingObserver=new MutationObserver(() => {
addPlayerSizing();
if(wrap.hidden) setSplit(hasOpenPlayer());
});
sizingObserver.observe(document.body,{childList:true,subtree:true,attributes:true,attributeFilter:['class','style','hidden']});
document.getElementById('homeButton')?.addEventListener('click',()=>navigate('libraries'));
close();
})();