427 lines
27 KiB
JavaScript
427 lines
27 KiB
JavaScript
'use strict';
|
|
|
|
const config = JSON.parse(document.querySelector('#dashboardConfig').textContent);
|
|
const $ = selector => document.querySelector(selector);
|
|
const $$ = selector => [...document.querySelectorAll(selector)];
|
|
const html = value => String(value ?? '—').replace(/[&<>"']/g, char => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''}[char]));
|
|
const icon = name => `<svg class="icon" aria-hidden="true"><use href="#icon-${name}"/></svg>`;
|
|
const set = (id, value) => {
|
|
const node = $(`#${id}`);
|
|
if (!node || node.textContent === String(value)) return;
|
|
node.textContent = value;
|
|
if (node.matches('.summary-card strong, .metric-line strong, .nav-count')) {
|
|
animate(node, [{opacity: .45, transform: 'translateY(3px)'}, {opacity: 1, transform: 'translateY(0)'}], {duration: 300});
|
|
}
|
|
};
|
|
const percent = value => Math.max(0, Math.min(100, Number(value) || 0));
|
|
const bar = (id, value) => { const node = $(`#${id}`); if (node) node.style.width = `${percent(value)}%`; };
|
|
let language = localStorage.getItem('dashboard-language') === 'en' ? 'en' : 'de';
|
|
const t = (de, en) => language === 'en' ? en : de;
|
|
const number = value => Number(value || 0).toLocaleString(language === 'en' ? 'en-GB' : 'de-DE');
|
|
const empty = message => `<div class="empty-state">${html(message)}</div>`;
|
|
let activeView = 'dashboard';
|
|
const snapshots = {};
|
|
const motionPreference = window.matchMedia('(prefers-reduced-motion: reduce)');
|
|
const entranceAnimations = new WeakMap();
|
|
const renderedContainers = new WeakSet();
|
|
let viewInitialized = false;
|
|
|
|
function animate(node, frames, options = {}) {
|
|
if (motionPreference.matches || document.hidden || !node.getClientRects().length || typeof node.animate !== 'function') return;
|
|
entranceAnimations.get(node)?.cancel();
|
|
const animation = node.animate(frames, {duration: 420, easing: 'cubic-bezier(.22, 1, .36, 1)', fill: 'backwards', ...options});
|
|
entranceAnimations.set(node, animation);
|
|
}
|
|
|
|
motionPreference.addEventListener('change', event => {
|
|
if (event.matches) document.getAnimations().forEach(animation => animation.cancel());
|
|
});
|
|
|
|
function animateEntrance(root) {
|
|
const targets = root.querySelectorAll('.page-heading, .summary-card, .panel, .toolbar, .series, .service-row, .raid-disk, .disk-row, .graphics-process');
|
|
// Bound the work even when a media library contains thousands of entries.
|
|
[...targets].slice(0, 24).forEach((node, index) => {
|
|
animate(node, [{opacity: 0, transform: 'translateY(12px)'}, {opacity: 1, transform: 'translateY(0)'}], {delay: Math.min(index * 35, 210)});
|
|
});
|
|
}
|
|
|
|
function renderContent(id, markup) {
|
|
const root = $(`#${id}`);
|
|
if (!root || root.innerHTML === markup) return;
|
|
const previousWidths = [...root.querySelectorAll('.track > span')].map(node => node.style.width);
|
|
root.innerHTML = markup;
|
|
root.querySelectorAll('.track > span').forEach((node, index) => {
|
|
const from = previousWidths[index] || '0%';
|
|
if (from !== node.style.width) animate(node, [{width: from}, {width: node.style.width}], {duration: 650});
|
|
});
|
|
// Polling updates must not make whole panels re-enter every few seconds.
|
|
if (!renderedContainers.has(root)) {
|
|
animateEntrance(root);
|
|
renderedContainers.add(root);
|
|
}
|
|
}
|
|
|
|
function closeSidebar() {
|
|
document.body.classList.remove('sidebar-open');
|
|
$('#menuToggle').setAttribute('aria-expanded', 'false');
|
|
$('#sidebar').inert = window.matchMedia('(max-width:700px)').matches;
|
|
}
|
|
|
|
function switchView(view) {
|
|
const button = $(`.nav button[data-view="${view}"]`);
|
|
if (!button || !$(`#${view}`)) return;
|
|
const changed = !viewInitialized || activeView !== view;
|
|
activeView = view;
|
|
$$('.view').forEach(node => node.classList.toggle('active', node.id === view));
|
|
$$('.nav button').forEach(node => {
|
|
node.classList.toggle('active', node === button);
|
|
if (node === button) node.setAttribute('aria-current', 'page');
|
|
else node.removeAttribute('aria-current');
|
|
});
|
|
set('pageTitle', button.querySelector('[data-de]').textContent);
|
|
sessionStorage.setItem('dashboard-active-view', view);
|
|
if (['radarr', 'sonarr', 'missing'].includes(view)) $('#scanSource').value = view;
|
|
closeSidebar();
|
|
if (changed) {
|
|
animateEntrance($(`#${view}`));
|
|
viewInitialized = true;
|
|
}
|
|
}
|
|
|
|
function translateLayout() {
|
|
document.documentElement.lang = language;
|
|
localStorage.setItem('dashboard-language', language);
|
|
$$('[data-de][data-en]').forEach(node => { node.textContent = node.dataset[language]; });
|
|
$$('[data-placeholder-de]').forEach(node => { node.placeholder = node.dataset[language === 'en' ? 'placeholderEn' : 'placeholderDe']; });
|
|
set('languageToggle', language === 'en' ? 'DE' : 'EN');
|
|
switchView(activeView);
|
|
applyFilters('movie');
|
|
applyFilters('series');
|
|
updateMissingCounts();
|
|
Object.entries(snapshots).forEach(([key, value]) => renderers[key](value));
|
|
}
|
|
|
|
$$('.nav button').forEach(button => button.addEventListener('click', () => switchView(button.dataset.view)));
|
|
$$('[data-go]').forEach(button => button.addEventListener('click', () => switchView(button.dataset.go)));
|
|
$('#languageToggle').addEventListener('click', () => { language = language === 'de' ? 'en' : 'de'; translateLayout(); });
|
|
$('#menuToggle').addEventListener('click', () => {
|
|
const open = document.body.classList.toggle('sidebar-open');
|
|
$('#sidebar').inert = !open;
|
|
$('#menuToggle').setAttribute('aria-expanded', String(open));
|
|
if (open) $('.nav button.active').focus();
|
|
});
|
|
$('#sidebarShade').addEventListener('click', () => { closeSidebar(); $('#menuToggle').focus(); });
|
|
window.matchMedia('(max-width:700px)').addEventListener('change', closeSidebar);
|
|
document.addEventListener('keydown', event => {
|
|
if (event.key === 'Escape' && document.body.classList.contains('sidebar-open')) {
|
|
closeSidebar(); $('#menuToggle').focus();
|
|
}
|
|
if (event.key === 'Tab' && document.body.classList.contains('sidebar-open')) {
|
|
const controls = $$('#sidebar a, #sidebar button');
|
|
const first = controls[0], last = controls[controls.length - 1];
|
|
if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
|
|
if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
|
|
}
|
|
});
|
|
|
|
function seasonVisible(row) {
|
|
return localStorage.getItem('show-season-zero') === 'true' || row.dataset.season !== '0';
|
|
}
|
|
|
|
function applyFilters(prefix) {
|
|
const search = $(`#${prefix}Search`);
|
|
if (!search) return;
|
|
const query = search.value.trim().toLowerCase();
|
|
const audio = $(`#${prefix}Audio`).value, subs = $(`#${prefix}Subs`).value, state = $(`#${prefix}State`).value;
|
|
let visible = 0;
|
|
const matches = (row, title = '') => (!query || `${row.dataset.title} ${title}`.includes(query)) &&
|
|
(!audio || row.dataset.audio.includes(audio)) && (!subs || row.dataset.subs.includes(subs)) &&
|
|
(!state || row.dataset.state === state) && seasonVisible(row);
|
|
if (prefix === 'movie') {
|
|
$$('#movies tbody tr[data-title]').forEach(row => {
|
|
const show = matches(row); row.classList.toggle('hidden', !show); if (show) visible++;
|
|
});
|
|
set('movieCount', `${number(visible)} ${t('Filme', 'movies')}`);
|
|
} else {
|
|
$$('#seriesList .series').forEach(series => {
|
|
let count = 0;
|
|
series.querySelectorAll('tr[data-title]').forEach(row => {
|
|
const show = matches(row, series.dataset.title); row.classList.toggle('hidden', !show); if (show) count++;
|
|
});
|
|
series.classList.toggle('hidden', !count);
|
|
if (count) visible++;
|
|
updateSeasonDividers(series);
|
|
});
|
|
$$('#seriesList .series-category').forEach(category => category.classList.toggle('hidden', !category.querySelector('.series:not(.hidden)')));
|
|
set('seriesCount', `${number(visible)} ${t('Serien', 'series')}`);
|
|
}
|
|
$(`#${prefix}NoResults`)?.classList.toggle('hidden', visible > 0);
|
|
}
|
|
|
|
function animateFilterResults(prefix) {
|
|
const root = $(prefix === 'movie' ? '#movies tbody' : '#seriesList');
|
|
if (!root) return;
|
|
const selector = prefix === 'movie' ? 'tr[data-title]:not(.hidden)' : '.series:not(.hidden)';
|
|
[...root.querySelectorAll(selector)].slice(0, 12).forEach((node, index) => {
|
|
animate(node, [{opacity: .35}, {opacity: 1}], {duration: 240, delay: index * 15});
|
|
});
|
|
}
|
|
|
|
function updateSeasonDividers(root) {
|
|
root.querySelectorAll('.season-divider').forEach(divider => {
|
|
let next = divider.nextElementSibling, count = 0;
|
|
while (next && !next.classList.contains('season-divider')) {
|
|
if (!next.classList.contains('hidden')) count++;
|
|
next = next.nextElementSibling;
|
|
}
|
|
divider.classList.toggle('hidden', count === 0);
|
|
divider.firstElementChild.textContent = `${t('Staffel', 'Season')} ${divider.dataset.season}`;
|
|
});
|
|
}
|
|
|
|
$$('.series tbody').forEach(body => {
|
|
let season = null;
|
|
[...body.querySelectorAll('tr[data-season]')].forEach(row => {
|
|
if (row.dataset.season === season) return;
|
|
season = row.dataset.season;
|
|
const divider = document.createElement('tr');
|
|
divider.className = 'season-divider'; divider.dataset.season = season;
|
|
divider.innerHTML = `<td colspan="7">${t('Staffel', 'Season')} ${html(season)}</td>`;
|
|
row.before(divider);
|
|
});
|
|
});
|
|
|
|
$$('[data-filter] input, [data-filter] select').forEach(input => {
|
|
const saved = sessionStorage.getItem(`filter-${input.id}`);
|
|
if (saved !== null) input.value = saved;
|
|
else if (input.id.endsWith('Audio')) input.value = localStorage.getItem('preferred-audio') || '';
|
|
else if (input.id.endsWith('Subs')) input.value = localStorage.getItem('preferred-subs') || '';
|
|
input.addEventListener(input.type === 'search' ? 'input' : 'change', () => {
|
|
sessionStorage.setItem(`filter-${input.id}`, input.value);
|
|
const prefix = input.closest('[data-filter]').dataset.filter;
|
|
applyFilters(prefix);
|
|
animateFilterResults(prefix);
|
|
});
|
|
});
|
|
|
|
function updateMissingCounts() {
|
|
$$('#missing .missing-series').forEach(series => {
|
|
let count = 0;
|
|
series.querySelectorAll('tr[data-title]').forEach(row => {
|
|
const show = seasonVisible(row); row.classList.toggle('hidden', !show); if (show) count++;
|
|
});
|
|
series.classList.toggle('hidden', count === 0);
|
|
updateSeasonDividers(series);
|
|
});
|
|
const count = $$('#missing tr[data-title]:not(.hidden)').length;
|
|
set('missingNavCount', number(count)); set('dashboardMissing', number(count));
|
|
set('missingCount', `${number(count)} ${t('Einträge ohne Deutsch', 'entries without German')}`);
|
|
set('seasonZeroHint', localStorage.getItem('show-season-zero') === 'true' ? t('Staffel 0 eingeblendet', 'Season 0 included') : t('Staffel 0 ausgeblendet', 'Season 0 hidden'));
|
|
$('#missingEmpty').classList.toggle('hidden', count > 0);
|
|
}
|
|
|
|
function highlightPreferences() {
|
|
$$('.media-table tr[data-title]').forEach(row => {
|
|
[[3, 'preferred-audio', 'audio-preferred'], [4, 'preferred-subs', 'subtitle-preferred']].forEach(([column, key, className]) => {
|
|
const preference = localStorage.getItem(key);
|
|
const badges = [...row.cells[column].querySelectorAll('.badge')];
|
|
badges.forEach(badge => {
|
|
badge.classList.toggle(className, badge.dataset.language === preference);
|
|
if (column === 4) badge.classList.toggle('subtitle-de', badge.dataset.language === 'Deutsch');
|
|
});
|
|
const preferred = badges.find(badge => badge.dataset.language === preference);
|
|
if (preferred) preferred.parentElement.prepend(preferred);
|
|
});
|
|
});
|
|
}
|
|
|
|
$('#settingsOpen').addEventListener('click', () => {
|
|
closeSidebar();
|
|
$('#preferredAudio').value = localStorage.getItem('preferred-audio') || '';
|
|
$('#preferredSubs').value = localStorage.getItem('preferred-subs') || '';
|
|
$('#showSeasonZero').checked = localStorage.getItem('show-season-zero') === 'true';
|
|
$('#settingsModal').showModal();
|
|
});
|
|
$('#settingsSave').addEventListener('click', () => {
|
|
localStorage.setItem('preferred-audio', $('#preferredAudio').value);
|
|
localStorage.setItem('preferred-subs', $('#preferredSubs').value);
|
|
localStorage.setItem('show-season-zero', String($('#showSeasonZero').checked));
|
|
for (const prefix of ['movie', 'series']) {
|
|
for (const [suffix, value] of [['Audio', $('#preferredAudio').value], ['Subs', $('#preferredSubs').value]]) {
|
|
const input = $(`#${prefix}${suffix}`);
|
|
if (input) { input.value = value; sessionStorage.setItem(`filter-${input.id}`, value); }
|
|
}
|
|
applyFilters(prefix);
|
|
}
|
|
highlightPreferences(); updateMissingCounts(); $('#settingsModal').close();
|
|
});
|
|
|
|
async function api(path, options = {}) {
|
|
const controller = new AbortController();
|
|
const timeout = setTimeout(() => controller.abort(), 25000);
|
|
try {
|
|
const response = await fetch(path, {cache: 'no-store', ...options, signal: controller.signal});
|
|
const data = await response.json();
|
|
if (!response.ok && !data.error && !data.storage?.error) throw new Error(`HTTP ${response.status}`);
|
|
return data;
|
|
} finally { clearTimeout(timeout); }
|
|
}
|
|
|
|
function duration(seconds) {
|
|
const minutes = Math.floor(Number(seconds || 0) / 60), days = Math.floor(minutes / 1440), hours = Math.floor(minutes % 1440 / 60);
|
|
return `${days ? `${days}${t(' T', 'd')} ` : ''}${hours}${t(' Std.', 'h')} ${minutes % 60}${t(' Min.', 'm')}`;
|
|
}
|
|
|
|
function renderSystem(data) {
|
|
if (data.error) { set('systemUpdated', data.error); return; }
|
|
const cpu = percent(data.cpu_percent), memory = data.memory || {};
|
|
set('cpuValue', `${cpu.toFixed(1)}%`); set('ramValue', `${percent(memory.percent).toFixed(1)}%`);
|
|
set('ramDetail', `${memory.used || '—'} / ${memory.total || '—'}`);
|
|
bar('cpuBar', cpu); bar('ramBar', memory.percent);
|
|
set('systemUpdated', `${t('Aktualisiert', 'Updated')} ${new Date().toLocaleTimeString(language === 'de' ? 'de-DE' : 'en-GB')}`);
|
|
renderContent('systemDetails', `<div><small>Load Average</small><strong>${(data.load || []).map(value => Number(value).toFixed(2)).join(' · ') || '—'}</strong></div><div><small>Uptime</small><strong>${html(duration(data.uptime_seconds))}</strong></div><div><small>${t('Prozesse', 'Processes')}</small><strong>${number(data.processes)}</strong></div>`);
|
|
renderContent('diskList', (data.disks || []).map(disk => `<div class="disk-row"><div>${html(disk.label)}<small>${html(disk.path)}</small></div><div class="track"><span style="width:${percent(disk.percent)}%"></span></div><div class="disk-values">${html(disk.used)} / ${html(disk.total)}<small>${percent(disk.percent).toFixed(1)}%</small></div></div>`).join('') || empty(t('Keine Laufwerke erkannt.', 'No disks detected.')));
|
|
}
|
|
|
|
function renderServices(data) {
|
|
set('serviceSummary', `${data.online || 0} / ${data.total || 0} online`);
|
|
const labels = {online: t('Aktiv', 'Online'), offline: 'Offline', timeout: 'Timeout', checking: t('Prüfe …', 'Checking …'), error: t('Fehler', 'Error')};
|
|
renderContent('serviceList', (data.services || []).map(service => `<div class="service-row"><span class="service-logo">${html(service.name.slice(0, 1))}</span><div><strong>${html(service.name)}</strong><small title="${html(service.detail)}">${html(service.detail || '—')}</small></div><span class="service-status ${html(service.status)}">${html(labels[service.status] || service.label)}</span></div>`).join(''));
|
|
}
|
|
|
|
function downloadRow(item) {
|
|
const pct = percent(item.percentage);
|
|
const languages = (item.languages || []).map(lang => `<span class="badge">${html(lang.flag)} ${html(lang.name)}</span>`).join('') || `<span class="muted">${t('Nicht erkannt', 'Not detected')}</span>`;
|
|
return `<tr><td><span class="title" title="${html(item.title)}">${html(item.title)}</span></td><td><span class="state ${item.completed ? 'ok' : 'downloading'}">${html(item.status)}</span></td><td><div class="progress-wrap"><div class="track"><span style="width:${pct}%"></span></div><span>${pct.toFixed(0)}%</span></div></td><td class="download-size">${html(item.size)}<small>${html(item.remaining)}</small></td><td>${html(item.timeleft)}</td><td>${html(item.source)}</td><td><div class="badges">${languages}</div></td></tr>`;
|
|
}
|
|
|
|
function renderDownloads(data) {
|
|
const count = Number(data.active_count) || 0;
|
|
set('dashboardDownloads', data.error ? '—' : number(count));
|
|
set('dashboardRemaining', data.error ? t('Nicht erreichbar', 'Unavailable') : `${t('Noch', 'Remaining')} ${data.remaining || '0 B'}`);
|
|
set('downloadNavCount', number(count)); $('#downloadNavCount')?.classList.toggle('hidden', count === 0);
|
|
set('sabRemaining', data.remaining || '—'); set('sabActive', number(count)); set('sabSpeed', data.speed || '—'); set('sabHistory', number(data.history_count));
|
|
set('sabQueueStatus', data.error ? t('Nicht erreichbar', 'Unavailable') : data.paused ? t('Pausiert', 'Paused') : `SABnzbd · ${data.queue_status || 'Idle'}`);
|
|
$('#downloadError').classList.toggle('hidden', !data.error); set('downloadError', data.error || '');
|
|
const items = data.items || [];
|
|
const active = items.filter(item => !item.completed && String(item.status).toLowerCase() === 'downloading');
|
|
const others = items.filter(item => !active.includes(item));
|
|
for (const [id, list] of [['activeDownloads', active], ['otherDownloads', others]]) {
|
|
set(`${id}Count`, number(list.length));
|
|
renderContent(`${id}Body`, list.length ? list.map(downloadRow).join('') : `<tr><td colspan="7" class="empty-state">${t('Keine Einträge.', 'No entries.')}</td></tr>`);
|
|
}
|
|
}
|
|
|
|
function renderDatastore(data) {
|
|
const storage = data.storage || {}, raid = data.raid || {};
|
|
for (const [id, key] of [['Total', 'total'], ['Used', 'used'], ['Free', 'free']]) set(`datastore${id}`, storage[key] || '—');
|
|
set('datastorePercent', storage.percent == null ? '—' : `${storage.percent}%`);
|
|
set('datastorePath', storage.path || '—'); set('datastoreCapacityLabel', storage.total ? `${storage.used} / ${storage.total}` : storage.error || '—');
|
|
bar('datastoreCapacityBar', storage.percent);
|
|
set('datastoreUpdated', storage.scanned_at ? `${t('Speicher-Scan', 'Storage scan')} ${new Date(storage.scanned_at * 1000).toLocaleTimeString()}` : t('Nicht verfügbar', 'Unavailable'));
|
|
$('#storageWarning').classList.toggle('hidden', !storage.error && !storage.warning);
|
|
set('storageWarning', storage.error || storage.warning || '');
|
|
renderContent('datastoreCategories', (storage.categories || []).map(category => `<div class="category-row"><div class="metric-line"><span>${html(category.label)}</span><strong>${html(category.size || '0 B')}</strong></div><div class="track"><span style="width:${percent(category.percent)}%"></span></div><small>${Number(category.percent || 0).toFixed(1)}% ${t('vom belegten Speicher', 'of used storage')} · ${number(category.files)} ${t('Dateien', 'files')}</small></div>`).join('') || empty(t('Keine Kategorien erkannt.', 'No categories detected.')));
|
|
const io = data.io_pressure || {}, some = Number(io.some?.avg10) || 0, full = Number(io.full?.avg10) || 0;
|
|
const pressure = Math.max(some, full);
|
|
set('ioPressureLabel', io.available ? pressure >= 20 ? t('Hoch', 'High') : pressure >= 5 ? t('Beobachten', 'Watch') : t('Normal', 'Normal') : t('Nicht verfügbar', 'Unavailable'));
|
|
for (const [key, value] of [['Some', some], ['Full', full]]) { set(`ioPressure${key}`, io.available ? `${value.toFixed(1)}%` : '—'); bar(`ioPressure${key}Bar`, value); }
|
|
set('raidDevice', raid.device || '—'); set('raidStatusBadge', raid.label || 'UNKNOWN');
|
|
$('#raidStatusBadge').className = `badge raid-status ${raid.status || 'unknown'}`;
|
|
$('#raidWarning').classList.toggle('hidden', !raid.error && !raid.warning); set('raidWarning', raid.error || raid.warning || '');
|
|
renderContent('raidSummary', `<div><small>Level</small><strong>${html(raid.level)}</strong></div><div><small>${t('Aktive Laufwerke', 'Active drives')}</small><strong>${html(raid.active_devices)} / ${html(raid.raid_devices)}</strong></div><div><small>${t('Fehlend', 'Missing')}</small><strong>${html(raid.failed_devices ?? '—')}</strong></div>`);
|
|
const recovery = raid.recovery || {};
|
|
$('#raidRecovery').classList.toggle('hidden', !recovery.active); set('raidRecoveryPercent', `${Number(recovery.percent || 0).toFixed(1)}%`);
|
|
set('raidRecoverySpeed', recovery.speed || '—'); set('raidRecoveryFinish', recovery.finish || '—'); bar('raidRecoveryBar', recovery.percent);
|
|
renderContent('raidDisks', (raid.devices || []).map(disk => `<div class="raid-disk"><span class="disk-status ${html(disk.status)}"></span><div><strong>${html(disk.device)}</strong><small>Slot ${html(disk.slot)} · ${html(disk.model)}</small><small>${html(disk.size)} · Serial: ${html(disk.serial)}</small><small>SMART: ${html(disk.smart || t('Nicht aktiviert', 'Not enabled'))} · ${html(disk.temperature || '—')}</small></div><b>${html(disk.status)}</b></div>`).join('') || empty(t('Keine RAID-Mitglieder erkannt.', 'No RAID members detected.')));
|
|
}
|
|
|
|
const gpuValue = (value, unit = '') => value == null || value === '' ? '—' : `${html(value)}${unit}`;
|
|
function renderGraphics(data) {
|
|
const gpus = data.gpus || [];
|
|
set('graphicsStatus', data.available ? `${gpus.length} GPU${gpus.length === 1 ? '' : 's'}` : t('Nicht verfügbar', 'Unavailable'));
|
|
const average = key => {
|
|
const values = gpus.map(gpu => gpu[key]).filter(value => value != null && Number.isFinite(Number(value))).map(Number);
|
|
return values.length ? Math.round(values.reduce((a, b) => a + b, 0) / values.length) : null;
|
|
};
|
|
const used = gpus.reduce((sum, gpu) => sum + (Number(gpu['memory.used']) || 0), 0), total = gpus.reduce((sum, gpu) => sum + (Number(gpu['memory.total']) || 0), 0);
|
|
const metrics = [['GPUs', gpus.length], [t('GPU-Auslastung', 'GPU usage'), gpuValue(average('utilization.gpu'), '%')], ['VRAM', total ? `${(used / 1024).toFixed(1)} / ${(total / 1024).toFixed(1)} GB` : '—'], [t('Temperatur', 'Temperature'), gpuValue(average('temperature.gpu'), ' °C')]];
|
|
renderContent('graphicsSummary', metrics.map(([label, value]) => `<article class="summary-card"><span class="summary-icon purple">${icon('chip')}</span><div><strong>${value}</strong><span>${html(label)}</span></div></article>`).join(''));
|
|
renderContent('graphicsCards', gpus.length ? gpus.map(gpu => {
|
|
const used = Number(gpu['memory.used']) || 0, total = Number(gpu['memory.total']) || 0;
|
|
return `<article class="panel"><div class="panel-heading"><div><small class="muted">GPU ${html(gpu.index)}</small><h2>${html(gpu.name)}</h2></div><span class="badge">${gpuValue(gpu['temperature.gpu'], ' °C')}</span></div><div class="graphics-meta-grid"><div><small>${t('GPU-Last', 'GPU load')}</small><strong>${gpuValue(gpu['utilization.gpu'], '%')}</strong></div><div><small>${t('Memory-Last', 'Memory load')}</small><strong>${gpuValue(gpu['utilization.memory'], '%')}</strong></div><div><small>${t('Leistung', 'Power')}</small><strong>${gpuValue(gpu['power.draw'], ' W')} / ${gpuValue(gpu['power.limit'], ' W')}</strong></div><div><small>P-State</small><strong>${html(gpu.pstate)}</strong></div></div><div class="coverage-row" style="margin-top:22px"><div class="metric-line"><span>VRAM</span><strong>${total ? `${(used / 1024).toFixed(1)} / ${(total / 1024).toFixed(1)} GB` : '—'}</strong></div><div class="track purple-track"><span style="width:${total ? percent(used / total * 100) : 0}%"></span></div></div><div class="graphics-details"><span>${t('Treiber', 'Driver')}: ${html(gpu.driver_version)} · PCI: ${html(gpu['pci.bus_id'])}</span><span>UUID: ${html(gpu.uuid)}</span><span>Serial: ${html(gpu.serial)}</span><span>Clocks: ${gpuValue(gpu['clocks.current.graphics'], ' MHz')} · Memory: ${gpuValue(gpu['clocks.current.memory'], ' MHz')}</span><span>Fan: ${gpuValue(gpu['fan.speed'], '%')} · Compute: ${html(gpu.compute_mode)}</span></div></article>`;
|
|
}).join('') : `<div class="panel">${empty(data.error || t('Keine NVIDIA-GPU erkannt.', 'No NVIDIA GPU detected.'))}</div>`);
|
|
renderContent('graphicsProcesses', (data.processes || []).map(process => `<div class="graphics-process"><strong>${html(process.name)}</strong><span>PID ${html(process.pid)}</span><span>${html(process.memory)}</span></div>`).join('') || empty(t('Keine GPU-Prozesse erkannt.', 'No GPU processes detected.')));
|
|
}
|
|
|
|
let scanRunning = false;
|
|
function renderScanStatus(data) {
|
|
scanRunning = false;
|
|
for (const source of ['radarr', 'sonarr', 'missing']) {
|
|
const job = data[source] || {};
|
|
const node = $(`#${source}Status`);
|
|
if (job.state === 'running') scanRunning = true;
|
|
if (!node) continue;
|
|
node.className = `scan-status ${job.state || ''}`;
|
|
node.textContent = job.state === 'running' ? `${t('Scan läuft', 'Scanning')} · ${job.done}/${job.total || '?'} · ${job.total ? Math.round(job.done / job.total * 100) : 0}%` :
|
|
job.state === 'done' ? t('Scan abgeschlossen', 'Scan complete') : job.state === 'error' ? `${t('Scanfehler', 'Scan error')}: ${job.error}` : t('Scan bereit', 'Ready to scan');
|
|
}
|
|
$('#rescan').disabled = scanRunning;
|
|
$('#rescan').classList.toggle('is-scanning', scanRunning);
|
|
$('#rescan').setAttribute('aria-busy', String(scanRunning));
|
|
const label = $('#rescan span');
|
|
label.textContent = scanRunning ? t('Scan läuft …', 'Scanning …') : t('Neu scannen', 'Rescan');
|
|
}
|
|
|
|
$('#rescan').addEventListener('click', async () => {
|
|
$('#rescan').disabled = true; $('#rescan').classList.add('is-scanning');
|
|
$('#rescan').setAttribute('aria-busy', 'true'); $('#actionError').classList.add('hidden');
|
|
try {
|
|
const data = await api(`/api/rescan?source=${encodeURIComponent($('#scanSource').value)}`, {method: 'POST'});
|
|
if (!data.ok) throw new Error(data.error || t('Scan konnte nicht gestartet werden.', 'Could not start scan.'));
|
|
renderScanStatus(await api('/api/scan-status'));
|
|
} catch (error) {
|
|
set('actionError', `${t('Scan fehlgeschlagen', 'Scan failed')}: ${error.message}`); $('#actionError').classList.remove('hidden');
|
|
} finally {
|
|
$('#rescan').disabled = scanRunning;
|
|
$('#rescan').classList.toggle('is-scanning', scanRunning);
|
|
$('#rescan').setAttribute('aria-busy', String(scanRunning));
|
|
}
|
|
});
|
|
|
|
const renderers = {system: renderSystem, services: renderServices, downloads: renderDownloads, datastore: renderDatastore, graphics: renderGraphics, scans: renderScanStatus};
|
|
function monitor(key, path, interval, onError) {
|
|
const update = async () => {
|
|
if (!document.hidden) {
|
|
try { const data = await api(path); snapshots[key] = data; renderers[key](data); }
|
|
catch (error) { onError?.(error); }
|
|
}
|
|
setTimeout(update, interval);
|
|
};
|
|
update();
|
|
}
|
|
|
|
async function pollLibrary() {
|
|
if (!document.hidden && !$('#settingsModal').open) {
|
|
try {
|
|
const data = await api('/api/library-status');
|
|
if (data.ready && (!config.libraryReady || Number(data.updated_at) > config.libraryUpdatedAt)) {
|
|
sessionStorage.setItem('dashboard-active-view', activeView);
|
|
location.reload(); return;
|
|
}
|
|
} catch (error) { /* Keep the current snapshot during a connection outage. */ }
|
|
}
|
|
setTimeout(pollLibrary, 5000);
|
|
}
|
|
|
|
switchView(sessionStorage.getItem('dashboard-active-view') || 'dashboard');
|
|
translateLayout(); highlightPreferences();
|
|
monitor('system', '/api/system', 5000, () => set('systemUpdated', t('Nicht erreichbar', 'Unavailable')));
|
|
monitor('services', '/api/services', 30000, () => set('serviceSummary', t('Nicht erreichbar', 'Unavailable')));
|
|
monitor('datastore', '/api/datastore', 5000, () => renderDatastore({storage: {error: t('Datastore nicht erreichbar.', 'Datastore unavailable.')}, raid: {error: t('RAID-Status nicht verfügbar.', 'RAID status unavailable.')}}));
|
|
monitor('graphics', '/api/graphics', 5000, () => renderGraphics({error: t('GPU-Status nicht verfügbar.', 'GPU status unavailable.')}));
|
|
monitor('scans', '/api/scan-status', 1500);
|
|
if (config.sabEnabled) monitor('downloads', '/api/downloads', 4000, () => renderDownloads({error: t('SABnzbd nicht erreichbar.', 'SABnzbd unavailable.')}));
|
|
pollLibrary();
|
|
if ('serviceWorker' in navigator) window.addEventListener('load', () => navigator.serviceWorker.register('/sw.js?v=10', {scope: '/'}).catch(() => {}));
|