Add persistent upload statistics alongside history
CI / verify (push) Canceled after 0s

This commit is contained in:
Sucukdeluxe committed 2026-10-24 13:21:04 +02:00
1 parent 54a6bcbb6f
commit dc1d042d73
10 files changed
+784 -8

No files matched your search

+7 -2
View File
@@ -137,7 +137,9 @@ class UploadManager extends EventEmitter {
_recordTransferred(entry, bytes, total) {
if (!Number.isFinite(bytes) || bytes < 0) return;
const next = Math.min(bytes, total);
this.transferredBytes += Math.max(0, next - entry.bytesUploaded);
const delta = Math.max(0, next - entry.bytesUploaded);
this.transferredBytes += delta;
if (delta > 0) this.emit('statistics-transfer', { hoster: entry.hoster, bytes: delta });
entry.bytesUploaded = next;
entry.phase = next >= total ? 'awaiting-confirmation' : 'uploading';
}
@@ -431,6 +433,7 @@ class UploadManager extends EventEmitter {
const batchId = `batch-${Date.now()}`;
const results = new Map(); // filePath -> { name, size, results: [] }
this._batchResults = results;
this._batchTaskCount = tasks.length;
this._additionalPromises = []; // Track jobs added mid-batch via addJobs()
const DEDUP_CHUNK = 200;
@@ -472,7 +475,7 @@ class UploadManager extends EventEmitter {
this._emitStats();
const files = Array.from(results.values());
const total = tasks.length;
const total = this._batchTaskCount;
const succeeded = files.reduce((count, file) => count + file.results.filter((result) => result.status === 'done').length, 0);
const skipped = files.reduce((count, file) => count + file.results.filter((result) => result.status === 'skipped').length, 0);
@@ -549,6 +552,7 @@ class UploadManager extends EventEmitter {
};
results.get(task.file).results.push(result);
this.emit('statistics-outcome', { id: uploadId, hoster: task.hoster, status });
};
const emitFinalStatus = (status, payload = {}) => {
@@ -1557,6 +1561,7 @@ class UploadManager extends EventEmitter {
}
this._additionalPromises.push(this._runJob(task, results, signal));
addResult.added++;
this._batchTaskCount++;
}
return addResult;
}
+186
View File
@@ -0,0 +1,186 @@
const fs = require('node:fs/promises');
const path = require('node:path');
const HOSTERS = Object.freeze({ 'doodstream.com': 'Doodstream', 'voe.sx': 'VOE', 'vidmoly.me': 'Vidmoly', 'byse.sx': 'Byse', 'clouddrop.cc': 'CloudDrop' });
const RANGES = new Set(['session', 'today', 'last24', 'week', 'month', 'all']);
const MINUTE = 60000;
const DAY = 86400000;
const empty = () => ({ bytes: 0, trackedBytes: 0, completed: 0, failed: 0, activeMs: 0, providers: {} });
const count = value => Number.isFinite(value) && value >= 0 ? value : 0;
const dayKey = time => {
const date = new Date(time);
return [date.getFullYear(), String(date.getMonth() + 1).padStart(2, '0'), String(date.getDate()).padStart(2, '0')].join('-');
};
function add(target, delta, hoster) {
for (const key of ['bytes', 'trackedBytes', 'completed', 'failed', 'activeMs']) target[key] = count(target[key]) + count(delta[key]);
if (Object.hasOwn(HOSTERS, hoster)) {
const provider = target.providers[hoster] ||= { bytes: 0, completed: 0, failed: 0 };
for (const key of ['bytes', 'completed', 'failed']) provider[key] += count(delta[key]);
}
}
function merge(target, source) {
add(target, source);
for (const [hoster, bucket] of Object.entries(source.providers || {})) {
if (!Object.hasOwn(HOSTERS, hoster)) continue;
const provider = target.providers[hoster] ||= { bytes: 0, completed: 0, failed: 0 };
for (const key of ['bytes', 'completed', 'failed']) provider[key] += count(bucket[key]);
}
}
function validState(value) {
return value?.version === 1 && value.days && value.minutes && value.total?.providers && Number.isFinite(value.startedAt);
}
class UploadStatistics {
constructor(filePath, { now = Date.now } = {}) {
this.filePath = filePath;
this.now = now;
this.session = empty();
this.sessionStartedAt = now();
this.seen = new Set();
this.activeSince = null;
this.writeChain = Promise.resolve();
this.revision = 0;
this.savedRevision = -1;
this.ready = false;
this.error = '';
}
async init(history = []) {
let present = false;
for (const name of [this.filePath, this.filePath + '.bak']) {
try {
const value = JSON.parse(await fs.readFile(name, 'utf8'));
if (!validState(value)) throw new Error('Ungültiges Statistikformat');
this.state = value;
this.savedRevision = 0;
break;
} catch (error) {
if (error.code !== 'ENOENT') present = true;
}
}
if (!this.state && present) throw new Error('Statistikdatei und Sicherung sind nicht lesbar');
if (!this.state) {
this.state = { version: 1, startedAt: this.now(), historyImported: false, total: empty(), days: {}, minutes: {} };
for (const batch of Array.isArray(history) ? history : []) {
const time = Date.parse(batch?.timestamp);
if (!Number.isFinite(time) || time > this.now()) continue;
for (const file of batch.files || []) {
for (const result of file.results || []) {
if (!Object.hasOwn(HOSTERS, result.hoster) || !['done', 'error'].includes(result.status)) continue;
this.record(result.hoster, { bytes: result.status === 'done' ? count(file.size) : 0, completed: Number(result.status === 'done'), failed: Number(result.status === 'error') }, time, false);
this.state.historyImported = true;
this.state.startedAt = Math.min(this.state.startedAt, time);
}
}
}
}
this.ready = true;
await this.flush();
}
record(hoster, delta, time = this.now(), session = true) {
if (session) {
delta = { ...delta, trackedBytes: count(delta.bytes) };
add(this.session, delta, hoster);
}
add(this.state.total, delta, hoster);
add(this.state.days[dayKey(time)] ||= empty(), delta, hoster);
if (time >= this.now() - 2 * DAY) add(this.state.minutes[Math.floor(time / MINUTE)] ||= empty(), delta, hoster);
this.revision++;
}
transfer(hoster, bytes) {
if (!this.ready || !Object.hasOwn(HOSTERS, hoster) || !Number.isFinite(bytes) || bytes <= 0) return;
this.record(hoster, { bytes });
}
outcome({ id, hoster, status }) {
if (!this.ready || !id || !Object.hasOwn(HOSTERS, hoster) || !['done', 'error'].includes(status) || this.seen.has(id)) return;
this.seen.add(id);
this.record(hoster, { completed: Number(status === 'done'), failed: Number(status === 'error') });
}
activity(active) {
if (!this.ready) return;
const now = this.now();
if (this.activeSince !== null) {
let start = this.activeSince;
while (start < now) {
const end = Math.min(now, (Math.floor(start / MINUTE) + 1) * MINUTE);
this.record(null, { activeMs: end - start }, start);
start = end;
}
}
this.activeSince = active ? now : null;
}
finishBatch() {
this.activity(false);
this.seen.clear();
}
snapshot(range = 'session') {
if (!RANGES.has(range)) throw new Error('Ungültiger Statistikzeitraum');
if (!this.ready) throw new Error('Statistik noch nicht verfügbar');
this.activity(this.activeSince !== null);
const total = empty();
if (range === 'session') merge(total, this.session);
else if (range === 'all') merge(total, this.state.total);
else if (range === 'last24') {
const cutoff = Math.floor((this.now() - DAY) / MINUTE);
for (const [minute, bucket] of Object.entries(this.state.minutes)) if (Number(minute) > cutoff && Number(minute) <= Math.floor(this.now() / MINUTE)) merge(total, bucket);
} else {
const date = new Date(this.now());
date.setDate(date.getDate() - (range === 'month' ? 29 : range === 'week' ? 6 : 0));
const start = dayKey(date.getTime());
const end = dayKey(this.now());
for (const [day, bucket] of Object.entries(this.state.days)) if (day >= start && day <= end) merge(total, bucket);
}
const outcomes = total.completed + total.failed;
return { ...total, range, startedAt: range === 'session' ? this.sessionStartedAt : this.state.startedAt,
historyImported: range !== 'session' && this.state.historyImported,
successRate: outcomes ? total.completed / outcomes * 100 : null,
averageSpeedBps: total.activeMs > 0 ? total.trackedBytes * 1000 / total.activeMs : null,
persistenceError: this.error,
providers: Object.entries(HOSTERS).map(([id, label]) => ({ id, label, ...(total.providers[id] || { bytes: 0, completed: 0, failed: 0 }) })) };
}
async reset(scope) {
if (!['session', 'all', 'errors'].includes(scope)) throw new Error('Ungültiger Statistikreset');
if (!this.ready) throw new Error('Statistik noch nicht verfügbar');
this.activity(this.activeSince !== null);
if (scope === 'session' || scope === 'all') { this.session = empty(); this.sessionStartedAt = this.now(); }
if (scope === 'all') this.state = { version: 1, startedAt: this.now(), historyImported: false, total: empty(), days: {}, minutes: {} };
if (scope === 'errors') {
for (const bucket of [this.session, this.state.total, ...Object.values(this.state.days), ...Object.values(this.state.minutes)]) {
bucket.failed = 0;
for (const provider of Object.values(bucket.providers)) provider.failed = 0;
}
}
this.revision++;
await this.flush();
}
flush() {
const task = this.writeChain.catch(() => {}).then(async () => {
if (!this.ready || this.savedRevision === this.revision) return;
const cutoff = Math.floor((this.now() - 2 * DAY) / MINUTE);
for (const minute of Object.keys(this.state.minutes)) if (Number(minute) < cutoff) delete this.state.minutes[minute];
const revision = this.revision;
const data = JSON.stringify(this.state);
await fs.mkdir(path.dirname(this.filePath), { recursive: true });
const handle = await fs.open(this.filePath + '.tmp', 'w');
try { await handle.writeFile(data, 'utf8'); await handle.sync(); } finally { await handle.close(); }
try {
const previous = await fs.readFile(this.filePath, 'utf8');
if (validState(JSON.parse(previous))) await fs.writeFile(this.filePath + '.bak', previous, 'utf8');
} catch (error) { if (error.code !== 'ENOENT' && !(error instanceof SyntaxError)) throw error; }
await fs.rename(this.filePath + '.tmp', this.filePath);
this.savedRevision = revision;
this.error = '';
});
this.writeChain = task;
return task.catch(error => { this.error = 'Statistik konnte nicht gespeichert werden'; throw error; });
}
}
module.exports = { UploadStatistics, HOSTERS };
+31
View File
@@ -45,6 +45,7 @@ const { selectOrphanTmps } = require('./lib/orphan-tmp');
const { sanitizeConfig, buildSupportBundleText, collectSecretValues, redactLogText, valueScrub, collectFile, collectFileSnapshot, REDACTED } = require('./lib/support-bundle');
const { buildWebhookRequest, isAllAborted } = require('./lib/webhook-notify');
const stats = require('./lib/stats');
const { UploadStatistics } = require('./lib/upload-statistics');
const { createCollectors } = require('./lib/diagnostics-collectors');
const { buildSessionReport, buildSessionReportCsv } = require('./lib/session-report');
const { inspectImportEntries, inspectReadableImportPath } = require('./lib/import-preflight');
@@ -160,6 +161,9 @@ let dropTargetWindow = null;
let tray = null;
let _cachedLogSettings = null;
const configStore = new ConfigStore(app);
const uploadStatistics = new UploadStatistics(path.join(app.getPath('userData'), 'upload-statistics.json'));
let statisticsReady;
let statisticsTimer;
const mcpUpdate = new McpUpdate({
directory: app.getPath('userData'), version: () => app.getVersion(),
canUpdate: () => mcpService?.capabilities().includes('updates') === true,
@@ -296,6 +300,7 @@ async function waitForConfigStoreWrites() {
await Promise.all([...cloudLogWrites]);
await cloudLogSync.flushLocal();
await configStore.drainWrites();
await uploadStatistics.flush();
await configStore.drainAutomationCompletionWrites();
}
@@ -2010,6 +2015,10 @@ async function runAutomaticUpdateCheck(forceRefresh) {
app.whenReady().then(async () => {
await mcpUpdate.load().catch(() => logError('MCP update state unavailable'));
if (!_hasSingleInstanceLock) return;
statisticsReady = configStore.loadHistory().then(history => uploadStatistics.init(history));
await statisticsReady.catch(error => debugLog(`statistics init failed: ${error.message}`));
statisticsTimer = setInterval(() => { void uploadStatistics.flush().catch(error => debugLog(`statistics save failed: ${error.message}`)); }, 5000);
statisticsTimer.unref();
startupDiagnostics.write('application-ready', { hardwareAcceleration: app.isHardwareAccelerationEnabled(), gpuFeatures: app.getGPUFeatureStatus() });
void app.getGPUInfo('basic').then(info => {
const devices = Array.isArray(info.gpuDevice) ? info.gpuDevice.map(device => ({
@@ -2109,6 +2118,7 @@ app.on('will-quit', () => {
if (quitTeardownStarted) return;
quitTeardownStarted = true;
systemMetrics.stop();
clearInterval(statisticsTimer);
void mcpService?.stop();
folderMonitorRendererReadyGeneration = null;
if (updateCheckInterval) clearInterval(updateCheckInterval);
@@ -2241,6 +2251,18 @@ ipcMain.handle('save-config', async (_event, config) => {
return true;
});
ipcMain.handle('get-statistics', async (_event, range) => {
await statisticsReady;
return uploadStatistics.snapshot(range);
});
ipcMain.handle('reset-statistics', async (_event, scope) => {
assertConfigWriteAllowed();
await statisticsReady;
await uploadStatistics.reset(scope);
return true;
});
ipcMain.handle('get-history', () => {
return configStore.loadHistory();
});
@@ -2824,6 +2846,12 @@ ipcMain.handle('start-upload', async (_event, payload) => {
onError: error => debugLog(`automation completion ledger failed: ${error.message}`)
});
uploadManager.on('statistics-transfer', ({ hoster, bytes }) => {
uploadStatistics.activity(true);
uploadStatistics.transfer(hoster, bytes);
});
uploadManager.on('statistics-outcome', data => uploadStatistics.outcome(data));
uploadManager.on('progress', (data) => {
if (data.status !== 'uploading') {
debugLog(`progress: ${data.fileName} ${data.hoster} ${data.status} ${data.error || ''}`);
@@ -2862,6 +2890,7 @@ ipcMain.handle('start-upload', async (_event, payload) => {
uploadManager.on('stats', (data) => {
try {
if (!data || typeof data !== 'object') return;
uploadStatistics.activity(data.activeJobs > 0 && data.state !== 'idle');
safeSend('upload-stats', data);
if (data.state === 'uploading' && data.activeJobs > 0) {
const speedMb = ((Number(data.globalSpeedKbs) || 0) / 1000).toFixed(1);
@@ -2939,6 +2968,8 @@ ipcMain.handle('start-upload', async (_event, payload) => {
// create a fresh manager which the trailing `uploadManager = null` then
// orphans (cancel/addJobs see null, the new batch keeps running invisibly).
uploadManager.on('batch-done', async (summary) => {
uploadStatistics.finishBatch();
void uploadStatistics.flush().catch(error => debugLog(`statistics save failed: ${error.message}`));
summary = stats.mergeSkippedIntoSummary(summary, skippedJobs);
let automationCompletionsPersisted = true;
try { await _thisManager._automationCompletionWriter?.flush(); } catch (error) {
+2
View File
@@ -28,6 +28,8 @@ ipcRenderer.on('folder-monitor:renderer-generation', (_event, generation) => {
});
contextBridge.exposeInMainWorld('api', {
getStatistics: range => ipcRenderer.invoke('get-statistics', range),
resetStatistics: scope => ipcRenderer.invoke('reset-statistics', scope),
mcpStatus: () => ipcRenderer.invoke('mcp:status'),
mcpConfigure: args => ipcRenderer.invoke('mcp:configure', args),
mcpRotate: () => ipcRenderer.invoke('mcp:rotate'),
+3
View File
@@ -42,6 +42,7 @@ function refreshLocalizedRuntimeUi() {
if (hint && activeRecentTab) hint.textContent = localizeUiText(activeRecentTab.dataset.panel === 'statsTab' ? 'Upload-Statistiken' : 'Zuletzt erzeugte Upload-Links');
renderManagedOnlineBackups();
renderManagedOnlineBackupRefreshIssue();
window.UploadStatisticsView?.localize();
}
// Dropdown options for "Add Account" modal: value -> label
@@ -1698,6 +1699,7 @@ function _isHistoryTabActive() {
syncTabIndicator(tab);
const activeSidebarButton = nextView?.querySelector('.view-sidebar-navigation > .view-sidebar-item.active, .settings-navigation .settings-nav-button.active');
_syncSidebarIndicator(activeSidebarButton, true);
if (tab.dataset.view === 'history') window.UploadStatisticsView?.refresh(true);
if (tab.dataset.view === 'history' && (_historyDirty || !_historyEverLoaded)) {
loadHistory();
}
@@ -6048,6 +6050,7 @@ function setAccountSidebarFilter(value) {
function setHistorySidebarFilter(value) {
if (!['all', 'success', 'error', 'skipped'].includes(value)) return;
window.UploadStatisticsView?.showHistory();
historySidebarFilter = value;
_syncSidebarFilterButtons('[data-history-filter]', 'historyFilter', value);
const container = document.getElementById('historyContainer');
+46
View File
@@ -4,6 +4,52 @@
if (root) root.I18n = api;
})(typeof window !== 'undefined' ? window : globalThis, function () {
const pairs = [
['Seit Beginn der Datenverkehrserfassung', 'Since traffic recording began'],
["Ungültiges Statistikformat","Invalid statistics format"],
["Statistikdatei und Sicherung sind nicht lesbar","Statistics file and backup cannot be read"],
["Ungültiger Statistikzeitraum","Invalid statistics period"],
["Statistik noch nicht verfügbar","Statistics not available yet"],
["Ungültiger Statistikreset","Invalid statistics reset"],
["Statistiken","Statistics"],
["Auswertung","Analysis"],
["Statistik-Zeitraum","Statistics period"],
["Statistik-Dashboard","Statistics dashboard"],
["Statistiken zurücksetzen","Reset statistics"],
["Heute","Today"],
["Letzte 24 Stunden","Last 24 hours"],
["Sieben Tage","Seven days"],
["30 Tage","30 days"],
["Sitzung zurücksetzen","Reset session"],
["Gesamt zurücksetzen","Reset all"],
["Fehler zurücksetzen","Reset errors"],
["Datenmenge","Data transferred"],
["Erfolgsquote","Success rate"],
["Durchschnitt","Average speed"],
["Bandbreitenverlauf","Bandwidth history"],
["Live · letzte 60 Sekunden","Live · last 60 seconds"],
["Daten","Data"],
["Ergebnisse","Results"],
["Upload-Nutzung je Hoster","Upload usage by host"],
["Statistiken werden geladen…","Loading statistics…"],
["Erfolgreiche Uploads werden je Hoster gezählt. Die Datenmenge enthält Wiederholungen.","Successful uploads are counted per host. Data transferred includes retries."],
["Enthält vorhandenen Verlauf. Frühere Wiederholungen und aktive Uploadzeit sind nicht vollständig erfasst.","Includes existing history. Earlier retries and active upload time were not fully recorded."],
["Lokale Upload-Statistik. Wiederholungen zählen zum Datenverkehr; abgebrochene und übersprungene Uploads nicht zur Erfolgsquote.","Local upload statistics. Traffic includes retries; success rate excludes cancelled and skipped uploads."],
["Erfolgreiche Uploads je Hoster","Successful uploads per host"],
["Erfolgreich / erfolgreich und fehlgeschlagen","Successful / successful and failed"],
["Keine vollständige aktive Uploadzeit verfügbar","Complete active upload time unavailable"],
["Daten / aktive Uploadzeit","Data / active upload time"],
["Endgültig fehlgeschlagene Uploads","Permanently failed uploads"],
["fertig","completed"],
["Statistiken konnten nicht geladen werden. Erneut versuchen.","Statistics could not be loaded. Try again."],
["Statistik konnte nicht gespeichert werden","Statistics could not be saved"],
["Statistikwerte dieser Sitzung zurücksetzen? Uploads, Dateien und Verlauf bleiben erhalten.","Reset statistics for this session? Uploads, files and history are preserved."],
["Alle gespeicherten Statistikwerte zurücksetzen? Uploads, Dateien und Verlauf bleiben erhalten.","Reset all saved statistics? Uploads, files and history are preserved."],
["Fehlerzähler in allen Statistikzeiträumen zurücksetzen? Uploads und Verlauf bleiben unverändert.","Reset error counts in all statistics periods? Uploads and history remain unchanged."],
["Statistiken zurücksetzen?","Reset statistics?"],
["Zurücksetzen","Reset"],
["Statistiken konnten nicht zurückgesetzt werden. Erneut versuchen.","Statistics could not be reset. Try again."],
["Upload-Bandbreitenverlauf der letzten 60 Sekunden","Upload bandwidth history for the last 60 seconds"],
["Kein Upload-Datenverkehr in den letzten 60 Sekunden","No upload traffic in the last 60 seconds"],
['MCP-Fernzugriff', 'MCP remote access'],
['MCP-Einstellungen werden gespeichert…', 'Saving MCP settings…'],
['MCP-Änderungen noch nicht gespeichert', 'MCP changes have not been saved yet'],
+10 -6
View File
@@ -7,6 +7,7 @@
<title>Multi-Hoster-Uploader</title>
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="mcp.css">
<link rel="stylesheet" href="statistics.css">
</head>
<body>
<svg class="icon-sprite" aria-hidden="true">
@@ -51,9 +52,9 @@
<svg class="top-nav-icon" aria-hidden="true"><use href="#icon-settings"></use></svg>
<span class="top-nav-label">Einstellungen</span>
</button>
<button class="tab" id="history-tab" role="tab" aria-selected="false" aria-controls="history-view" tabindex="-1" data-view="history" title="Verlauf">
<button class="tab" id="history-tab" role="tab" aria-selected="false" aria-controls="history-view" tabindex="-1" data-view="history" title="Statistiken">
<svg class="top-nav-icon" aria-hidden="true"><use href="#icon-history"></use></svg>
<span class="top-nav-label">Verlauf</span>
<span class="top-nav-label">Statistiken</span>
</button>
<span class="tab-indicator" aria-hidden="true"></span>
</nav>
@@ -575,14 +576,15 @@
</div>
</div>
<div id="history-view" class="view" role="tabpanel" aria-labelledby="history-tab">
<div id="history-view" class="view statistics-mode" role="tabpanel" aria-labelledby="history-tab">
<aside class="view-sidebar" aria-label="Verlaufsübersicht">
<div class="view-navigation-card">
<div class="view-sidebar-header">
<span class="view-sidebar-kicker">Archiv</span>
<h1 class="view-sidebar-title"><svg aria-hidden="true"><use href="#icon-history"></use></svg><span>Verlauf</span></h1>
<span class="view-sidebar-kicker">Auswertung</span>
<h1 class="view-sidebar-title"><svg aria-hidden="true"><use href="#icon-history"></use></svg><span>Statistiken</span></h1>
</div>
<nav class="view-sidebar-navigation" aria-label="Verlaufsstatus">
<nav class="view-sidebar-navigation statistics-ranges" aria-label="Statistik-Zeitraum"><span class="view-sidebar-indicator" aria-hidden="true"></span><button class="view-sidebar-item active" data-statistics-range="session" aria-label="Sitzung" aria-pressed="true"><svg class="view-sidebar-icon" aria-hidden="true"><use href="#icon-clock"></use></svg><span class="view-sidebar-copy">Sitzung</span></button><button class="view-sidebar-item" data-statistics-range="today" aria-label="Heute" aria-pressed="false"><svg class="view-sidebar-icon" aria-hidden="true"><use href="#icon-clock"></use></svg><span class="view-sidebar-copy">Heute</span></button><button class="view-sidebar-item" data-statistics-range="last24" aria-label="Letzte 24 Stunden" aria-pressed="false"><svg class="view-sidebar-icon" aria-hidden="true"><use href="#icon-clock"></use></svg><span class="view-sidebar-copy">Letzte 24 Stunden</span></button><button class="view-sidebar-item" data-statistics-range="week" aria-label="Sieben Tage" aria-pressed="false"><svg class="view-sidebar-icon" aria-hidden="true"><use href="#icon-clock"></use></svg><span class="view-sidebar-copy">Sieben Tage</span></button><button class="view-sidebar-item" data-statistics-range="month" aria-label="30 Tage" aria-pressed="false"><svg class="view-sidebar-icon" aria-hidden="true"><use href="#icon-clock"></use></svg><span class="view-sidebar-copy">30 Tage</span></button><button class="view-sidebar-item" data-statistics-range="all" aria-label="Gesamt" aria-pressed="false"><svg class="view-sidebar-icon" aria-hidden="true"><use href="#icon-clock"></use></svg><span class="view-sidebar-copy">Gesamt</span></button></nav><div class="statistics-nav-divider"><span>Upload-Verlauf</span></div>
<nav class="view-sidebar-navigation" id="statisticsHistoryNavigation" aria-label="Verlaufsstatus">
<span class="view-sidebar-indicator" aria-hidden="true"></span>
<button class="view-sidebar-item active" data-history-filter="all" aria-label="Gesamten Verlauf anzeigen">
<svg class="view-sidebar-icon" aria-hidden="true"><use href="#icon-history"></use></svg>
@@ -615,6 +617,7 @@
</div>
<div class="view-sidebar-footnote">Links wiederfinden, kopieren oder als Datei exportieren.</div>
</aside>
<section id="statisticsContent" class="statistics-content" aria-label="Statistik-Dashboard"><header class="statistics-heading"><div><h2>Statistiken</h2><p id="statisticsMessage">Statistiken werden geladen…</p></div><div class="statistics-reset-actions" aria-label="Statistiken zurücksetzen"><button class="statistics-reset" data-statistics-reset="session">Sitzung zurücksetzen</button><button class="statistics-reset" data-statistics-reset="all">Gesamt zurücksetzen</button><button class="statistics-reset statistics-reset-danger" data-statistics-reset="errors">Fehler zurücksetzen</button></div></header><div id="statisticsNotice" class="statistics-notice" role="status" hidden><span id="statisticsNoticeText"></span><button class="statistics-reset" id="statisticsRetry">Erneut versuchen</button></div><div class="statistics-kpis"><article class="statistics-kpi" data-statistics-card="bytes"><span class="statistics-kpi-label">Datenmenge</span><strong class="statistics-kpi-value" data-statistics-value="bytes">–</strong><span class="statistics-kpi-source" data-statistics-source="bytes"></span></article><article class="statistics-kpi" data-statistics-card="completed"><span class="statistics-kpi-label">Uploads</span><strong class="statistics-kpi-value" data-statistics-value="completed">–</strong><span class="statistics-kpi-source" data-statistics-source="completed"></span></article><article class="statistics-kpi" data-statistics-card="successRate"><span class="statistics-kpi-label">Erfolgsquote</span><strong class="statistics-kpi-value" data-statistics-value="successRate">–</strong><span class="statistics-kpi-source" data-statistics-source="successRate"></span></article><article class="statistics-kpi" data-statistics-card="averageSpeedBps"><span class="statistics-kpi-label">Durchschnitt</span><strong class="statistics-kpi-value" data-statistics-value="averageSpeedBps">–</strong><span class="statistics-kpi-source" data-statistics-source="averageSpeedBps"></span></article><article class="statistics-kpi" data-statistics-card="failed"><span class="statistics-kpi-label">Fehler</span><strong class="statistics-kpi-value" data-statistics-value="failed">–</strong><span class="statistics-kpi-source" data-statistics-source="failed"></span></article></div><div class="statistics-detail-grid"><section class="statistics-chart"><div class="statistics-section-heading"><h3>Bandbreitenverlauf</h3><span>Live · letzte 60 Sekunden</span></div><div class="statistics-chart-canvas"><canvas id="statisticsCanvas" role="img" aria-label="Upload-Bandbreitenverlauf der letzten 60 Sekunden"></canvas></div></section><section class="statistics-providers"><div class="statistics-section-heading"><h3>Hoster</h3><span id="statisticsProviderScope">Sitzung</span></div><div class="statistics-provider-table" role="table" aria-label="Upload-Nutzung je Hoster"><div class="statistics-provider-header" role="row"><span role="columnheader">Hoster</span><span role="columnheader">Daten</span><span role="columnheader">Ergebnisse</span></div><div class="statistics-provider-body" id="statisticsProviders" role="rowgroup"></div></div><p class="statistics-provider-hint">Erfolgreiche Uploads werden je Hoster gezählt. Die Datenmenge enthält Wiederholungen.</p></section></div></section>
<main class="history-container view-main history-main">
<div class="history-header">
<h2>Upload-Verlauf</h2>
@@ -743,5 +746,6 @@
<script src="i18n.js"></script>
<script src="mcp.js"></script>
<script src="app.js"></script>
<script src="statistics.js"></script>
</body>
</html>
+297
View File
@@ -0,0 +1,297 @@
.statistics-content {
display: grid;
min-width: 0;
min-height: 100%;
align-content: start;
gap: 16px;
padding: 20px 24px 24px;
overflow: auto;
}
.statistics-heading {
display: flex;
min-width: 0;
align-items: flex-start;
justify-content: space-between;
gap: 24px;
}
.statistics-heading h2,
.statistics-section-heading h3 {
margin: 0;
color: var(--text);
}
.statistics-heading h2 {
font-size: 20px;
font-weight: 600;
line-height: 28px;
}
.statistics-heading p {
max-width: 760px;
margin: 4px 0 0;
color: var(--text-dim);
font-size: 12px;
line-height: 18px;
}
.statistics-reset-actions {
display: flex;
flex: 0 0 auto;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
}
.statistics-reset {
min-height: 36px;
padding: 7px 12px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg-input);
color: var(--text-muted);
cursor: pointer;
font: inherit;
font-weight: 500;
}
.statistics-reset:hover:not(:disabled) {
background: var(--bg-card-hover);
color: var(--text);
}
.statistics-reset-danger {
color: var(--danger);
}
.statistics-reset:disabled {
color: var(--text-dim);
cursor: not-allowed;
opacity: 0.6;
}
.statistics-kpis {
display: grid;
min-width: 0;
grid-template-columns: repeat(5, minmax(0, 1fr));
gap: 8px;
}
.statistics-kpi {
display: flex;
min-width: 0;
min-height: 116px;
padding: 14px 16px;
flex-direction: column;
justify-content: space-between;
gap: 8px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg-card);
}
.statistics-kpi-label {
color: var(--text-muted);
font-size: 12px;
font-weight: 600;
line-height: 16px;
}
.statistics-kpi-value {
min-width: 0;
color: var(--text);
font-size: clamp(20px, 1.6vw, 28px);
font-weight: 600;
line-height: 1.2;
white-space: nowrap;
}
.statistics-kpi-danger .statistics-kpi-value {
color: var(--danger);
}
.statistics-kpi-source {
min-height: 32px;
color: var(--text-dim);
font-size: 12px;
line-height: 16px;
overflow-wrap: anywhere;
}
.statistics-detail-grid {
display: grid;
min-width: 0;
grid-template-columns: minmax(0, 1.25fr) minmax(360px, 0.75fr);
gap: 16px;
}
.statistics-chart,
.statistics-providers {
display: flex;
min-width: 0;
min-height: 340px;
padding: 16px;
flex-direction: column;
gap: 12px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg-card);
}
.statistics-section-heading {
display: flex;
min-width: 0;
align-items: baseline;
justify-content: space-between;
gap: 16px;
}
.statistics-section-heading h3 {
font-size: 16px;
font-weight: 600;
line-height: 22px;
}
.statistics-section-heading span {
color: var(--text-dim);
font-size: 12px;
line-height: 16px;
text-align: right;
}
.statistics-chart-canvas {
min-width: 0;
min-height: 280px;
flex: 1 1 auto;
}
.statistics-chart-canvas .bandwidth-chart-container {
height: 100%;
min-height: 280px;
margin: 0;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--bg-input);
}
.statistics-provider-table {
display: flex;
min-width: 0;
flex: 1 1 auto;
flex-direction: column;
overflow: hidden;
border: 1px solid var(--border);
border-radius: 6px;
}
.statistics-provider-header,
.statistics-provider-row {
display: grid;
min-width: 0;
grid-template-columns: minmax(120px, 1fr) minmax(88px, 0.65fr) minmax(130px, 1fr);
align-items: center;
gap: 12px;
}
.statistics-provider-header {
min-height: 41px;
padding: 0 12px;
border-bottom: 1px solid var(--border);
background: var(--bg-raised);
color: var(--text-muted);
font-size: 12px;
font-weight: 600;
line-height: 16px;
}
.statistics-provider-body {
min-height: 0;
flex: 1 1 auto;
overflow: auto;
}
.statistics-provider-row {
min-height: 48px;
padding: 8px 12px;
border-bottom: 1px solid var(--border);
color: var(--text-muted);
font-size: 13px;
line-height: 18px;
}
.statistics-provider-row:last-child {
border-bottom: 0;
}
.statistics-provider-row:hover {
background: var(--bg-card-hover);
}
.statistics-provider-row > span {
min-width: 0;
overflow-wrap: anywhere;
}
.statistics-provider-name {
color: var(--text);
font-weight: 600;
}
.statistics-provider-errors {
color: var(--danger);
}
.statistics-provider-empty {
display: grid;
min-height: 180px;
padding: 24px;
place-items: center;
color: var(--text-dim);
font-size: 13px;
line-height: 20px;
text-align: center;
}
#history-view:not(.statistics-mode) .statistics-content,
#history-view.statistics-mode .history-main { display: none; }
.statistics-content { min-height: 0; font-size: 13px; }
.statistics-content button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.statistics-chart-canvas { position: relative; border: 1px solid var(--border); border-radius: 6px; background: var(--bg-input); }
.statistics-chart-canvas canvas { display: block; width: 100%; height: 280px; }
.statistics-provider-hint { font-size: 12px; color: var(--text-dim); line-height: 1.5; }
.statistics-notice { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px; border: 1px solid var(--border); border-radius: 6px; background: var(--bg-input); }
.statistics-notice[hidden] { display: none; }
.statistics-kpi-value,.statistics-provider-row { font-variant-numeric: tabular-nums; }
.statistics-provider-row > span { user-select: text; }
.statistics-nav-divider { margin: 8px 12px 0; padding: 16px 10px 4px; border-top: 1px solid var(--border); color: var(--text-dim); font-size: 12px; }
#history-view.statistics-mode [data-history-filter].active { background: transparent; color: var(--text-muted); }
#history-view.statistics-mode #statisticsHistoryNavigation > .view-sidebar-indicator { visibility: hidden; }
#history-view:not(.statistics-mode) .statistics-ranges > .view-sidebar-indicator { visibility: hidden; }
#history-view.statistics-mode .view-sidebar-section,
#history-view.statistics-mode .view-sidebar-footnote { display: none; }
@media (max-width: 1600px) {
.statistics-detail-grid { grid-template-columns: minmax(0,1fr); }
.statistics-kpis { grid-template-columns: repeat(3,minmax(0,1fr)); }
.statistics-heading { flex-direction: column; gap: 12px; }
.statistics-reset-actions { justify-content: flex-start; }
}
@media (max-width: 999px) {
#history-view.active { grid-template-columns: 216px minmax(0,1fr); }
#history-view .view-sidebar-copy, #history-view .view-sidebar-badge { display: block; }
#history-view .view-navigation-card .view-sidebar-header { display: grid; padding: 14px; }
#history-view .view-navigation-card .view-sidebar-item { grid-template-columns: 20px minmax(0,1fr) auto; place-items: initial; align-items: center; padding: 8px; font-size: 12px; }
.statistics-content { padding: 16px; }
.statistics-kpis { grid-template-columns: repeat(2,minmax(0,1fr)); }
}
@media (max-width: 700px) {
#history-view.active { grid-template-columns: 166px minmax(0,1fr); }
#history-view .view-sidebar-icon { display: none; }
#history-view .view-navigation-card .view-sidebar-item { grid-template-columns: minmax(0,1fr) auto; }
.statistics-provider-header,.statistics-provider-row { grid-template-columns: minmax(65px,1fr) minmax(65px,.8fr) minmax(95px,1.2fr); gap: 6px; padding: 8px; }
.statistics-reset { font-size: 12px; }
.statistics-section-heading { flex-wrap: wrap; gap: 4px; }
}
#history-view.statistics-mode [data-history-filter].active .view-sidebar-badge { background: var(--bg-raised); color: var(--text-muted); }
+199
View File
@@ -0,0 +1,199 @@
(() => {
const view = document.getElementById('history-view');
const labels = { session: 'Sitzung', today: 'Heute', last24: 'Letzte 24 Stunden', week: 'Sieben Tage', month: '30 Tage', all: 'Gesamt' };
const byId = id => document.getElementById(id);
const text = value => window.localizeUiText(value);
let range = 'session';
let generation = 0;
let pending = false;
let resetting = false;
let current = null;
let lastSpeed = 0;
let lastSpeedAt = 0;
const points = [];
const count = value => new Intl.NumberFormat(window.getUiLocale(), { maximumFractionDigits: 0 }).format(value);
const decimal = value => new Intl.NumberFormat(window.getUiLocale(), { maximumFractionDigits: 1 }).format(value);
function bytes(value) {
const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
let index = 0;
while (value >= 1024 && index < units.length - 1) { value /= 1024; index++; }
return decimal(value) + ' ' + units[index];
}
function speed(value) {
const units = ['B/s', 'KB/s', 'MB/s', 'GB/s'];
let index = 0;
while (value >= 1000 && index < units.length - 1) { value /= 1000; index++; }
return decimal(value) + ' ' + units[index];
}
function notice(message) {
byId('statisticsNotice').hidden = !message;
byId('statisticsNoticeText').textContent = message;
}
function controls(disabled) {
view.querySelectorAll('[data-statistics-reset]').forEach(button => { button.disabled = disabled || (button.dataset.statisticsReset === 'errors' && !current?.failed); });
}
function render(data) {
current = data;
const message = data.historyImported
? 'Enthält vorhandenen Verlauf. Frühere Wiederholungen und aktive Uploadzeit sind nicht vollständig erfasst.'
: 'Lokale Upload-Statistik. Wiederholungen zählen zum Datenverkehr; abgebrochene und übersprungene Uploads nicht zur Erfolgsquote.';
byId('statisticsMessage').textContent = text(message);
byId('statisticsProviderScope').textContent = text(labels[range]);
const values = { bytes: bytes(data.bytes), completed: count(data.completed), successRate: data.successRate === null ? '–' : decimal(data.successRate) + ' %', averageSpeedBps: data.averageSpeedBps === null ? '–' : speed(data.averageSpeedBps), failed: count(data.failed) };
const sources = { bytes: labels[range], completed: 'Erfolgreiche Uploads je Hoster', successRate: 'Erfolgreich / erfolgreich und fehlgeschlagen', averageSpeedBps: data.averageSpeedBps === null ? 'Keine vollständige aktive Uploadzeit verfügbar' : 'Seit Beginn der Datenverkehrserfassung', failed: 'Endgültig fehlgeschlagene Uploads' };
for (const [key, value] of Object.entries(values)) {
view.querySelector('[data-statistics-value="' + key + '"]').textContent = value;
view.querySelector('[data-statistics-source="' + key + '"]').textContent = text(sources[key]);
}
view.querySelector('[data-statistics-card="failed"]').classList.toggle('statistics-kpi-danger', data.failed > 0);
const rows = data.providers.map(provider => {
const row = document.createElement('div');
row.className = 'statistics-provider-row';
row.setAttribute('role', 'row');
for (const [index, value] of [provider.label, bytes(provider.bytes), count(provider.completed) + ' ' + text('fertig') + ' · ' + count(provider.failed) + ' ' + text('Fehler')].entries()) {
const cell = document.createElement('span');
cell.setAttribute('role', 'cell');
cell.textContent = value;
if (!index) cell.className = 'statistics-provider-name';
if (index === 2 && provider.failed) cell.className = 'statistics-provider-errors';
row.append(cell);
}
return row;
});
byId('statisticsProviders').replaceChildren(...rows);
notice(data.persistenceError ? text(data.persistenceError) : '');
controls(resetting);
draw();
}
async function refresh(force = false) {
if ((!force && (!view.classList.contains('active') || !view.classList.contains('statistics-mode'))) || pending || resetting) return;
const request = ++generation;
pending = true;
try {
const data = await window.api.getStatistics(range);
if (request === generation) render(data);
} catch {
if (request === generation) {
notice(text('Statistiken konnten nicht geladen werden. Erneut versuchen.'));
controls(true);
}
} finally { if (request === generation) pending = false; }
}
function selectRange(value) {
if (!Object.hasOwn(labels, value)) return;
generation++;
pending = false;
current = null;
range = value;
view.classList.add('statistics-mode');
window.closeHistoryRetentionMenu();
view.querySelectorAll('[data-statistics-range]').forEach(button => {
const active = button.dataset.statisticsRange === range;
button.classList.toggle('active', active);
button.setAttribute('aria-pressed', String(active));
if (active) window._syncSidebarIndicator(button, true);
});
view.querySelectorAll('[data-statistics-value]').forEach(node => { node.textContent = '–'; });
byId('statisticsProviders').replaceChildren();
byId('statisticsMessage').textContent = text('Statistiken werden geladen…');
byId('statisticsProviderScope').textContent = text(labels[range]);
controls(true);
void refresh(true);
}
function showHistory() {
view.classList.remove('statistics-mode');
view.querySelectorAll('[data-statistics-range]').forEach(button => {
button.classList.remove('active');
button.setAttribute('aria-pressed', 'false');
});
}
async function reset(scope) {
if (resetting) return;
const messages = {
session: 'Statistikwerte dieser Sitzung zurücksetzen? Uploads, Dateien und Verlauf bleiben erhalten.',
all: 'Alle gespeicherten Statistikwerte zurücksetzen? Uploads, Dateien und Verlauf bleiben erhalten.',
errors: 'Fehlerzähler in allen Statistikzeiträumen zurücksetzen? Uploads und Verlauf bleiben unverändert.'
};
if (!await window.showAppConfirm({ title: 'Statistiken zurücksetzen?', message: messages[scope], confirmText: 'Zurücksetzen', danger: true })) return;
generation++;
pending = false;
resetting = true;
controls(true);
try {
await window.api.resetStatistics(scope);
resetting = false;
await refresh(true);
} catch {
resetting = false;
notice(text('Statistiken konnten nicht zurückgesetzt werden. Erneut versuchen.'));
controls(false);
}
}
function draw() {
if (!view.classList.contains('active') || !view.classList.contains('statistics-mode')) return;
const canvas = byId('statisticsCanvas');
const width = canvas.clientWidth;
const height = canvas.clientHeight;
if (!width || !height) return;
const ctx = canvas.getContext('2d');
const dpr = window.devicePixelRatio || 1;
canvas.width = Math.round(width * dpr);
canvas.height = Math.round(height * dpr);
ctx.scale(dpr, dpr);
const style = window.getComputedStyle(document.documentElement);
const color = name => style.getPropertyValue(name).trim();
ctx.font = '11px ' + window.getComputedStyle(document.body).fontFamily;
const now = Date.now();
const visible = points.filter(p => p.time >= now - 60000);
const max = Math.max(1000000, ...visible.map(p => p.speed));
const magnitude = Math.pow(10, Math.floor(Math.log10(max)));
const ceiling = [1, 2, 5, 10].map(n => n * magnitude).find(n => n >= max);
const left = Math.ceil(Math.max(...Array.from({ length: 6 }, (_, i) => ctx.measureText(speed(ceiling * i / 5)).width))) + 16;
const chartWidth = Math.max(1, width - left - 20);
const chartHeight = height - 50;
ctx.strokeStyle = color('--border');
ctx.fillStyle = color('--text-dim');
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
for (let i = 0; i <= 5; i++) {
const y = 20 + chartHeight * i / 5;
ctx.beginPath(); ctx.moveTo(left, y); ctx.lineTo(width - 20, y); ctx.stroke();
ctx.fillText(speed(ceiling * (1 - i / 5)), left - 8, y);
}
ctx.textAlign = 'center';
ctx.fillText('60s', left, height - 12);
ctx.fillText('30s', left + chartWidth / 2, height - 12);
ctx.fillText('0s', width - 20, height - 12);
canvas.setAttribute('aria-label', text('Upload-Bandbreitenverlauf der letzten 60 Sekunden') + ': ' + speed(lastSpeed));
if (!visible.some(p => p.speed > 0)) {
ctx.font = '13px ' + window.getComputedStyle(document.body).fontFamily;
ctx.fillText(text('Kein Upload-Datenverkehr in den letzten 60 Sekunden'), left + chartWidth / 2, height / 2);
return;
}
const coords = visible.map(p => ({ x: left + (p.time - now + 60000) / 60000 * chartWidth, y: 20 + chartHeight * (1 - p.speed / ceiling) }));
ctx.beginPath();
coords.forEach((p, index) => index ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y));
ctx.lineTo(coords.at(-1).x, 20 + chartHeight); ctx.lineTo(coords[0].x, 20 + chartHeight); ctx.closePath();
ctx.save(); ctx.globalAlpha = .15; ctx.fillStyle = color('--accent'); ctx.fill(); ctx.restore();
ctx.beginPath(); coords.forEach((p, index) => index ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y));
ctx.strokeStyle = color('--accent'); ctx.lineWidth = 2; ctx.stroke();
}
view.querySelectorAll('[data-statistics-range]').forEach(button => button.addEventListener('click', () => selectRange(button.dataset.statisticsRange)));
view.querySelectorAll('[data-statistics-reset]').forEach(button => button.addEventListener('click', () => reset(button.dataset.statisticsReset)));
byId('statisticsRetry').addEventListener('click', () => refresh(true));
window.api.onUploadStats(data => {
lastSpeed = data.state === 'idle' ? 0 : Math.max(0, Number(data.globalSpeedKbs) || 0) * 1000;
lastSpeedAt = Date.now();
});
setInterval(() => {
const now = Date.now();
if (now - lastSpeedAt > 3000) lastSpeed = 0;
points.push({ time: now, speed: lastSpeed });
while (points.length && points[0].time < now - 60000) points.shift();
void refresh();
draw();
}, 1000);
new window.ResizeObserver(draw).observe(byId('statisticsCanvas'));
window.UploadStatisticsView = { refresh, showHistory, selectRange, localize: () => { if (current) render(current); else draw(); } };
controls(true);
})();
+3
View File
@@ -78,6 +78,7 @@ const sourceFiles = [
'lib/speed-history.js',
'lib/startup-renderer.js',
'lib/stats.js',
'lib/upload-statistics.js',
'lib/support-bundle.js',
'lib/session-report.js',
'lib/throttle-timer.js',
@@ -110,6 +111,8 @@ const sourceFiles = [
'renderer/mcp.css',
'renderer/history-status.js',
'renderer/queue-stats.js',
'renderer/statistics.js',
'renderer/statistics.css',
'renderer/styles.css',
'scripts/afterPack.cjs',
'scripts/backup-recovery.cjs',