diff --git a/JS/admin.js b/JS/admin.js new file mode 100644 index 0000000..329c8d1 --- /dev/null +++ b/JS/admin.js @@ -0,0 +1,547 @@ +const $ = id => document.getElementById(id); +let state = {users: [], groups: [], memberships: [], rooms: []}; +let explicitRoomMembers = []; +const selectedForPurge = new Set(); + +async function api(url, opts = {}) { + opts.credentials = 'same-origin'; + if (opts.body && typeof opts.body !== 'string') { + opts.headers = {...(opts.headers || {}), 'Content-Type': 'application/json'}; + opts.body = JSON.stringify(opts.body); + } + const response = await fetch(url, opts); + const data = await response.json().catch(() => ({})); + if (response.status === 401) { + location.replace('/login?admin=1'); + throw new Error('Login required'); + } + if (!response.ok) throw new Error(data.detail || data.error || 'Request failed'); + return data; +} + +function esc(value) { + return String(value ?? '').replace(/[&<>"']/g, char => ({ + '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' + }[char])); +} + +function msg(text) { + $('status').textContent = text; + setTimeout(() => { if ($('status').textContent === text) $('status').textContent = ''; }, 3500); +} + +function fill(element, items, valueKey, labelKey) { + const old = element.value; + element.innerHTML = items.map(item => ``).join(''); + if ([...element.options].some(option => option.value === old)) element.value = old; +} + +function render() { + const pending = state.users.filter(user => user.status === 'pending'); + $('pendingUsers').innerHTML = pending.length + ? pending.map(user => `
${esc(user.username)}
${esc(user.email)}
`).join('') + : '
No pending accounts.
'; + + $('users').innerHTML = state.users.map(user => `
${esc(user.username)} ${esc(user.status)} ${user.isPlatformAdmin ? 'platform admin' : ''}
${esc(user.email)}
Rooms: ${explicitRoomMembers.filter(m=>m.user_id===user.id).map(m=>esc(m.display_name||m.room_name)).join(", ")||"None"}
${user.status === 'active' ? `` : ``} ${user.isPlatformAdmin ? '' : ``}
`).join(''); + + $('groups').innerHTML = '
' + state.groups.map(group => `
${esc(group.name)}
${esc(group.slug)} · ${group.user_count}/${group.max_users} users
media: ${group.media_enabled ? 'enabled' : 'disabled'} · subscription: ${esc(group.subscription_status)}
`).join('') + '
'; + + $('memberships').innerHTML = state.memberships.map(membership => `
${esc(membership.username)} → ${esc(membership.group_name)}
${esc(membership.role)}
`).join('') || '
No memberships.
'; + + fill($('createRoomGroup'), state.groups, 'id', 'name'); + $('managedRoomList').innerHTML = (state.rooms || []).map(room => + `
${esc(room.room_name)}Group: ${esc(room.group_name)} · ${esc(room.display_name)}
` + ).join('') || '

No chat rooms yet. Create one to enable signup and voice-room access.

'; + renderInventory(); + renderRoomMemberships(); + renderRoomOverview(); + fill($('memberGroup'), state.groups, 'id', 'name'); + fill($('memberUser'), state.users.filter(user => user.status === 'active'), 'id', 'username'); +} + +async function load() { + try { + state = await api('/api/admin/overview'); + try { + const roomData = await api('/api/admin/room-memberships'); + explicitRoomMembers = roomData.memberships || []; + delete $('roomMembersAdmin').dataset.loadError; + } catch (roomError) { + explicitRoomMembers = []; + console.error('Room membership inventory failed:', roomError); + $('roomMembersAdmin').dataset.loadError = roomError.message; + } + $('inventoryError').textContent = ''; + const presentIds = new Set(state.users.map(u => u.id)); + for (const id of selectedForPurge) if (!presentIds.has(id)) selectedForPurge.delete(id); + render(); + } catch (error) { + msg(error.message); + $('inventoryError').textContent = 'Unable to retrieve account inventory: ' + error.message; + console.error('Admin overview failed:', error); + } +} + +window.setStatus = async (id, status) => { + try { + await api(`/api/admin/users/${id}/status`, {method: 'PATCH', body: {status}}); + await load(); + msg(`User ${status}.`); + } catch (error) { msg(error.message); } +}; + +window.deleteAccount = async id => { + const user = state.users.find(u => u.id === id); + if (!user || user.isPlatformAdmin) return; + const typed = prompt(`PERMANENTLY delete ${user.username} and release ${user.email}?\nType the exact username to confirm:`); + if (typed !== user.username) return; + try { + await api(`/api/admin/users/${id}`, {method: 'DELETE'}); + await load(); + msg('Account permanently deleted.'); + } catch (error) { msg(error.message); } +}; + +window.toggleGroupMedia = async (id, enabled) => { + try { + await api(`/api/admin/groups/${id}/media`, {method: 'PATCH', body: {enabled}}); + await load(); + msg(enabled ? 'Media access enabled.' : 'Media access disabled.'); + } catch (error) { msg(error.message); } +}; + +window.removeMembership = async (groupId, userId) => { + if (!confirm('Remove this user from the media group?')) return; + try { + await api(`/api/admin/groups/${groupId}/members/${userId}`, {method: 'DELETE'}); + await load(); + msg('Membership removed.'); + } catch (error) { msg(error.message); } +}; + +$('groupForm').onsubmit = async event => { + event.preventDefault(); + try { + await api('/api/admin/groups', {method: 'POST', body: { + name: $('groupName').value, + slug: $('groupSlug').value, + max_users: +$('groupMaxUsers').value, + media_enabled: true, + }}); + event.target.reset(); + $('groupMaxUsers').value = 10; + await load(); + msg('Media group created.'); + } catch (error) { msg(error.message); } +}; + +$('memberForm').onsubmit = async event => { + event.preventDefault(); + try { + await api(`/api/admin/groups/${$('memberGroup').value}/members`, {method: 'POST', body: { + user_id: +$('memberUser').value, + role: $('memberRole').value, + }}); + await load(); + msg('Membership saved.'); + } catch (error) { msg(error.message); } +}; + + + +function renderRoomMemberships() { + fill($('instanceRoom'), state.rooms || [], 'id', 'room_name'); + fill($('instanceRoomUser'), state.users.filter(u=>u.status==='active'), 'id', 'username'); + const id=Number($('instanceRoom').value); + const items=explicitRoomMembers.filter(m=>m.room_id===id); + $('roomMembersAdmin').innerHTML = items.map(m=>`
+
${esc(m.username)} ${esc(m.role)} ${m.is_platform_admin?'instance admin':''}
+
+
+
`).join('') || `

${$('roomMembersAdmin').dataset.loadError ? 'Room membership API: '+esc($('roomMembersAdmin').dataset.loadError) : 'No explicit memberships for this room.'}

`; +} +$('instanceRoom').addEventListener('change',renderRoomMemberships); +$('roomMembersAdmin').addEventListener('click', event=>{ + const edit=event.target.closest('[data-room-user]'); + if(edit){$('instanceRoomUser').value=edit.dataset.roomUser;$('instanceRoomRole').value=edit.dataset.roomRole;return;} + const remove=event.target.closest('[data-remove-room-user]'); + if(remove) removeRoomMember(Number(remove.dataset.removeRoomUser)); +}); +$('roomMemberForm').addEventListener('submit',async event=>{ + event.preventDefault(); + try{ + await api(`/api/admin/rooms/${$('instanceRoom').value}/members`,{method:'PUT',body:{ + user_id:Number($('instanceRoomUser').value),role:$('instanceRoomRole').value + }}); + await load();msg('Room role saved independently of group role.'); + }catch(error){msg(error.message);} +}); +async function removeRoomMember(userId){ + const room=state.rooms.find(r=>r.id===Number($('instanceRoom').value)); + const user=state.users.find(u=>u.id===userId); + if(!confirm(`Remove ${user?.username||userId} from room ${room?.room_name||''}? Their account and group membership will remain.`))return; + try{await api(`/api/admin/rooms/${room.id}/members/${userId}`,{method:'DELETE'}); + await load();msg('Room membership removed (account retained).');} + catch(error){msg(error.message);} +} + +// This view intentionally includes every user row returned by /api/admin/overview. +// Filtering only happens in the browser; no status is omitted by default. +function renderInventory() { + const search = ($('inventorySearch').value || '').trim().toLowerCase(); + const filter = $('inventoryStatus').value; + const all = state.users || []; + const shown = all.filter(u => (filter === 'all' || u.status === filter) && + (!search || [u.username,u.email,String(u.id)].some(v => String(v ?? '').toLowerCase().includes(search)))); + $('inventoryCount').textContent = `(${shown.length} shown / ${all.length} total)`; + if (!shown.length) { + $('inventoryTable').innerHTML = '

No matching database records.

'; + return; + } + const memberships = state.memberships || []; + const rooms = state.rooms || []; + $('inventoryTable').innerHTML = ` + + ${shown.map(u=>{ + const groupCount = memberships.filter(m=>m.user_id === u.id).length; + const formatDate = timestamp => timestamp ? new Date(timestamp * 1000).toLocaleDateString() : '—'; + return ` + + + + + + `; + }).join('')}
SelectIDUsernameEmailStatusGroupsCreatedLast loginAction
${u.id}${esc(u.username)}${u.isPlatformAdmin?' (platform admin)':''}${esc(u.email)}${esc(u.status)}${groupCount}${formatDate(u.createdAt)}${formatDate(u.lastLoginAt)}${u.isPlatformAdmin?'Protected':``}
`; +} + +$('inventorySearch').addEventListener('input', renderInventory); +$('inventoryStatus').addEventListener('change', renderInventory); +$('inventoryRefresh').addEventListener('click', load); +$('inventoryTable').addEventListener('change', e=>{ + const box = e.target.closest('[data-purge-id]'); + if (!box) return; + const id = Number(box.dataset.purgeId); + if (box.checked) selectedForPurge.add(id); else selectedForPurge.delete(id); +}); +$('inventoryTable').addEventListener('click', e=>{ + const button = e.target.closest('[data-delete-id]'); + if (button) deleteAccount(Number(button.dataset.deleteId)); +}); +$('purgeSelected').addEventListener('click', async ()=>{ + const targets = state.users.filter(u=>selectedForPurge.has(u.id) && !u.isPlatformAdmin); + if (!targets.length) return msg('Select at least one non-admin account.'); + const typed = prompt(`Permanently delete ${targets.length} account(s), freeing their usernames and emails?\nThis cannot be undone.\nType PURGE ${targets.length} to confirm:`); + if (typed !== `PURGE ${targets.length}`) return; + let deleted = 0; + const failed = []; + for (const u of targets) { + try { await api(`/api/admin/users/${u.id}`, {method:'DELETE'}); selectedForPurge.delete(u.id); deleted++; } + catch (error) { failed.push(`${u.username}: ${error.message}`); } + } + await load(); + if (failed.length) { + $('inventoryError').textContent = `${deleted} deleted; ${failed.length} failed: ${failed.join('; ')}`; + } else msg(`${deleted} account(s) permanently deleted.`); +}); + +$('logoutBtn').onclick = async () => { + await api('/api/auth/logout', {method: 'POST'}).catch(() => {}); + location.replace('/login?admin=1'); +}; + +load(); + +// Room bootstrap is deliberately explicit and instance-admin-only. +$('createRoomForm').addEventListener('submit', async event => { + event.preventDefault(); + const groupId = Number($('createRoomGroup').value); + if (!groupId) { msg('Create a media group first.'); return; } + try { + const response = await api(`/api/admin/groups/${groupId}/rooms`, { + method: 'POST', + body: { + room_name: $('createRoomName').value.trim().toLowerCase(), + display_name: $('createRoomLabel').value.trim(), + template_id: $('createRoomTemplate').value || null + } + }); + await load(); + $('instanceRoom').value = String(response.roomId); + renderRoomMemberships(); + $('createRoomName').value = ''; + $('createRoomLabel').value = ''; + msg(`Room ${response.room} created. Users can now request access.`); + } catch (error) { msg(error.message); } +}); + + +// Central role-based permissions. Every checkbox is persisted and independently +// checked by the Chat backend on protected room-admin endpoints. +const ROLE_ACTION_LABELS = { + media_access: 'Media access permissions', + user_permissions: 'User permissions', + room_permissions: 'Room permissions / invitations', + password_resets: 'Password resets', + account_approvals: 'Room-level account approval' +}; +const ROLE_NAMES = ['member','moderator','admin','owner']; +const ACTION_KEYS = Object.keys(ROLE_ACTION_LABELS); +let savedRolePolicy = null; +async function loadRolePolicy() { + try { + const data = await api('/api/admin/role-permissions'); + savedRolePolicy = data.roles; + const matrix = $('rolePolicyMatrix'); + matrix.replaceChildren(); + const table = document.createElement('table'); + table.style.cssText = 'width:100%;border-collapse:collapse;min-width:720px'; + const head = document.createElement('tr'); + for (const label of ['Role / Action',...ACTION_KEYS.map(k=>ROLE_ACTION_LABELS[k])]) { + const th=document.createElement('th');th.textContent=label;th.style.padding='8px';head.append(th); + } + table.append(head); + for (const role of ROLE_NAMES) { + const tr=document.createElement('tr');tr.style.borderTop='1px solid #454b54'; + const td=document.createElement('td');td.textContent=role;td.style.padding='10px';tr.append(td); + for(const action of ACTION_KEYS){ + const cell=document.createElement('td');cell.style.padding='8px'; + const input=document.createElement('input');input.type='checkbox'; + input.dataset.role=role;input.dataset.action=action; + input.checked=!!data.roles?.[role]?.[action]; + if(role==='owner'){input.disabled=true;input.title='Owners must retain management privileges';} + input.setAttribute('aria-label',`${role}: ${ROLE_ACTION_LABELS[action]}`); + cell.append(input);tr.append(cell); + } + table.append(tr); + } + matrix.append(table); + $('rolePolicyError').textContent=''; + } catch(error){$('rolePolicyError').textContent=error.message;} +} +$('saveRolePolicy').addEventListener('click',async()=>{ + const roles={};for(const role of ROLE_NAMES)roles[role]={}; + for(const input of $('rolePolicyMatrix').querySelectorAll('input[data-role][data-action]')){ + roles[input.dataset.role][input.dataset.action]=input.checked; + } + try { + await api('/api/admin/role-permissions',{method:'PUT',body:{roles}}); + await loadRolePolicy();msg('Role permissions updated.'); + } catch(error){$('rolePolicyError').textContent=error.message;} +}); +$('reloadRolePolicy').addEventListener('click',loadRolePolicy); +loadRolePolicy(); + + + +// Consolidated room-centric admin, keeping original APIs and role checks. +function activateAdminPanel(panel){ + document.querySelectorAll('[data-admin-panel]').forEach(el=>{ + el.hidden = el.dataset.adminPanel !== panel; + }); + document.querySelectorAll('[data-admin-nav]').forEach(el=>{ + el.classList.toggle('active',el.dataset.adminNav===panel); + el.setAttribute('aria-current', el.dataset.adminNav===panel ? 'page':'false'); + }); + sessionStorage.setItem('kronic-admin-tab',panel); +} +document.querySelectorAll('[data-admin-nav]').forEach(el=>el.addEventListener('click',()=>activateAdminPanel(el.dataset.adminNav))); +activateAdminPanel(['users','rooms','permissions','media-policy','templates','appearance'].includes(sessionStorage.getItem('kronic-admin-tab'))?sessionStorage.getItem('kronic-admin-tab'):'rooms'); + +function renderRoomOverview(){ + const root=$('roomOverview'); + if(!root)return; + const groups=state.groups||[], rooms=state.rooms||[], memberships=state.memberships||[]; + root.innerHTML=groups.map(group=>{ + const groupMembers=memberships.filter(m=>m.group_id===group.id); + const children=rooms.filter(r=>r.group_id===group.id); + return `
+

${esc(group.name)} ${esc(group.slug)}

+
Parent group · ${groupMembers.length}/${group.max_users} members · Media ${group.media_enabled?'enabled':'disabled'}
+
+ ${children.map(room=>{ + const members=explicitRoomMembers.filter(m=>m.room_id===room.id); + return `
+

${esc(room.display_name||room.room_name)}

Internal ID: ${esc(room.room_name)} · ${members.length} room members
+
+
+ ${members.map(m=>{ + const parent=groupMembers.find(g=>g.user_id===m.user_id); + return ` + `; + }).join('')||''} +
UserParent group roleRoom roleManage
${esc(m.username)}${esc(parent?.role||'Not assigned')}${esc(m.role)}
No room members
+
+ +
+
`; + }).join('')||'

No rooms under this group.

'} +
`; + }).join('')||'

No groups or rooms configured.

'; +} +$('roomOverview').addEventListener('click', async event=>{ + const control=event.target.closest('button');if(!control)return; + try{ + if(control.dataset.groupMedia){await window.toggleGroupMedia(Number(control.dataset.groupMedia),control.dataset.enabled==='true');return;} + if(control.dataset.renameRoom){ + const id=Number(control.dataset.renameRoom),room=state.rooms.find(r=>r.id===id); + if(!room)return; + const name=prompt(`Change display name for ${room.room_name}. Internal room identifier will not change.`,room.display_name||room.room_name); + if(name===null)return; + if(!name.trim()||name.length>100)throw new Error('Display name must be 1–100 characters.'); + await api(`/api/admin/rooms/${id}/display-name`,{method:'PATCH',body:{display_name:name.trim()}}); + await load();msg('Room display name updated.');return; + } + if(control.dataset.manageRoomMember){ + $('instanceRoom').value=String(control.dataset.manageRoomMember); + renderRoomMemberships(); + $('instanceRoomUser').value=String(control.dataset.userId); + const member=explicitRoomMembers.find(m=>m.room_id===Number(control.dataset.manageRoomMember)&&m.user_id===Number(control.dataset.userId)); + if(member)$('instanceRoomRole').value=member.role; + document.getElementById('roomMembershipSection').classList.add('admin-show-advanced'); + document.getElementById('roomMembershipSection').scrollIntoView({behavior:'smooth',block:'center'}); + return; + } + if(control.dataset.roomAdd){ + const id=Number(control.dataset.roomAdd),root=control.closest('[data-room-id]'); + const userId=Number(root.querySelector('[data-room-add-user]').value); + const role=root.querySelector('[data-room-add-role]').value; + await api(`/api/admin/rooms/${id}/members`,{method:'PUT',body:{user_id:userId,role}}); + await load();msg('Room member updated.'); + } + }catch(error){msg(error.message);} +}); +// Keep the original detailed forms accessible for advanced group-role operations. +const advanced=document.createElement('button');advanced.type='button';advanced.className='admin-advanced-toggle'; +advanced.textContent='Advanced: edit parent-group memberships and room roles'; +advanced.addEventListener('click',()=>document.querySelectorAll('.admin-advanced').forEach(s=>s.classList.toggle('admin-show-advanced'))); +$('roomOverviewSection').append(advanced); + + +// AI Command access is independent of parent-group and room memberships. +async function loadAiAccess(){ + try{ + const data=await api('/api/admin/ai-access'); + const rows=data.users||[]; + document.getElementById('aiAccessTable').innerHTML=` + + ${rows.map(u=>` + + + + + `).join('')}
UserAI chatAgent toolsSave
${esc(u.username)} ${esc(u.status)}${u.is_platform_admin?' platform admin':''}${u.is_platform_admin?'Always allowed':''}
`; + document.getElementById('aiAccessError').textContent=''; + }catch(error){document.getElementById('aiAccessError').textContent=error.message;} +} +document.getElementById('aiAccessTable').addEventListener('change',e=>{ + const row=e.target.closest('[data-ai-user]');if(!row)return; + const chat=row.querySelector('[data-ai-chat]'),tools=row.querySelector('[data-ai-tools]'); + if(e.target===chat&&!chat.checked)tools.checked=false; + if(e.target===tools&&tools.checked)chat.checked=true; +}); +document.getElementById('aiAccessTable').addEventListener('click',async e=>{ + const button=e.target.closest('[data-ai-save]');if(!button)return; + const row=button.closest('[data-ai-user]'); + try{ + button.disabled=true; + await api('/api/admin/ai-access',{method:'POST',body:{user_id:Number(row.dataset.aiUser), + can_chat:row.querySelector('[data-ai-chat]').checked, + can_use_tools:row.querySelector('[data-ai-tools]').checked}}); + msg('AI Command access updated.'); + }catch(error){document.getElementById('aiAccessError').textContent=error.message;} + finally{button.disabled=false;} +}); +void loadAiAccess(); + +// Instance-level media policy editor. All writes require platform admin on server. +let policyState; +const mediaTypes = ['movies','tv','music','iptv','tube','twitch']; +function policyFields(id, policy){ + const el=$(id); el.replaceChildren(); + const add=(name, value, type, checked)=>{ + const label=document.createElement('label'); label.style.cssText='display:inline-flex;align-items:center;gap:6px;margin:8px 20px 8px 0'; + const input=document.createElement('input');input.type='checkbox';input.dataset.kind=type;input.value=value;input.checked=checked; + label.append(input,document.createTextNode(name));el.append(label); + }; + const title=document.createElement('h3');title.textContent='Media types';el.append(title); + mediaTypes.forEach(k=>add(k,k,'types',policy.types.includes(k))); + const heading=document.createElement('h3');heading.textContent='Named libraries';el.append(heading); + policyState.sources.forEach(s=>add(s.name+' ('+s.library_type+')',s.id,'libraries',policy.libraries.includes(s.id))); +} +function getPolicy(id){const checked=[...$(id).querySelectorAll('input:checked')];return {types:checked.filter(x=>x.dataset.kind==='types').map(x=>x.value),libraries:checked.filter(x=>x.dataset.kind==='libraries').map(x=>Number(x.value))};} +function fullPolicy(){return {types:mediaTypes,libraries:policyState.sources.map(s=>s.id)};} +function showUserPolicy(){const p=policyState.policies[$('policyUser').value];$('policyInherit').checked=!p;policyFields('policyFields',p||fullPolicy());} +const templateActions=['media_access','user_permissions','room_permissions','password_resets','account_approvals']; +const templateRoles=['member','moderator','admin','owner']; +function showTemplate(){const t=policyState.templates.find(t=>String(t.id)===$('templateExisting').value);$('templateName').value=t?.name||'';policyFields('templateFields',t?.policy||{types:[],libraries:[]});$('templateAI').checked=t?.policy.ai_chat??false;$('templateTools').checked=t?.policy.ai_tools??false;renderHistory('templateHistory',t?.policy.history||{}); +$('templateRoles').innerHTML=templateRoles.map(role=>'
'+role+''+templateActions.map(a=>'').join('')+'
').join('');} +function getTemplateRoles(){return Object.fromEntries(templateRoles.map(r=>[r,[...$('templateRoles').querySelectorAll('input:checked[data-role="'+r+'"]')].map(e=>e.value)]));} +async function loadMediaPolicies(){ + policyState=await api('/api/admin/media-policies'); + const old=$('policyUser').value; + fill($('policyUser'),policyState.users.filter(u=>!u.is_platform_admin),'id','username'); + if([...$('policyUser').options].some(o=>o.value===old))$('policyUser').value=old; + for(const id of ['templateExisting','createRoomTemplate','applyTemplate']){const el=$(id);el.replaceChildren(new Option(id==='templateExisting'?'New template':id==='applyTemplate'?'Remove template ceiling':'No template',''));for(const t of policyState.templates)el.add(new Option(t.name,t.id));} + const previousBrandRoom=$("brandRoom").value; + fill($("applyRoom"),policyState.rooms.map(r=>({...r,label:r.display_name||r.room_name})),"id","label");fill($("brandRoom"),policyState.rooms.map(r=>({...r,label:r.display_name||r.room_name})),"id","label"); + if ([...$("brandRoom").options].some(o=>o.value===previousBrandRoom)) $("brandRoom").value=previousBrandRoom; + const previousHistoryRoom=$('historyRoom').value; + fill($('historyRoom'),policyState.rooms.map(r=>({...r,label:r.display_name||r.room_name})), 'id','label'); + if ([...$('historyRoom').options].some(o=>o.value===previousHistoryRoom)) $('historyRoom').value=previousHistoryRoom; + loadRoomHistory().catch(e=>$('historyStatus').textContent=e.message); + showUserPolicy();showTemplate();loadRoomBrand().catch(e=>$("roomBrandStatus").textContent=e.message); +} +$('policyUser').onchange=showUserPolicy; +$('policyFields').onchange=()=>{$('policyInherit').checked=false;}; +$('templateExisting').onchange=showTemplate; +$('policySave').onclick=async()=>{try{await api('/api/admin/media-policies',{method:'POST',body:{user_id:Number($('policyUser').value),inherit:$('policyInherit').checked,...getPolicy('policyFields')}});$('policyStatus').textContent='Saved. Existing room restrictions still apply.';await loadMediaPolicies();}catch(e){$('policyStatus').textContent=e.message;}}; +$('templateSave').onclick=async()=>{try{await api('/api/admin/room-templates',{method:'POST',body:{name:$('templateName').value,...getPolicy('templateFields'),roles:getTemplateRoles(),history:readHistory('templateHistory'),ai_chat:$('templateAI').checked,ai_tools:$('templateTools').checked}});$('templateStatus').textContent='Saved. Existing rooms unchanged.';await loadMediaPolicies();}catch(e){$('templateStatus').textContent=e.message;}}; +loadMediaPolicies().catch(e=>{$('policyStatus').textContent=e.message;$('templateStatus').textContent=e.message;}); + +$('applyTemplateSave').onclick=async()=>{if(!confirm('Replace the room template ceiling? This changes effective access for all assigned members.'))return;try{await api('/api/admin/apply-template',{method:'POST',body:{room_id:Number($('applyRoom').value),template_id:$('applyTemplate').value||null}});$('applyStatus').textContent='Saved.';await loadMediaPolicies();}catch(e){$('applyStatus').textContent=e.message;}}; +async function loadBrand(){const b=await api('/api/admin/appearance');$('brandName').value=b.name;$('brandTitle').value=b.login_title;$('brandSubtitle').value=b.login_subtitle;$('brandPowered').checked=b.powered_by;$('brandRename').checked=b.allow_owner_rename;} +async function loadRoomBrand(){ + const id=$('brandRoom').value; + const room=policyState.rooms.find(r=>String(r.id)===id); + $('brandRoomTitle').value=room?.display_name||room?.room_name||''; + $('brandRoomTitleSave').disabled=!room; + if(!room)return; + const b=await api('/api/admin/appearance?room_id='+encodeURIComponent(id)); + if($('brandRoom').value!==id)return; + $('brandIcon').value=b.room?.icon||'';$('brandAccent').value=b.room?.accent||''; +} +$('brandRoomTitleSave').onclick=async()=>{ + const id=$('brandRoom').value, title=$('brandRoomTitle').value.trim(); + if(!id||!title||title.length>100){$('roomBrandStatus').textContent='Select a room and enter a title of 1–100 characters.';return;} + const button=$('brandRoomTitleSave');button.disabled=true; + try{ + await api(`/api/admin/rooms/${Number(id)}/display-name`,{method:'PATCH',body:{display_name:title}}); + const room=policyState.rooms.find(r=>String(r.id)===id);if(room)room.display_name=title; + for(const selectId of ['brandRoom','applyRoom'])for(const option of $(selectId).options)if(option.value===id)option.textContent=title; + await load(); + $('roomBrandStatus').textContent='Room title saved. Reload the room to see it.'; + }catch(e){$('roomBrandStatus').textContent=e.message;}finally{button.disabled=!$('brandRoom').value;} +}; +$('brandRoom').onchange=()=>loadRoomBrand().catch(e=>$('roomBrandStatus').textContent=e.message); +$('brandSave').onclick=async()=>{try{await api('/api/admin/appearance',{method:'POST',body:{name:$('brandName').value,login_title:$('brandTitle').value,login_subtitle:$('brandSubtitle').value,powered_by:$('brandPowered').checked,allow_owner_rename:$('brandRename').checked}});$('brandStatus').textContent='Saved.';}catch(e){$('brandStatus').textContent=e.message;}}; +$('brandRoomSave').onclick=async()=>{try{await api('/api/admin/room-appearance',{method:'POST',body:{room_id:Number($('brandRoom').value),icon:$('brandIcon').value,accent:$('brandAccent').value}});$('roomBrandStatus').textContent='Saved. Reload room to see changes.';}catch(e){$('roomBrandStatus').textContent=e.message;}}; +loadBrand().catch(e=>$('brandStatus').textContent=e.message); + +function renderHistory(id, settings){ + const root=$(id);root.replaceChildren(); + for(const [key,label] of [['tube','YouTube / Tube'],['movies','Movies (resume positions)'],['tv','TV shows (resume positions)']]){ + const row=document.createElement('label');row.style.cssText='display:flex;align-items:center;gap:12px;margin:10px 0;max-width:520px;justify-content:space-between';row.append(document.createTextNode(label)); + const select=document.createElement('select');select.dataset.historyKind=key; + for(const [v,t] of [['shared','Shared instance history'],['group','Parent group history'],['room','Room-only history'],['user','Personal account history'],['off','Disabled']])select.add(new Option(t,v)); + select.value=settings[key]||'shared';row.append(select);root.append(row); + } +} +function readHistory(id){return Object.fromEntries([...$(id).querySelectorAll('select[data-history-kind]')].map(e=>[e.dataset.historyKind,e.value]));} +async function loadRoomHistory(){ + const id=$('historyRoom').value;$('historySave').disabled=true;$('historyFields').replaceChildren();if(!id)return; + const settings=await api('/api/admin/history-settings?room_id='+encodeURIComponent(id)); + if($('historyRoom').value!==id)return;renderHistory('historyFields',settings);$('historySave').disabled=false; +} +$('historyRoom').onchange=()=>loadRoomHistory().catch(e=>$('historyStatus').textContent=e.message); +$('historySave').onclick=async()=>{const id=$('historyRoom').value;if(!id)return;try{await api('/api/admin/history-settings',{method:'POST',body:{room_id:Number(id),history:readHistory('historyFields')}});$('historyStatus').textContent='Saved. Reopen media views to refresh history.';}catch(e){$('historyStatus').textContent=e.message;}}; diff --git a/JS/app.js b/JS/app.js new file mode 100644 index 0000000..eb54f98 --- /dev/null +++ b/JS/app.js @@ -0,0 +1,4196 @@ +// Media volume starts at 50% (then remembers the viewer's own choice). +(function(){ + const KEY='kronic-media-volume', DEFAULT=0.5; + const read=()=>{try{const v=parseFloat(localStorage.getItem(KEY));return Number.isFinite(v)?Math.min(1,Math.max(0,v)):DEFAULT;}catch(_){return DEFAULT;}}; + const init=e=>{const el=e.target; if(!(el instanceof HTMLMediaElement)||el.dataset.kronicVolume)return; el.dataset.kronicVolume='1'; el.volume=read();}; + document.addEventListener('loadstart',init,true); + document.addEventListener('play',init,true); + document.addEventListener('volumechange',e=>{const el=e.target; if(!(el instanceof HTMLMediaElement)||!el.dataset.kronicVolume)return; try{localStorage.setItem(KEY,String(el.volume));}catch(_){}},true); +})(); +let currentSourceId = null; +let currentSourceName = null; +let currentSourceType = null; +let currentShowName = null; +let currentSeasonName = null; +let scanPollTimer = null; +let metadataSources = []; +let youtubePollTimer = null; +let cacheJobPollTimer = null; +let musicImportJobPollTimer = null; +const musicImportCompletedSeen = new Set(); +let musicImportJobsInitialized = false; +let twitchPollTimer = null; +let twitchPlayerOverlay = null; +let twitchVideoElement = null; +let twitchActiveChannel = null; +let twitchPlayerDragBound = false; +let mediaAuthContext = null; + +const librarySortStates = new Map(); + +function getSortState(key) { + if (!librarySortStates.has(key)) { + librarySortStates.set(key, {mode:"alpha", direction:"asc"}); + } + return librarySortStates.get(key); +} + +function dateAddedValue(item) { + const parsed = Date.parse(item?.added_at || ""); + return Number.isFinite(parsed) ? parsed : 0; +} + +function durationValue(item) { + return Math.max(0, Number(item?.duration_seconds) || 0); +} + +function compareText(a,b) { + return String(a||"").localeCompare( + String(b||""), + undefined, + {numeric:true,sensitivity:"base"} + ); +} + +function sortedMediaItems(items,key,titleGetter) { + const state=getSortState(key); + const direction=state.direction==="desc"?-1:1; + return [...items].sort((a,b)=>{ + let result=0; + if(state.mode==="date") result=dateAddedValue(a)-dateAddedValue(b); + else if(state.mode==="length") result=durationValue(a)-durationValue(b); + else result=compareText(titleGetter(a),titleGetter(b)); + if(result===0) result=compareText(titleGetter(a),titleGetter(b)); + return result*direction; + }); +} + +function sortedGroups(entries,key) { + const state=getSortState(key); + const direction=state.direction==="desc"?-1:1; + return [...entries].sort((a,b)=>{ + const [aName,aItems]=a; + const [bName,bItems]=b; + let result=0; + if(state.mode==="date"){ + result=Math.max(0,...aItems.map(dateAddedValue))-Math.max(0,...bItems.map(dateAddedValue)); + }else if(state.mode==="length"){ + result=aItems.reduce((sum,item)=>sum+durationValue(item),0)-bItems.reduce((sum,item)=>sum+durationValue(item),0); + }else result=compareText(aName,bName); + if(result===0) result=compareText(aName,bName); + return result*direction; + }); +} + +function formatDurationShort(seconds) { + seconds=Math.max(0,Math.round(Number(seconds)||0)); + if(!seconds)return"Unknown"; + const hours=Math.floor(seconds/3600); + const minutes=Math.floor((seconds%3600)/60); + return hours>0?`${hours}h ${minutes}m`:`${minutes}m`; +} + +function librarySortControls(key,rerender) { + const state=getSortState(key); + const wrapper=document.createElement("span"); + wrapper.className="library-sort-controls"; + wrapper.innerHTML=` + + `; + const mode=wrapper.querySelector(".library-sort-mode"); + const direction=wrapper.querySelector(".library-sort-direction"); + mode.value=state.mode; + direction.value=state.direction; + mode.addEventListener("change",()=>{state.mode=mode.value;rerender();}); + direction.addEventListener("change",()=>{state.direction=direction.value;rerender();}); + return wrapper; +} + + +function canManageMedia() { + return !!mediaAuthContext?.canManageMedia; +} + +function isPlatformAdmin() { + return !!mediaAuthContext?.isPlatformAdmin; +} + +const content = document.getElementById("content"); +const toolbar = document.getElementById("toolbar"); +const breadcrumb = document.getElementById("breadcrumb"); +const searchForm = document.getElementById("searchForm"); +const searchInput = document.getElementById("searchInput"); +const playerOverlay = document.getElementById("playerOverlay"); +const playerWindow = document.getElementById("playerWindow"); +const playerTitle = document.getElementById("playerTitle"); +const playerCloseButton = document.getElementById("playerCloseButton"); +const playerFullscreenButton = document.getElementById("playerFullscreenButton"); + +let mediaPlayer = null; +let activeMediaId = null; +let activeMediaTitle = null; +let playbackBaseOffset = 0; +let playbackSeekMode = "client"; +let playbackKnownDuration = null; +let playbackSaveTimer = null; +let pendingClientSeek = null; +let activePlaybackPlan = null; +let activePlaybackQuality = "original"; +let activePlaybackAudio = null; +let playbackFallbackUsed = false; +let playerHealthTimer = null; +let lastObservedPlayerTime = 0; +let lastPlayerAdvanceAt = 0; +let playerStatusElement = null; +let activeIptvChannel = null; +let iptvOverviewCache = null; + +let playerMinimized = false; +let playerRestoreGeometry = null; +let playerPreFullscreenGeometry = null; +let playerMinimizeButton = null; +let playerResizeHandles = []; + +// Native media and image requests cannot attach fetch headers. +function roomMediaUrl(value) { + if (!value || !document.body.dataset.roomId) return value; + let url; + try { url = new URL(value, location.origin); } catch (_) { return value; } + if (url.origin !== location.origin || !/^\/(api\/|thumbnail\/|play\/|stream\/|external\/)/.test(url.pathname)) return value; + url.searchParams.set("kronic_room", document.body.dataset.roomId); + return url.pathname + url.search + url.hash; +} +async function api(url, options = {}) { + options.credentials = "same-origin"; + if (document.body.dataset.roomId && String(url).startsWith("/api/")) { + options.headers = new Headers(options.headers || {}); + options.headers.set("X-Kronic-Room", document.body.dataset.roomId || ""); + } + const response = await fetch(url, options); + let data = null; + try { data = await response.json(); } catch { data = null; } + if (response.status === 401) { + window.location.replace("/login"); + throw new Error("Login required"); + } + if (!response.ok) throw new Error(data?.detail || data?.error || `HTTP ${response.status}`); + return data; +} + +function escapeHtml(value) { + if (value === null || value === undefined) return ""; + return String(value).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'"); +} +const escapeAttribute = escapeHtml; +function clearScanPolling() { if (scanPollTimer) { clearInterval(scanPollTimer); scanPollTimer = null; } } +function resetLibraryContext() { currentSourceId = currentSourceName = currentSourceType = currentShowName = currentSeasonName = null; updateSearchPlaceholder(); } +function showError(error) { content.innerHTML = `
Error

${escapeHtml(error?.message || error)}
`; } +function nullableNumber(value) { const t = String(value ?? "").trim(); if (!t) return null; const n = Number(t); return Number.isFinite(n) ? n : null; } +function mediaPathParts(item) { return String(item.relative_path || "").split(/[\\/]+/).filter(Boolean); } +function updateSearchPlaceholder() { searchInput.placeholder = currentSourceId === null ? "Search all media..." : `Search ${currentSourceName}...`; } + +function ensureInterfaceRefreshStyles() { + if (document.getElementById("interfaceRefreshStyles")) return; + const link = document.createElement("link"); + link.id = "interfaceRefreshStyles"; + link.rel = "stylesheet"; + link.href = "/CSS/interface_refresh.css?v=20261103-2"; + document.head.appendChild(link); +} + +function closeTopNavMenus() { + document.querySelectorAll("#mediaPrimaryNav details[open]").forEach(menu => { + menu.removeAttribute("open"); + }); +} + +function navAction(label, action, options={}) { + const button = document.createElement("button"); + button.type = "button"; + button.className = `top-nav-action${options.primary ? " primary" : ""}`; + button.textContent = label; + button.addEventListener("click", async event => { + event.preventDefault(); + closeTopNavMenus(); + await action(); + }); + return button; +} + +function navDropdown(label, items, active=false) { + const details = document.createElement("details"); + details.className = `top-nav-dropdown${active ? " active" : ""}`; + const summary = document.createElement("summary"); + summary.textContent = label; + details.appendChild(summary); + // Keep only one main navigation dropdown open at a time. + details.addEventListener("toggle", () => { + if (!details.open) return; + document.querySelectorAll("#mediaPrimaryNav details[open]").forEach(other => { + if (other !== details) other.open = false; + }); + }); + + const menu = document.createElement("div"); + menu.className = "top-nav-menu"; + for (const item of items) { + if (!item || item.hidden) continue; + const button = document.createElement("button"); + button.type = "button"; + button.textContent = item.label; + if (item.muted) button.classList.add("muted-action"); + button.addEventListener("click", async event => { + event.preventDefault(); + details.removeAttribute("open"); + await item.action(); + }); + menu.appendChild(button); + } + details.appendChild(menu); + return details; +} + +function getTopNavHost() { + const existing = document.getElementById("mediaPrimaryNav"); + if (existing?.parentElement) return existing.parentElement; + + const anchor = document.getElementById("librariesButton") + || document.getElementById("manageButton") + || document.getElementById("addLibraryButton") + || document.getElementById("searchForm"); + return anchor?.parentElement || document.querySelector("header"); +} + +function cleanLegacyTopNav() { + ["librariesButton","manageButton","metadataButton","addLibraryButton","mediaAccountNav","mediaPrimaryNav"] + .forEach(id => document.getElementById(id)?.remove()); +} + +// Browser-local preference; the server selects the frontend on the next request. +function getInterfacePreference() { + const entry = document.cookie.split(';').map(v => v.trim()).find(v => v.startsWith('kronic_interface=')); + const mode = entry ? entry.slice('kronic_interface='.length) : 'auto'; + return ['auto', 'desktop', 'mobile'].includes(mode) ? mode : 'auto'; +} +function setInterfacePreference(mode) { + if (!['auto', 'desktop', 'mobile'].includes(mode)) return false; + if (!window.confirm('Switch interface? This reloads Kronic and may disconnect your voice room or interrupt playback.')) return false; + document.cookie = 'kronic_interface=' + mode + '; Path=/; Max-Age=31536000; SameSite=Lax' + (location.protocol === 'https:' ? '; Secure' : ''); + if (getInterfacePreference() !== mode) { + alert('Could not save the interface preference. Check browser cookie settings.'); + return false; + } + window.location.assign('/' + location.search); + return true; +} + +function buildAccountNav() { + const wrap = document.createElement("span"); + wrap.id = "mediaAccountNav"; + wrap.className = "media-account-nav"; + + const name = document.createElement("span"); + name.className = "media-account-name"; + name.textContent = mediaAuthContext?.user?.username || "Account"; + wrap.appendChild(name); + + const identity = String(mediaAuthContext?.user?.username || 'guest').toLowerCase(); + const homeKey = 'kronic.start-view.v1.' + identity; + const groupRoles = (mediaAuthContext?.groups || []).map(group => String(group.role || '').toLowerCase()); + const canModerate = groupRoles.some(role => ['owner', 'admin', 'moderator'].includes(role)); + wrap.appendChild(navDropdown("Account", [ + {label: "Switch room", action: switchAssignedRoom}, + {label: "Rename room title", action: renameSelectedRoom, hidden: !isPlatformAdmin() && document.body.dataset.roomOwner !== 'true'}, + {label: "Start in Room", action: () => { localStorage.setItem(homeKey, 'room'); window.location.reload(); }}, + {label: "Start in Media Library", hidden: !mediaAuthContext?.hasMediaAccess, action: () => { localStorage.setItem(homeKey, 'libraries'); window.location.reload(); }}, + ...[['auto', 'Automatic'], ['desktop', 'Desktop'], ['mobile', 'Mobile']].map(([mode, label]) => ({ + label: (getInterfacePreference() === mode ? '✓ ' : '') + 'Interface: ' + label, + action: () => setInterfacePreference(mode) + })), + {label: "Admin", hidden: !isPlatformAdmin(), action: () => {window.location.href="/admin";}}, + {label: "Logout", action: async () => { + try {await fetch("/api/auth/logout",{method:"POST",credentials:"same-origin"});} catch {} + window.location.replace("/login"); + }} + ])); + return wrap; +} + +function installTopNav(mode="home", options={}) { + const host = getTopNavHost(); + if (!host) return; + cleanLegacyTopNav(); + + const nav = document.createElement("nav"); + nav.id = "mediaPrimaryNav"; + nav.className = `media-primary-nav media-primary-nav-${mode}`; + + if (!mediaAuthContext?.hasMediaAccess) { /* Communication-only account: keep Account navigation. */ } else if (mode === "library") { + // Compact library actions live in one menu, rather than spanning the header. + + const title = document.createElement("span"); + title.className = "top-nav-context-title"; + title.textContent = currentSourceName || "Library"; + nav.appendChild(title); + + if (canManageMedia()) { + nav.appendChild(navDropdown("Library actions", [ + {label:"Scan library",action:()=>scanOneLibrary(currentSourceId)}, + {label:"Edit metadata",action:()=>showMetadataEditor(currentSourceId)}, + {label:"Manage library",action:()=>showManageLibraries(currentSourceId)}, + {label:"Back to libraries",action:options.backHandler || showLibraries} + ])); + } + + if (options.sortKey && options.rerender) { + const sortWrap = document.createElement("span"); + sortWrap.className = "top-nav-sort"; + sortWrap.appendChild(librarySortControls(options.sortKey, options.rerender)); + nav.appendChild(sortWrap); + } + } else { + nav.appendChild(navDropdown("Libraries", [ + {label:"Local", action:showLibraries}, + {label:"Manage", action:showManageLibraries, hidden:!canManageMedia()}, + {label:"Add Library", action:()=>showFolderBrowser("/"), hidden:!canManageMedia()}, + {label:"Scan", action:showScanDialog, hidden:!canManageMedia()}, + ], mode === "home")); + + nav.appendChild(navDropdown("Metadata", [ + {label:"Edit Metadata", action:()=>showMetadataEditor()}, + {label:"Add / Override Metadata", action:()=>showMetadataEditor()}, + {label:"New / Re-analyze Metadata", action:()=>showMetadataEditor()}, + ], mode === "metadata")); + + nav.appendChild(navDropdown("Live", [ + {label:"Tube", action:showTubeSettings}, + {label:"Twitch", action:showTwitchSettings}, + {label:"IPTV", action:showIptvSettings}, + ], mode === "tube" || mode === "twitch" || mode === "iptv")); + } + + // Only expose administrative entry points when the authenticated role allows them. + if (isPlatformAdmin()) { + nav.appendChild(navAction('⚙ Admin', () => { window.location.href = '/admin'; })); + } + nav.appendChild(buildAccountNav()); + // Preserve the native per-view back handler without a redundant topbar button. + ensureKronicBackButton(options); + document.getElementById("kronicSiteBack").hidden = true; + ensureKronicSearchToggle(); + + const search = document.getElementById("searchForm"); + if (search && search.parentElement === host) host.insertBefore(nav, search); + else host.appendChild(nav); +} + +// Keep search/back together in a dedicated header utility area instead of floating over menus. +function ensureKronicHeaderTools() { + const host = document.querySelector("header .topbar-left") || document.querySelector("header"); + if (!host) return null; + let tools = document.getElementById("kronicHeaderTools"); + if (!tools) { + tools = document.createElement("div"); + tools.id = "kronicHeaderTools"; + tools.className = "kronic-header-tools"; + } + const title = host.querySelector(".site-title"); + if (title && title.parentElement === host) title.insertAdjacentElement("afterend", tools); + else if (tools.parentElement !== host) host.prepend(tools); + return tools; +} + +// Compact, shared search for desktop and mobile. Keep the original form/API intact. +function ensureKronicSearchToggle() { + const form = document.getElementById("searchForm"); + if (!form) return; + form.classList.add("kronic-search-popover"); + let toggle = document.getElementById("kronicSiteSearch"); + if (!toggle) { + toggle = document.createElement("button"); + toggle.id = "kronicSiteSearch"; + toggle.type = "button"; + toggle.textContent = "⌕"; + toggle.title = "Search media"; + toggle.setAttribute("aria-label", "Open search"); + toggle.setAttribute("aria-expanded", "false"); + (ensureKronicHeaderTools() || document.body).appendChild(toggle); + } + ensureKronicHeaderTools()?.appendChild(toggle); + const submit = form.querySelector('button[type="submit"],button:not([type])'); + if (submit) { + submit.textContent = "➜"; + submit.title = "Submit search"; + submit.setAttribute("aria-label", "Submit search"); + } + function closeSearch() { + form.classList.remove("kronic-search-open"); + toggle.setAttribute("aria-expanded", "false"); + } + toggle.onclick = () => { + const open = form.classList.toggle("kronic-search-open"); + toggle.setAttribute("aria-expanded", String(open)); + if (open) { + closeTopNavMenus(); + searchInput.focus(); + } + }; + if (!form.dataset.kronicSearchBound) { + form.dataset.kronicSearchBound = "1"; + form.addEventListener("submit", closeSearch); + document.addEventListener("keydown", event => { + if (event.key === "Escape") closeSearch(); + }); + document.addEventListener("pointerdown", event => { + if (!form.contains(event.target) && !document.getElementById("kronicSiteSearch")?.contains(event.target)) closeSearch(); + }); + } +} + +// Back control is independent of rebuilt navigation elements. +// The app is a single-page renderer, so prefer the library-provided back handler. +function ensureKronicBackButton(options={}) { + let button=document.getElementById("kronicSiteBack"); + if(!button){ + button=document.createElement("button"); + button.id="kronicSiteBack"; + button.type="button"; + button.textContent="←"; + button.title="Back"; + button.setAttribute("aria-label","Go back"); + (ensureKronicHeaderTools() || document.body).appendChild(button); + } + ensureKronicHeaderTools()?.appendChild(button); + button.onclick=async()=>{ + if(document.getElementById("youtubePlayerOverlay")?.classList.contains("active")) { + await closeYouTubePlayer();return; + } + if(document.getElementById("playerOverlay")?.classList.contains("active")) { + await closePlayer();return; + } + const handler=options.backHandler || showLibraries; + await handler(); + }; +} + +function installMobileVideoBack(win, close) { + if(!win || win.querySelector(".kronic-video-back"))return; + const header=win.querySelector(".player-header,.youtube-player-header"); + if(!header)return; + const btn=document.createElement("button"); + btn.type="button"; + btn.className="kronic-video-back"; + btn.textContent="←"; + btn.setAttribute("aria-label","Back to library"); + btn.title="Back to library"; + btn.onclick=(event)=>{event.stopPropagation();close();}; + header.appendChild(btn); +} + +function setupNavigation() { + document.getElementById("homeButton")?.addEventListener("click", event => { + event.preventDefault(); + if (mediaAuthContext?.hasMediaAccess) showLibraries(); + }); + installTopNav("home"); +} + +async function showTubeSettings() { + await showYouTubeLibrary(); + installTopNav("tube"); +} + +async function showTwitchSettings() { + await showTwitchLibrary(); + installTopNav("twitch"); +} + +async function showIptvSettings() { + await showIptvLibrary("settings"); +} + +function detectPlaybackBrowser() { + const ua = navigator.userAgent || ""; + if (/Firefox\//i.test(ua)) return "firefox"; + if (/Edg\//i.test(ua)) return "edge"; + if (/Chrome\//i.test(ua) || /Chromium\//i.test(ua)) return "chrome"; + if (/Safari\//i.test(ua) && !/Chrome|Chromium|Edg/i.test(ua)) return "safari"; + return "unknown"; +} + +function canPlayMime(mime) { + const probe = document.createElement("video"); + const result = probe.canPlayType(mime); + return result === "probably" || result === "maybe"; +} + +function getPlaybackCapabilities() { + return { + browser: detectPlaybackBrowser(), + h264: canPlayMime('video/mp4; codecs="avc1.640028, mp4a.40.2"'), + av1: canPlayMime('video/mp4; codecs="av01.0.08M.08, mp4a.40.2"'), + hevc: canPlayMime('video/mp4; codecs="hvc1.1.6.L120.B0, mp4a.40.2"'), + webm_vp9: canPlayMime('video/webm; codecs="vp9,opus"'), + webm_av1: canPlayMime('video/webm; codecs="av01.0.08M.08,opus"'), + }; +} + +function playbackCapabilityQuery(forceCompat=false, quality=activePlaybackQuality, audio=activePlaybackAudio) { + const caps = getPlaybackCapabilities(); + return new URLSearchParams({ + browser: caps.browser, + h264: caps.h264 ? "1" : "0", + av1: caps.av1 ? "1" : "0", + hevc: caps.hevc ? "1" : "0", + webm_vp9: caps.webm_vp9 ? "1" : "0", + webm_av1: caps.webm_av1 ? "1" : "0", + force_compat: forceCompat ? "1" : "0", + quality: quality || "original", + audio: audio === null || audio === undefined ? "" : String(audio), + }); +} + +async function getPlaybackPlan(mediaId, forceCompat=false) { + const params = playbackCapabilityQuery(forceCompat); + return await api(`/api/media/${mediaId}/playback-plan?${params.toString()}`); +} + +function ensurePlayerStatusElement() { + if (playerStatusElement?.isConnected) return playerStatusElement; + if (!playerWindow) return null; + playerStatusElement = document.createElement("div"); + playerStatusElement.id = "playerPlaybackStatus"; + playerStatusElement.className = "player-playback-status"; + playerStatusElement.hidden = true; + const video = document.getElementById("mediaPlayerFrame"); + if (video?.parentElement) video.parentElement.insertBefore(playerStatusElement, video); + else playerWindow.appendChild(playerStatusElement); + return playerStatusElement; +} + +function showPlayerStatus(message, kind="info") { + const status = ensurePlayerStatusElement(); + if (!status) return; + status.textContent = message || ""; + status.dataset.kind = kind; + status.hidden = !message; +} + +function hidePlayerStatus() { + if (!playerStatusElement) return; + playerStatusElement.hidden = true; + playerStatusElement.textContent = ""; + playerStatusElement.dataset.kind = ""; +} + +function playbackModeDescription(plan) { + if (!plan) return "Preparing playback…"; + if (plan.mode === "direct") return "Direct browser playback"; + if (plan.mode === "remux_stream") return "Browser compatibility remux: video copy + AAC audio"; + if (plan.mode === "remux_cache") return plan.cache?.cached ? "Using cached browser-compatible MP4" : "Preparing browser-compatible playback…"; + if (plan.mode === "transcode_stream") return "Live compatibility transcode: H.264 + AAC"; + return "Preparing playback…"; +} + +function resetPlayerHealth() { + if (playerHealthTimer) clearTimeout(playerHealthTimer); + playerHealthTimer = null; + lastObservedPlayerTime = Number(mediaPlayer?.currentTime) || 0; + lastPlayerAdvanceAt = performance.now(); +} + +function observePlayerProgress() { + const current = Number(mediaPlayer?.currentTime) || 0; + if (current > lastObservedPlayerTime + 0.15) { + lastObservedPlayerTime = current; + lastPlayerAdvanceAt = performance.now(); + hidePlayerStatus(); + } +} + +function schedulePlaybackHealthCheck(reason) { + if (!mediaPlayer || (!activeMediaId && !activeIptvChannel)) return; + if (playerHealthTimer) clearTimeout(playerHealthTimer); + const snapshot = Number(mediaPlayer.currentTime) || 0; + const mediaError = mediaPlayer.error; + const errorDetail = mediaError + ? ` (code ${mediaError.code}${mediaError.message ? `: ${mediaError.message}` : ""})` + : ""; + showPlayerStatus( + reason === "error" + ? `Browser reported a media error${errorDetail}; checking whether playback actually stopped…` + : "Buffering…" + ); + playerHealthTimer = setTimeout(async () => { + playerHealthTimer = null; + if (!mediaPlayer || (!activeMediaId && !activeIptvChannel)) return; + const current = Number(mediaPlayer.currentTime) || 0; + const advanced = current > snapshot + 0.25; + if (advanced || (!mediaPlayer.paused && performance.now() - lastPlayerAdvanceAt < 5000)) { + hidePlayerStatus(); + return; + } + if (!playbackFallbackUsed) { + playbackFallbackUsed = true; + showPlayerStatus("Playback stopped. Retrying compatibility playback…", "warning"); + try { + if (activeIptvChannel) { + await beginIptvPlayback(activeIptvChannel, true); + return; + } + const resumeAt = getAbsolutePlaybackPosition(); + activePlaybackPlan = await getPlaybackPlan(activeMediaId, true); + playbackSeekMode = activePlaybackPlan.seek_mode || "client"; + await beginPlayback(resumeAt, true); + return; + } catch (error) { + console.warn("Compatibility playback retry failed:", error); + } + } + showPlayerStatus( + activeIptvChannel + ? "Live channel stopped. Try the channel again; the upstream stream may be offline." + : "Browser playback stopped. Try External to open this item in VLC or mpv.", + "error" + ); + }, 10000); +} + +function setupVideoPlayer() { + const oldFrame = document.getElementById("mediaPlayerFrame"); + if (!oldFrame) return; + mediaPlayer = document.createElement("video"); + mediaPlayer.id = "mediaPlayerFrame"; + mediaPlayer.className = oldFrame.className || "media-player-frame"; + mediaPlayer.controls = true; + mediaPlayer.autoplay = true; + mediaPlayer.playsInline = true; + mediaPlayer.preload = "metadata"; + oldFrame.replaceWith(mediaPlayer); + ensurePlayerStatusElement(); + mediaPlayer.addEventListener("loadedmetadata", handlePlayerLoadedMetadata); + mediaPlayer.addEventListener("play", () => { startPlaybackSaveTimer(); resetPlayerHealth(); }); + mediaPlayer.addEventListener("playing", () => { resetPlayerHealth(); hidePlayerStatus(); }); + mediaPlayer.addEventListener("timeupdate", observePlayerProgress); + mediaPlayer.addEventListener("waiting", () => schedulePlaybackHealthCheck("waiting")); + mediaPlayer.addEventListener("stalled", () => schedulePlaybackHealthCheck("stalled")); + mediaPlayer.addEventListener("error", () => schedulePlaybackHealthCheck("error")); + mediaPlayer.addEventListener("pause", saveCurrentPlaybackProgress); + mediaPlayer.addEventListener("ended", handlePlaybackEnded); +} + +async function getSavedPlaybackProgress(mediaId) { + try { return await api(`/api/media/${mediaId}/progress`); } + catch { return {position_seconds:0, duration_seconds:null, completed:false, seek_mode:"client"}; } +} + +async function openPlayer(mediaId, title, options={}) { + if (!mediaPlayer) return; + await saveCurrentPlaybackProgress(); + stopPlaybackSaveTimer(); + resetPlayerHealth(); + mediaPlayer.pause(); + mediaPlayer.removeAttribute("src"); + mediaPlayer.load(); + activeMediaId = Number(mediaId); + activeMediaTitle = title || "Media Player"; + activePlaybackQuality = options.quality || "original"; + activePlaybackAudio = options.audio === "" || options.audio === undefined ? null : Number(options.audio); + playbackBaseOffset = 0; + pendingClientSeek = null; + playbackFallbackUsed = false; + activePlaybackPlan = null; + playerTitle.textContent = activeMediaTitle; + installMobileVideoBack(playerWindow,()=>closePlayer()); + playerOverlay.classList.add("active"); + playerOverlay.setAttribute("aria-hidden", "false"); + document.body.classList.add("player-open"); + playerWindow?.classList.remove("player-minimized"); + playerMinimized=false; + updateMinimizeButton(); + prepareFloatingPlayerPosition(); + showPlayerStatus("Selecting the best playback mode for this browser…"); + const [progress, plan] = await Promise.all([ + options.roomSync ? Promise.resolve({position_seconds:0,completed:true,seek_mode:"client"}) : getSavedPlaybackProgress(activeMediaId), + getPlaybackPlan(activeMediaId, false), + ]); + activePlaybackPlan = plan; + playbackSeekMode = plan.seek_mode || progress.seek_mode || "client"; + playbackKnownDuration = Number(progress.duration_seconds) || null; + showPlayerStatus(playbackModeDescription(plan)); + const saved = Number(progress.position_seconds) || 0; + const duration = Number(progress.duration_seconds) || 0; + let offer = !progress.completed && saved >= 30; + if (duration > 0 && (duration - saved <= 300 || saved / duration >= 0.95)) offer = false; + let resume = 0; + if (offer) { + const ok = window.confirm(`Resume "${activeMediaTitle}" from ${formatPlaybackTime(saved)}?\n\nOK = Resume\nCancel = Start Over`); + if (ok) resume = saved; + else await resetPlaybackProgress(activeMediaId); + } + if (options.roomSync) resume = Math.max(0, Number(options.startPosition) || 0); + await beginPlayback(resume, false); +} + +async function beginPlayback(startSeconds, forceCompat=false) { + startSeconds = Math.max(0, Number(startSeconds) || 0); + playbackBaseOffset = 0; + pendingClientSeek = null; + if (forceCompat || !activePlaybackPlan) { + activePlaybackPlan = await getPlaybackPlan(activeMediaId, forceCompat); + playbackSeekMode = activePlaybackPlan.seek_mode || "client"; + } + showPlayerStatus(playbackModeDescription(activePlaybackPlan)); + const params = playbackCapabilityQuery(forceCompat); + if (playbackSeekMode === "server" && startSeconds > 0) { + playbackBaseOffset = startSeconds; + params.set("start", String(startSeconds)); + } else if (startSeconds > 0) { + pendingClientSeek = startSeconds; + } + mediaPlayer.src = roomMediaUrl(`/play/${activeMediaId}?${params.toString()}`); + mediaPlayer.load(); + mediaPlayer.play().catch(error => console.debug("mediaPlayer.play() did not start immediately:", error)); +} + +function handlePlayerLoadedMetadata() { + if ((!playbackKnownDuration || playbackKnownDuration <= 0) && Number.isFinite(mediaPlayer.duration) && mediaPlayer.duration > 0) playbackKnownDuration = mediaPlayer.duration; + if (pendingClientSeek !== null && playbackSeekMode === "client") { try { mediaPlayer.currentTime = pendingClientSeek; } catch {} pendingClientSeek = null; } +} +function getAbsolutePlaybackPosition() { const local = Number(mediaPlayer?.currentTime) || 0; return playbackSeekMode === "server" ? playbackBaseOffset + local : local; } +function startPlaybackSaveTimer() { stopPlaybackSaveTimer(); playbackSaveTimer = setInterval(saveCurrentPlaybackProgress, 10000); } +function stopPlaybackSaveTimer() { if (playbackSaveTimer) { clearInterval(playbackSaveTimer); playbackSaveTimer = null; } } + +async function saveCurrentPlaybackProgress() { + if (!activeMediaId || !mediaPlayer) return; + const position = getAbsolutePlaybackPosition(); if (position < 2) return; + let duration = playbackKnownDuration; + if ((!duration || duration <= 0) && Number.isFinite(mediaPlayer.duration) && mediaPlayer.duration > 0) duration = mediaPlayer.duration; + const completed = !!(duration && duration > 0 && ((duration - position) <= 300 || position / duration >= 0.95)); + try { await api(`/api/media/${activeMediaId}/progress`, {method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({position_seconds:position, duration_seconds:duration, completed})}); } catch {} +} + +async function handlePlaybackEnded() { + stopPlaybackSaveTimer(); if (!activeMediaId) return; + const duration = playbackKnownDuration || (Number.isFinite(mediaPlayer.duration) ? mediaPlayer.duration : null); + try { await api(`/api/media/${activeMediaId}/progress`, {method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({position_seconds:duration || getAbsolutePlaybackPosition(), duration_seconds:duration, completed:true})}); } catch {} +} +async function resetPlaybackProgress(mediaId) { try { await api(`/api/media/${mediaId}/progress`, {method:"DELETE"}); } catch {} } + +async function closePlayer() { + stopPlaybackSaveTimer(); await saveCurrentPlaybackProgress(); + if (document.fullscreenElement === playerWindow) { try { await document.exitFullscreen(); } catch {} } + mediaPlayer?.pause(); mediaPlayer?.removeAttribute("src"); mediaPlayer?.load(); playerOverlay.classList.remove("active"); playerOverlay.setAttribute("aria-hidden", "true"); document.body.classList.remove("player-open"); + activeMediaId = activeMediaTitle = null; + activeIptvChannel = null; + playbackBaseOffset = 0; + playbackKnownDuration = null; + pendingClientSeek = null; + activePlaybackPlan = null; + playbackFallbackUsed = false; + playerMinimized = false; + playerRestoreGeometry = null; + playerPreFullscreenGeometry = null; + playerWindow?.classList.remove("player-minimized"); + updateMinimizeButton(); + resetPlayerHealth(); + hidePlayerStatus(); + + // Only a real Close/Stop destroys the media element. + setupVideoPlayer(); +} +function capturePlayerGeometry() { + if (!playerWindow || window.innerWidth <= 760) return null; + const r = playerWindow.getBoundingClientRect(); + return {left:r.left, top:r.top, width:r.width, height:r.height}; +} +function applyPlayerGeometry(g) { + if (!playerWindow || !g || window.innerWidth <= 760) return; + const w=Math.max(360,Math.min(window.innerWidth-12,Number(g.width)||720)); + const h=Math.max(220,Math.min(window.innerHeight-12,Number(g.height)||440)); + playerWindow.style.width=`${w}px`; playerWindow.style.height=`${h}px`; + playerWindow.style.left=`${Math.max(0,Math.min(Number(g.left)||0,window.innerWidth-80))}px`; + playerWindow.style.top=`${Math.max(0,Math.min(Number(g.top)||0,window.innerHeight-50))}px`; + playerWindow.classList.add("floating-player-positioned"); +} +function updateMinimizeButton() { + if (!playerMinimizeButton) return; + playerMinimizeButton.textContent=playerMinimized?"Restore":"Minimize"; +} +function minimizePlayer() { + if (!playerWindow || playerMinimized) return; + playerRestoreGeometry=capturePlayerGeometry(); + playerMinimized=true; playerWindow.classList.add("player-minimized"); updateMinimizeButton(); + if (window.innerWidth>760) { + const w=Math.min(520,Math.max(320,playerRestoreGeometry?.width||420)); + playerWindow.style.width=`${w}px`; playerWindow.style.height=""; + playerWindow.style.left=`${Math.max(8,window.innerWidth-w-18)}px`; + playerWindow.style.top=`${Math.max(8,window.innerHeight-66)}px`; + playerWindow.classList.add("floating-player-positioned"); + } +} +function restorePlayer() { + if (!playerWindow || !playerMinimized) return; + playerMinimized=false; playerWindow.classList.remove("player-minimized"); updateMinimizeButton(); + if (window.innerWidth>760 && playerRestoreGeometry) applyPlayerGeometry(playerRestoreGeometry); +} +function togglePlayerMinimized(){ playerMinimized?restorePlayer():minimizePlayer(); } +async function togglePlayerFullscreen() { + if (!playerWindow) return; + try { + if (document.fullscreenElement===playerWindow) return await document.exitFullscreen(); + if (playerMinimized) restorePlayer(); + playerPreFullscreenGeometry=capturePlayerGeometry(); + await playerWindow.requestFullscreen(); + } catch(e){ console.debug("Fullscreen request failed:",e); } +} +function updateFullscreenButton() { + const fs=document.fullscreenElement===playerWindow; + if (playerFullscreenButton) playerFullscreenButton.textContent=fs?"Exit Fullscreen":"Fullscreen"; + if (!fs && playerPreFullscreenGeometry && !playerMinimized) { + applyPlayerGeometry(playerPreFullscreenGeometry); playerPreFullscreenGeometry=null; + } +} +function formatPlaybackTime(seconds) { seconds = Math.max(0, Math.floor(Number(seconds)||0)); const h=Math.floor(seconds/3600), m=Math.floor((seconds%3600)/60), s=seconds%60; return h>0 ? `${h}:${String(m).padStart(2,"0")}:${String(s).padStart(2,"0")}` : `${m}:${String(s).padStart(2,"0")}`; } + +playerCloseButton?.addEventListener("click", closePlayer); +playerFullscreenButton?.addEventListener("click", togglePlayerFullscreen); +document.addEventListener("fullscreenchange", updateFullscreenButton); +document.addEventListener("keydown", e => { + if (e.key !== "Escape") return; + if (document.getElementById("metadataInfoOverlay")) return closeMetadataInfo(); + if (document.getElementById("scanDialogOverlay")) return closeScanDialog(); +}); + +searchForm.addEventListener("submit", async e => { e.preventDefault(); const q = searchInput.value.trim(); if (!q) return currentSourceId !== null ? showLibrary(currentSourceId,currentSourceName,currentSourceType) : showLibraries(); await performSearch(q); }); + +function mosaicHtml(urls, fallback="MEDIA") { + const safe = (urls || []).filter(Boolean).slice(0, 6); + if (!safe.length) { + return `
${escapeHtml(fallback)}
`; + } + return `
${safe.map(url => `
`).join("")}
`; +} + +function homeModuleCard({id, title, badge, subtitle, count, urls, extraClass="", actionName=""}) { + return `
+ ${mosaicHtml(urls, badge || title)} +
+
+
+

${escapeHtml(title)}

+ ${badge ? `${escapeHtml(badge)}` : ""} +
+
${escapeHtml(subtitle || "")}
+
${escapeHtml(count || "")}
+
+
`; +} + +function bindHomeModule(id, action) { + const node = document.getElementById(id); + if (!node) return; + node.addEventListener("click", action); + node.addEventListener("keydown", event => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + action(); + } + }); +} + +async function showLibraries() { + clearScanPolling(); + resetLibraryContext(); + breadcrumb.innerHTML = ""; + toolbar.innerHTML = ""; + installTopNav("home"); + content.innerHTML = `
Loading your media…
`; + + try { + const sources = await api("/api/sources"); + + const sampleResults = await Promise.all( + sources.map(async source => { + try { + return await api(`/api/sources/${source.id}/samples?limit=6`); + } catch { + return []; + } + }) + ); + + const [youtubeHistory, musicOverview, twitchOverview, iptvOverview] = await Promise.all([ + api("/api/youtube/history?limit=6").catch(() => ({items:[]})), + api("/api/music/overview?limit=6").catch(() => ({tracks:[]})), + api("/api/twitch/overview").catch(() => ({channels:[],recordings:[]})), + api("/api/iptv/overview").catch(() => ({channels:[]})), + ]); + + const localCards = sources.map((source, index) => { + const samples = sampleResults[index] || []; + return homeModuleCard({ + id:`library-card-${source.id}`, + title:source.name, + badge:source.library_type === "shows" ? "TV Shows" : "Movies", + subtitle:`${source.paths?.length || 0} folder${(source.paths?.length || 0) === 1 ? "" : "s"}`, + count:`${source.media_count || 0} items`, + urls:samples.map(item => roomMediaUrl(`/thumbnail/${item.id}`)), + extraClass:"local-library-module", + actionName:`Open ${source.name}`, + }); + }).join(""); + + const tubeItems = youtubeHistory?.items || []; + const tubeCard = homeModuleCard({ + id:"homeTubeModule", + title:"Tube", + badge:"Stream", + subtitle:"Search, watch and cached history", + count:tubeItems.length ? `${tubeItems.length} recent items` : "YouTube streaming", + urls:tubeItems.map(item => item.thumbnail_url || item.thumbnail), + extraClass:"tube-module", + actionName:"Open Tube", + }); + + const musicTracks = musicOverview?.tracks || []; + const musicCard = homeModuleCard({ + id:"homeMusicModule", + title:"Music", + badge:"Audio", + subtitle:"Spotify catalog + Kronic audio", + count:musicTracks.length ? `${musicTracks.length} track${musicTracks.length === 1 ? "" : "s"}` : "Import Spotify music", + urls:musicTracks.map(item => item.cover_url).filter(Boolean), + extraClass:"music-module", + actionName:"Open Music", + }); + + const twitchChannels = twitchOverview?.channels || []; + const twitchLive = twitchChannels.filter(channel => Boolean(Number(channel.live || 0))); + const twitchCard = homeModuleCard({ + id:"homeTwitchModule", + title:"Twitch", + badge:twitchLive.length ? "LIVE" : "Stream", + subtitle:"Saved Twitch channels and DVR", + count:twitchChannels.length + ? `${twitchChannels.length} channel${twitchChannels.length === 1 ? "" : "s"} · ${twitchLive.length} live` + : "Add Twitch channels", + urls:[], + extraClass:"twitch-module", + actionName:"Open Twitch", + }); + + const iptvChannels = iptvOverview?.channels || []; + const iptvCard = homeModuleCard({ + id:"homeIptvModule", + title:"IPTV", + badge:"LIVE", + subtitle:"Curated live channels and playlists", + count:`${iptvChannels.length} channel${iptvChannels.length === 1 ? "" : "s"}`, + urls:iptvChannels.map(item => item.tvg_logo).filter(Boolean), + extraClass:"iptv-module", + actionName:"Open IPTV", + }); + + content.innerHTML = ` +
+
+
+

Media

+
Libraries, Tube and live TV in one place.
+
+
+
${localCards}${tubeCard}${musicCard}${twitchCard}${iptvCard}
+
`; + + sources.forEach(source => { + bindHomeModule(`library-card-${source.id}`, () => showLibrary(source.id, source.name, source.library_type)); + }); + bindHomeModule("homeTubeModule", showYouTubeLibrary); + bindHomeModule("homeMusicModule", showMusicLibrary); + bindHomeModule("homeTwitchModule", showTwitchLibrary); + bindHomeModule("homeIptvModule", showIptvLibrary); + startScanPolling(); + } catch (error) { + showError(error); + } +} + +async function showScanDialog(){ + try{ + const st=await api("/api/scan/status"); if(st.running) return alert("A library scan is already running."); + const sources=(await api("/api/sources")).filter(s=>s.enabled); if(!sources.length) return alert("There are no enabled libraries to scan."); + closeScanDialog(); const overlay=document.createElement("div"); overlay.id="scanDialogOverlay"; overlay.className="scan-dialog-overlay"; + overlay.innerHTML=`

Scan Libraries

${sources.map(s=>``).join("")}
`; + document.body.appendChild(overlay); overlay.onclick=e=>{if(e.target===overlay)closeScanDialog();}; + document.getElementById("closeScanDialogButton").onclick=closeScanDialog; document.getElementById("cancelScanButton").onclick=closeScanDialog; document.getElementById("selectAllScanButton").onclick=()=>setAllScanSelections(true); document.getElementById("clearAllScanButton").onclick=()=>setAllScanSelections(false); document.getElementById("startSelectedScanButton").onclick=startSelectedLibraryScan; + }catch(e){alert(e.message);} +} +function closeScanDialog(){document.getElementById("scanDialogOverlay")?.remove();} +function setAllScanSelections(v){document.querySelectorAll(".scan-library-checkbox").forEach(c=>c.checked=v);} +async function startSelectedLibraryScan(){const ids=[...document.querySelectorAll(".scan-library-checkbox:checked")].map(c=>Number(c.value)); if(!ids.length)return alert("Select at least one library."); const mode=document.getElementById("scanMode")?.value||"quick"; closeScanDialog(); await startLibraryScan(ids,mode);} +async function scanOneLibrary(id,mode="quick"){await startLibraryScan([Number(id)],mode);} +// Standalone scan monitor: remains visible regardless of the selected media window. +let activeScanMonitorTimer = null; +let scanMonitorWasRunning = false; +function ensureScanMonitor(){ + if(document.getElementById("kronicScanMonitor"))return document.getElementById("kronicScanMonitor"); + if(!document.getElementById("kronicScanMonitorStyles")){ + const style=document.createElement("style");style.id="kronicScanMonitorStyles"; + style.textContent=`#kronicScanMonitor{position:fixed;right:16px;bottom:76px;width:min(440px,calc(100vw - 24px));max-height:60vh;overflow:auto;z-index:2147483000;color:#e7edf7;background:#172332;border:1px solid #46627d;border-radius:12px;box-shadow:0 10px 35px #0009;padding:14px;font:14px system-ui,sans-serif}#kronicScanMonitor .scan-monitor-top{display:flex;justify-content:space-between;align-items:center;gap:10px}#kronicScanMonitor button{border:1px solid #536980;color:#e7edf7;background:#273b50;border-radius:6px;padding:5px 9px;cursor:pointer}#kronicScanMonitor .scan-monitor-item{border-top:1px solid #354659;margin-top:10px;padding-top:10px}#kronicScanMonitor .scan-monitor-track{height:9px;background:#303e50;border-radius:12px;overflow:hidden;margin-top:6px}#kronicScanMonitor .scan-monitor-fill{height:100%;background:#5a89ff;transition:width .3s}#kronicScanMonitor .scan-monitor-muted{color:#acbad0;font-size:12px;overflow-wrap:anywhere}#kronicScanMonitor .scan-monitor-warning{color:#ffc375;overflow-wrap:anywhere;margin-top:6px}@media(max-width:760px){#kronicScanMonitor{bottom:86px;right:8px;width:calc(100vw - 16px);max-height:45vh}}`; + document.head.appendChild(style); + } + const panel=document.createElement("aside");panel.id="kronicScanMonitor";panel.setAttribute("role","status");panel.setAttribute("aria-live","polite"); + panel.innerHTML='
Library scan
Checking scan status…
'; + document.body.appendChild(panel); + panel.querySelector("#kronicScanMonitorClose").onclick=()=>{panel.remove();if(activeScanMonitorTimer){clearInterval(activeScanMonitorTimer);activeScanMonitorTimer=null;}}; + return panel; +} +function renderScanMonitor(state){ + const panel=document.getElementById("kronicScanMonitor");if(!panel)return; + const items=Object.values(state.libraries||{}); + const stage=state.running?"Scanning in background…":(state.completed_at?"Scan finished":"Scan starting…"); + const lines=items.map(st=>{ + const percent=Math.max(0,Math.min(100,Number(st.percent)||0)); + const warnings=(st.unavailable_paths||[]).map(path=>`
Unavailable: ${escapeHtml(path)}
`).join(""); + const errors=Number(st.errors||0); + return `
${escapeHtml(st.name||"Library")} — ${escapeHtml(st.status||"waiting")}
${escapeHtml(st.stage||"")} · ${Number(st.processed||0)}/${Number(st.total||0)} (${percent}%)
New: ${Number(st.new||0)} · Changed: ${Number(st.changed||0)} · Unchanged: ${Number(st.unchanged||0)} · Removed: ${Number(st.removed||0)}${errors?` · Errors: ${errors}`:""}
${escapeHtml(st.current_path||"")}
${warnings}${errors?`
${errors} file(s) failed. Check server journal for [SCAN] errors.
`:""}
`; + }).join(""); + panel.querySelector("#kronicScanMonitorBody").innerHTML=`

${escapeHtml(stage)}

${lines||'

Waiting for the first library…

'}${!state.running&&state.completed_at?'

Reopen the library to see newly indexed items.

':''}`; + if(scanMonitorWasRunning&&!state.running){ + clearInterval(activeScanMonitorTimer);activeScanMonitorTimer=null; + } + scanMonitorWasRunning=Boolean(state.running); +} +async function pollScanMonitor(){ + try{renderScanMonitor(await api("/api/scan/status"));} + catch(e){const body=document.getElementById("kronicScanMonitorBody");if(body)body.textContent=`Unable to read scan status: ${e.message}`;} +} +function openScanMonitor(){ + ensureScanMonitor();scanMonitorWasRunning=true;pollScanMonitor(); + if(activeScanMonitorTimer)clearInterval(activeScanMonitorTimer); + activeScanMonitorTimer=setInterval(pollScanMonitor,1000); +} +async function startLibraryScan(ids,mode="quick"){ + try{ + const result=await api("/api/scan",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({source_ids:ids,mode})}); + if(result?.started===false||result?.success===false)throw Error(result?.error||"Scan not started"); + openScanMonitor(); // Do NOT navigate to the main Libraries screen. + }catch(e){alert(`Library scan could not start: ${e.message}`);} +} +function startScanPolling(){clearScanPolling();updateScanStatus();scanPollTimer=setInterval(updateScanStatus,1000);} +async function updateScanStatus(){ + try{ + const s=await api("/api/scan/status"); + if(s.running&&!document.getElementById("kronicScanMonitor"))openScanMonitor(); + if(document.getElementById("kronicScanMonitor"))renderScanMonitor(s); + if(!s.running)clearScanPolling(); + }catch(e){console.warn("Scan status unavailable",e);} +} +// Recover a running scan after refreshing a page without showing an idle popup. +document.addEventListener("DOMContentLoaded",async()=>{ + try{const status=await api("/api/scan/status");if(status.running)openScanMonitor();}catch(_){/* page may not be authenticated */} +},{once:true}); + +async function showManageLibraries(focusSourceId=null){clearScanPolling();resetLibraryContext();installTopNav("home");toolbar.innerHTML='';document.getElementById("manageBack").onclick=showLibraries;document.getElementById("newLib").onclick=()=>showFolderBrowser("/");const sources=await api("/api/sources");content.innerHTML=`

Manage Libraries

${sources.map(s=>`

${escapeHtml(s.name)}

${s.media_count||0} indexed items
${(s.paths||[]).map(p=>`
${escapeHtml(p.path)}
`).join("")}
`).join("")}`;document.querySelectorAll("[data-library-type]").forEach(x=>x.onchange=()=>changeLibraryType(Number(x.dataset.libraryType),x.value));document.querySelectorAll("[data-library-artwork]").forEach(x=>x.onchange=async()=>{const id=Number(x.dataset.libraryArtwork);try{await api(`/api/sources/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({artwork_preference:x.value})});}catch(e){alert(e.message);showManageLibraries(id);}});document.querySelectorAll("[data-manage-quick-scan]").forEach(x=>x.onclick=()=>scanOneLibrary(Number(x.dataset.manageQuickScan),"quick"));document.querySelectorAll("[data-manage-deep-scan]").forEach(x=>x.onclick=()=>scanOneLibrary(Number(x.dataset.manageDeepScan),"deep"));document.querySelectorAll("[data-toggle-library]").forEach(x=>x.onclick=()=>toggleLibrary(Number(x.dataset.toggleLibrary),Number(x.dataset.enableValue)));document.querySelectorAll("[data-remove-library-path]").forEach(x=>x.onclick=()=>removeLibraryPath(Number(x.dataset.removeLibraryPath)));document.querySelectorAll("[data-remove-library]").forEach(x=>{const s=sources.find(v=>v.id===Number(x.dataset.removeLibrary));x.onclick=()=>removeLibrary(s.id,s.name)});document.querySelectorAll("[data-add-path]").forEach(x=>{const s=sources.find(v=>v.id===Number(x.dataset.addPath));x.onclick=()=>showAddPathBrowser(s.id,s.name,"/")});if(focusSourceId){document.querySelector(`[data-manage-library-card="${Number(focusSourceId)}"]`)?.scrollIntoView({behavior:"smooth",block:"center"});}} + +async function showFolderBrowser(path){clearScanPolling();const d=await api(`/api/browse?path=${encodeURIComponent(path)}`);toolbar.innerHTML='';document.getElementById("folderBack").onclick=showManageLibraries;content.innerHTML=`

Add Library

Current Folder

${escapeHtml(d.path)}
${d.parent?`
📁 ..
`:""}${d.folders.map(f=>`
📁 ${escapeHtml(f.name)}
`).join("")}
`;document.querySelectorAll("[data-folder-path]").forEach(x=>x.onclick=()=>showFolderBrowser(x.dataset.folderPath));document.getElementById("createLibraryButton").onclick=()=>addLibrary(d.path);} +async function showAddPathBrowser(id,name,path){const d=await api(`/api/browse?path=${encodeURIComponent(path)}`);content.innerHTML=`

Add Folder to ${escapeHtml(name)}

${escapeHtml(d.path)}
${d.parent?`
📁 ..
`:""}${d.folders.map(f=>`
📁 ${escapeHtml(f.name)}
`).join("")}
`;document.querySelectorAll("[data-add-folder-path]").forEach(x=>x.onclick=()=>showAddPathBrowser(id,name,x.dataset.addFolderPath));document.getElementById("addCurrentFolderButton").onclick=()=>addPathToLibrary(id,d.path);} +async function addLibrary(path){const name=document.getElementById("newLibraryName").value.trim(),type=document.getElementById("newLibraryType").value;if(!name)return alert("Library name is required.");try{await api("/api/sources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name,path,library_type:type})});showManageLibraries();}catch(e){alert(e.message);}} +async function addPathToLibrary(id,path){try{await api(`/api/sources/${id}/paths`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({path})});showManageLibraries();}catch(e){alert(e.message);}} +async function removeLibraryPath(id){if(!confirm("Remove this folder from the library?\n\nNo files will be deleted."))return;try{await api(`/api/source-paths/${id}`,{method:"DELETE"});showManageLibraries();}catch(e){alert(e.message);}} +async function changeLibraryType(id,t){try{await api(`/api/sources/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({library_type:t})});}catch(e){alert(e.message);}} +async function toggleLibrary(id,en){try{await api(`/api/sources/${id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:Boolean(en)})});showManageLibraries();}catch(e){alert(e.message);}} +async function removeLibrary(id,name){if(!confirm(`Remove "${name}"?\n\nNo media files will be deleted.`))return;try{await api(`/api/sources/${id}`,{method:"DELETE"});showManageLibraries();}catch(e){alert(e.message);}} +async function showMoveDialog(mediaId,currentLibraryId){const sources=await api("/api/sources");const a=sources.filter(s=>s.enabled&&s.id!==currentLibraryId);if(!a.length)return alert("No other enabled libraries.");const selected=prompt(`Move to which library?\n\n${a.map(s=>`${s.id}: ${s.name}`).join("\n")}`);if(!selected)return;const target=Number(selected);if(!a.some(s=>s.id===target))return alert("Invalid library ID.");await api("/api/media/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({media_id:mediaId,target_source_id:target})});showLibrary(currentSourceId,currentSourceName,currentSourceType);} + + + +function getDisplayTitle(i,episodeView=false){ + const t=i.effective_title||i.title_override||i.title||"Unknown"; + + if(!episodeView)return t; + + const s=Number(getSeasonNumber(i)); + const e=Number(getEpisodeNumber(i)); + const et=getEpisodeTitle(i); + + let prefix=""; + + if(Number.isFinite(s)&&s>0&&Number.isFinite(e)&&e>0){ + prefix=`S${String(s).padStart(2,"0")}E${String(e).padStart(2,"0")}`; + }else if(Number.isFinite(e)&&e>0){ + prefix=`Episode ${e}`; + } + + return prefix&&et + ?`${prefix} — ${et}` + :prefix||et||t; +} + +async function performSearch(q){ + let url=`/api/search?q=${encodeURIComponent(q)}`; + + if(currentSourceId!==null){ + url+=`&source_id=${currentSourceId}`; + } + + try{ + const results=await api(url); + + if(currentSourceType==="shows"&¤tSourceId!==null){ + renderMediaGrid( + results, + `Search: ${q}`, + "", + true + ); + }else{ + renderMediaGrid( + results, + `Search: ${q}` + ); + } + }catch(error){ + showError(error); + } +} + +function setLibraryToolbar(backLabel,backHandler,sortKey=null,rerender=null){ + toolbar.innerHTML=""; + installTopNav("library", { + backLabel, + backHandler, + sortKey, + rerender, + }); +} + +async function showLibrary(id,name,type){ + clearScanPolling(); + currentSourceId=Number(id); + currentSourceName=name; + currentSourceType=type||"movies"; + currentShowName=null; + updateSearchPlaceholder(); + const sortKey=`library:${currentSourceId}`; + breadcrumb.innerHTML=`Libraries › ${escapeHtml(name)}`; + try{ + const media=await api(`/api/media?source_id=${id}`); + if(type==="shows"){renderShows(media);return;} + const rerender=()=>{ + setLibraryToolbar("Libraries",showLibraries,sortKey,rerender); + renderMediaGrid( + sortedMediaItems(media,sortKey,item=>getDisplayTitle(item,false)), + name + ); + }; + rerender(); + }catch(e){showError(e);} +} + +function getShowName(i){return i.effective_series_title||i.series_title_override||i.series_title||(mediaPathParts(i).length>=2?mediaPathParts(i)[0]:(i.effective_title||i.title||"Unknown Show"));} +function getSeasonNumber(i){return i.effective_season??i.season_override??i.season??null;} +function getEpisodeNumber(i){return i.effective_episode??i.episode_override??i.episode??null;} +function getEpisodeTitle(i){return i.effective_episode_title??i.episode_title_override??i.episode_title??null;} +function getSeasonName(i){const n=getSeasonNumber(i);if(n!==null&&n!=="")return`Season ${Number(n)}`;const p=mediaPathParts(i);return p.length>=3?p[1]:"Episodes";} + +function renderShows(media){ + const sortKey=`library:${currentSourceId}`; + breadcrumb.innerHTML=`Libraries › ${escapeHtml(currentSourceName)}`; + const shows=new Map(); + media.forEach(i=>{const n=getShowName(i);if(!shows.has(n))shows.set(n,[]);shows.get(n).push(i);}); + const rerender=()=>{ + setLibraryToolbar("Libraries",showLibraries,sortKey,rerender); + const entries=sortedGroups([...shows.entries()],sortKey); + content.innerHTML=`

${escapeHtml(currentSourceName)}

${entries.map(([n,items])=>{ + const totalLength=items.reduce((sum,item)=>sum+durationValue(item),0); + return`
${escapeHtml(n)}
${new Set(items.map(getSeasonName)).size} seasons
${items.length} episodes
${escapeHtml(formatDurationShort(totalLength))}
`; + }).join("")}
`; + document.querySelectorAll(".show-card").forEach(c=>c.onclick=()=>openShow(c.dataset.showName)); + }; + rerender(); +} + +async function openShow(name){ + currentShowName=name; + const sortKey=`show:${currentSourceId}:${name}`; + breadcrumb.innerHTML=`Libraries › ${escapeHtml(currentSourceName)} › ${escapeHtml(name)}`; + const media=await api(`/api/media?source_id=${currentSourceId}`); + const items=media.filter(i=>getShowName(i)===name); + const seasons=new Map(); + items.forEach(i=>{const n=getSeasonName(i);if(!seasons.has(n))seasons.set(n,[]);seasons.get(n).push(i);}); + const rerender=()=>{ + setLibraryToolbar(currentSourceName,()=>showLibrary(currentSourceId,currentSourceName,currentSourceType),sortKey,rerender); + const entries=sortedGroups([...seasons.entries()],sortKey); + content.innerHTML=`

${escapeHtml(name)}

${entries.map(([seasonName,seasonItems])=>{ + const totalLength=seasonItems.reduce((sum,item)=>sum+durationValue(item),0); + return`
${escapeHtml(seasonName)}
${seasonItems.length} episodes
${escapeHtml(formatDurationShort(totalLength))}
`; + }).join("")}
`; + document.querySelectorAll(".season-card").forEach(c=>c.onclick=()=>openSeason(name,c.dataset.seasonName)); + }; + rerender(); +} + +async function openSeason(show,season){ + currentShowName=show; + const sortKey=`season:${currentSourceId}:${show}:${season}`; + breadcrumb.innerHTML=`Libraries › ${escapeHtml(currentSourceName)} › ${escapeHtml(show)} › ${escapeHtml(season)}`; + const media=await api(`/api/media?source_id=${currentSourceId}`); + const eps=media.filter(i=>getShowName(i)===show&&getSeasonName(i)===season); + const rerender=()=>{ + setLibraryToolbar(show,()=>openShow(show),sortKey,rerender); + renderMediaGrid( + sortedMediaItems(eps,sortKey,item=>getDisplayTitle(item,true)), + `${show} — ${season}`, + "", + true + ); + }; + rerender(); +} + +function normalizeAudioLanguage(value){ + const code=String(value||"").toLowerCase(); + const names={eng:"English",en:"English",fra:"French",fre:"French",fr:"French",spa:"Spanish",es:"Spanish",deu:"German",ger:"German",de:"German",jpn:"Japanese",ja:"Japanese",ita:"Italian",it:"Italian"}; + return names[code]||code.toUpperCase()||"Audio"; +} +function audioTrackLabel(track){ + const parts=[]; + if(track.title)parts.push(track.title); + else parts.push(normalizeAudioLanguage(track.language)); + if(track.codec)parts.push(String(track.codec).toUpperCase()); + const channels=Number(track.channels)||0; + if(channels)parts.push(channels===1?"1.0":channels===2?"2.0":channels===6?"5.1":channels===8?"7.1":`${channels}ch`); + return parts.join(" · "); +} +function qualityChoices(item){ + const h=Number(item.video_height)||(()=>{const m=String(item.resolution||"").match(/x(\d+)$/);return m?Number(m[1]):0;})(); + const choices=[{value:"original",label:h?`Original ${h}p`:"Original"}]; + [720,480,360].forEach(v=>{if(h>v)choices.push({value:String(v),label:`${v}p`});}); + return choices; +} +function playbackSelectorMarkup(item){ + const q=qualityChoices(item); + const tracks=Array.isArray(item.audio_tracks)?item.audio_tracks:[]; + const qHtml=q.length>1 + ?`` + :`
Quality${escapeHtml(q[0].label)}
`; + let aHtml=""; + if(tracks.length>1){ + aHtml=``; + }else if(tracks.length===1){ + aHtml=`
Audio${escapeHtml(audioTrackLabel(tracks[0]))}
`; + }else{ + aHtml=`
AudioDetecting…
`; + } + return `
${qHtml}${aHtml}
`; +} +function playbackOptionsForMedia(id){ + return { + quality:document.querySelector(`[data-quality-for="${id}"]`)?.value||"original", + audio:document.querySelector(`[data-audio-for="${id}"]`)?.value??null, + }; +} +async function hydratePlaybackOptionsForCard(mediaId){ + const pending=document.querySelector(`[data-audio-pending="${mediaId}"]`); + if(!pending) return; + try{ + const data=await api(`/api/media/${mediaId}/playback-options`); + const tracks=Array.isArray(data.audio_tracks)?data.audio_tracks:[]; + let replacement=""; + if(tracks.length>1){ + replacement=``; + }else if(tracks.length===1){ + replacement=`
Audio${escapeHtml(audioTrackLabel(tracks[0]))}
`; + }else{ + replacement=`
AudioNo audio stream
`; + } + pending.outerHTML=replacement; + const select=document.querySelector(`[data-audio-for="${mediaId}"]`); + if(select) select.onclick=event=>event.stopPropagation(); + }catch(error){ + const target=document.querySelector(`[data-audio-pending="${mediaId}"] strong`); + if(target) target.textContent="Unavailable"; + } +} + +function hydrateVisiblePlaybackOptions(){ + const cards=[...document.querySelectorAll("[data-audio-pending]")]; + if(!cards.length) return; + + if(!("IntersectionObserver" in window)){ + cards.forEach(node=>hydratePlaybackOptionsForCard(Number(node.dataset.audioPending))); + return; + } + + const observer=new IntersectionObserver(entries=>{ + for(const entry of entries){ + if(!entry.isIntersecting) continue; + const node=entry.target; + observer.unobserve(node); + hydratePlaybackOptionsForCard(Number(node.dataset.audioPending)); + } + },{rootMargin:"180px"}); + + cards.forEach(node=>observer.observe(node)); +} + +function launchTileMedia(id,title){ + return openPlayer(Number(id),title,playbackOptionsForMedia(id)); +} + +function renderMediaGrid(media,title,extra="",episodeView=false){ + content.innerHTML=`

${escapeHtml(title)}

${extra}
${media.map(i=>{ + const t=getDisplayTitle(i,episodeView); + return`
▶
▶
${escapeHtml(t)}${escapeHtml(i.effective_year??i.year??"")} ${i.duration_seconds?`· ${escapeHtml(formatDurationShort(i.duration_seconds))}`:""}
${escapeHtml(i.resolution||"Unknown")}${escapeHtml(i.source_name||"Uncategorized")}
${playbackSelectorMarkup(i)}
External${canManageMedia()?``:""}
`; + }).join("")}
`; + document.querySelectorAll("[data-play-id]").forEach(e=>e.onclick=()=>launchTileMedia(Number(e.dataset.playId),e.dataset.playTitle)); + document.querySelectorAll("[data-play-button]").forEach(e=>e.onclick=()=>launchTileMedia(Number(e.dataset.playButton),e.dataset.playTitle)); + document.querySelectorAll("[data-quality-for],[data-audio-for]").forEach(e=>{e.onclick=ev=>ev.stopPropagation();}); + document.querySelectorAll("[data-move-id]").forEach(e=>e.onclick=()=>showMoveDialog(Number(e.dataset.moveId),Number(e.dataset.currentLibrary))); + hydrateVisiblePlaybackOptions(); +} + +async function showMoveDialog(mediaId,currentLibraryId){const sources=await api("/api/sources");const a=sources.filter(s=>s.enabled&&s.id!==currentLibraryId);if(!a.length)return alert("No other enabled libraries.");const selected=prompt(`Move to which library?\n\n${a.map(s=>`${s.id}: ${s.name}`).join("\n")}`);if(!selected)return;const target=Number(selected);if(!a.some(s=>s.id===target))return alert("Invalid library ID.");await api("/api/media/move",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({media_id:mediaId,target_source_id:target})});showLibrary(currentSourceId,currentSourceName,currentSourceType);} + +async function showMetadataEditor(initialSourceId=null) { + clearScanPolling(); + installTopNav("metadata"); + resetLibraryContext(); + stopYouTubePolling(); + + const sources = await api("/api/sources"); + metadataSources = sources; + const selectedId = Number(initialSourceId) || 0; + + content.innerHTML = ` +

Metadata

+ +
+
+
+

YouTube Metadata

+
Read the YouTube video ID from filenames, preview the real YouTube title, then update this media server. Rename mode is optional and never deletes a media file.
+
+
+ +
+ + + + + + + + +
+ +
Choose a library and click Preview.
+ +
+
+ +
+
+ + +
+
+ + +
+ +
+
+ `; + + document.getElementById("metadataLoadButton").onclick = loadMetadataTable; + document.getElementById("metadataLibraryFilter").onchange = loadMetadataTable; + document.getElementById("metadataSearchInput").onkeydown = e => { if (e.key === "Enter") loadMetadataTable(); }; + document.getElementById("youtubePreviewButton").onclick = startYouTubePreview; + document.getElementById("youtubeApplyButton").onclick = applyYouTubeChanges; + document.getElementById("youtubeLibrarySelect").onchange = () => { + document.getElementById("youtubeApplyButton").disabled = true; + document.getElementById("youtubePreviewResults").innerHTML = ""; + document.getElementById("youtubeStatus").textContent = "Click Preview to inspect this library."; + }; + + loadMetadataTable(); + refreshYouTubeStatus(); +} +async function loadMetadataTable(){const target=document.getElementById("metadataTableContainer");const sid=document.getElementById("metadataLibraryFilter")?.value||"";const q=document.getElementById("metadataSearchInput")?.value.trim()||"";let url=q?`/api/search?q=${encodeURIComponent(q)}`:"/api/media";if(sid)url+=`${url.includes("?")?"&":"?"}source_id=${sid}`;try{renderMetadataTable(await api(url));}catch(e){target.innerHTML=`
${escapeHtml(e.message)}
`;}} +function renderMetadataTable(media){const target=document.getElementById("metadataTableContainer");if(!media.length){target.innerHTML='
No media found.
';return;}target.innerHTML=`
${media.map(i=>``).join("")}
PreviewTitleSeriesEpisode TitleYearSeasonEpisodeResolutionLibraryActions
`;document.querySelectorAll("[data-metadata-save]").forEach(b=>b.onclick=()=>saveMetadataRow(Number(b.dataset.metadataSave)));document.querySelectorAll("[data-metadata-reset]").forEach(b=>b.onclick=()=>resetMetadataRow(Number(b.dataset.metadataReset)));document.querySelectorAll("[data-metadata-reanalyze]").forEach(b=>b.onclick=()=>reanalyzeMedia(Number(b.dataset.metadataReanalyze)));document.querySelectorAll("[data-metadata-info]").forEach(b=>b.onclick=()=>showMediaInfo(Number(b.dataset.metadataInfo)));} +async function saveMetadataRow(id){const r=document.querySelector(`.metadata-row[data-media-id="${id}"]`);const p={title:r.querySelector(".metadata-title-input").value.trim(),series_title:r.querySelector(".metadata-series-input").value.trim(),episode_title:r.querySelector(".metadata-episode-title-input").value.trim(),year:nullableNumber(r.querySelector(".metadata-year-input").value),season:nullableNumber(r.querySelector(".metadata-season-input").value),episode:nullableNumber(r.querySelector(".metadata-episode-input").value)};try{await api(`/api/media/${id}/metadata`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)});r.classList.add("metadata-row-saved");setTimeout(()=>r.classList.remove("metadata-row-saved"),1000);}catch(e){alert(e.message);}} +async function resetMetadataRow(id){if(!confirm("Reset manual metadata overrides for this item?"))return;await api(`/api/media/${id}/metadata-overrides`,{method:"DELETE"});loadMetadataTable();} +async function reanalyzeMedia(id){const r=await api(`/api/media/${id}/reanalyze`,{method:"POST"});if(r.removed_short)alert("This item is under the minimum duration and was removed from the media index.");loadMetadataTable();} +async function showMediaInfo(id){const d=await api(`/api/media/${id}/mediainfo`);closeMetadataInfo();const o=document.createElement("div");o.id="metadataInfoOverlay";o.className="metadata-info-overlay";o.innerHTML=`

MediaInfo

${escapeHtml(d.file||"")}

Normalized Metadata

${escapeHtml(JSON.stringify(d.normalized||{},null,2))}

GuessIt

${escapeHtml(JSON.stringify(d.guessit||{},null,2))}

MediaInfo

${escapeHtml(JSON.stringify(d.mediainfo||{},null,2))}
`;document.body.appendChild(o);document.getElementById("closeMetadataInfoButton").onclick=closeMetadataInfo;o.onclick=e=>{if(e.target===o)closeMetadataInfo();};} +function closeMetadataInfo(){document.getElementById("metadataInfoOverlay")?.remove();} + + + +function injectYouTubeMetadataStyles() { + if (document.getElementById("youtubeMetadataStyles")) return; + const style = document.createElement("style"); + style.id = "youtubeMetadataStyles"; + style.textContent = ` + .youtube-metadata-panel { margin-bottom: 24px; } + .youtube-metadata-heading { display:flex; justify-content:space-between; gap:16px; align-items:flex-start; margin-bottom:16px; } + .youtube-metadata-heading h3 { margin:0 0 6px 0; } + .youtube-controls { display:flex; flex-wrap:wrap; gap:12px; align-items:end; margin-bottom:14px; } + .youtube-controls .metadata-filter-group { min-width:220px; } + .youtube-force-refresh { display:flex; gap:8px; align-items:center; min-height:38px; } + .youtube-status { margin:8px 0; } + .youtube-progress-wrap { margin:10px 0 16px; } + .youtube-preview-table { width:100%; border-collapse:collapse; margin-top:14px; } + .youtube-preview-table th, .youtube-preview-table td { padding:9px 10px; border-bottom:1px solid rgba(255,255,255,.1); text-align:left; vertical-align:top; } + .youtube-preview-table th { position:sticky; top:0; background:#171717; z-index:1; } + .youtube-preview-table code { white-space:normal; overflow-wrap:anywhere; } + .youtube-preview-scroll { overflow:auto; max-height:520px; border:1px solid rgba(255,255,255,.08); border-radius:6px; } + .youtube-status-ready { opacity:.95; } + .youtube-status-error { color:#ff8a8a; } + .youtube-status-applied { color:#9be29b; } + .youtube-summary { margin:10px 0; display:flex; flex-wrap:wrap; gap:14px; } + .youtube-title-arrow { opacity:.55; padding:0 5px; } + `; + document.head.appendChild(style); +} + +function stopYouTubePolling() { + if (youtubePollTimer) { + clearInterval(youtubePollTimer); + youtubePollTimer = null; + } +} + +function startYouTubePolling() { + stopYouTubePolling(); + youtubePollTimer = setInterval(refreshYouTubeStatus, 750); +} + +async function startYouTubePreview() { + const sourceId = Number(document.getElementById("youtubeLibrarySelect")?.value || 0); + if (!sourceId) return alert("Choose the library you want to inspect first."); + + const forceRefresh = !!document.getElementById("youtubeForceRefresh")?.checked; + const applyButton = document.getElementById("youtubeApplyButton"); + if (applyButton) applyButton.disabled = true; + + try { + await api("/api/youtube/preview", { + method: "POST", + headers: {"Content-Type": "application/json"}, + body: JSON.stringify({source_id: sourceId, force_refresh: forceRefresh}) + }); + startYouTubePolling(); + await refreshYouTubeStatus(); + } catch (error) { + alert(error.message); + } +} + +async function applyYouTubeChanges() { + const sourceId = Number(document.getElementById("youtubeLibrarySelect")?.value || 0); + const mode = document.getElementById("youtubeModeSelect")?.value || "metadata"; + if (!sourceId) return alert("Choose a library first."); + + if (mode === "rename") { + const ok = confirm( + "Rename the matching media files using their YouTube titles?\n\n" + + "The YouTube ID will be kept in [brackets]. Existing files are never overwritten." + ); + if (!ok) return; + } + + try { + await api("/api/youtube/apply", { + method: "POST", + headers: {"Content-Type": "application/json"}, + body: JSON.stringify({source_id: sourceId, mode}) + }); + document.getElementById("youtubeApplyButton").disabled = true; + startYouTubePolling(); + await refreshYouTubeStatus(); + } catch (error) { + alert(error.message); + } +} + +async function refreshYouTubeStatus() { + const statusElement = document.getElementById("youtubeStatus"); + if (!statusElement) { + stopYouTubePolling(); + return; + } + + try { + const state = await api("/api/youtube/status"); + renderYouTubeStatus(state); + if (state.running) startYouTubePolling(); + else stopYouTubePolling(); + } catch (error) { + statusElement.textContent = `YouTube metadata status error: ${error.message}`; + stopYouTubePolling(); + } +} + +function renderYouTubeStatus(state) { + const statusElement = document.getElementById("youtubeStatus"); + const progressWrap = document.getElementById("youtubeProgressWrap"); + const progressBar = document.getElementById("youtubeProgressBar"); + const progressText = document.getElementById("youtubeProgressText"); + const resultsElement = document.getElementById("youtubePreviewResults"); + const applyButton = document.getElementById("youtubeApplyButton"); + const selectedLibrary = Number(document.getElementById("youtubeLibrarySelect")?.value || 0); + if (!statusElement || !resultsElement) return; + + const belongsToSelection = !selectedLibrary || Number(state.source_id || 0) === selectedLibrary; + if (!belongsToSelection && state.phase !== "idle") return; + + statusElement.textContent = state.message || (state.running ? "Working..." : "Choose a library and click Preview."); + + if (state.running || state.phase === "preview_complete" || state.phase === "apply_complete") { + progressWrap.hidden = false; + progressBar.style.width = `${Number(state.percent || 0)}%`; + progressText.textContent = `${state.processed || 0} / ${state.total || 0} — ${state.percent || 0}%`; + } else { + progressWrap.hidden = true; + } + + if (Array.isArray(state.results) && state.results.length) { + renderYouTubePreviewResults(state.results, state); + } else if (!state.running) { + resultsElement.innerHTML = ""; + } + + if (applyButton) { + const ready = Array.isArray(state.results) && state.results.some(item => item.status === "ready"); + applyButton.disabled = state.running || state.phase !== "preview_complete" || !ready || !belongsToSelection; + } + + if (state.phase === "apply_complete") { + loadMetadataTable(); + } +} + +function renderYouTubePreviewResults(results, state) { + const target = document.getElementById("youtubePreviewResults"); + if (!target) return; + + const readyCount = results.filter(item => item.status === "ready").length; + const errorCount = results.filter(item => item.status === "error" || item.apply_status === "error").length; + const cachedCount = results.filter(item => item.cached).length; + + target.innerHTML = ` +
+ ${readyCount} matched YouTube videos + ${state.skipped || 0} files without an ID + ${cachedCount} cache hits + ${errorCount} errors +
+
+ + + + + + + + + + + + + ${results.map(item => { + const statusClass = item.apply_status === "applied" ? "youtube-status-applied" : (item.error ? "youtube-status-error" : "youtube-status-ready"); + const statusText = item.apply_status === "applied" ? "Applied" : (item.error || (item.cached ? "Ready (cached)" : "Ready")); + return ` + + + + + + + + `; + }).join("")} + +
IDCurrent titleYouTube titleChannelFilenameStatus
${escapeHtml(item.video_id || "-")}${escapeHtml(item.current_title || "-")}${escapeHtml(item.proposed_title || "-")}${escapeHtml(item.channel_name || "-")}${escapeHtml(item.current_filename || "-")}${item.proposed_filename ? `→${escapeHtml(item.proposed_filename)}` : ""}${escapeHtml(statusText)}
+
`; +} + + +// ============================================================ +// YOUTUBE LIBRARY TAB / SEARCH / WATCHED CACHE +// ============================================================ + +let youtubeItemRegistry = new Map(); +let youtubePlayerOverlay = null; +let youtubeVideoElement = null; +let youtubeActiveItem = null; + +// Kronic Cast receiver bridge. One open/authenticated Kronic browser is the +// active "screen"; commands arrive by long-poll from the Python receiver. +let kronicCastClientId = null; +let kronicCastSeq = 0; +let kronicCastRunning = false; +let kronicCastLastStateSent = 0; +let kronicCastStateTimer = null; +let youtubeProgressTimer = null; +let youtubePlaybackBaseOffset = 0; +let youtubeKnownDuration = null; +let youtubePendingClientSeek = null; +let youtubeSeekMode = "server"; + +let musicTrackRegistry = new Map(); +let musicQueue = []; +let musicQueueIndex = -1; +let musicPlayer = null; + + +function ensureTwitchPlayer(){ + if(twitchPlayerOverlay)return; + + twitchPlayerOverlay=document.createElement("div"); + twitchPlayerOverlay.className="youtube-player-overlay twitch-player-overlay"; + twitchPlayerOverlay.style.display="none"; + twitchPlayerOverlay.innerHTML=` +
+
+
Twitch
+
+ + + + +
+
+
+ +
+
+
`; + document.body.appendChild(twitchPlayerOverlay); + + twitchVideoElement=document.getElementById("twitchVideoElement"); + + document.getElementById("twitchPlayerClose").onclick=closeTwitchPlayer; + document.getElementById("twitchPlayerMinimize").onclick=()=>{ + const win=twitchPlayerOverlay.querySelector(".youtube-player-window"); + const minimizing=!twitchPlayerOverlay.classList.contains("minimized"); + + if(minimizing && win){ + win.dataset.restoreLeft=win.style.left||""; + win.dataset.restoreTop=win.style.top||""; + win.dataset.restoreWidth=win.style.width||""; + win.dataset.restoreHeight=win.style.height||""; + twitchPlayerOverlay.classList.add("minimized"); + }else{ + twitchPlayerOverlay.classList.remove("minimized"); + if(win){ + if(win.dataset.restoreLeft)win.style.left=win.dataset.restoreLeft; + if(win.dataset.restoreTop)win.style.top=win.dataset.restoreTop; + if(win.dataset.restoreWidth)win.style.width=win.dataset.restoreWidth; + if(win.dataset.restoreHeight)win.style.height=win.dataset.restoreHeight; + } + } + }; + document.getElementById("twitchPlayerFullscreen").onclick=async()=>{ + const windowElement=twitchPlayerOverlay.querySelector(".youtube-player-window"); + if(!document.fullscreenElement){ + try{await windowElement.requestFullscreen();}catch{} + }else{ + try{await document.exitFullscreen();}catch{} + } + }; + document.getElementById("twitchPlayerRecord").onclick=()=>{ + if(twitchActiveChannel) startTwitchRecording(twitchActiveChannel.id); + }; + + bindTwitchPlayerDragResize(); +} + + +function bindTwitchPlayerDragResize(){ + if(twitchPlayerDragBound || !twitchPlayerOverlay)return; + + const win=twitchPlayerOverlay.querySelector(".youtube-player-window"); + const header=twitchPlayerOverlay.querySelector(".youtube-player-header"); + const resizeHandle=twitchPlayerOverlay.querySelector(".twitch-player-resize-handle"); + if(!win || !header || !resizeHandle)return; + + twitchPlayerDragBound=true; + + // Convert from CSS inset positioning to pixel left/top sizing the first time + // the user interacts with the Twitch player. + const normalizeWindowRect=()=>{ + const rect=win.getBoundingClientRect(); + win.style.position="fixed"; + win.style.transform="none"; + win.style.left=`${rect.left}px`; + win.style.top=`${rect.top}px`; + win.style.right="auto"; + win.style.bottom="auto"; + win.style.width=`${rect.width}px`; + win.style.height=`${rect.height}px`; + return rect; + }; + + header.style.cursor="move"; + header.title="Drag player · double-click to reset position"; + + header.addEventListener("dblclick",event=>{ + if(event.target.closest("button,select,input,a"))return; + positionTwitchPlayerOnScreen(true); + }); + + header.addEventListener("pointerdown",event=>{ + if(event.button!==0)return; + if(event.target.closest("button,select,input,a"))return; + if(twitchPlayerOverlay.classList.contains("minimized"))return; + + event.preventDefault(); + const rect=normalizeWindowRect(); + const startX=event.clientX; + const startY=event.clientY; + const startLeft=rect.left; + const startTop=rect.top; + + header.setPointerCapture?.(event.pointerId); + + const move=moveEvent=>{ + const dx=moveEvent.clientX-startX; + const dy=moveEvent.clientY-startY; + + const maxLeft=Math.max(0,window.innerWidth-win.offsetWidth); + const maxTop=Math.max(0,window.innerHeight-win.offsetHeight); + + win.style.left=`${Math.max(0,Math.min(maxLeft,startLeft+dx))}px`; + win.style.top=`${Math.max(0,Math.min(maxTop,startTop+dy))}px`; + }; + + const up=upEvent=>{ + header.releasePointerCapture?.(upEvent.pointerId); + header.removeEventListener("pointermove",move); + header.removeEventListener("pointerup",up); + header.removeEventListener("pointercancel",up); + }; + + header.addEventListener("pointermove",move); + header.addEventListener("pointerup",up); + header.addEventListener("pointercancel",up); + }); + + resizeHandle.addEventListener("pointerdown",event=>{ + if(event.button!==0)return; + if(twitchPlayerOverlay.classList.contains("minimized"))return; + + event.preventDefault(); + event.stopPropagation(); + + const rect=normalizeWindowRect(); + const startX=event.clientX; + const startY=event.clientY; + const startWidth=rect.width; + const startHeight=rect.height; + + resizeHandle.setPointerCapture?.(event.pointerId); + + const move=moveEvent=>{ + const minWidth=360; + const minHeight=240; + const maxWidth=Math.max(minWidth,window.innerWidth-rect.left); + const maxHeight=Math.max(minHeight,window.innerHeight-rect.top); + + const width=Math.max( + minWidth, + Math.min(maxWidth,startWidth+(moveEvent.clientX-startX)) + ); + const height=Math.max( + minHeight, + Math.min(maxHeight,startHeight+(moveEvent.clientY-startY)) + ); + + win.style.width=`${width}px`; + win.style.height=`${height}px`; + }; + + const up=upEvent=>{ + resizeHandle.releasePointerCapture?.(upEvent.pointerId); + resizeHandle.removeEventListener("pointermove",move); + resizeHandle.removeEventListener("pointerup",up); + resizeHandle.removeEventListener("pointercancel",up); + }; + + resizeHandle.addEventListener("pointermove",move); + resizeHandle.addEventListener("pointerup",up); + resizeHandle.addEventListener("pointercancel",up); + }); + + // Keep the window on-screen after browser resize. + window.addEventListener("resize",()=>{ + if(!twitchPlayerOverlay.classList.contains("open"))return; + if(twitchPlayerOverlay.classList.contains("minimized"))return; + positionTwitchPlayerOnScreen(false); + }); +} + + + +function positionTwitchPlayerOnScreen(forceReset=false){ + if(!twitchPlayerOverlay)return; + const win=twitchPlayerOverlay.querySelector(".youtube-player-window"); + const header=twitchPlayerOverlay.querySelector(".youtube-player-header"); + if(!win)return; + + const viewportW=Math.max(360,window.innerWidth); + const viewportH=Math.max(260,window.innerHeight); + + let rect=win.getBoundingClientRect(); + const headerHeight=Math.max(44,header?.getBoundingClientRect().height||44); + + const headerOffscreen= + rect.top < 8 || + rect.left < 0 || + rect.top + headerHeight > viewportH || + rect.left + 120 > viewportW; + + if(forceReset || headerOffscreen){ + const width=Math.min(900,Math.max(520,Math.floor(viewportW*0.62))); + const height=Math.min(620,Math.max(360,Math.floor(viewportH*0.62))); + + const left=Math.max(12,Math.floor((viewportW-width)/2)); + const top=Math.max(70,Math.floor((viewportH-height)/2)); + + win.style.position="fixed"; + win.style.transform="none"; + win.style.left=`${left}px`; + win.style.top=`${top}px`; + win.style.right="auto"; + win.style.bottom="auto"; + win.style.width=`${Math.min(width,viewportW-left-12)}px`; + win.style.height=`${Math.min(height,viewportH-top-12)}px`; + }else{ + // Clamp an existing user-sized window so the header always remains + // reachable even after browser resize. + const width=Math.min(rect.width,viewportW-24); + const height=Math.min(rect.height,viewportH-24); + const left=Math.max( + 12, + Math.min(rect.left,viewportW-width-12) + ); + const top=Math.max( + 70, + Math.min(rect.top,viewportH-headerHeight-12) + ); + + win.style.position="fixed"; + win.style.transform="none"; + win.style.left=`${left}px`; + win.style.top=`${top}px`; + win.style.right="auto"; + win.style.bottom="auto"; + win.style.width=`${Math.max(360,width)}px`; + win.style.height=`${Math.max(240,height)}px`; + } +} + + +async function openTwitchPlayer(channel){ + ensureTwitchPlayer(); + twitchActiveChannel=channel; + + document.getElementById("twitchPlayerTitle").textContent= + channel.title || channel.channel_name || "Twitch"; + + twitchPlayerOverlay.classList.add("open"); + twitchPlayerOverlay.classList.remove("minimized"); + twitchPlayerOverlay.style.display="block"; + twitchPlayerOverlay.style.visibility="visible"; + twitchPlayerOverlay.style.opacity="1"; + twitchPlayerOverlay.style.pointerEvents="auto"; + twitchPlayerOverlay.style.zIndex="9999"; + + // The Twitch player must never open with its drag header above the + // viewport. Older inline geometry can otherwise pin the video at 0,0. + positionTwitchPlayerOnScreen(false); + + const quality=channel.quality||"best"; + twitchVideoElement.controls=true; + twitchVideoElement.autoplay=true; + twitchVideoElement.playsInline=true; + twitchVideoElement.src=roomMediaUrl( + channel.roomSyncLive + ? `/api/twitch/live/${encodeURIComponent(channel.channel_name)}/play?quality=${encodeURIComponent(quality)}` + : `/api/twitch/channels/${encodeURIComponent(channel.id)}/play?quality=${encodeURIComponent(quality)}`); + + twitchVideoElement.play().catch(error => console.debug("Twitch autoplay delayed or blocked", error)); +} + +function closeTwitchPlayer(){ + if(twitchVideoElement){ + try{twitchVideoElement.pause();}catch{} + twitchVideoElement.removeAttribute("src"); + twitchVideoElement.load(); + } + if(twitchPlayerOverlay){ + twitchPlayerOverlay.classList.remove("open","minimized"); + twitchPlayerOverlay.style.display="none"; + } + twitchActiveChannel=null; +} + +async function twitchApiPost(url,data={}){ + return api(url,{ + method:"POST", + headers:{"Content-Type":"application/json"}, + body:JSON.stringify(data), + }); +} + +async function showTwitchLibrary(){ + clearScanPolling(); + stopYouTubePolling?.(); + + installTopNav("twitch"); + breadcrumb.innerHTML=`Live  ›  Twitch`; + + content.innerHTML=` +
+
+
+

Twitch

+
Streamlink resolves Twitch. Kronic handles playback and DVR recording through FFmpeg.
+
+ +
+ +
+ + +
+ +
+ +
+
+

Channels

+ Watch · Record Live · Auto Record When Live +
+
+
Loading Twitch channels…
+
+
+ +
+
+

Recordings

+ +
+
+
+
+
`; + + document.getElementById("twitchAddForm").onsubmit=async event=>{ + event.preventDefault(); + const input=document.getElementById("twitchChannelInput"); + const status=document.getElementById("twitchStatus"); + const value=input.value.trim(); + if(!value)return; + status.textContent="Resolving Twitch channel…"; + try{ + const channel=await twitchApiPost("/api/twitch/channels",{url:value}); + input.value=""; + status.textContent=`Added ${channel.channel_name}.`; + await loadTwitchOverview(); + }catch(error){ + status.textContent=`Add failed: ${error.message}`; + } + }; + + document.getElementById("twitchRefreshAll").onclick=async()=>{ + const data=await api("/api/twitch/overview"); + for(const channel of data.channels||[]){ + try{ + await twitchApiPost(`/api/twitch/channels/${channel.id}/refresh`); + }catch{} + } + await loadTwitchOverview(); + }; + + document.getElementById("twitchClearFinished").onclick=async()=>{ + await twitchApiPost("/api/twitch/recordings/clear"); + await loadTwitchOverview(); + }; + + await loadTwitchOverview(); + clearInterval(twitchPollTimer); + twitchPollTimer=setInterval(loadTwitchOverview,5000); +} + +function twitchChannelCard(channel){ + const live=Boolean(Number(channel.live||0)); + const qualities=String(channel.available_qualities||"") + .split(",") + .filter(Boolean); + if(!qualities.includes("best"))qualities.unshift("best"); + + return ` +
+
+
+ ${escapeHtml(channel.author||channel.channel_name)} +
${live?"LIVE":"Offline"}${channel.category?` · ${escapeHtml(channel.category)}`:""}
+
+ ${live?`LIVE`:""} +
+
+ ${escapeHtml(channel.title || (live?"Live stream":"Channel offline"))} +
+ + + +
+ + + + + + +
+
`; +} + +async function loadTwitchOverview(){ + const channelArea=document.getElementById("twitchChannelArea"); + const recordingArea=document.getElementById("twitchRecordingArea"); + if(!channelArea||!recordingArea)return; + + try{ + const data=await api("/api/twitch/overview"); + const channels=data.channels||[]; + const recordings=data.recordings||[]; + api('/api/recordings/scheduled').then(jobs=>{ + const host=document.getElementById('kronicScheduledRecordingList'); + if(!host)return; + const relevant=(jobs||[]).filter(job=>job.provider==='twitch').slice(0,12); + host.replaceChildren(); + if(!relevant.length)return; + const label=document.createElement('h4');label.textContent='Scheduled recordings';host.append(label); + relevant.forEach(job=>{ + const row=document.createElement('div');row.className='kronic-scheduled-item'; + const name=document.createElement('span'); + name.textContent=`${job.title||job.media_key} — ${new Date(job.start_at*1000).toLocaleString()} (${job.status})`; + row.append(name); + if(job.status==='scheduled'){ + const cancel=document.createElement('button');cancel.textContent='Cancel'; + cancel.onclick=async()=>{ + await api(`/api/recordings/scheduled/${job.id}`,{method:'DELETE'}); + loadTwitchOverview().catch(()=>{}); + }; + row.append(cancel); + } + host.append(row); + }); + }).catch(error=>console.debug('Scheduled recordings unavailable',error)); + const byId=new Map(channels.map(channel=>[String(channel.id),channel])); + + channelArea.innerHTML=channels.length + ?channels.map(twitchChannelCard).join("") + :`
No Twitch channels yet.
`; + + recordingArea.innerHTML=recordings.length + ?recordings.map(job=>` +
+
+ ${escapeHtml(job.title||job.channel_name||"Twitch recording")} +
${escapeHtml(job.channel_name||"")} · ${escapeHtml(job.status)} · ${escapeHtml(job.message||"")}
+ ${job.output_path?`${escapeHtml(job.output_path)}`:""} + ${job.error?`${escapeHtml(job.error)}`:""} +
+
+ ${job.status==="recording"||job.status==="queued" + ?`` + :""} +
+
`).join("") + :`
No Twitch recordings yet.
`; + + channelArea.querySelectorAll("[data-twitch-watch]").forEach(button=>{ + button.onclick=()=>{ + const channel=byId.get(String(button.dataset.twitchWatch)); + if(channel)openTwitchPlayer(channel); + }; + }); + + channelArea.querySelectorAll("[data-twitch-record]").forEach(button=>{ + button.onclick=()=>startTwitchRecording(button.dataset.twitchRecord); + }); + + channelArea.querySelectorAll("[data-twitch-schedule]").forEach(button=>{ + button.onclick=()=>{ + const channel=byId.get(String(button.dataset.twitchSchedule)); + if(channel) openRecordingScheduler('twitch', String(channel.id), channel.channel_name || 'Twitch'); + }; + }); + + channelArea.querySelectorAll("[data-twitch-auto]").forEach(button=>{ + button.onclick=async()=>{ + const channel=byId.get(String(button.dataset.twitchAuto)); + if(!channel)return; + await twitchApiPost( + `/api/twitch/channels/${channel.id}/auto`, + {enabled:!Boolean(Number(channel.auto_record))} + ); + await loadTwitchOverview(); + }; + }); + + channelArea.querySelectorAll("[data-twitch-refresh]").forEach(button=>{ + button.onclick=async()=>{ + await twitchApiPost(`/api/twitch/channels/${button.dataset.twitchRefresh}/refresh`); + await loadTwitchOverview(); + }; + }); + + channelArea.querySelectorAll("[data-twitch-remove]").forEach(button=>{ + button.onclick=async()=>{ + try{ + await api(`/api/twitch/channels/${button.dataset.twitchRemove}`,{ + method:"DELETE" + }); + await loadTwitchOverview(); + }catch(error){ + alert(`Remove failed: ${error.message}`); + } + }; + }); + + channelArea.querySelectorAll("[data-twitch-quality]").forEach(select=>{ + select.onchange=async()=>{ + await twitchApiPost( + `/api/twitch/channels/${select.dataset.twitchQuality}/quality`, + {quality:select.value} + ); + await loadTwitchOverview(); + }; + }); + + recordingArea.querySelectorAll("[data-twitch-stop]").forEach(button=>{ + button.onclick=async()=>{ + await twitchApiPost(`/api/twitch/recordings/${button.dataset.twitchStop}/stop`); + await loadTwitchOverview(); + }; + }); + + }catch(error){ + channelArea.innerHTML=`
${escapeHtml(error.message)}
`; + } +} + +// Scheduling is persisted on the server; closing this page does not cancel a job. +async function openRecordingScheduler(provider, mediaKey, title){ + const existing=document.getElementById('kronicRecordingScheduleDialog'); + existing?.remove(); + const dialog=document.createElement('dialog'); + dialog.id='kronicRecordingScheduleDialog'; + dialog.className='kronic-recording-dialog'; + const now=new Date(Date.now()+60000); + const localValue = new Date(now.getTime()-now.getTimezoneOffset()*60000).toISOString().slice(0,16); + dialog.innerHTML=`
+

Schedule ${provider==='twitch'?'Twitch':'YouTube live'} recording

+

${escapeHtml(title||mediaKey)} — the server starts the recording at this time, even with the browser closed.

+ +
+
+
`; + document.body.append(dialog); + dialog.showModal(); + dialog.querySelector('#kronicScheduleConfirm').onclick=async()=>{ + const input=dialog.querySelector('[name="start"]'); + const date=new Date(input.value); + if(!input.value || !Number.isFinite(date.valueOf())){ + dialog.querySelector('#kronicRecordingError').textContent='Select a valid date and time.';return; + } + try{ + await api('/api/recordings/scheduled',{ + method:'POST',headers:{'Content-Type':'application/json'}, + body:JSON.stringify({provider,media_key:String(mediaKey),title,start_at:date.toISOString()}) + }); + dialog.close();dialog.remove(); + if(provider==='twitch') loadTwitchOverview().catch(()=>{}); + alert('Recording scheduled. The server will start at the selected time.'); + }catch(error){dialog.querySelector('#kronicRecordingError').textContent=error.message;} + }; + dialog.addEventListener('close',()=>dialog.remove()); +} + +async function startTwitchRecording(channelId){ + try{ + await twitchApiPost(`/api/twitch/channels/${channelId}/record`); + await loadTwitchOverview(); + }catch(error){ + alert(`Record Live failed: ${error.message}`); + } +} + + +function ensureYouTubeLibraryStyles() { + if (document.getElementById("youtubeLibraryStyles")) return; + const link = document.createElement("link"); + link.id = "youtubeLibraryStyles"; + link.rel = "stylesheet"; + link.href = "/CSS/youtube.css"; + document.head.appendChild(link); +} + +function renderLibraryTabs(active) { return ""; } +function bindLibraryTabs() {} + +function formatYouTubeDuration(value) { + const seconds = Number(value); + return Number.isFinite(seconds) && seconds > 0 ? formatPlaybackTime(seconds) : ""; +} + +function formatByteSize(value) { + let bytes = Number(value) || 0; + if (bytes < 1024) return `${bytes} B`; + const units = ["KB", "MB", "GB", "TB"]; + let unit = -1; + do { + bytes /= 1024; + unit += 1; + } while (bytes >= 1024 && unit < units.length - 1); + return `${bytes.toFixed(bytes >= 10 ? 1 : 2)} ${units[unit]}`; +} + +async function showYouTubeLibrary() { + clearScanPolling(); + resetLibraryContext(); + ensureYouTubeLibraryStyles(); + youtubeItemRegistry.clear(); + breadcrumb.innerHTML = `Live  ›  Tube`; + toolbar.innerHTML = ""; + installTopNav("tube"); + + content.innerHTML = ` + ${renderLibraryTabs("youtube")} +
+
+
+

YouTube

+
Search through the Kronic resolver. Videos you finish streaming are retained in the local watched-video cache.
+
+
Loading cache...
+
+ +
+ + +
+ +
+
+
+

Background Cache

+ Video → Tube cache · Audio → Music library +
+
Loading jobs…
+
+ +
Loading watched videos...
+
+ `; + bindLibraryTabs(); + + document.getElementById("youtubeSearchForm").addEventListener("submit", async event => { + event.preventDefault(); + const query = document.getElementById("youtubeSearchInput").value.trim(); + if (!query) return; + await searchYouTube(query); + }); + + await Promise.allSettled([ + loadYouTubeHistory(), + loadYouTubeCacheStatus(), + loadCacheJobs(), + ]); + clearInterval(cacheJobPollTimer); + cacheJobPollTimer = setInterval(loadCacheJobs, 1500); +} + +async function loadYouTubeCacheStatus() { + const target = document.getElementById("youtubeCacheStatus"); + if (!target) return; + try { + const state = await api("/api/youtube/cache/status"); + const maxText = state.max_gb > 0 ? `${state.max_gb} GB` : `${state.max_items} items`; + target.textContent = `${state.items} cached · ${formatByteSize(state.total_bytes)} / ${maxText}`; + } catch (error) { + target.textContent = `Cache unavailable: ${error.message}`; + } +} + +async function loadYouTubeHistory() { + const target = document.getElementById("youtubeHistoryArea"); + if (!target) return; + try { + const data = await api("/api/youtube/history?limit=60"); + const items = data.items || []; + const continueItems = items.filter(item => !item.completed && Number(item.position_seconds || 0) >= 30); + const recentItems = items.slice(0, 24); + + target.innerHTML = ` + ${continueItems.length ? `
Continue Watching ${continueItems.length} items
${continueItems.map(item => youtubeCardHtml(item, true)).join("")}
` : ""} + ${recentItems.length ? `
Recently Watched ${recentItems.length} items
${recentItems.map(item => youtubeCardHtml(item, true)).join("")}
` : `
No YouTube watch history yet.
`} + `; + registerYouTubeItems(items); + bindYouTubeWatchButtons(); + } catch (error) { + target.innerHTML = `
${escapeHtml(error.message)}
`; + } +} + +async function searchYouTube(query, existingItems=null) { + const target = document.getElementById("youtubeSearchArea"); + if (!target) return; + target.innerHTML = `
Search Results
Searching...
`; + try { + const data = existingItems === null ? await api(`/api/youtube/search?q=${encodeURIComponent(query)}&limit=24`) : {items:existingItems}; + const items = data.items || []; + registerYouTubeItems(items); + target.innerHTML = ` +
+ Search Results ${items.length} result${items.length === 1 ? "" : "s"} +
${items.map(item => youtubeCardHtml(item, false)).join("") || `
No results.
`}
+
+ `; + bindYouTubeWatchButtons(); + } catch (error) { + target.innerHTML = `
${escapeHtml(error.message)}
`; + } +} + +function registerYouTubeItems(items) { + for (const item of items || []) { + const id = item.id || item.video_id; + if (!id) continue; + youtubeItemRegistry.set(String(id), { + id: String(id), + title: item.title || id, + artist: item.artist || item.channel_name || "", + thumbnail: item.thumbnail || item.thumbnail_url || "", + duration: item.duration ?? item.duration_seconds ?? null, + cached: Boolean(item.cached), + position_seconds: Number(item.position_seconds || 0), + completed: Boolean(item.completed), + }); + } +} + +function youtubeCardHtml(item, historyMode=false) { + const id = String(item.id || item.video_id || ""); + const title = item.title || id; + const channel = item.artist || item.channel_name || ""; + const thumbnail = item.thumbnail || item.thumbnail_url || ""; + const duration = item.duration ?? item.duration_seconds; + const position = Number(item.position_seconds || 0); + const total = Number(duration || 0); + const progressPercent = total > 0 ? Math.max(0, Math.min(100, position * 100 / total)) : 0; + const cached = Boolean(item.cached); + + return ` +
+ +
+
${escapeHtml(title)}
+
${escapeHtml(channel)}
+
+ ${cached ? `Cached` : ""} + ${historyMode && position >= 30 && !item.completed ? `Resume ${escapeHtml(formatPlaybackTime(position))}` : ""} + ${historyMode && item.completed ? `Watched` : ""} +
+
+ + + ${item.is_live ? `` : ''} + +
+
+
+ `; +} + +async function queueYouTubeCache(item, mode){ + if(!item)return; + const label=mode==="music" + ?"Save as Music" + :(item.is_live?"Record Live":"Cache Video"); + try{ + const job=await api("/api/youtube/cache-job",{ + method:"POST", + headers:{"Content-Type":"application/json"}, + body:JSON.stringify({ + video_id:item.id, + mode, + title:item.title, + artist:item.artist, + thumbnail:item.thumbnail, + duration:item.duration, + }), + }); + console.debug(label,"queued",job); + await loadCacheJobs(); + }catch(error){ + alert(`${label} failed: ${error.message}`); + } +} + +async function cacheJobAction(jobId,action){ + try{ + await api(`/api/cache/jobs/${encodeURIComponent(jobId)}/${action}`,{ + method:"POST", + headers:{"Content-Type":"application/json"}, + body:"{}", + }); + await loadCacheJobs(); + }catch(error){ + alert(`Cache job ${action} failed: ${error.message}`); + } +} + +async function clearCacheJobs(statuses){ + try{ + await api("/api/cache/jobs/clear",{ + method:"POST", + headers:{"Content-Type":"application/json"}, + body:JSON.stringify({statuses}), + }); + await loadCacheJobs(); + }catch(error){ + alert(`Could not clear cache jobs: ${error.message}`); + } +} + +async function loadCacheJobs(){ + const target=document.getElementById("cacheJobsArea"); + if(!target)return; + try{ + const data=await api("/api/cache/jobs?limit=50"); + const jobs=data.jobs||[]; + + const toolbar=` +
+ + + +
`; + + if(!jobs.length){ + target.innerHTML=toolbar+`
No cache jobs.
`; + }else{ + target.innerHTML=toolbar+jobs.map(job=>{ + const title=job.title||job.video_id; + const live=Boolean(Number(job.is_live||0)); + const mode=job.mode==="music" + ?"Music audio" + :(live?"Live recording":"Video"); + const progress=Math.max(0,Math.min(100,Number(job.progress||0))); + + let actions=""; + if(job.status==="queued"||job.status==="running"){ + actions=``; + }else if(job.status==="failed"||job.status==="cancelled"){ + actions=` + + `; + }else if(job.status==="complete"){ + actions=``; + } + + const progressDisplay=(live&&job.status==="running") + ?`
LIVE
` + :`
${Math.round(progress)}%`; + + return `
+
+ ${escapeHtml(title)} + ${escapeHtml(mode)} · ${escapeHtml(job.status)} + ${job.error + ?`${escapeHtml(job.error)}` + :`${escapeHtml(job.message||"")}`} +
+
${progressDisplay}
+
${actions}
+
`; + }).join(""); + } + + target.querySelectorAll("[data-cache-job]").forEach(button=>{ + button.onclick=()=>cacheJobAction( + button.dataset.cacheJob, + button.dataset.cacheAction + ); + }); + target.querySelectorAll("[data-cache-clear]").forEach(button=>{ + button.onclick=()=>clearCacheJobs( + String(button.dataset.cacheClear||"") + .split(",") + .filter(Boolean) + ); + }); + + loadYouTubeCacheStatus().catch(()=>{}); + }catch(error){ + target.innerHTML=`
${escapeHtml(error.message)}
`; + } +} + +function bindYouTubeWatchButtons() { + document.querySelectorAll("[data-youtube-watch]").forEach(button => { + button.addEventListener("click", () => { + const item = youtubeItemRegistry.get(String(button.dataset.youtubeWatch)); + if (item) openYouTubePlayer(item); + }); + }); + document.querySelectorAll("[data-youtube-cache-video]").forEach(button=>{ + button.onclick=event=>{ + event.stopPropagation(); + queueYouTubeCache( + youtubeItemRegistry.get(String(button.dataset.youtubeCacheVideo)), + "video" + ); + }; + }); + document.querySelectorAll('[data-youtube-schedule]').forEach(button=>{ + button.onclick=event=>{ + event.stopPropagation(); + const item=youtubeItemRegistry.get(String(button.dataset.youtubeSchedule)); + if(item) openRecordingScheduler('youtube',String(item.id),item.title||'YouTube Live'); + }; + }); + document.querySelectorAll("[data-youtube-cache-music]").forEach(button=>{ + button.onclick=event=>{ + event.stopPropagation(); + queueYouTubeCache( + youtubeItemRegistry.get(String(button.dataset.youtubeCacheMusic)), + "music" + ); + }; + }); +} + +function ensureYouTubePlayerOverlay() { + if (youtubePlayerOverlay) return; + youtubePlayerOverlay = document.createElement("div"); + youtubePlayerOverlay.id = "youtubePlayerOverlay"; + youtubePlayerOverlay.className = "youtube-player-overlay"; + youtubePlayerOverlay.setAttribute("aria-hidden", "true"); + youtubePlayerOverlay.innerHTML = ` +
+
+
YouTube
+
+ + + + + +
+
+ +
+ `; + document.body.appendChild(youtubePlayerOverlay); + installMobileVideoBack(document.getElementById("youtubePlayerWindow"), () => closeYouTubePlayer()); + youtubeVideoElement = document.getElementById("youtubeVideoElement"); + + document.getElementById("youtubePlayerClose").onclick = closeYouTubePlayer; + document.getElementById("youtubePlayerCacheVideo").onclick = () => queueYouTubeCache(youtubeActiveItem, "video"); + document.getElementById("youtubePlayerSaveMusic").onclick = () => queueYouTubeCache(youtubeActiveItem, "music"); + + const tubeWindow = document.getElementById("youtubePlayerWindow"); + const tubeHeader = tubeWindow.querySelector(".youtube-player-header"); + const tubeMinimize = document.getElementById("youtubePlayerMinimize"); + + let tubeMinimized = false; + let tubeRestore = null; + let tubeDrag = null; + + function tubeGeometry(){ + const r=tubeWindow.getBoundingClientRect(); + return {left:r.left,top:r.top,width:r.width,height:r.height}; + } + + function placeTube(g){ + if(!g||window.innerWidth<=760)return; + const width=Math.max(360,Math.min(g.width,window.innerWidth-12)); + const height=Math.max(220,Math.min(g.height,window.innerHeight-12)); + tubeWindow.style.left=`${Math.max(0,Math.min(g.left,window.innerWidth-80))}px`; + tubeWindow.style.top=`${Math.max(0,Math.min(g.top,window.innerHeight-50))}px`; + tubeWindow.style.width=`${width}px`; + tubeWindow.style.height=`${height}px`; + tubeWindow.classList.add("youtube-floating-positioned"); + } + + tubeMinimize.onclick=()=>{ + if(!tubeMinimized){ + tubeRestore=tubeGeometry(); + tubeMinimized=true; + tubeWindow.classList.add("youtube-player-minimized"); + tubeMinimize.textContent="Restore"; + if(window.innerWidth>760){ + const width=Math.min(520,Math.max(320,tubeRestore.width||420)); + tubeWindow.style.width=`${width}px`; + tubeWindow.style.height=""; + tubeWindow.style.left=`${Math.max(8,window.innerWidth-width-18)}px`; + tubeWindow.style.top=`${Math.max(8,window.innerHeight-66)}px`; + tubeWindow.classList.add("youtube-floating-positioned"); + } + }else{ + tubeMinimized=false; + tubeWindow.classList.remove("youtube-player-minimized"); + tubeMinimize.textContent="Minimize"; + if(tubeRestore)placeTube(tubeRestore); + } + }; + + document.getElementById("youtubePlayerFullscreen").onclick = async () => { + try { + if (document.fullscreenElement === tubeWindow) await document.exitFullscreen(); + else { + if(tubeMinimized) tubeMinimize.click(); + await tubeWindow.requestFullscreen(); + } + } catch {} + }; + + tubeHeader.addEventListener("pointerdown",event=>{ + if(window.innerWidth<=760||tubeMinimized||document.fullscreenElement===tubeWindow)return; + if(event.button!==0||event.target.closest("button,input,select,a,video"))return; + const r=tubeWindow.getBoundingClientRect(); + tubeDrag={id:event.pointerId,x:event.clientX,y:event.clientY,left:r.left,top:r.top,width:r.width}; + tubeHeader.setPointerCapture?.(event.pointerId); + event.preventDefault(); + }); + tubeHeader.addEventListener("pointermove",event=>{ + if(!tubeDrag||tubeDrag.id!==event.pointerId)return; + const left=Math.max(0,Math.min(window.innerWidth-80,tubeDrag.left+event.clientX-tubeDrag.x)); + const top=Math.max(0,Math.min(window.innerHeight-50,tubeDrag.top+event.clientY-tubeDrag.y)); + tubeWindow.style.left=`${left}px`; + tubeWindow.style.top=`${top}px`; + tubeWindow.classList.add("youtube-floating-positioned"); + }); + const stopTubeDrag=()=>{ + if(!tubeDrag)return; + try{tubeHeader.releasePointerCapture?.(tubeDrag.id);}catch{} + tubeDrag=null; + }; + tubeHeader.addEventListener("pointerup",stopTubeDrag); + tubeHeader.addEventListener("pointercancel",stopTubeDrag); + + youtubePlayerOverlay.addEventListener("click", event => { + if (event.target === youtubePlayerOverlay) event.stopPropagation(); + }); + youtubeVideoElement.addEventListener("play", startYouTubeProgressTimer); + youtubeVideoElement.addEventListener("playing", () => clearTimeout(youtubeCacheFallbackTimer)); + youtubeVideoElement.addEventListener("pause", saveYouTubeProgress); + youtubeVideoElement.addEventListener("ended", async () => { + stopYouTubeProgressTimer(); + await saveYouTubeProgress(true); + }); + youtubeVideoElement.addEventListener("loadedmetadata", () => { + if ((!youtubeKnownDuration || youtubeKnownDuration <= 0) && Number.isFinite(youtubeVideoElement.duration) && youtubeVideoElement.duration > 0) { + youtubeKnownDuration = youtubeVideoElement.duration; + } + if (youtubePendingClientSeek !== null) { + try { youtubeVideoElement.currentTime = youtubePendingClientSeek; } catch {} + youtubePendingClientSeek = null; + } + }); +} + +async function openYouTubePlayer(item, options={}) { + ensureYouTubePlayerOverlay(); + await closeYouTubePlayer(false); + youtubeActiveItem = item; + const cacheButton=document.getElementById("youtubePlayerCacheVideo"); + if(cacheButton){ + cacheButton.textContent=item?.is_live ? "Record Live" : "Cache Video"; + } + youtubeKnownDuration = Number(item.duration) || null; + youtubePlaybackBaseOffset = 0; + youtubePendingClientSeek = null; + document.getElementById("youtubePlayerTitle").textContent = item.title || "YouTube"; + youtubePlayerOverlay.classList.add("active"); + youtubePlayerOverlay.setAttribute("aria-hidden", "false"); + document.body.classList.add("player-open"); + const tubeWindow=document.getElementById("youtubePlayerWindow"); + if(tubeWindow.classList.contains("youtube-player-minimized")){ + document.getElementById("youtubePlayerMinimize")?.click(); + } + if(window.innerWidth>760&&!tubeWindow.classList.contains("youtube-floating-positioned")){ + requestAnimationFrame(()=>{ + const width=Math.min(900,window.innerWidth-32); + const height=Math.min(560,window.innerHeight-32); + tubeWindow.style.width=`${width}px`; + tubeWindow.style.height=`${height}px`; + tubeWindow.style.left=`${Math.max(16,(window.innerWidth-width)/2)}px`; + tubeWindow.style.top=`${Math.max(16,(window.innerHeight-height)/2)}px`; + tubeWindow.classList.add("youtube-floating-positioned"); + }); + } + + try { + await api("/api/youtube/watch", { + method: "POST", + headers: {"Content-Type": "application/json"}, + body: JSON.stringify({ + video_id: item.id, + title: item.title, + channel_name: item.artist, + thumbnail_url: item.thumbnail, + duration_seconds: item.duration, + }), + }); + } catch (error) { + console.warn("Could not record YouTube watch:", error); + } + + let progress = {position_seconds: 0, completed: false, seek_mode: "server"}; + try { progress = await api(`/api/youtube/progress/${encodeURIComponent(item.id)}`); } catch {} + youtubeSeekMode = progress.seek_mode || "server"; + youtubeKnownDuration = Number(progress.duration_seconds) || youtubeKnownDuration; + const saved = Number(progress.position_seconds) || 0; + const duration = Number(progress.duration_seconds || youtubeKnownDuration) || 0; + let start = Number(options.startPosition) || 0; + let offer = !options.cast && !progress.completed && saved >= 30; + if (duration > 0 && (duration - saved <= 300 || saved / duration >= 0.95)) offer = false; + + if (offer) { + const resume = window.confirm(`Resume "${item.title}" from ${formatPlaybackTime(saved)}?\n\nOK = Resume\nCancel = Start Over`); + if (resume) start = saved; + else { + try { await api(`/api/youtube/progress/${encodeURIComponent(item.id)}`, {method: "DELETE"}); } catch {} + } + } + + if (youtubeSeekMode === "client") { + youtubeVideoElement.src = roomMediaUrl(`/api/youtube/video/${encodeURIComponent(item.id)}`); + if (start > 0) youtubePendingClientSeek = start; + } else { + youtubePlaybackBaseOffset = start; + youtubeVideoElement.src = roomMediaUrl(`/api/youtube/video/${encodeURIComponent(item.id)}${start > 0 ? `?start=${encodeURIComponent(start)}` : ""}`); + } + youtubeVideoElement.load(); + armYouTubeCacheFallback(item.id); + youtubeVideoElement.play().catch(error => console.debug("YouTube autoplay delayed or blocked", error)); +} + +// A cached YouTube MP4 can contain fragmented data from an earlier live mux. +// If the cached-file HTTP path never becomes playable, request a fresh mux for +// THIS browser without deleting or modifying the existing cache. +let youtubeCacheFallbackTimer=null; +let youtubeCacheFallbackVideoId=null; +function armYouTubeCacheFallback(videoId){ + clearTimeout(youtubeCacheFallbackTimer); + youtubeCacheFallbackVideoId=String(videoId); + if(youtubeSeekMode!=='client')return; + youtubeCacheFallbackTimer=setTimeout(()=>{ + if(!youtubeActiveItem || String(youtubeActiveItem.id)!==youtubeCacheFallbackVideoId || + !youtubeVideoElement || youtubeVideoElement.readyState>=3) return; + console.warn('[Kronic Media] Cached YouTube stream stalled; retrying uncached mux',videoId); + const element=youtubeVideoElement; + const wasPaused=element.paused; + const lastPosition=Number(element.currentTime)||0; + element.src=roomMediaUrl(`/api/youtube/video/${encodeURIComponent(videoId)}?uncached=1`); + youtubeSeekMode='server'; + youtubePlaybackBaseOffset=0; + youtubePendingClientSeek=lastPosition > 0 ? lastPosition : null; + element.load(); + if(!wasPaused || lastPosition===0)element.play().catch(err=>console.warn('[Kronic Media] Uncached retry autoplay blocked',err)); + },11000); +} +function getYouTubeAbsolutePosition() { + const local = Number(youtubeVideoElement?.currentTime) || 0; + return youtubeSeekMode === "server" ? youtubePlaybackBaseOffset + local : local; +} + +function startYouTubeProgressTimer() { + stopYouTubeProgressTimer(); + youtubeProgressTimer = setInterval(saveYouTubeProgress, 10000); +} + +function stopYouTubeProgressTimer() { + if (youtubeProgressTimer) { + clearInterval(youtubeProgressTimer); + youtubeProgressTimer = null; + } +} + +async function saveYouTubeProgress(forceCompleted=false) { + if (!youtubeActiveItem || !youtubeVideoElement) return; + const position = getYouTubeAbsolutePosition(); + if (position < 2 && !forceCompleted) return; + let duration = youtubeKnownDuration; + if ((!duration || duration <= 0) && Number.isFinite(youtubeVideoElement.duration) && youtubeVideoElement.duration > 0) duration = youtubeVideoElement.duration; + const completed = forceCompleted || Boolean(duration && duration > 0 && ((duration - position) <= 300 || position / duration >= 0.95)); + try { + await api(`/api/youtube/progress/${encodeURIComponent(youtubeActiveItem.id)}`, { + method: "POST", + headers: {"Content-Type": "application/json"}, + body: JSON.stringify({ + position_seconds: completed && duration ? duration : position, + duration_seconds: duration, + completed, + }), + }); + } catch (error) { + console.warn("Could not save YouTube playback progress:", error); + } +} + +async function closeYouTubePlayer(save=true) { + if (!youtubePlayerOverlay || !youtubeVideoElement) return; + stopYouTubeProgressTimer(); + if (save) await saveYouTubeProgress(false); + youtubeVideoElement.pause(); + youtubeVideoElement.removeAttribute("src"); + youtubeVideoElement.load(); + youtubePlayerOverlay.classList.remove("active"); + youtubePlayerOverlay.setAttribute("aria-hidden", "true"); + document.body.classList.remove("player-open"); + youtubeActiveItem = null; + youtubePlaybackBaseOffset = 0; + youtubeKnownDuration = null; + youtubePendingClientSeek = null; +} + + + +function ensureKronicCastClientId(){ + if(kronicCastClientId)return kronicCastClientId; + try{ + kronicCastClientId=localStorage.getItem("kronicCastClientId"); + if(!kronicCastClientId){ + kronicCastClientId=(crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`); + localStorage.setItem("kronicCastClientId",kronicCastClientId); + } + }catch{ + kronicCastClientId=`${Date.now()}-${Math.random()}`; + } + return kronicCastClientId; +} + +function kronicCastStatusFromVideo(){ + if(!youtubeVideoElement || !youtubeActiveItem)return "stopped"; + if(youtubeVideoElement.readyState < 3 && !youtubeVideoElement.paused)return "loading"; + if(youtubeVideoElement.ended)return "stopped"; + if(youtubeVideoElement.paused)return "paused"; + return "playing"; +} + +async function reportKronicCastState(force=false,statusOverride=null){ + if(!kronicCastClientId)return; + const now=Date.now(); + if(!force && now-kronicCastLastStateSent<1000)return; + kronicCastLastStateSent=now; + + const video=youtubeVideoElement; + const volume=video ? Math.round((Number(video.volume)||0)*100) : 100; + const duration=(youtubeKnownDuration&&Number(youtubeKnownDuration)>0) + ? Number(youtubeKnownDuration) + : (video&&Number.isFinite(video.duration)&&video.duration>0 ? Number(video.duration) : 0); + + try{ + await api("/api/cast/player-state",{ + method:"POST", + headers:{"Content-Type":"application/json"}, + body:JSON.stringify({ + client_id:kronicCastClientId, + status:statusOverride || kronicCastStatusFromVideo(), + position:youtubeActiveItem ? getYouTubeAbsolutePosition() : 0, + duration, + volume, + muted:Boolean(video?.muted), + video_id:youtubeActiveItem?.id || null, + }), + }); + }catch(error){ + console.debug("Kronic Cast state report failed",error); + } +} + +async function handleKronicCastCommand(message){ + if(!message?.command)return; + + const command=message.command; + if(command==="play"){ + const videoId=String(message.video_id||"").trim(); + if(!videoId)return; + + const item={ + id:videoId, + title:"YouTube Cast", + artist:"", + thumbnail:`https://i.ytimg.com/vi/${encodeURIComponent(videoId)}/hqdefault.jpg`, + duration:null, + }; + await openYouTubePlayer(item,{ + cast:true, + startPosition:Number(message.position)||0, + }); + await reportKronicCastState(true); + return; + } + + if(command==="pause"){ + youtubeVideoElement?.pause(); + await reportKronicCastState(true,"paused"); + return; + } + + if(command==="resume"){ + if(youtubeVideoElement){ + try{await youtubeVideoElement.play();}catch{} + } + await reportKronicCastState(true); + return; + } + + if(command==="seek"){ + if(!youtubeActiveItem || !youtubeVideoElement)return; + const target=Math.max(0,Number(message.position)||0); + + // Client-seekable media can seek in place. Server-seek streams (and + // live/remux paths) are reopened at the requested source position. + if(youtubeSeekMode==="client"){ + try{ + youtubeVideoElement.currentTime=target; + await youtubeVideoElement.play(); + }catch{} + }else{ + const item={...youtubeActiveItem}; + await openYouTubePlayer(item,{cast:true,startPosition:target}); + } + await reportKronicCastState(true,"loading"); + return; + } + + if(command==="volume"){ + if(youtubeVideoElement){ + youtubeVideoElement.volume=Math.max(0,Math.min(1,(Number(message.volume)||0)/100)); + } + await reportKronicCastState(true); + return; + } + + if(command==="stop"){ + await closeYouTubePlayer(false); + await reportKronicCastState(true,"stopped"); + } +} + +async function kronicCastLoop(){ + if(kronicCastRunning)return; + kronicCastRunning=true; + ensureKronicCastClientId(); + + while(kronicCastRunning){ + try{ + const response=await api( + `/api/cast/command?client_id=${encodeURIComponent(kronicCastClientId)}&after=${encodeURIComponent(kronicCastSeq)}&timeout=20` + ); + + if(Number(response?.seq)>kronicCastSeq){ + kronicCastSeq=Number(response.seq); + } + + if(response?.active && response?.command){ + await handleKronicCastCommand(response); + }else if(response?.standby){ + await new Promise(resolve=>setTimeout(resolve,2000)); + } + }catch(error){ + console.debug("Kronic Cast long-poll reconnect",error); + await new Promise(resolve=>setTimeout(resolve,1500)); + } + } +} + +function bindKronicCastPlayerState(){ + ensureYouTubePlayerOverlay(); + + const video=youtubeVideoElement; + if(!video)return; + + ["play","pause","waiting","seeking","seeked","loadedmetadata","volumechange"].forEach(name=>{ + video.addEventListener(name,()=>reportKronicCastState(true)); + }); + + video.addEventListener("ended",()=>reportKronicCastState(true,"stopped")); + + clearInterval(kronicCastStateTimer); + kronicCastStateTimer=setInterval(()=>{ + if(youtubeActiveItem)reportKronicCastState(false); + },5000); +} + +function startKronicCastReceiverBridge(){ + ensureKronicCastClientId(); + bindKronicCastPlayerState(); + kronicCastLoop(); +} + +// ============================================================ +// IPTV / CURATED M3U SOURCES +// ============================================================ + +function ensureIptvStyles() { + if (document.getElementById("iptvStyles")) return; + const link = document.createElement("link"); + link.id = "iptvStyles"; + link.rel = "stylesheet"; + link.href = "/CSS/iptv.css"; + document.head.appendChild(link); +} + +async function getIptvOverview(force=false) { + if (!force && iptvOverviewCache) return iptvOverviewCache; + iptvOverviewCache = await api("/api/iptv/overview"); + return iptvOverviewCache; +} + +function iptvCollectionOptions(collections, selectedId=null) { + const chosen = selectedId == null ? "" : String(selectedId); + return ` + + ${(collections || []).map(item => ` + + `).join("")} + `; +} + +let iptvViewMode = "library"; + +async function showIptvLibrary(mode="library") { + clearScanPolling(); + resetLibraryContext(); + ensureIptvStyles(); + iptvViewMode = mode === "settings" ? "settings" : "library"; + breadcrumb.innerHTML = iptvViewMode === "settings" + ? `Live  ›  IPTV  ›  Settings` + : `Live  ›  IPTV`; + toolbar.innerHTML = ""; + installTopNav("iptv"); + + content.innerHTML = `
Loading IPTV…
`; + + try { + const overview = await getIptvOverview(true); + if (iptvViewMode === "settings") renderIptvSettingsPage(overview); + else renderIptvChannelPage(overview); + } catch (error) { + showError(error); + } +} + +function renderIptvChannelPage(overview) { + const channels = overview.channels || []; + content.innerHTML = ` +
+
+
+

IPTV

+
Live channels
+
+
+
+
+

Channels

+ +
+
${iptvSelectedChannelsHtml(channels)}
+
+
`; + bindIptvChannelOnly(); +} + +function renderIptvSettingsPage(overview) { + const collections = overview.collections || []; + const sources = overview.sources || []; + + content.innerHTML = ` +
+
+
+

IPTV Settings

+
Add playlists, direct channels, sharing and channel selections.
+
+ +
+ +
+
+
+

Playlists

+
+ + + +
+
+ ${collections.length ? collections.map(c => ` +
+ ${escapeHtml(c.name)}${c.channel_count || 0} selected channels + + +
`).join("") : `
No named playlists yet.
`} +
+
+ +
+

1. Upload M3U

+
+ + + + + +
+
+ +
+

2. M3U URL

+
+ + + + + +
+
+ +
+

3. Direct Channel URL

+
+ + + + + +
+
+
+ +
+

Sources

Choose exactly which channels from each list appear in IPTV.
+
+ ${sources.length ? sources.map(source => iptvSourceRow(source, collections)).join("") : `
No IPTV sources yet.
`} +
+
+
+
`; + + document.getElementById("iptvSettingsWatch")?.addEventListener("click", () => showIptvLibrary("library")); + bindIptvPage(overview); +} + +function bindIptvChannelOnly() { + const search = document.getElementById("iptvChannelSearch"); + if (search) search.oninput = () => filterIptvChannels(search.value); + bindIptvSnapshotFallbacks(); + bindIptvChannelActions(); +} + +function iptvSourceRow(source, collections) { + const error = source.last_error ? `
${escapeHtml(source.last_error)}
` : ""; + const kind = source.source_type === "upload" ? "Uploaded M3U" : (source.source_type === "url" ? "Remote M3U" : "Direct channel"); + return ` +
+
+ ${escapeHtml(source.name)} + ${escapeHtml(kind)} · ${source.selected_count || 0}/${source.channel_count || 0} selected + ${error} +
+ + + ${source.source_type !== "channel" ? `` : ""} + +
+ `; +} + +function iptvSelectedChannelsHtml(channels) { + if (!channels.length) return `
No channels selected yet. Add a source, then choose the channels you want.
`; + + const groups = new Map(); + for (const channel of channels) { + const collection = channel.display_collection_name || channel.collection_name || (channel.is_shared ? "Shared Channels" : "My Channels"); + const group = channel.group_name || channel.source_name || "Channels"; + const key = `${collection}\u0000${group}`; + if (!groups.has(key)) groups.set(key, {collection, group, channels:[]}); + groups.get(key).channels.push(channel); + } + + return [...groups.values()].map(section => ` +
+
+
${escapeHtml(section.collection)}${escapeHtml(section.group)}
+ ${section.channels.length} channel${section.channels.length === 1 ? "" : "s"} +
+
+ ${section.channels.map(channel => iptvChannelCard(channel)).join("")} +
+
+ `).join(""); +} + +function iptvChannelCard(channel) { + const fallback = channel.tvg_logo ? escapeAttribute(channel.tvg_logo) : ""; + const snapshot = roomMediaUrl(`/api/iptv/channels/${channel.id}/snapshot`); + const fallbackAttr = fallback ? `data-fallback="${fallback}"` : ""; + return ` +
+
+ +
LIVE
+
+
+
+ ${escapeHtml(channel.name)}${Number(channel.is_shared) ? ` SHARED` : ""} + ${escapeHtml(channel.group_name || channel.source_name || "")} + ${channel.tvg_id ? `${escapeHtml(channel.tvg_id)}` : ""} +
+ + +
+
+
`; +} + +function bindIptvPage(overview) { + + document.getElementById("iptvCollectionForm")?.addEventListener("submit", async event => { + event.preventDefault(); + const name = document.getElementById("iptvCollectionName").value.trim(); + if (!name) return; + try { + await api("/api/iptv/collections", { + method:"POST", + headers:{"Content-Type":"application/json"}, + body:JSON.stringify({ + name, + is_public:document.getElementById("iptvCollectionPublic")?.checked || false, + }), + }); + iptvOverviewCache = null; + await showIptvLibrary("settings"); + document.getElementById("iptvManagePanel").hidden = false; + } catch (error) { alert(error.message); } + }); + + document.getElementById("iptvUploadForm")?.addEventListener("submit", async event => { + event.preventDefault(); + const file = document.getElementById("iptvUploadFile").files?.[0]; + if (!file) return; + const text = await file.text(); + await addIptvSource({ + name: document.getElementById("iptvUploadName").value.trim(), + source_type:"upload", + source_payload:text, + collection_id: document.getElementById("iptvUploadCollection").value || null, + is_public:document.getElementById("iptvUploadPublic")?.checked || false, + }); + }); + + document.getElementById("iptvUrlForm")?.addEventListener("submit", async event => { + event.preventDefault(); + await addIptvSource({ + name: document.getElementById("iptvUrlName").value.trim(), + source_type:"url", + source_value: document.getElementById("iptvUrlValue").value.trim(), + collection_id: document.getElementById("iptvUrlCollection").value || null, + is_public:document.getElementById("iptvUrlPublic")?.checked || false, + }); + }); + + document.getElementById("iptvChannelForm")?.addEventListener("submit", async event => { + event.preventDefault(); + const name = document.getElementById("iptvChannelName").value.trim(); + await addIptvSource({ + name, + channel_name:name, + source_type:"channel", + source_value: document.getElementById("iptvChannelUrl").value.trim(), + collection_id: document.getElementById("iptvChannelCollection").value || null, + is_public:document.getElementById("iptvChannelPublic")?.checked || false, + }); + }); + + document.querySelectorAll("[data-iptv-choose]").forEach(button => { + button.onclick = () => showIptvSourceChooser(Number(button.dataset.iptvChoose)); + }); + document.querySelectorAll("[data-iptv-refresh]").forEach(button => { + button.onclick = async () => { + button.disabled = true; + button.textContent = "Refreshing…"; + try { + await api(`/api/iptv/sources/${button.dataset.iptvRefresh}/refresh`, {method:"POST"}); + iptvOverviewCache = null; + await showIptvLibrary("settings"); + document.getElementById("iptvManagePanel").hidden = false; + } catch (error) { alert(error.message); button.disabled = false; button.textContent = "Refresh"; } + }; + }); + document.querySelectorAll("[data-iptv-delete-source]").forEach(button => { + button.onclick = async () => { + if (!confirm("Delete this IPTV source and its imported channels?")) return; + await api(`/api/iptv/sources/${button.dataset.iptvDeleteSource}`, {method:"DELETE"}); + iptvOverviewCache = null; + await showIptvLibrary("settings"); + document.getElementById("iptvManagePanel").hidden = false; + }; + }); + document.querySelectorAll("[data-iptv-delete-collection]").forEach(button => { + button.onclick = async () => { + if (!confirm("Delete this playlist? Sources are kept and moved back to My Channels.")) return; + await api(`/api/iptv/collections/${button.dataset.iptvDeleteCollection}`, {method:"DELETE"}); + iptvOverviewCache = null; + await showIptvLibrary("settings"); + document.getElementById("iptvManagePanel").hidden = false; + }; + }); + document.querySelectorAll("[data-iptv-collection-public]").forEach(box => { + box.onchange = async () => { + box.disabled = true; + try { + await api(`/api/iptv/collections/${box.dataset.iptvCollectionPublic}/public`, { + method:"PATCH", + headers:{"Content-Type":"application/json"}, + body:JSON.stringify({is_public:box.checked}), + }); + iptvOverviewCache = null; + } catch (error) { + box.checked = !box.checked; + alert(error.message); + } finally { + box.disabled = false; + } + }; + }); + + document.querySelectorAll("[data-iptv-source-public]").forEach(box => { + box.onchange = async () => { + box.disabled = true; + try { + await api(`/api/iptv/sources/${box.dataset.iptvSourcePublic}/public`, { + method:"PATCH", + headers:{"Content-Type":"application/json"}, + body:JSON.stringify({is_public:box.checked}), + }); + iptvOverviewCache = null; + } catch (error) { + box.checked = !box.checked; + alert(error.message); + } finally { + box.disabled = false; + } + }; + }); + + document.querySelectorAll("[data-iptv-source-collection]").forEach(select => { + select.onchange = async () => { + await api(`/api/iptv/sources/${select.dataset.iptvSourceCollection}/collection`, { + method:"PATCH", headers:{"Content-Type":"application/json"}, + body:JSON.stringify({collection_id:select.value || null}), + }); + iptvOverviewCache = null; + }; + }); + bindIptvChannelActions(); + + document.getElementById("iptvChannelSearch")?.addEventListener("input", event => { + const query = event.target.value.trim().toLowerCase(); + document.querySelectorAll("[data-iptv-channel-card]").forEach(card => { + card.hidden = !!query && !String(card.dataset.search || "").includes(query); + }); + document.querySelectorAll("[data-iptv-group]").forEach(group => { + const visible = [...group.querySelectorAll("[data-iptv-channel-card]")].some(card => !card.hidden); + group.hidden = !visible; + }); + }); +} + +async function addIptvSource(payload) { + try { + const source = await api("/api/iptv/sources", { + method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify(payload), + }); + iptvOverviewCache = null; + if (payload.source_type === "channel") { + await showIptvLibrary("settings"); + } else { + await showIptvSourceChooser(Number(source.id)); + } + } catch (error) { + alert(error.message); + } +} + +async function showIptvSourceChooser(sourceId) { + ensureIptvStyles(); + breadcrumb.innerHTML = `Libraries  ›  IPTV  ›  Choose Channels`; + toolbar.innerHTML = ``; + document.getElementById("iptvChooserBack").onclick = () => showIptvLibrary("settings"); + content.innerHTML = `
Loading channels…
`; + + try { + const data = await api(`/api/iptv/sources/${sourceId}/channels`); + const source = data.source; + const channels = data.channels || []; + content.innerHTML = ` +
+
+

${escapeHtml(source?.name || "IPTV source")}

Check only the channels you want in your IPTV channel list.
+ 0 / ${channels.length} selected +
+
+ + + + +
+
+ ${channels.map(channel => ` + + `).join("") || `
No channels were found in this source.
`} +
+
+ `; + + const updateCount = () => { + const count = document.querySelectorAll("[data-iptv-choice]:checked").length; + const target = document.getElementById("iptvCheckedCount"); + if (target) target.textContent = String(count); + }; + document.querySelectorAll("[data-iptv-choice]").forEach(box => box.onchange = updateCount); + updateCount(); + + document.getElementById("iptvChooserSearch").oninput = event => { + const query = event.target.value.trim().toLowerCase(); + document.querySelectorAll("[data-iptv-choice-row]").forEach(row => { + row.hidden = !!query && !String(row.dataset.search || "").includes(query); + }); + }; + document.getElementById("iptvSelectVisible").onclick = () => { + document.querySelectorAll("[data-iptv-choice-row]").forEach(row => { + if (!row.hidden) row.querySelector("[data-iptv-choice]").checked = true; + }); + updateCount(); + }; + document.getElementById("iptvClearVisible").onclick = () => { + document.querySelectorAll("[data-iptv-choice-row]").forEach(row => { + if (!row.hidden) row.querySelector("[data-iptv-choice]").checked = false; + }); + updateCount(); + }; + document.getElementById("iptvSaveSelection").onclick = async () => { + const ids = [...document.querySelectorAll("[data-iptv-choice]:checked")].map(box => Number(box.dataset.iptvChoice)); + await api(`/api/iptv/sources/${sourceId}/selection`, { + method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify({channel_ids:ids}), + }); + iptvOverviewCache = null; + await showIptvLibrary("settings"); + }; + } catch (error) { + showError(error); + } +} + +function bindIptvSnapshotFallbacks() { + document.querySelectorAll(".iptv-channel-snapshot").forEach(img => { + img.addEventListener("error", () => { + const fallback = img.dataset.fallback; + if (fallback && img.src !== fallback) { + img.dataset.fallback = ""; + img.src = fallback; + return; + } + img.closest(".iptv-channel-visual")?.classList.add("snapshot-missing"); + img.remove(); + }, {once:false}); + }); +} + +let playerFloatingInstalled = false; +function ensurePlayerMinimizeButton() { + if (playerMinimizeButton?.isConnected) return playerMinimizeButton; + const header=playerTitle?.parentElement||playerWindow?.firstElementChild; + if (!header) return null; + playerMinimizeButton=document.createElement("button"); + playerMinimizeButton.type="button"; + playerMinimizeButton.id="playerMinimizeButton"; + playerMinimizeButton.onclick=e=>{e.stopPropagation();togglePlayerMinimized();}; + if (playerFullscreenButton?.parentElement===header) header.insertBefore(playerMinimizeButton,playerFullscreenButton); + else if (playerCloseButton?.parentElement===header) header.insertBefore(playerMinimizeButton,playerCloseButton); + else header.appendChild(playerMinimizeButton); + updateMinimizeButton(); + return playerMinimizeButton; +} +function installPlayerResizeHandles() { + if (!playerWindow || playerResizeHandles.length) return; + for (const d of ["n","ne","e","se","s","sw","w","nw"]) { + const h=document.createElement("div"); + h.className=`player-resize-handle player-resize-${d}`; h.dataset.resizeDirection=d; + playerWindow.appendChild(h); playerResizeHandles.push(h); + let rs=null; + h.addEventListener("pointerdown",e=>{ + if(window.innerWidth<=760||playerMinimized||document.fullscreenElement===playerWindow||e.button!==0)return; + const r=playerWindow.getBoundingClientRect(); + rs={id:e.pointerId,x:e.clientX,y:e.clientY,left:r.left,top:r.top,width:r.width,height:r.height}; + h.setPointerCapture?.(e.pointerId); e.preventDefault(); e.stopPropagation(); + }); + h.addEventListener("pointermove",e=>{ + if(!rs||rs.id!==e.pointerId)return; + const dx=e.clientX-rs.x,dy=e.clientY-rs.y,minW=360,minH=220; + let l=rs.left,t=rs.top,w=rs.width,hh=rs.height; + if(d.includes("e"))w=Math.max(minW,rs.width+dx); + if(d.includes("s"))hh=Math.max(minH,rs.height+dy); + if(d.includes("w")){w=Math.max(minW,rs.width-dx);l=rs.left+(rs.width-w);} + if(d.includes("n")){hh=Math.max(minH,rs.height-dy);t=rs.top+(rs.height-hh);} + l=Math.max(0,l);t=Math.max(0,t); + w=Math.min(w,window.innerWidth-l-4);hh=Math.min(hh,window.innerHeight-t-4); + playerWindow.style.left=`${l}px`;playerWindow.style.top=`${t}px`; + playerWindow.style.width=`${Math.max(minW,w)}px`;playerWindow.style.height=`${Math.max(minH,hh)}px`; + playerWindow.classList.add("floating-player-positioned"); + }); + const stop=()=>{if(!rs)return;try{h.releasePointerCapture?.(rs.id);}catch{}rs=null;}; + h.addEventListener("pointerup",stop);h.addEventListener("pointercancel",stop); + } +} +function setupFloatingPlayer() { + if(playerFloatingInstalled||!playerWindow||!playerOverlay)return; + playerFloatingInstalled=true; + playerOverlay.classList.add("persistent-player-overlay"); + playerWindow.classList.add("floating-player-window"); + ensurePlayerMinimizeButton();installPlayerResizeHandles(); + const handle=playerTitle?.parentElement||playerWindow.firstElementChild; + handle?.classList.add("floating-player-handle"); + let drag=null; + handle?.addEventListener("dblclick",e=>{if(!e.target.closest("button,a,input,select,video"))togglePlayerMinimized();}); + handle?.addEventListener("pointerdown",e=>{ + if(window.innerWidth<=760||playerMinimized||document.fullscreenElement===playerWindow||e.button!==0)return; + if(e.target.closest("button,a,input,select,video,.player-resize-handle"))return; + const r=playerWindow.getBoundingClientRect(); + Object.assign(playerWindow.style,{width:`${r.width}px`,height:`${r.height}px`,left:`${r.left}px`,top:`${r.top}px`}); + playerWindow.classList.add("floating-player-positioned"); + drag={id:e.pointerId,x:e.clientX,y:e.clientY,left:r.left,top:r.top,width:r.width}; + handle.setPointerCapture?.(e.pointerId);e.preventDefault(); + }); + handle?.addEventListener("pointermove",e=>{ + if(!drag||drag.id!==e.pointerId)return; + const l=Math.max(0,Math.min(window.innerWidth-80,drag.left+e.clientX-drag.x)); + const t=Math.max(0,Math.min(window.innerHeight-50,drag.top+e.clientY-drag.y)); + playerWindow.style.left=`${l}px`;playerWindow.style.top=`${t}px`; + }); + const stop=()=>{if(!drag)return;try{handle.releasePointerCapture?.(drag.id);}catch{}drag=null;}; + handle?.addEventListener("pointerup",stop);handle?.addEventListener("pointercancel",stop); +} +function prepareFloatingPlayerPosition() { + setupFloatingPlayer(); + if(!playerWindow||document.fullscreenElement===playerWindow)return; + if(window.innerWidth<=760){ + playerWindow.classList.remove("floating-player-positioned"); + for(const k of ["left","top","width","height"])playerWindow.style.removeProperty(k); + return; + } + if(playerMinimized)restorePlayer(); + if(!playerWindow.classList.contains("floating-player-positioned")){ + requestAnimationFrame(()=>{ + const r=playerWindow.getBoundingClientRect(); + const w=Math.min(Math.max(r.width||860,560),window.innerWidth-24); + const h=Math.min(Math.max(r.height||540,340),window.innerHeight-24); + applyPlayerGeometry({left:(window.innerWidth-w)/2,top:(window.innerHeight-h)/2,width:w,height:h}); + }); + } +} + +function bindIptvChannelActions() { + document.querySelectorAll("[data-iptv-play]").forEach(button => { + button.onclick = () => openIptvChannel({ + id:Number(button.dataset.iptvPlay), + name:button.dataset.iptvTitle || "Live TV", + }); + }); + document.querySelectorAll("[data-iptv-hide]").forEach(button => { + button.onclick = async () => { + await api(`/api/iptv/channels/${button.dataset.iptvHide}`, { + method:"PATCH", headers:{"Content-Type":"application/json"}, body:JSON.stringify({hidden:true}), + }); + iptvOverviewCache = null; + await showIptvLibrary(); + }; + }); +} + +async function openIptvChannel(channel) { + if (!mediaPlayer) return; + await saveCurrentPlaybackProgress(); + stopPlaybackSaveTimer(); + resetPlayerHealth(); + mediaPlayer.pause(); + mediaPlayer.removeAttribute("src"); + mediaPlayer.load(); + + activeMediaId = null; + activeMediaTitle = channel.name; + activeIptvChannel = channel; + playbackFallbackUsed = false; + playbackBaseOffset = 0; + playbackKnownDuration = null; + pendingClientSeek = null; + activePlaybackPlan = null; + + playerTitle.textContent = `${channel.name} · LIVE`; + installMobileVideoBack(playerWindow,()=>closePlayer()); + playerOverlay.classList.add("active"); + playerOverlay.setAttribute("aria-hidden", "false"); + document.body.classList.add("player-open"); + playerWindow?.classList.remove("player-minimized"); + playerMinimized=false; + updateMinimizeButton(); + prepareFloatingPlayerPosition(); + showPlayerStatus("Connecting to live stream and normalizing it for this browser…"); + await beginIptvPlayback(channel, false); +} + +async function beginIptvPlayback(channel, retry=false) { + if (!channel || !mediaPlayer) return; + if (retry) { + mediaPlayer.pause(); + mediaPlayer.removeAttribute("src"); + mediaPlayer.load(); + await new Promise(resolve => setTimeout(resolve, 350)); + } + activeIptvChannel = channel; + showPlayerStatus(retry ? "Reconnecting live stream…" : "Buffering live stream…"); + mediaPlayer.src = roomMediaUrl(`/api/iptv/channels/${channel.id}/play?ts=${Date.now()}`); + mediaPlayer.load(); + // Starting a live stream can leave play() pending for a long time. + // Never hold the LiveKit room-event queue hostage to network buffering. + mediaPlayer.play().catch(error => console.debug("IPTV play did not start immediately:", error)); +} + +injectYouTubeMetadataStyles(); +async function bootMediaServer() { + try { + mediaAuthContext = await api("/api/auth/media-context"); + document.body.dataset.hasMediaAccess = String(!!mediaAuthContext.hasMediaAccess); + const rooms = await api('/api/my/assigned-rooms'); + const room = (rooms.rooms || []).find(r => String(r.id) === document.body.dataset.roomId); + document.body.dataset.roomOwner = String(room?.role === 'owner'); + const rename = document.getElementById('mobileRenameRoom'); + if (rename) rename.hidden = !(room?.role === 'owner' || mediaAuthContext.isPlatformAdmin); + ensureInterfaceRefreshStyles(); + installTopNav(); + setupVideoPlayer(); + setupFloatingPlayer(); + setupNavigation(); + startKronicCastReceiverBridge(); + const accountKey = 'kronic.start-view.v1.' + String(mediaAuthContext?.user?.username || 'guest').toLowerCase(); + const startView = localStorage.getItem(accountKey) || 'room'; + if (startView === 'libraries' && mediaAuthContext.hasMediaAccess) { + await showLibraries(); + window.dispatchEvent(new CustomEvent('kronic:preferred-start-view', {detail:{section:'libraries'}})); + } else { + // The room shell is the default landing screen; defer library fetch until requested. + window.dispatchEvent(new CustomEvent('kronic:preferred-start-view', {detail:{section:'room'}})); + } + } catch (error) { + if (content) showError(error); + } +} + +bootMediaServer(); + + +function ensureMusicStyles(){ + if(document.getElementById("musicLibraryStyles"))return; + const link=document.createElement("link"); + link.id="musicLibraryStyles"; link.rel="stylesheet"; link.href="/CSS/music.css"; + document.head.appendChild(link); +} + +// Move the persistent music player without interrupting audio. Double-click the +// cover/title region to re-dock at the bottom. Positions are local per browser. +function setupDraggableMusicPlayer(root) { + const storageKey = "kronic.music.player.position.v1"; + function setPosition(left, top) { + const width = root.offsetWidth, height = root.offsetHeight; + root.style.left = Math.max(0, Math.min(window.innerWidth - width, left)) + "px"; + root.style.top = Math.max(0, Math.min(window.innerHeight - height, top)) + "px"; + root.style.right = "auto"; + root.style.bottom = "auto"; + root.classList.add("music-undocked"); + } + function dock() { + root.classList.remove("music-undocked"); + for (const property of ["left", "top", "right", "bottom"]) root.style.removeProperty(property); + try { localStorage.removeItem(storageKey); } catch (_) {} + } + let saved; + try { saved = JSON.parse(localStorage.getItem(storageKey) || "null"); } catch (_) {} + if (saved && Number.isFinite(saved.left) && Number.isFinite(saved.top)) { + requestAnimationFrame(() => setPosition(saved.left, saved.top)); + } + const handles = [root.querySelector(".music-player-info"), root.querySelector(".music-player-cover")]; + let drag = null; + for (const handle of handles) { + if (!handle) continue; + handle.classList.add("music-drag-handle"); + handle.title = "Drag to move · Double-click to dock"; + handle.addEventListener("dblclick", dock); + handle.addEventListener("pointerdown", event => { + if (event.button !== 0) return; + const rect = root.getBoundingClientRect(); + drag = { id: event.pointerId, x: event.clientX, y: event.clientY, left: rect.left, top: rect.top }; + handle.setPointerCapture(event.pointerId); + event.preventDefault(); + }); + handle.addEventListener("pointermove", event => { + if (!drag || drag.id !== event.pointerId) return; + setPosition(drag.left + event.clientX - drag.x, drag.top + event.clientY - drag.y); + }); + const finish = event => { + if (!drag || drag.id !== event.pointerId) return; + drag = null; + if (root.classList.contains("music-undocked")) { + try { localStorage.setItem(storageKey, JSON.stringify({ left: parseFloat(root.style.left), top: parseFloat(root.style.top) })); } catch (_) {} + } + }; + handle.addEventListener("pointerup", finish); + handle.addEventListener("pointercancel", finish); + } + window.addEventListener("resize", () => { + if (root.classList.contains("music-undocked")) { + setPosition(parseFloat(root.style.left) || 0, parseFloat(root.style.top) || 0); + } + }); +} + +function ensureMusicPlayer(){ + if(musicPlayer?.root?.isConnected)return musicPlayer; + const root=document.createElement("div"); + root.id="musicPersistentPlayer"; + root.className="music-persistent-player"; + root.innerHTML=` + +
Nothing playing
+ + + + +
+
+ + + + +
+
+ 0:00 + + 0:00 + +
+
`; + document.body.appendChild(root); + const audio=root.querySelector("#musicAudio"); + musicPlayer={root,audio,cover:root.querySelector("#musicPlayerCover"),title:root.querySelector("#musicPlayerTitle"),artist:root.querySelector("#musicPlayerArtist")}; + root.querySelector("#musicPrev").onclick=()=>playMusicQueueOffset(-1); + root.querySelector("#musicNext").onclick=()=>playMusicQueueOffset(1); + root.querySelector("#musicClose").onclick=()=>{audio.pause();audio.removeAttribute("src");audio.load();root.classList.remove("active");musicQueueIndex=-1;}; + const touchToggle=root.querySelector("#musicTouchToggle"); + const touchSeek=root.querySelector("#musicTouchSeek"); + const elapsed=root.querySelector("#musicTouchElapsed"); + const duration=root.querySelector("#musicTouchDuration"); + const mute=root.querySelector("#musicTouchMute"); + const timeText=value=>{if(!Number.isFinite(value))return "0:00";const n=Math.floor(value);return `${Math.floor(n/60)}:${String(n%60).padStart(2,"0")}`;}; + const sync=()=>{ + const length=audio.duration; + touchToggle.textContent=audio.paused?"▶":"❚❚"; + touchToggle.setAttribute("aria-label",audio.paused?"Play":"Pause"); + elapsed.textContent=timeText(audio.currentTime); + duration.textContent=timeText(length); + if(!touchSeek.matches(":active") && document.activeElement!==touchSeek) + touchSeek.value=Number.isFinite(length)&&length>0?String(Math.round(audio.currentTime/length*1000)):"0"; + touchSeek.disabled=!(Number.isFinite(length)&&length>0); + mute.textContent=audio.muted?"◖×":"◖))"; + mute.setAttribute("aria-label",audio.muted?"Unmute":"Mute"); + }; + root.querySelector("#musicTouchPrev").onclick=()=>playMusicQueueOffset(-1); + root.querySelector("#musicTouchNext").onclick=()=>playMusicQueueOffset(1); + root.querySelector("#musicTouchClose").onclick=()=>root.querySelector("#musicClose").click(); + touchToggle.onclick=()=>{if(audio.paused)audio.play().catch(()=>{});else audio.pause();}; + mute.onclick=()=>{audio.muted=!audio.muted;sync();}; + touchSeek.addEventListener("input",()=>{if(Number.isFinite(audio.duration)&&audio.duration>0){audio.currentTime=audio.duration*Number(touchSeek.value)/1000;sync();}}); + for(const event of ["timeupdate","loadedmetadata","durationchange","play","pause","volumechange","emptied"])audio.addEventListener(event,sync); + sync(); + audio.addEventListener("ended",()=>playMusicQueueOffset(1)); + setupDraggableMusicPlayer(root); + return musicPlayer; +} + +function playMusicQueueOffset(delta){ + if(!musicQueue.length)return; + let next=musicQueueIndex+delta; + if(next<0)next=musicQueue.length-1; + if(next>=musicQueue.length)next=0; + playMusicTrack(musicQueue[next], musicQueue, next); +} + +async function playMusicTrack(track, queue=null, index=null){ + const p=ensureMusicPlayer(); + if(queue){musicQueue=[...queue];musicQueueIndex=index ?? musicQueue.findIndex(x=>x.id===track.id);} + else if(musicQueueIndex<0){musicQueue=[track];musicQueueIndex=0;} + p.title.textContent=track.title||"Unknown"; + p.artist.textContent=[track.artist,track.album].filter(Boolean).join(" · "); + p.cover.src=roomMediaUrl(track.cover_url||""); + p.cover.style.visibility=track.cover_url?"visible":"hidden"; + p.root.classList.add("active"); + p.audio.src=roomMediaUrl(`/api/music/tracks/${encodeURIComponent(track.id)}/audio`); + p.audio.load(); + p.audio.play().catch(error=>console.debug("Music playback did not start immediately",error)); +} + +function musicTrackCard(track,queue,index){ + musicTrackRegistry.set(String(track.id),track); + const cover=track.cover_url?``:`
♪
`; + return `
+ +
+ ${escapeHtml(track.title||"Unknown")} + ${escapeHtml(track.artist||"")} + ${escapeHtml(track.album||track.list_name||"")} +
${track.cached?`Cached`:""}
+
+
`; +} + +function bindMusicCards(tracks){ + document.querySelectorAll("[data-music-play]").forEach(button=>{ + button.onclick=()=>{ + const id=Number(button.dataset.musicPlay); + const index=tracks.findIndex(item=>Number(item.id)===id); + if(index>=0)playMusicTrack(tracks[index],tracks,index); + }; + }); +} + +async function loadMusicTracks(query=""){ + const target=document.getElementById("musicTrackArea"); + if(!target)return; + target.innerHTML=`
Loading music…
`; + try{ + const data=await api(`/api/music/overview?limit=2000${query?`&q=${encodeURIComponent(query)}`:""}`); + const tracks=data.tracks||[]; + musicTrackRegistry.clear(); + const groups=new Map(); + tracks.forEach(track=>{ + const group=track.list_name||track.album||"Music"; + if(!groups.has(group))groups.set(group,[]); + groups.get(group).push(track); + }); + target.innerHTML=tracks.length?[...groups.entries()].map(([name,items])=>` +

${escapeHtml(name)}

${items.length} track${items.length===1?"":"s"}
+
${items.map((track,index)=>musicTrackCard(track,tracks,tracks.indexOf(track))).join("")}
`).join(""):`
No music imported yet. Paste a Spotify track, album, playlist, or artist URL above.
`; + const status=document.getElementById("musicCacheStatus"); + if(status&&data.cache)status.textContent=`${data.cache.items||0} cached · ${formatByteSize(data.cache.total_bytes||0)}`; + bindMusicCards(tracks); + }catch(error){target.innerHTML=`
${escapeHtml(error.message)}
`;} +} + + +async function loadMusicImportJobs(){ + const target=document.getElementById("musicImportJobs"); + if(!target)return; + + try{ + const data=await api("/api/music/import-jobs"); + const jobs=data.jobs||[]; + + if(!jobs.length){ + target.innerHTML=""; + return; + } + + target.innerHTML=` +
+ Spotify imports + +
+ ${jobs.map(job=>` +
+
+ ${escapeHtml(job.query||"Spotify import")} +
+ ${escapeHtml(job.status||"")} · ${escapeHtml(job.message||"")} +
+ ${job.error?`
${escapeHtml(job.error)}
`:""} +
+
+ ${job.resolved||0} resolved · + ${job.inserted||0} new · + ${job.updated||0} updated · + ${job.repaired||0} metadata repaired +
+
+ `).join("")} + `; + + const clearButton=document.getElementById("musicImportJobsClear"); + if(clearButton){ + clearButton.onclick=async()=>{ + try{ + await api("/api/music/import-jobs/clear",{ + method:"POST", + headers:{"Content-Type":"application/json"}, + body:"{}", + }); + await loadMusicImportJobs(); + }catch(error){ + alert(`Could not clear Spotify import jobs: ${error.message}`); + } + }; + } + + const completedJobs=jobs.filter(job=>job.status==="complete"); + + if(!musicImportJobsInitialized){ + // The first status poll is just establishing current state. + // Existing historical completed jobs must NOT trigger a library + // reload every 2.5 seconds. + completedJobs.forEach(job=>musicImportCompletedSeen.add(String(job.id))); + musicImportJobsInitialized=true; + }else{ + const newlyCompleted=completedJobs.filter( + job=>!musicImportCompletedSeen.has(String(job.id)) + ); + + completedJobs.forEach(job=>musicImportCompletedSeen.add(String(job.id))); + + // Refresh the music library exactly once when an import changes + // into complete while this page is open. + if(newlyCompleted.length){ + await loadMusicTracks( + document.getElementById("musicFilterInput")?.value?.trim()||"" + ); + } + } + }catch(error){ + target.innerHTML=`
${escapeHtml(error.message)}
`; + } +} + +async function showMusicLibrary(){ + musicImportJobsInitialized=false; + clearScanPolling();resetLibraryContext();ensureMusicStyles();ensureMusicPlayer(); + breadcrumb.innerHTML=`Libraries  ›  Music`; toolbar.innerHTML=""; installTopNav("home"); + content.innerHTML=`
+
+

Music

Cached audio files are discovered automatically. Spotify enriches metadata when the match is confident.
+
Loading cache…
+
+
Scan music folder
+
Add music / Spotify import +
+
+
+
+
`; + document.getElementById("musicImportForm").onsubmit=async event=>{ + event.preventDefault(); + const input=document.getElementById("musicImportInput"); + const status=document.getElementById("musicImportStatus"); + const url=input.value.trim(); + if(!url)return; + const button=event.submitter; if(button)button.disabled=true; + status.textContent="Queueing Spotify import…"; + try{ + const job=await api("/api/music/import",{ + method:"POST", + headers:{"Content-Type":"application/json"}, + body:JSON.stringify({url}) + }); + status.textContent=`Spotify import queued (#${job.id}). It will continue in the background.`; + input.value=""; + + try{ + await loadMusicImportJobs(); + }catch(refreshError){ + console.error("Spotify import queued, but job panel refresh failed",refreshError); + status.textContent=`Spotify import queued (#${job.id}). Background import is running; status panel refresh failed: ${refreshError.message}`; + } + }catch(error){ + status.textContent=`Import request failed: ${error.message}`; + } + finally{if(button)button.disabled=false;} + }; + document.getElementById("musicReconcileButton").onclick=async()=>{ + const button=document.getElementById("musicReconcileButton"); + button.disabled=true; + try{ + const result=await api("/api/music/reconcile",{method:"POST"}); + document.getElementById("musicImportStatus").textContent=`Folder scan: ${result.checked||0} checked, ${result.added||0} added, ${result.enriched||0} Spotify matches.`; + await loadMusicTracks(); + }catch(error){ + document.getElementById("musicImportStatus").textContent=`Folder scan failed: ${error.message}`; + }finally{button.disabled=false;} + }; + document.getElementById("musicFilterForm").onsubmit=event=>{event.preventDefault();loadMusicTracks(document.getElementById("musicFilterInput").value.trim());}; + document.getElementById("musicFilterClear").onclick=()=>{document.getElementById("musicFilterInput").value="";loadMusicTracks();}; + await loadMusicTracks(); + await loadMusicImportJobs(); + clearInterval(musicImportJobPollTimer); + musicImportJobPollTimer=setInterval(loadMusicImportJobs,2500); +} + + +// Kronic mobile: resize the video panel by touch, without stealing gestures +// from the actual HTML5 video controls. Reattached when YouTube is recreated. +(function installKronicMobilePlayers(){ + const MOBILE = window.matchMedia('(max-width:760px)'); + const clamp=(n,lo,hi)=>Math.min(hi,Math.max(lo,n)); + function attach(win,kind){ + if(!win||win.dataset.mobileReady==='1')return; + win.dataset.mobileReady='1'; + const header=win.querySelector('.player-header,.youtube-player-header'); + if(!header)return; + const tools=document.createElement('div'); + tools.className='kronic-mobile-player-tools'; + tools.innerHTML='◢'; + header.appendChild(tools); + let pct=95; + const key='kronic.mobile.'+kind+'.width.v1'; + try{const stored=Number(localStorage.getItem(key));if(stored>=45&&stored<=100)pct=stored;}catch(_){} + function update(value,save=true){ + pct=clamp(Math.round(value),45,100); + win.style.setProperty('--kronic-mobile-player-width',pct+'vw'); + const grip=tools.querySelector('.kronic-mobile-resize-grip'); + grip.setAttribute('aria-valuenow',String(pct)); + if(save)try{localStorage.setItem(key,String(pct));}catch(_){} + } + update(pct,false); + tools.addEventListener('click',event=>{ + const op=event.target.closest('[data-mobile-size]')?.dataset.mobileSize; + if(!op||!MOBILE.matches)return; + update(op==='fit'?100:pct+(op==='plus'?10:-10)); + }); + const grip=tools.querySelector('.kronic-mobile-resize-grip'); + let drag=null; + grip.addEventListener('pointerdown',event=>{ + if(!MOBILE.matches||document.fullscreenElement||event.button!==0)return; + drag={id:event.pointerId,x:event.clientX,pct}; + grip.setPointerCapture(event.pointerId);event.preventDefault();event.stopPropagation(); + }); + grip.addEventListener('pointermove',event=>{ + if(!drag||event.pointerId!==drag.id)return; + update(drag.pct+(event.clientX-drag.x)/window.innerWidth*100,false); + }); + const finish=event=>{if(!drag||event.pointerId!==drag.id)return;drag=null;update(pct);}; + grip.addEventListener('pointerup',finish); + grip.addEventListener('pointercancel',finish); + grip.addEventListener('keydown',event=>{ + if(event.key==='ArrowLeft'||event.key==='ArrowDown'){update(pct-5);event.preventDefault();} + if(event.key==='ArrowRight'||event.key==='ArrowUp'){update(pct+5);event.preventDefault();} + }); + } + let queued=false; + function scan(){ + queued=false; + attach(document.getElementById('playerWindow'),'local'); + attach(document.getElementById('youtubePlayerWindow'),'youtube'); + } + function schedule(){if(!queued){queued=true;requestAnimationFrame(scan);}} + if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',()=>{ + scan();new MutationObserver(schedule).observe(document.body,{childList:true,subtree:true}); + },{once:true}); + else{scan();new MutationObserver(schedule).observe(document.body,{childList:true,subtree:true});} +})(); + +function switchAssignedRoom(){ + if(confirm('Switch rooms? Voice and playback in this window will stop.')) location.assign(location.pathname+'?choose=1'); +} +async function renameSelectedRoom(){ + const id=document.body.dataset.roomId; + const name=prompt('Room display title (internal room ID will stay unchanged)',document.title); + if(name===null)return; + try{await api('/api/my/rooms/'+encodeURIComponent(id)+'/display-name',{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({display_name:name})}); + // Update displayed branding without disconnecting the current voice session. + document.title=name.trim(); + for(const el of document.querySelectorAll('[data-room-brand]'))el.textContent=name.trim(); + }catch(e){alert(e.message);} +} diff --git a/JS/balroc.js b/JS/balroc.js new file mode 100644 index 0000000..405ff3d --- /dev/null +++ b/JS/balroc.js @@ -0,0 +1,351 @@ +(() => { + const $ = id => document.getElementById(id); + const win=$('balrocWindow'), log=$('balrocMessages'), input=$('balrocInput'); + const status=$('balrocStatus'), mic=$('balrocMic'), send=$('balrocSend'); + // Live destination selector: Kronic is ALWAYS default, other targets require approval. + const destinationSelect=document.createElement('select'); + destinationSelect.id='aiCommandDestination';destinationSelect.add(new Option('Kronic (this window)','kronic')); + destinationSelect.title='Playback destination'; + destinationSelect.setAttribute('aria-label','Playback destination'); + destinationSelect.style.cssText='background:#142237;color:#e8efff;border:1px solid #456084;border-radius:6px;padding:7px;flex:1;min-width:170px'; + const destinationRow=document.createElement('div'); + destinationRow.style.cssText='display:flex;align-items:center;gap:7px;padding:6px 9px;flex-wrap:wrap'; + const destinationLabel=document.createElement('label'); + destinationLabel.textContent='Player:'; + destinationLabel.setAttribute('for','aiCommandDestination'); + destinationLabel.style.cssText='font-size:12px'; + const refreshPlayers=document.createElement('button'); + refreshPlayers.type='button';refreshPlayers.textContent='Refresh players'; + refreshPlayers.style.cssText='padding:6px 8px;border:1px solid #456084;border-radius:5px'; + const approvePlayer=document.createElement('button'); + approvePlayer.type='button';approvePlayer.textContent='Approve player'; + approvePlayer.title='Platform administrators can approve selected Jellyfin clients'; + approvePlayer.style.cssText='padding:6px 9px;border:1px solid #54769b;border-radius:6px;background:#294365;color:#fff;cursor:pointer'; + approvePlayer.hidden=true; + destinationRow.append(destinationLabel,destinationSelect,refreshPlayers,approvePlayer); + const aiForm=$('balrocForm'); + // kronic-ai-players-v6: controls above messages, chat composer stays pinned at bottom. + destinationRow.classList.add('ai-command-player-toolbar'); + destinationRow.style.cssText='display:flex;align-items:center;gap:8px;padding:10px 12px;flex-wrap:wrap;background:#16263b;border-bottom:1px solid #30455f'; + if(win && log)win.insertBefore(destinationRow,log); + + let aiClientList=[];let canApproveAiPlayers=false;let playersLoading=false; + function updateApproveButton(){ + const c=aiClientList.find(x=>x.device_id===destinationSelect.value); + approvePlayer.hidden=!canApproveAiPlayers || !c || !!c.approved || !c.controllable; + approvePlayer.disabled=!c || !c.controllable; + } + destinationSelect.addEventListener('change',()=>{updateApproveButton();renderPlayback();}); + approvePlayer.addEventListener('click',async()=>{ + const c=aiClientList.find(x=>x.device_id===destinationSelect.value); + if(!c || !c.controllable || c.approved)return; + if(!confirm('Approve remote playback control for '+c.device+' ('+c.client+')?'))return; + approvePlayer.disabled=true; + try{ + const response=await fetch('/api/balroc/approve-client',{method:'POST',headers:{'Content-Type':'application/json','X-Kronic-Room':document.body.dataset.roomId},credentials:'same-origin',body:JSON.stringify({device_id:c.device_id})}); + const data=await response.json().catch(()=>({})); + if(!response.ok)throw new Error(data.error||data.detail||'HTTP '+response.status); + await refreshAiPlayers(); + }catch(error){alert('Player approval failed: '+error.message);updateApproveButton();} + }); + async function refreshAiPlayers(){ + const previous=destinationSelect.value; + if(playersLoading)return;playersLoading=true; + try{ + const response=await fetch('/api/balroc/clients',{credentials:'same-origin',cache:'no-store',headers:{'X-Kronic-Room':document.body.dataset.roomId}}); + if(!response.ok)throw Error('HTTP '+response.status); + const data=await response.json(); + const selected=destinationSelect.value||previous; + destinationSelect.replaceChildren(new Option('Kronic (this window)','kronic')); + aiClientList=Array.isArray(data.clients)?data.clients:[]; + canApproveAiPlayers=!!data.can_approve; + for(const c of aiClientList){ + if(!c.device_id||!c.device)continue; + const allowed=!!c.approved && !!c.controllable; + const option=new Option(String(c.device)+' · '+String(c.client||'Jellyfin')+(c.approved?'':' (approval required)')+(!c.controllable?' (not controllable)':''),String(c.device_id)); + option.disabled=!c.controllable; + destinationSelect.add(option); + } + if(selected && ![...destinationSelect.options].some(o=>o.value===selected)){destinationSelect.add(new Option('Previously selected player (offline)',selected));} + if(selected)destinationSelect.value=selected; + refreshPlayers.title='Live Jellyfin clients refreshed'; + updateApproveButton(); + }catch(error){refreshPlayers.title='Client list failed: '+error.message;approvePlayer.hidden=true;aiClientList=[];}finally{playersLoading=false;renderPlayback();} + } + refreshPlayers.addEventListener('click',()=>{void refreshAiPlayers();}); + $('balrocOpen')?.addEventListener('click',()=>{void refreshAiPlayers();}); + + + let session='',busy=false,recorder=null,stream=null,chunks=[]; + const windowId = (globalThis.crypto?.randomUUID?.() || 'win_'+Math.random().toString(36).slice(2)+Date.now().toString(36)).replace(/[^A-Za-z0-9_-]/g,''); + async function navigateMedia(kind){ + // The Borg navigator opens the FLOATING media window and loads its content. + // showYouTubeLibrary()/showMusicLibrary()/showIptvLibrary() alone only render hidden content. + const expected={youtube:'youtubeSearchInput',music:'musicFilterInput',iptv:'iptvChannelSearch'}[kind]; + if(!expected)throw Error('Unknown media destination'); + await new Promise((resolve,reject)=>{ + let complete=false; + const timeout=setTimeout(()=>{if(complete)return;complete=true;reject(Error('Media window navigation timed out'));},15000); + const finish=(err)=>{if(complete)return;complete=true;clearTimeout(timeout);if(err)reject(Error(String(err.message||err)));else resolve();}; + window.dispatchEvent(new CustomEvent('kronic:ai-media-navigate',{detail:{kind,finish}})); + }); + const wrap=document.getElementById('borgWindowWrap'); + const field=document.getElementById(expected); + if(!wrap||wrap.hidden||!field)throw Error('The '+kind+' media window did not open (check library access permissions)'); + return field; + } + async function navigateMediaTree(kind,action){ + await navigateMediaV3(kind); + if(!action || !Number.isSafeInteger(Number(action.source_id)) || Number(action.source_id)<=0)return; + await new Promise((resolve,reject)=>{ + let done=false; + const finish=error=>{if(done)return;done=true;clearTimeout(timer);error?reject(Error(String(error.message||error))):resolve();}; + const timer=setTimeout(()=>finish(Error('Kronic library navigation timed out')),15000); + window.dispatchEvent(new CustomEvent('kronic:ai-open-library',{detail:{source_id:Number(action.source_id),kind,show_name:action.show_name||'',season:action.season,finish}})); + }); + } + async function navigateMediaV3(kind){ + if(!['movies','shows','twitch'].includes(kind))throw Error('Unsupported media category'); + await new Promise((resolve,reject)=>{ + let done=false; + const finish=error=>{if(done)return;done=true;clearTimeout(timer);error?reject(Error(String(error.message||error))):resolve();}; + const timer=setTimeout(()=>finish(new Error('Kronic media navigation timed out')),15000); + window.dispatchEvent(new CustomEvent('kronic:ai-media-navigate',{detail:{kind,finish}})); + }); + const wrap=document.getElementById('borgWindowWrap'); + if(!wrap||wrap.hidden)throw Error('Kronic media window did not open'); + } + async function runUiAction(action){ + if(!action||!action.type)return; + if(action.type==='kronic_video_play'){ + const kind=action.kind==='shows'?'shows':'movies'; + await navigateMediaTree(kind,action); + const id=Number(action.media_id); + if(!Number.isSafeInteger(id)||id<=0)throw Error('Invalid Kronic media ID'); + if(typeof api!=='function'||typeof openPlayer!=='function')throw Error('Kronic video player is unavailable'); + const item=(await api('/api/media')).find(x=>Number(x.id)===id); + if(!item)throw Error('Media is no longer available to this user'); + await openPlayer(id,String(action.title||item.effective_title||item.title||'Media')); + return; + } + if(action.type==='kronic_video_browse'){ + await navigateMediaTree(action.kind==='shows'?'shows':'movies',action); + return; + } + if(action.type==='twitch_search'||action.type==='twitch_play'){ + await navigateMediaV3('twitch'); + if(action.type==='twitch_play'){ + if(typeof api!=='function'||typeof openTwitchPlayer!=='function')throw Error('Kronic Twitch player unavailable'); + const data=await api('/api/twitch/overview'); + const channel=(data.channels||[]).find(c=>String(c.id)===String(action.channel_id)); + if(!channel)throw Error('Twitch channel is not accessible to this account'); + await openTwitchPlayer(channel); + } + return; + } + if(action.type==='tube_search'){ + const inp=await navigateMedia('youtube'); + inp.value=String(action.query||''); + if(typeof searchYouTube!=='function')throw Error('Kronic Tube search function is unavailable'); + await searchYouTube(inp.value); + }else if(action.type==='tube_play'){ + const inp=await navigateMedia('youtube'); + inp.value=String(action.query||''); + if(typeof searchYouTube!=='function'||typeof openYouTubePlayer!=='function')throw Error('Kronic Tube playback is unavailable'); + await searchYouTube(inp.value); + const targetId=String(action.video_id||''); + if(!targetId)throw Error('No matching YouTube video ID was provided'); + // Use the exact result that the authenticated server matched, not the first search card. + let item=(typeof youtubeItemRegistry!=='undefined'&&youtubeItemRegistry.get(targetId))||null; + if(!item&&action.item&&String(action.item.id)===targetId){ + item={...action.item,id:targetId}; + } + if(!item)throw Error('Selected video is no longer available; choose a search result'); + await openYouTubePlayer(item); + if(!document.getElementById('youtubePlayerWindow')||!document.getElementById('youtubeVideoElement')){ + throw Error('Kronic Tube player failed to open'); + } + }else if(action.type==='music_search'||action.type==='music_play'){ + const inp=await navigateMedia('music'); + inp.value=String(action.query||''); + if(typeof loadMusicTracks!=='function')throw Error('Kronic music search function is unavailable'); + await loadMusicTracks(inp.value); + if(action.type==='music_play'){ + if(typeof musicTrackRegistry==='undefined'||typeof playMusicTrack!=='function')throw Error('Kronic music playback is unavailable'); + const item=musicTrackRegistry.get(String(action.track_id)); + if(!item)throw Error('Music track no longer available'); + await playMusicTrack(item); + } + }else if(action.type==='iptv_search'||action.type==='iptv_play'){ + const inp=await navigateMedia('iptv'); + inp.value=String(action.query||''); + inp.dispatchEvent(new Event('input',{bubbles:true})); + if(action.type==='iptv_play'){ + if(typeof api!=='function'||typeof openIptvChannel!=='function')throw Error('Kronic IPTV player is unavailable'); + const overview=await api('/api/iptv/overview'); + const item=(overview.channels||[]).find(x=>Number(x.id)===Number(action.channel_id)); + if(!item)throw Error('IPTV channel is not accessible'); + await openIptvChannel(item); + } + } + } + + // Inline search previews use the authenticated resolver's actual result IDs. + const searchTypes=new Set(['tube_search','music_search','iptv_search','twitch_search','kronic_video_browse']); + let pendingSearch=null, resultActionBusy=false; + function resultKind(action){return ({tube_search:'youtube',music_search:'music',iptv_search:'iptv',twitch_search:'twitch'})[action.type] || (action.kind==='shows'?'shows':'movies');} + function resultRow(item,action,index){ + const kind=resultKind(action), row=document.createElement('button');row.type='button';row.className='balroc-result-row'; + const thumb=document.createElement('span');thumb.className='balroc-result-thumb';thumb.textContent=kind==='music'?'♪':kind==='iptv'?'TV':'▶'; + const id=String(item.id||item.video_id||''); + const raw=kind==='movies'||kind==='shows'?`/thumbnail/${encodeURIComponent(id)}`:kind==='iptv'?`/api/iptv/channels/${encodeURIComponent(id)}/snapshot`:item.thumbnail||item.thumbnail_url; + if(raw){try{const url=new URL(raw,location.origin);if(['https:','http:'].includes(url.protocol)){const img=document.createElement('img');img.alt='';img.loading='lazy';img.referrerPolicy='no-referrer';img.onerror=()=>img.remove();img.src=roomMediaUrl(url.href);thumb.append(img);}}catch(e){}} + const words=document.createElement('span');words.className='balroc-result-text';const title=document.createElement('strong');title.textContent=item.title||item.name||id;words.append(title); + const subtitle=document.createElement('small');subtitle.textContent=item.artist||item.subtitle||({movies:'Movie',shows:'TV episode',iptv:'Live TV',twitch:'Twitch',youtube:'Tube',music:'Music'})[kind];words.append(subtitle); + const arrow=document.createElement('span');arrow.textContent='›';arrow.setAttribute('aria-hidden','true');row.append(thumb,words,arrow); + row.onclick=()=>void resultTask(async()=>{ + // Preview cards are Kronic-local; never silently retarget a remote player. + if(destinationSelect.value!=='kronic')throw Error('Select Kronic (this window) to play this local result.'); + const rights=await api('/api/auth/media-context');const key=({youtube:'tube',shows:'tv'})[kind]||kind;if(rights.allowedLibraries?.[key]!==true)throw Error('Library access denied'); + if(kind==='youtube'){await openYouTubePlayer({...item,id});} + else if(kind==='movies'||kind==='shows'){const fresh=(await api('/api/media')).find(x=>String(x.id)===id);if(!fresh)throw Error('Media no longer accessible');await openPlayer(Number(id),title.textContent);} + else if(kind==='iptv'){const d=await api('/api/iptv/overview');const fresh=(d.channels||[]).find(x=>String(x.id)===id);if(!fresh)throw Error('Channel no longer accessible');await openIptvChannel(fresh);} + else if(kind==='twitch'){const d=await api('/api/twitch/overview');const fresh=(d.channels||[]).find(x=>String(x.id)===id);if(!fresh)throw Error('Channel no longer accessible');await openTwitchPlayer(fresh);} + else if(kind==='music'){const d=await api(`/api/music/overview?limit=2000&q=${encodeURIComponent(action.query||'')}`);const fresh=(d.tracks||[]).find(x=>String(x.id)===id);if(!fresh)throw Error('Track no longer accessible');await playMusicTrack(fresh);} + renderPlayback(); + });return row; + } + async function resultTask(fn){if(resultActionBusy||busy||voicePhase!=='idle'||!toolsAllowed)return;resultActionBusy=true;try{await fn();}catch(e){append('assistant','Media: '+e.message);if(win.hidden)alert('Media: '+e.message);}finally{resultActionBusy=false;}} + async function showFullResults(search){ + const {action,items}=search,kind=resultKind(action); + if(kind==='youtube'){const inp=await navigateMedia('youtube');inp.value=action.query||'';await searchYouTube(inp.value,items);$('youtubeSearchArea')?.scrollIntoView({block:'start'});} + else{ + if(['music','iptv'].includes(kind))await navigateMedia(kind);else await navigateMediaV3(kind); + // Preserve the native library beneath the exact matched results. + const area=$('content');if(!area)throw Error('Media view unavailable');$('aiFullSearchResults')?.remove(); + const section=document.createElement('section');section.id='aiFullSearchResults';section.className='balroc-full-results';const heading=document.createElement('h2');heading.textContent=`Search results · ${action.query||kind} (${items.length})`;section.append(heading); + for(const [i,item] of items.entries())section.append(resultRow(item,action,i));area.prepend(section);section.scrollIntoView({block:'start'}); + } + if(pendingSearch===search)pendingSearch=null; + } + function inlineSearch(reply,action,items){ + const valid=items.filter(x=>x&&String(x.id||x.video_id||'')); + const search={action,items:valid};pendingSearch=search; + reply.textContent=valid.length?`${valid.length} matching result${valid.length===1?'':'s'}. Choose one to play.`:'No matching results.'; + if(!valid.length){pendingSearch=null;return;} + reply.classList.add('balroc-result-message');const list=document.createElement('div');list.className='balroc-result-list'; + valid.slice(0,5).forEach((item,i)=>list.append(resultRow(item,action,i)));reply.append(list); + const full=document.createElement('button');full.type='button';full.className='balroc-view-results';full.textContent=`Media · View all ${valid.length} results ›`;full.onclick=()=>void resultTask(()=>showFullResults(search));reply.append(full);log.scrollTop=reply.offsetTop-log.offsetTop; + } + // On mobile, tapping Media directly after a Find also opens its exact result list. + document.addEventListener('click',e=>{if(!pendingSearch||!document.body.classList.contains('kronic-mobile')||document.body.dataset.mobileTab!=='ai'||!e.target.closest('#mobileNav [data-tab="media"]'))return;if(busy||resultActionBusy||voicePhase!=='idle')return;e.preventDefault();e.stopImmediatePropagation();const search=pendingSearch;void resultTask(()=>showFullResults(search));},true); + + let aiAllowed=false, toolsAllowed=false; + async function checkAccess(){ + try{ + const response=await fetch('/api/balroc/access',{credentials:'same-origin',cache:'no-store',headers:{'X-Kronic-Room':document.body.dataset.roomId}}); + if(!response.ok)throw Error('Access denied'); + const rights=await response.json(); + aiAllowed=!!rights.can_chat;toolsAllowed=!!rights.can_use_tools; + }catch(e){aiAllowed=false;} + const launcher=$('balrocOpen');if(launcher){launcher.hidden=!aiAllowed;launcher.style.display=aiAllowed?'':'none';} + if(!aiAllowed)win.hidden=true;else void refreshAiPlayers(); + } + void checkAccess(); + function append(role,text){const e=document.createElement('div');e.className='balroc-message '+role;e.textContent=text;log.appendChild(e);log.scrollTop=log.scrollHeight;return e;} + function open(){if(!aiAllowed)return;win.hidden=false;renderPlayback();} + $('balrocOpen')?.addEventListener('click',open); + $('balrocClose')?.addEventListener('click',()=>{win.hidden=true;}); + async function post(url,data){const response=await fetch(url,{method:'POST',headers:{'Content-Type':'application/json','X-Kronic-Room':document.body.dataset.roomId},credentials:'same-origin',body:JSON.stringify(data)});const json=await response.json().catch(()=>({}));if(!response.ok)throw Error(json.error||json.detail||`HTTP ${response.status}`);return json;} + async function submit(text,destination=destinationSelect.value,fromVoice=false){if(!aiAllowed||busy||resultActionBusy||(!fromVoice&&voicePhase!=='idle')||!String(text||'').trim())return;busy=true;send.disabled=true;input.value='';append('user',text);const reply=append('assistant','Working…');status.textContent='Thinking';renderPlayback();try{const data=await post('/api/balroc/chat',{message:text,window_id:windowId,destination:destination});if(data.session_id)session=data.session_id;reply.textContent=data.reply||data.error||'Balroc returned no reply'; if(data.reply){reply.textContent=reply.textContent.replace(/\s*\(device ID [a-z0-9_-]+\)/gi,'');if(reply.textContent!==data.reply){const detail=document.createElement('details');const summary=document.createElement('summary');summary.textContent='Execution details';detail.append(summary,document.createTextNode(data.reply));reply.append(detail);}}if(data.ui_action)try{if(destination==='kronic'&&searchTypes.has(data.ui_action.type)&&Array.isArray(data.results)){inlineSearch(reply,data.ui_action,data.results);}else{pendingSearch=null;await runUiAction(data.ui_action);}}catch(uiErr){reply.append(document.createTextNode('\nWindow action failed: '+uiErr.message));}status.textContent='Ready';}catch(e){reply.textContent=`Error: ${e.message}`;status.textContent='Error';}finally{busy=false;send.disabled=false;renderPlayback();void refreshAiPlayers();}} + $('balrocForm')?.addEventListener('submit',e=>{e.preventDefault();submit(input.value);}); + input?.addEventListener('keydown',e=>{if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();submit(input.value);}}); + function bytes64(bytes){let out='';for(let i=0;it.stop());stream=null;}} + // Hold-to-speak: one recording per physical hold, including delayed permission prompts. + let voicePhase='idle', held=false, discard=false, holdDestination='', holdStart=0, voiceTimer=null, activePointer=null; + const voiceBox=document.createElement('div');voiceBox.className='balroc-voice'; + mic.textContent='🎙';mic.title='Hold to speak; release to send';mic.setAttribute('aria-label',mic.title);mic.setAttribute('aria-pressed','false'); + const voiceLabel=document.createElement('span');voiceLabel.textContent='Hold to speak';voiceLabel.className='balroc-voice-label';voiceLabel.setAttribute('aria-live','polite'); + voiceBox.append(mic,voiceLabel);win.insertBefore(voiceBox,aiForm); + if($('balrocHint'))$('balrocHint').textContent='Hold microphone to speak, release to send. Or type a command.'; + function voiceReset(){clearTimeout(voiceTimer);stopTracks();recorder=null;held=false;activePointer=null;voicePhase='idle';mic.disabled=false;mic.setAttribute('aria-pressed','false');voiceLabel.textContent='Hold to speak';renderPlayback();} + async function startHold(){ + if(busy||resultActionBusy||voicePhase!=='idle'||!aiAllowed)return; + if(!navigator.mediaDevices?.getUserMedia||!window.MediaRecorder){append('assistant','Microphone recording is not supported here. Use HTTPS or localhost.');return;} + held=true;discard=false;voicePhase='starting';holdDestination=destinationSelect.value;voiceLabel.textContent='Opening microphone…';status.textContent='Opening microphone';renderPlayback(); + try{ + stream=await navigator.mediaDevices.getUserMedia({audio:true}); + if(!held||discard){voiceReset();status.textContent='Hold again to speak';return;} + chunks=[];const mime=['audio/webm;codecs=opus','audio/webm','audio/ogg;codecs=opus','audio/mp4'].find(t=>MediaRecorder.isTypeSupported(t)); + const active=new MediaRecorder(stream,mime?{mimeType:mime}:{});recorder=active; + active.ondataavailable=e=>{if(e.data.size)chunks.push(e.data);}; + active.onerror=()=>{discard=true;finishHold(true);}; + active.onstop=async()=>{ + clearTimeout(voiceTimer);stopTracks();mic.setAttribute('aria-pressed','false'); + if(discard||performance.now()-holdStart<250||!chunks.length){voiceReset();status.textContent='Ready';return;} + voicePhase='transcribing';mic.disabled=true;voiceLabel.textContent='Transcribing…';status.textContent='Transcribing'; + try{const blob=new Blob(chunks,{type:active.mimeType});const audio=new Uint8Array(await blob.arrayBuffer()); + const result=await post('/api/balroc/transcribe',{audio_base64:bytes64(audio),mime_type:blob.type}); + if(!discard&&String(result.text||'').trim())await submit(result.text,holdDestination,true); + }catch(e){append('assistant',`Whisper: ${e.message}`);status.textContent='Error';}finally{voiceReset();} + }; + active.start();holdStart=performance.now();voicePhase='recording';mic.setAttribute('aria-pressed','true');voiceLabel.textContent='Recording — release to send';status.textContent='Recording';voiceTimer=setTimeout(()=>finishHold(false),60000); + }catch(e){voiceReset();status.textContent='Error';append('assistant',`Microphone: ${e.message}`);} + } + function finishHold(cancel=false){held=false;if(cancel)discard=true;if(voicePhase==='recording'&&recorder?.state==='recording'){voicePhase='stopping';recorder.stop();} } + // Track the original contact until release, even if capture is lost. + mic.addEventListener('pointerdown',e=>{ + if(e.button!==0||!e.isPrimary)return;e.preventDefault(); + if(voicePhase!=='idle'||busy||resultActionBusy||!aiAllowed)return; + activePointer=e.pointerId; + try{mic.setPointerCapture(e.pointerId);}catch(_){} + void startHold(); + }); + window.addEventListener('pointerup',e=>{if(e.pointerId!==activePointer)return;activePointer=null;finishHold();},true); + window.addEventListener('pointercancel',e=>{if(e.pointerId!==activePointer)return;activePointer=null;finishHold(true);},true); + // A capture change is not a physical release; window listeners remain active. + mic.addEventListener('contextmenu',e=>e.preventDefault()); + mic.addEventListener('keydown',e=>{if(e.code==='Space'||e.code==='Enter'){e.preventDefault();if(!e.repeat)void startHold();}}); + mic.addEventListener('keyup',e=>{if(e.code==='Space'||e.code==='Enter'){e.preventDefault();finishHold();}}); + window.addEventListener('blur',()=>{if(held)finishHold(true);}); + document.addEventListener('visibilitychange',()=>{if(document.hidden&&held)finishHold(true);}); + new MutationObserver(()=>{if(win.hidden&&held)finishHold(true);}).observe(win,{attributes:true,attributeFilter:['hidden']}); + + // Live playback panel. Remote metadata is optional; never invent a title or position. + const playback=document.createElement('section');playback.className='balroc-playback'; + playback.innerHTML='
NOW PLAYING
'; + win.insertBefore(playback,log); + const controls=[['previous','⏮','Previous'],['rewind','⏪','Back 10 seconds'],['toggle','▶','Play / pause'],['forward','⏩','Forward 10 seconds'],['next','⏭','Next'],['stop','■','Stop']]; + const transport=playback.querySelector('.balroc-transport'); + for(const [key,icon,label] of controls){const btn=document.createElement('button');btn.type='button';btn.dataset.action=key;btn.textContent=icon;btn.title=label;btn.setAttribute('aria-label',label);btn.onclick=()=>void transportAction(key);transport.append(btn);} + function localPlayback(){ + const music=$('musicAudio'), video=typeof mediaPlayer!=='undefined'?mediaPlayer:null, tube=$('youtubeVideoElement'), twitch=$('twitchVideoElement'); + const candidates=[{el:video,title:$('playerTitle')?.textContent,stop:()=>closePlayer(),kind:'video'},{el:tube,title:$('youtubePlayerTitle')?.textContent,stop:()=>closeYouTubePlayer(),kind:'tube'},{el:twitch,title:$('twitchPlayerTitle')?.textContent,stop:()=>closeTwitchPlayer(),kind:'twitch'},{el:music,title:$('musicPlayerTitle')?.textContent,artist:$('musicPlayerArtist')?.textContent,cover:$('musicPlayerCover')?.getAttribute('src'),stop:()=>$('musicClose')?.click(),kind:'music'}].filter(x=>x.el?.getAttribute('src')); + return candidates.find(x=>!x.el.paused&&!x.el.ended)||candidates[0]; + } + function remotePlayback(){const c=aiClientList.find(x=>String(x.device_id)===destinationSelect.value);const item=c?.now_playing_item||c?.NowPlayingItem||c?.now_playing;const state=c?.play_state||c?.PlayState||{};return {c,title:typeof item==='string'?item:item?.Name||item?.name||item?.title,pos:Number(state.PositionTicks??state.position_ticks??c?.position_ticks)/1e7,duration:Number(item?.RunTimeTicks??item?.run_time_ticks??c?.duration_ticks)/1e7,paused:state.IsPaused??state.is_paused??c?.is_paused};} + function fmtTime(n){n=Math.max(0,Math.floor(n));return `${Math.floor(n/60)}:${String(n%60).padStart(2,'0')}`;} + function renderPlayback(){ + const local=destinationSelect.value==='kronic', x=local?localPlayback():remotePlayback(), el=x?.el; + const name=local?'Kronic':x?.c?.device||'Selected player'; + playback.querySelector('strong').textContent=x?.title||(local?'Nothing playing':'Playback status unavailable'); + playback.querySelector('.balroc-now span').textContent=local?(x?.artist||name):name+(x?.title?(x.paused===true?' · Paused':x.paused===false?' · Playing':''):''); + const cover=playback.querySelector('img');if(local&&x?.cover){if(cover.getAttribute('src')!==x.cover)cover.src=x.cover;cover.hidden=false;}else{cover.hidden=true;cover.removeAttribute('src');} + const pos=el?.currentTime??x?.pos,dur=el?.duration??x?.duration,progress=playback.querySelector('progress');const valid=Number.isFinite(pos)&&Number.isFinite(dur)&&dur>0;progress.hidden=!valid;if(valid){progress.max=dur;progress.value=Math.min(pos,dur);}playback.querySelector('.balroc-time').textContent=valid?`${fmtTime(pos)} / ${fmtTime(dur)}`:''; + for(const btn of transport.children){const k=btn.dataset.action;btn.disabled=!toolsAllowed||busy||voicePhase!=='idle'||(local?(!el||(['previous','next'].includes(k)&&x.kind!=='music')||(['rewind','forward'].includes(k)&&(!Number.isFinite(el.duration)||(x.kind==='video'&&typeof playbackSeekMode!=='undefined'&&playbackSeekMode==='server')))):(!x?.c?.approved||!x?.c?.controllable));if(k==='toggle'){btn.textContent=(local?el&&!el.paused:x?.paused===false)?'❚❚':'▶';}} + } + async function transportAction(key){ + if(!toolsAllowed||busy||voicePhase!=='idle')return; + if(destinationSelect.value!=='kronic'){const x=remotePlayback();if(!x.c?.approved||!x.c?.controllable)return;const command={previous:'Play previous item',rewind:'Seek backward 10 seconds',toggle:x.paused===true?'Resume playback':x.paused===false?'Pause playback':'Toggle play pause',forward:'Seek forward 10 seconds',next:'Play next item',stop:'Stop playback'}[key];await submit(command);return;} + const x=localPlayback(),el=x?.el;if(!el)return; + try{if(key==='toggle'){if(el.paused)await el.play();else el.pause();}else if(key==='stop')await x.stop();else if(key==='previous'||key==='next'){if(x.kind==='music')$(key==='previous'?'musicPrev':'musicNext')?.click();}else if(Number.isFinite(el.duration)&&!(x.kind==='video'&&typeof playbackSeekMode!=='undefined'&&playbackSeekMode==='server')){el.currentTime=Math.max(0,Math.min(el.duration,el.currentTime+(key==='rewind'?-10:10)));}}catch(e){append('assistant','Playback: '+e.message);}renderPlayback(); + } + setInterval(()=>{if(!win.hidden)renderPlayback();},1000); + setInterval(()=>{if(!win.hidden&&aiAllowed&&destinationSelect.value!=='kronic'&&!busy&&voicePhase==='idle')void refreshAiPlayers();},15000); + renderPlayback(); + let drag=null; + $('balrocHeader')?.addEventListener('pointerdown',e=>{if(e.target.closest('button'))return;const r=win.getBoundingClientRect();drag={x:e.clientX,y:e.clientY,left:r.left,top:r.top};$('balrocHeader').setPointerCapture(e.pointerId);}); + $('balrocHeader')?.addEventListener('pointermove',e=>{if(!drag)return;win.style.left=Math.max(0,Math.min(window.innerWidth-120,drag.left+e.clientX-drag.x))+'px';win.style.top=Math.max(0,Math.min(window.innerHeight-80,drag.top+e.clientY-drag.y))+'px';win.style.right='auto';}); + $('balrocHeader')?.addEventListener('pointerup',()=>{drag=null;}); +})(); diff --git a/JS/borg_shell.js b/JS/borg_shell.js new file mode 100644 index 0000000..a71c379 --- /dev/null +++ b/JS/borg_shell.js @@ -0,0 +1,442 @@ +/* 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(); +})(); diff --git a/JS/room-picker.js b/JS/room-picker.js new file mode 100644 index 0000000..20bf51a --- /dev/null +++ b/JS/room-picker.js @@ -0,0 +1 @@ +document.getElementById('roomPickerLogout').addEventListener('click',async()=>{try{const r=await fetch('/api/auth/logout',{method:'POST',credentials:'same-origin'});if(!r.ok)throw Error('Sign out failed');location.replace('/login');}catch(e){document.getElementById('roomPickerError').textContent=e.message;}}); \ No newline at end of file