Upload files to "JS"

This commit is contained in:
2026-11-25 20:21:57 -06:00
parent f630b9fbb9
commit 30c4b8aed8
5 changed files with 5537 additions and 0 deletions
+547
View File
@@ -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 => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
}[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 => `<option value="${item[valueKey]}">${esc(item[labelKey])}</option>`).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 => `<div class="row"><div><b>${esc(user.username)}</b><div class="muted">${esc(user.email)}</div></div><div><button class="approve" onclick="setStatus(${user.id},'active')">Approve</button> <button class="deny" onclick="setStatus(${user.id},'denied')">Deny</button></div></div>`).join('')
: '<div class="muted">No pending accounts.</div>';
$('users').innerHTML = state.users.map(user => `<div class="row"><div><b>${esc(user.username)}</b> <span class="pill">${esc(user.status)}</span> ${user.isPlatformAdmin ? '<span class="pill">platform admin</span>' : ''}<div class="muted">${esc(user.email)}</div><div class="muted">Rooms: ${explicitRoomMembers.filter(m=>m.user_id===user.id).map(m=>esc(m.display_name||m.room_name)).join(", ")||"None"}</div></div><div>${user.status === 'active' ? `<button onclick="setStatus(${user.id},'disabled')">Disable</button>` : `<button onclick="setStatus(${user.id},'active')">Activate</button>`} ${user.isPlatformAdmin ? '' : `<button class="danger" onclick="deleteAccount(${user.id})">Delete Account</button>`}</div></div>`).join('');
$('groups').innerHTML = '<div class="grid">' + state.groups.map(group => `<div class="card"><b>${esc(group.name)}</b><div class="muted">${esc(group.slug)} · ${group.user_count}/${group.max_users} users</div><div class="muted">media: ${group.media_enabled ? 'enabled' : 'disabled'} · subscription: ${esc(group.subscription_status)}</div><div style="margin-top:8px"><button onclick="toggleGroupMedia(${group.id},${group.media_enabled ? 'false' : 'true'})">${group.media_enabled ? 'Disable Media' : 'Enable Media'}</button></div></div>`).join('') + '</div>';
$('memberships').innerHTML = state.memberships.map(membership => `<div class="row"><div><b>${esc(membership.username)}</b> → ${esc(membership.group_name)}</div><div><span class="pill">${esc(membership.role)}</span> <button class="danger" onclick="removeMembership(${membership.group_id},${membership.user_id})">Remove</button></div></div>`).join('') || '<div class="muted">No memberships.</div>';
fill($('createRoomGroup'), state.groups, 'id', 'name');
$('managedRoomList').innerHTML = (state.rooms || []).map(room =>
`<div class="row"><b>${esc(room.room_name)}</b><span class="muted">Group: ${esc(room.group_name)} · ${esc(room.display_name)}</span></div>`
).join('') || '<p class="muted">No chat rooms yet. Create one to enable signup and voice-room access.</p>';
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=>`<div class="row">
<div><b>${esc(m.username)}</b> <span class="pill">${esc(m.role)}</span> ${m.is_platform_admin?'<span class="pill">instance admin</span>':''}</div>
<div><button type="button" data-room-user="${m.user_id}" data-room-role="${esc(m.role)}">Edit role</button>
<button type="button" class="danger" data-remove-room-user="${m.user_id}">Remove from room</button></div>
</div>`).join('') || `<p class="muted">${$('roomMembersAdmin').dataset.loadError ? 'Room membership API: '+esc($('roomMembersAdmin').dataset.loadError) : 'No explicit memberships for this room.'}</p>`;
}
$('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 = '<p class="muted">No matching database records.</p>';
return;
}
const memberships = state.memberships || [];
const rooms = state.rooms || [];
$('inventoryTable').innerHTML = `<table style="width:100%;border-collapse:collapse;text-align:left;min-width:760px">
<thead><tr><th>Select</th><th>ID</th><th>Username</th><th>Email</th><th>Status</th><th>Groups</th><th>Created</th><th>Last login</th><th>Action</th></tr></thead>
<tbody>${shown.map(u=>{
const groupCount = memberships.filter(m=>m.user_id === u.id).length;
const formatDate = timestamp => timestamp ? new Date(timestamp * 1000).toLocaleDateString() : '—';
return `<tr style="border-top:1px solid #484b52">
<td><input type="checkbox" data-purge-id="${u.id}" ${selectedForPurge.has(u.id)?'checked':''} ${u.isPlatformAdmin?'disabled title="Platform admins are protected"':''}></td>
<td>${u.id}</td><td><b>${esc(u.username)}</b>${u.isPlatformAdmin?' (platform admin)':''}</td>
<td>${esc(u.email)}</td><td>${esc(u.status)}</td><td>${groupCount}</td>
<td>${formatDate(u.createdAt)}</td><td>${formatDate(u.lastLoginAt)}</td>
<td>${u.isPlatformAdmin?'<span class="muted">Protected</span>':`<button type="button" class="danger" data-delete-id="${u.id}">Purge</button>`}</td>
</tr>`;
}).join('')}</tbody></table>`;
}
$('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 `<article class="room-group-card">
<div class="room-group-head"><div><h3>${esc(group.name)} <span class="pill">${esc(group.slug)}</span></h3>
<div class="muted">Parent group · ${groupMembers.length}/${group.max_users} members · Media ${group.media_enabled?'enabled':'disabled'}</div></div>
<button type="button" data-group-media="${group.id}" data-enabled="${group.media_enabled?'false':'true'}">${group.media_enabled?'Disable media':'Enable media'}</button></div>
${children.map(room=>{
const members=explicitRoomMembers.filter(m=>m.room_id===room.id);
return `<div class="room-admin-card" data-room-id="${room.id}">
<div class="room-group-head"><div><h4>${esc(room.display_name||room.room_name)}</h4><div class="muted">Internal ID: ${esc(room.room_name)} · ${members.length} room members</div></div>
<button type="button" data-rename-room="${room.id}">Rename</button></div>
<div class="table-scroll"><table class="room-members-table"><thead><tr><th>User</th><th>Parent group role</th><th>Room role</th><th>Manage</th></tr></thead><tbody>
${members.map(m=>{
const parent=groupMembers.find(g=>g.user_id===m.user_id);
return `<tr><td>${esc(m.username)}</td><td>${esc(parent?.role||'Not assigned')}</td><td>${esc(m.role)}</td>
<td><button type="button" data-manage-room-member="${room.id}" data-user-id="${m.user_id}">Edit</button></td></tr>`;
}).join('')||'<tr><td colspan="4" class="muted">No room members</td></tr>'}
</tbody></table></div>
<div class="inline room-quick-assign"><select aria-label="User" data-room-add-user="${room.id}">${(state.users||[]).filter(u=>u.status==='active').map(u=>`<option value="${u.id}">${esc(u.username)}</option>`).join('')}</select>
<select aria-label="Room role" data-room-add-role="${room.id}"><option>member</option><option>moderator</option><option>admin</option><option>owner</option></select>
<button type="button" data-room-add="${room.id}">Add / update room member</button></div>
</div>`;
}).join('')||'<p class="muted">No rooms under this group.</p>'}
</article>`;
}).join('')||'<p class="muted">No groups or rooms configured.</p>';
}
$('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=`<table style="width:100%;min-width:520px;text-align:left;border-collapse:collapse">
<thead><tr><th>User</th><th>AI chat</th><th>Agent tools</th><th>Save</th></tr></thead>
<tbody>${rows.map(u=>`<tr style="border-top:1px solid #454b54" data-ai-user="${u.id}">
<td>${esc(u.username)} <span class="pill">${esc(u.status)}</span>${u.is_platform_admin?' <span class="pill">platform admin</span>':''}</td>
<td><input type="checkbox" data-ai-chat ${u.can_chat?'checked':''} ${u.is_platform_admin?'disabled':''}></td>
<td><input type="checkbox" data-ai-tools ${u.can_use_tools?'checked':''} ${u.is_platform_admin?'disabled':''}></td>
<td>${u.is_platform_admin?'<span class="muted">Always allowed</span>':'<button type="button" data-ai-save>Save</button>'}</td>
</tr>`).join('')}</tbody></table>`;
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=>'<fieldset><legend>'+role+'</legend>'+templateActions.map(a=>'<label style="margin-right:18px;display:inline-block"><input type="checkbox" data-role="'+role+'" value="'+a+'" '+((t?.policy.roles?.[role]??(['owner','admin'].includes(role)?templateActions:[])).includes(a)?'checked':'')+'> '+a.replaceAll('_',' ')+'</label>').join('')+'</fieldset>').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;}};
+4196
View File
File diff suppressed because it is too large Load Diff
+351
View File
@@ -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;i<bytes.length;i+=0x8000)out+=String.fromCharCode(...bytes.subarray(i,i+0x8000));return btoa(out);}
function stopTracks(){if(stream){stream.getTracks().forEach(t=>t.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='<div class="balroc-now"><img alt="" hidden><div><small>NOW PLAYING</small><strong></strong><span></span></div></div><progress max="1" value="0" hidden></progress><div class="balroc-time"></div><div class="balroc-transport"></div>';
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;});
})();
+442
View File
@@ -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();
})();
+1
View File
@@ -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;}});