Compare commits

..

4 Commits

Author SHA1 Message Date
Sucukdeluxe
380fd0d77e Release v1.7.191 2026-06-09 20:54:11 +02:00
Sucukdeluxe
e753ea1296 Feature: Push-Benachrichtigungen (ntfy/Webhook) bei Paket fertig/fehlgeschlagen + Run-Ende
Headless-Server: Paket-Ausgaenge waren bisher nur per RDP+Log sichtbar. Neues
Modul notify.ts schickt einen fire-and-forget POST (ntfy-kompatibel: Title/
Priority/Tags als Header, Nachricht als Body) an eine konfigurierbare URL —
mit der kostenlosen ntfy-App aufs Handy, ohne Account/Port/Firewall (outbound).

- Settings: notifyUrl + 3 Ereignis-Toggles (Default aus) in Allgemein.
- Hook 1: Post-Processing-Ende (Paket completed/failed nach Entpacken).
- Hook 2: refreshPackageStatus fuer den Alle-Items-fehlgeschlagen-Fall (Link
  tot -> Paket erreicht das Post-Processing nie; ohne diesen Hook schwiege
  ausgerechnet der haeufigste Fehlerfall).
- Hook 3: finishRun mit Run-Summary (X/Y erfolgreich, Dauer, Schnitt).
- Dedup-Set pro Paket+Run, Lifecycle gespiegelt an historyRecordedPackages
  (Run-Start-Clear, Retry-Deletes, removePackageFromSession). Guard
  session.running || runPackageIds.has(id): nachlaufendes Entpacken nach
  Run-Ende benachrichtigt noch, Startup-Recovery nach App-Neustart nicht
  (sonst Doppel-Push fuer laengst fertige Pakete).
- 5s-Timeout, Fehler nur als logger.warn — blockiert nie den Download-Pfad.
- 9 Unit-Tests fuer notify.ts.
2026-06-09 20:50:58 +02:00
Sucukdeluxe
be4d54a6b5 Feature: "Letzte Fehler anzeigen" im Hilfe-Menue (Error-Ring ins UI)
Der Error-Ring aus v1.7.185 war bisher nur ueber die Debug-Server-URL mit
Token erreichbar — per RDP ist ein Menueklick drastisch schneller als curl.
Neuer Menuepunkt im Hilfe-Dropdown zeigt die letzten 200 WARN/ERROR-Eintraege
(Kopf: "X Fehler, Y Warnungen") im bestehenden Bestaetigungs-Dialog mit
aufklappbaren Details; der Bestaetigen-Knopf kopiert die komplette Liste in
die Zwischenablage — direkt verwertbar fuer Bug-Reports.

IPC-Kette nach dem GET_DEBUG_SETUP_CHECK-Muster (ipc.ts, main.ts mit direktem
error-ring-Import wie debug-server/support-bundle, preload, preload-api).
Read-only auf den In-Memory-Snapshot, kein neues CSS.
2026-06-09 20:45:21 +02:00
Sucukdeluxe
2a1a55401e Feature: Tonspur-Ergebnis sichtbar am Paket (audioStripSummary)
Die Antwort auf "warum hat Paket X noch .DL.?" steht bisher nur in den
Rename-/Item-Logs — "kein Deutsch-Tag" ist INFO-Level und taucht nirgends im
UI auf. Jetzt speichert keepGermanAudioOnlyImpl pro Paket eine Zusammenfassung
(remuxed/kept-single/ohne-DE-Tag/ffmpeg-fehlt/Fehler + bis zu 100 Datei-Details
mit Aktion, Grund und erkannten Sprachen) direkt am PackageEntry:

- Status-Spalte zeigt "Tonspur: 5 OK / 1 ohne DE-Tag / ffmpeg fehlt" (rot bei
  Auffaelligkeiten, flacher Stil), Datei-Details als Tooltip.
- Auch der ffmpeg-nicht-gefunden-Fruehausstieg schreibt die Summary.
- pkg.updatedAt wird gesetzt + Feld im Paket-Delta-Hash, damit der Snapshot
  die Aenderung pusht; normalizeLoadedSession whitelistet das Feld mit
  Shape-Validierung, sonst waere es nach jedem App-Neustart weg.
- 2 neue Integrationstests (Summary-Zaehler + ffmpeg-fehlt-Pfad).
2026-06-09 20:42:22 +02:00
14 changed files with 352 additions and 6 deletions

View File

@ -1,6 +1,6 @@
{ {
"name": "real-debrid-downloader", "name": "real-debrid-downloader",
"version": "1.7.190", "version": "1.7.191",
"description": "Desktop downloader", "description": "Desktop downloader",
"main": "build/main/main/main.js", "main": "build/main/main/main.js",
"author": "Sucukdeluxe", "author": "Sucukdeluxe",

View File

@ -107,6 +107,10 @@ export function defaultSettings(): AppSettings {
hideExtractedItems: true, hideExtractedItems: true,
confirmDeleteSelection: true, confirmDeleteSelection: true,
backupIncludeDownloads: false, backupIncludeDownloads: false,
notifyUrl: "",
notifyOnPackageCompleted: false,
notifyOnPackageFailed: false,
notifyOnRunFinished: false,
totalDownloadedAllTime: 0, totalDownloadedAllTime: 0,
totalCompletedFilesAllTime: 0, totalCompletedFilesAllTime: 0,
totalRuntimeAllTimeMs: 0, totalRuntimeAllTimeMs: 0,

View File

@ -7,6 +7,7 @@ import {
AllDebridHostInfo, AllDebridHostInfo,
AppSettings, AppSettings,
DebridProvider, DebridProvider,
AudioStripSummary,
DownloadItem, DownloadItem,
DownloadStats, DownloadStats,
DownloadSummary, DownloadSummary,
@ -55,6 +56,7 @@ import { cleanupArchives, clearExtractResumeState, collectArchiveCleanupTargets,
import { validateFileAgainstManifest } from "./integrity"; import { validateFileAgainstManifest } from "./integrity";
import { classifyDiskError } from "./fs-error"; import { classifyDiskError } from "./fs-error";
import { processVideoFile, resolveVideoTooling, stripDualLangMarker, hasDualLangMarker, isRemuxableVideoFile, type GermanAudioMode, type VideoProcessResult } from "./video-processor"; import { processVideoFile, resolveVideoTooling, stripDualLangMarker, hasDualLangMarker, isRemuxableVideoFile, type GermanAudioMode, type VideoProcessResult } from "./video-processor";
import { sendNotification } from "./notify";
import { logger } from "./logger"; import { logger } from "./logger";
import { getRecentRotationEvents, runWithRotationItemSink, setRotationEventListener } from "./account-rotation-log"; import { getRecentRotationEvents, runWithRotationItemSink, setRotationEventListener } from "./account-rotation-log";
import type { RotationEvent } from "../shared/types"; import type { RotationEvent } from "../shared/types";
@ -1749,6 +1751,8 @@ export class DownloadManager extends EventEmitter {
private historyRecordedPackages = new Set<string>(); private historyRecordedPackages = new Set<string>();
private notifiedPackages = new Set<string>();
private itemCount = 0; private itemCount = 0;
private lastSchedulerHeartbeatAt = 0; private lastSchedulerHeartbeatAt = 0;
@ -2189,7 +2193,7 @@ export class DownloadManager extends EventEmitter {
} }
private buildPackageHash(pkg: PackageEntry): string { private buildPackageHash(pkg: PackageEntry): string {
return `${pkg.updatedAt}|${pkg.status}|${pkg.name}|${pkg.enabled ? 1 : 0}|${pkg.cancelled ? 1 : 0}|${pkg.priority || ""}|${pkg.itemIds.length}|${pkg.postProcessLabel || ""}`; return `${pkg.updatedAt}|${pkg.status}|${pkg.name}|${pkg.enabled ? 1 : 0}|${pkg.cancelled ? 1 : 0}|${pkg.priority || ""}|${pkg.itemIds.length}|${pkg.postProcessLabel || ""}|${pkg.audioStripSummary?.at || 0}`;
} }
public getSnapshotForEmit(forceFull = false): UiSnapshot { public getSnapshotForEmit(forceFull = false): UiSnapshot {
@ -2787,6 +2791,7 @@ export class DownloadManager extends EventEmitter {
this.runOutcomes.clear(); this.runOutcomes.clear();
this.runCompletedPackages.clear(); this.runCompletedPackages.clear();
this.historyRecordedPackages.clear(); this.historyRecordedPackages.clear();
this.notifiedPackages.clear();
this.retryAfterByItem.clear(); this.retryAfterByItem.clear();
this.providerStartReservations.clear(); this.providerStartReservations.clear();
this.pacedStartReservationByItem.clear(); this.pacedStartReservationByItem.clear();
@ -3951,6 +3956,28 @@ export class DownloadManager extends EventEmitter {
this.logRenameProcess(pkg, "INFO", "audio-strip", "Tonspur-Bereinigung gestartet", { extractDir, candidates: targets.length, mode: this.settings.germanAudioMode }); this.logRenameProcess(pkg, "INFO", "audio-strip", "Tonspur-Bereinigung gestartet", { extractDir, candidates: targets.length, mode: this.settings.germanAudioMode });
} }
const summary: AudioStripSummary = {
at: nowMs(),
candidates: targets.length,
remuxed: 0,
keptSingle: 0,
skippedNoGerman: 0,
skippedNoTool: 0,
failed: 0,
files: []
};
const recordFile = (name: string, action: string, reason: string, languages?: string): void => {
if (summary.files.length < 100) {
summary.files.push({ name, action, reason, ...(languages ? { languages } : {}) });
}
};
const writeSummary = (): void => {
if (pkg) {
pkg.audioStripSummary = summary;
pkg.updatedAt = nowMs();
}
};
// Resolve ffmpeg/ffprobe ONCE up front and log it loudly — a missing tool is // Resolve ffmpeg/ffprobe ONCE up front and log it loudly — a missing tool is
// the single most common reason the whole step silently does nothing. // the single most common reason the whole step silently does nothing.
const tooling = await resolveVideoTooling(); const tooling = await resolveVideoTooling();
@ -3959,6 +3986,11 @@ export class DownloadManager extends EventEmitter {
if (pkg) { if (pkg) {
this.logRenameProcess(pkg, "WARN", "audio-strip", "Tonspur-Bereinigung uebersprungen: ffmpeg/ffprobe nicht gefunden", { candidates: targets.length }); this.logRenameProcess(pkg, "WARN", "audio-strip", "Tonspur-Bereinigung uebersprungen: ffmpeg/ffprobe nicht gefunden", { candidates: targets.length });
} }
summary.skippedNoTool = targets.length;
for (const p of targets) {
recordFile(path.basename(p), "skipped-no-tool", "ffmpeg/ffprobe nicht gefunden");
}
writeSummary();
return 0; return 0;
} }
logger.info(`Tonspur-Bereinigung: ffmpeg=${tooling.ffmpeg} ffprobe=${tooling.ffprobe}`); logger.info(`Tonspur-Bereinigung: ffmpeg=${tooling.ffmpeg} ffprobe=${tooling.ffprobe}`);
@ -3992,18 +4024,29 @@ export class DownloadManager extends EventEmitter {
...(result.error ? { error: result.error } : {}) ...(result.error ? { error: result.error } : {})
}, resolved.item, resolved.matchedBy); }, resolved.item, resolved.matchedBy);
} }
recordFile(sourceName, result.action, result.error ? `${result.reason}${result.error}` : result.reason, langs || undefined);
// Per-file main-log lines so the cause of any unprocessed file is visible // Per-file main-log lines so the cause of any unprocessed file is visible
// without opening the rename/item logs. // without opening the rename/item logs.
if (result.action === "error") { if (result.action === "error") {
failed += 1; failed += 1;
summary.failed += 1;
logger.warn(`Tonspur-Bereinigung FEHLER: ${sourceName}${result.reason}${result.error ? `${result.error}` : ""} (Spuren: ${langs || "?"}, ${result.totalAudioTracks ?? "?"} Audio)`); logger.warn(`Tonspur-Bereinigung FEHLER: ${sourceName}${result.reason}${result.error ? `${result.error}` : ""} (Spuren: ${langs || "?"}, ${result.totalAudioTracks ?? "?"} Audio)`);
} else if (result.action === "remuxed") { } else if (result.action === "remuxed") {
processed += 1; processed += 1;
summary.remuxed += 1;
logger.info(`Tonspur-Bereinigung OK: ${sourceName} — Spur ${result.keptTrackIndex} behalten (${langs || "?"})`); logger.info(`Tonspur-Bereinigung OK: ${sourceName} — Spur ${result.keptTrackIndex} behalten (${langs || "?"})`);
} else if (result.action === "kept-single") {
summary.keptSingle += 1;
} else if (result.action === "skipped-no-german") { } else if (result.action === "skipped-no-german") {
summary.skippedNoGerman += 1;
logger.info(`Tonspur-Bereinigung uebersprungen (kein Deutsch-Tag, Spuren: ${langs || "?"}): ${sourceName}`); logger.info(`Tonspur-Bereinigung uebersprungen (kein Deutsch-Tag, Spuren: ${langs || "?"}): ${sourceName}`);
} else if (result.action === "skipped-no-space") { } else if (result.action === "skipped-no-space") {
summary.failed += 1;
logger.warn(`Tonspur-Bereinigung uebersprungen (zu wenig Speicher): ${sourceName}`); logger.warn(`Tonspur-Bereinigung uebersprungen (zu wenig Speicher): ${sourceName}`);
} else if (result.action === "skipped-no-tool") {
summary.skippedNoTool += 1;
} else {
summary.failed += 1;
} }
// Only strip ".DL." once the file is confirmed German-only (remuxed) or // Only strip ".DL." once the file is confirmed German-only (remuxed) or
// already single-track. Skips/errors leave the file fully untouched so the // already single-track. Skips/errors leave the file fully untouched so the
@ -4012,6 +4055,7 @@ export class DownloadManager extends EventEmitter {
await this.stripDualLangFromFileName(sourcePath, pkg); await this.stripDualLangFromFileName(sourcePath, pkg);
} }
} }
writeSummary();
logger.info(`Tonspur-Bereinigung fertig: ${processed} verarbeitet, ${failed} Fehler von ${targets.length} Kandidaten in ${extractDir}`); logger.info(`Tonspur-Bereinigung fertig: ${processed} verarbeitet, ${failed} Fehler von ${targets.length} Kandidaten in ${extractDir}`);
if (pkg) { if (pkg) {
this.logRenameProcess(pkg, failed > 0 ? "WARN" : "INFO", "audio-strip", "Tonspur-Bereinigung fertig", { processed, failed, candidates: targets.length }); this.logRenameProcess(pkg, failed > 0 ? "WARN" : "INFO", "audio-strip", "Tonspur-Bereinigung fertig", { processed, failed, candidates: targets.length });
@ -5069,6 +5113,7 @@ export class DownloadManager extends EventEmitter {
pkg.enabled = true; pkg.enabled = true;
pkg.updatedAt = nowMs(); pkg.updatedAt = nowMs();
this.historyRecordedPackages.delete(packageId); this.historyRecordedPackages.delete(packageId);
this.notifiedPackages.delete(packageId);
if (this.session.running) { if (this.session.running) {
for (const itemId of itemIds) { for (const itemId of itemIds) {
@ -5136,6 +5181,7 @@ export class DownloadManager extends EventEmitter {
this.abortPackagePostProcessing(pkgId, "reset"); this.abortPackagePostProcessing(pkgId, "reset");
this.runCompletedPackages.delete(pkgId); this.runCompletedPackages.delete(pkgId);
this.historyRecordedPackages.delete(pkgId); this.historyRecordedPackages.delete(pkgId);
this.notifiedPackages.delete(pkgId);
const pkg = this.session.packages[pkgId]; const pkg = this.session.packages[pkgId];
if (pkg && (pkg.status === "completed" || pkg.status === "failed" || pkg.status === "cancelled")) { if (pkg && (pkg.status === "completed" || pkg.status === "failed" || pkg.status === "cancelled")) {
@ -7568,6 +7614,7 @@ export class DownloadManager extends EventEmitter {
} }
} }
this.historyRecordedPackages.delete(packageId); this.historyRecordedPackages.delete(packageId);
this.notifiedPackages.delete(packageId);
this.abortPackagePostProcessing(packageId, "package_removed"); this.abortPackagePostProcessing(packageId, "package_removed");
for (const itemId of itemIds) { for (const itemId of itemIds) {
this.retryAfterByItem.delete(itemId); this.retryAfterByItem.delete(itemId);
@ -10428,6 +10475,34 @@ export class DownloadManager extends EventEmitter {
return /\b0\s*B\b/i.test(item.fullStatus || ""); return /\b0\s*B\b/i.test(item.fullStatus || "");
} }
// Once per package and run; trailing post-processing after run-end still
// notifies (runPackageIds keeps the id), startup recovery does not (set empty).
private notifyPackageOutcome(pkg: PackageEntry, kind: "completed" | "failed", detail: string): void {
const url = String(this.settings.notifyUrl || "").trim();
if (!url) {
return;
}
if (kind === "completed" && !this.settings.notifyOnPackageCompleted) {
return;
}
if (kind === "failed" && !this.settings.notifyOnPackageFailed) {
return;
}
if (!this.session.running && !this.runPackageIds.has(pkg.id)) {
return;
}
if (this.notifiedPackages.has(pkg.id)) {
return;
}
this.notifiedPackages.add(pkg.id);
void sendNotification(url, {
title: kind === "completed" ? "Paket fertig" : "Paket fehlgeschlagen",
message: `${pkg.name}\n${detail}`,
priority: kind === "failed" ? "high" : "default",
tags: kind === "completed" ? "white_check_mark" : "x"
});
}
private refreshPackageStatus(pkg: PackageEntry): void { private refreshPackageStatus(pkg: PackageEntry): void {
let pending = 0; let pending = 0;
let success = 0; let success = 0;
@ -10461,6 +10536,7 @@ export class DownloadManager extends EventEmitter {
return; return;
} }
const prevStatus = pkg.status;
if (failed > 0) { if (failed > 0) {
pkg.status = "failed"; pkg.status = "failed";
} else if (cancelled > 0) { } else if (cancelled > 0) {
@ -10469,6 +10545,11 @@ export class DownloadManager extends EventEmitter {
pkg.status = "completed"; pkg.status = "completed";
} }
pkg.updatedAt = nowMs(); pkg.updatedAt = nowMs();
// A package whose items ALL failed never enters post-processing, so the
// post-process notify hook can't fire for it — cover that case here.
if (pkg.status === "failed" && prevStatus !== "failed" && success === 0) {
this.notifyPackageOutcome(pkg, "failed", `${failed} von ${total} Datei(en) fehlgeschlagen`);
}
} }
private cachedSpeedLimitKbps = 0; private cachedSpeedLimitKbps = 0;
@ -11691,6 +11772,12 @@ export class DownloadManager extends EventEmitter {
pkg.status = "completed"; pkg.status = "completed";
} }
if (pkg.status === "completed") {
this.notifyPackageOutcome(pkg, "completed", `${success} Datei(en)${extractedCount > 0 ? `, ${extractedCount} entpackt` : ""}`);
} else if (pkg.status === "failed") {
this.notifyPackageOutcome(pkg, "failed", `${failed} von ${success + failed + cancelled} Datei(en) fehlgeschlagen`);
}
this.emitState(); this.emitState();
if (pkg.status === "completed" || (pkg.status === "failed" && success > 0)) { if (pkg.status === "completed" || (pkg.status === "failed" && success > 0)) {
@ -12033,6 +12120,14 @@ export class DownloadManager extends EventEmitter {
averageSpeedBps: avgSpeed averageSpeedBps: avgSpeed
}; };
this.session.summaryText = `Summary: Dauer ${duration}s, Ø Speed ${humanSize(avgSpeed)}/s, Erfolg ${success}/${total}`; this.session.summaryText = `Summary: Dauer ${duration}s, Ø Speed ${humanSize(avgSpeed)}/s, Erfolg ${success}/${total}`;
if (this.settings.notifyOnRunFinished && total > 0) {
void sendNotification(this.settings.notifyUrl, {
title: "Durchlauf beendet",
message: `${success}/${total} erfolgreich, ${failed} fehlgeschlagen, ${cancelled} abgebrochen\nDauer ${duration}s, Durchschnitt ${humanSize(avgSpeed)}/s`,
priority: failed > 0 ? "high" : "default",
tags: failed > 0 ? "warning" : "checkered_flag"
});
}
this.runItemIds.clear(); this.runItemIds.clear();
this.runOutcomes.clear(); this.runOutcomes.clear();
if (this.packagePostProcessTasks.size === 0 && !this.hasAnyDeferredPostProcessPending()) { if (this.packagePostProcessTasks.size === 0 && !this.hasAnyDeferredPostProcessPending()) {

View File

@ -5,6 +5,7 @@ import { AddLinksPayload, AppSettings, DebridProvider, UpdateInstallProgress } f
import { AppController } from "./app-controller"; import { AppController } from "./app-controller";
import { IPC_CHANNELS } from "../shared/ipc"; import { IPC_CHANNELS } from "../shared/ipc";
import { getLogFilePath, logger } from "./logger"; import { getLogFilePath, logger } from "./logger";
import { getRecentErrors } from "./error-ring";
import { APP_NAME } from "./constants"; import { APP_NAME } from "./constants";
import { extractHttpLinksFromText } from "./utils"; import { extractHttpLinksFromText } from "./utils";
import { cleanupStaleSubstDrives, shutdownDaemon } from "./extractor"; import { cleanupStaleSubstDrives, shutdownDaemon } from "./extractor";
@ -626,6 +627,8 @@ function registerIpcHandlers(): void {
ipcMain.handle(IPC_CHANNELS.GET_DEBUG_SETUP_CHECK, async () => controller.getDebugSetupCheck()); ipcMain.handle(IPC_CHANNELS.GET_DEBUG_SETUP_CHECK, async () => controller.getDebugSetupCheck());
ipcMain.handle(IPC_CHANNELS.GET_RECENT_ERRORS, async () => getRecentErrors());
ipcMain.handle(IPC_CHANNELS.GET_TRACE_CONFIG, async () => controller.getTraceConfig()); ipcMain.handle(IPC_CHANNELS.GET_TRACE_CONFIG, async () => controller.getTraceConfig());
ipcMain.handle(IPC_CHANNELS.SET_TRACE_ENABLED, async (_event: IpcMainInvokeEvent, enabled: boolean, note?: string, durationMinutes?: number) => { ipcMain.handle(IPC_CHANNELS.SET_TRACE_ENABLED, async (_event: IpcMainInvokeEvent, enabled: boolean, note?: string, durationMinutes?: number) => {

49
src/main/notify.ts Normal file
View File

@ -0,0 +1,49 @@
import { logger } from "./logger";
export interface NotifyPayload {
title: string;
message: string;
priority?: "default" | "high";
tags?: string;
}
const NOTIFY_TIMEOUT_MS = 5000;
export function isNotifyUrlValid(url: string): boolean {
return /^https?:\/\/\S+$/i.test(String(url || "").trim());
}
export function buildNotifyRequest(url: string, payload: NotifyPayload): { url: string; init: RequestInit } {
const headers: Record<string, string> = {
"Title": payload.title,
"Content-Type": "text/plain; charset=utf-8"
};
if (payload.priority && payload.priority !== "default") {
headers["Priority"] = payload.priority;
}
if (payload.tags) {
headers["Tags"] = payload.tags;
}
return {
url: String(url || "").trim(),
init: { method: "POST", headers, body: payload.message }
};
}
export async function sendNotification(url: string, payload: NotifyPayload, fetchFn: typeof fetch = fetch): Promise<boolean> {
if (!isNotifyUrlValid(url)) {
return false;
}
try {
const request = buildNotifyRequest(url, payload);
const response = await fetchFn(request.url, { ...request.init, signal: AbortSignal.timeout(NOTIFY_TIMEOUT_MS) });
if (!response.ok) {
logger.warn(`Benachrichtigung fehlgeschlagen (HTTP ${response.status}): ${payload.title}`);
return false;
}
return true;
} catch (error) {
logger.warn(`Benachrichtigung fehlgeschlagen: ${String(error)}`);
return false;
}
}

View File

@ -3,7 +3,7 @@ import fsp from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { getDebridLinkApiKeyIds } from "../shared/debrid-link-keys"; import { getDebridLinkApiKeyIds } from "../shared/debrid-link-keys";
import { getMegaDebridAccountIds } from "../shared/mega-debrid-accounts"; import { getMegaDebridAccountIds } from "../shared/mega-debrid-accounts";
import { AppSettings, BandwidthScheduleEntry, DebridAccountStatus, DebridFallbackProvider, DebridProvider, DownloadItem, DownloadStatus, HistoryEntry, HistoryRetentionMode, PackageEntry, PackagePriority, SessionState } from "../shared/types"; import { AppSettings, AudioStripSummary, BandwidthScheduleEntry, DebridAccountStatus, DebridFallbackProvider, DebridProvider, DownloadItem, DownloadStatus, HistoryEntry, HistoryRetentionMode, PackageEntry, PackagePriority, SessionState } from "../shared/types";
import { getProviderUsageDayKey } from "../shared/provider-daily-limits"; import { getProviderUsageDayKey } from "../shared/provider-daily-limits";
import { defaultSettings } from "./constants"; import { defaultSettings } from "./constants";
import { logger } from "./logger"; import { logger } from "./logger";
@ -459,6 +459,10 @@ export function normalizeSettings(settings: AppSettings): AppSettings {
hideExtractedItems: settings.hideExtractedItems !== undefined ? Boolean(settings.hideExtractedItems) : defaults.hideExtractedItems, hideExtractedItems: settings.hideExtractedItems !== undefined ? Boolean(settings.hideExtractedItems) : defaults.hideExtractedItems,
confirmDeleteSelection: settings.confirmDeleteSelection !== undefined ? Boolean(settings.confirmDeleteSelection) : defaults.confirmDeleteSelection, confirmDeleteSelection: settings.confirmDeleteSelection !== undefined ? Boolean(settings.confirmDeleteSelection) : defaults.confirmDeleteSelection,
backupIncludeDownloads: settings.backupIncludeDownloads !== undefined ? Boolean(settings.backupIncludeDownloads) : defaults.backupIncludeDownloads, backupIncludeDownloads: settings.backupIncludeDownloads !== undefined ? Boolean(settings.backupIncludeDownloads) : defaults.backupIncludeDownloads,
notifyUrl: asText(settings.notifyUrl) || defaults.notifyUrl,
notifyOnPackageCompleted: settings.notifyOnPackageCompleted !== undefined ? Boolean(settings.notifyOnPackageCompleted) : defaults.notifyOnPackageCompleted,
notifyOnPackageFailed: settings.notifyOnPackageFailed !== undefined ? Boolean(settings.notifyOnPackageFailed) : defaults.notifyOnPackageFailed,
notifyOnRunFinished: settings.notifyOnRunFinished !== undefined ? Boolean(settings.notifyOnRunFinished) : defaults.notifyOnRunFinished,
totalDownloadedAllTime: typeof settings.totalDownloadedAllTime === "number" && settings.totalDownloadedAllTime >= 0 ? settings.totalDownloadedAllTime : defaults.totalDownloadedAllTime, totalDownloadedAllTime: typeof settings.totalDownloadedAllTime === "number" && settings.totalDownloadedAllTime >= 0 ? settings.totalDownloadedAllTime : defaults.totalDownloadedAllTime,
totalCompletedFilesAllTime: typeof settings.totalCompletedFilesAllTime === "number" && settings.totalCompletedFilesAllTime >= 0 ? settings.totalCompletedFilesAllTime : defaults.totalCompletedFilesAllTime, totalCompletedFilesAllTime: typeof settings.totalCompletedFilesAllTime === "number" && settings.totalCompletedFilesAllTime >= 0 ? settings.totalCompletedFilesAllTime : defaults.totalCompletedFilesAllTime,
totalRuntimeAllTimeMs: typeof settings.totalRuntimeAllTimeMs === "number" && settings.totalRuntimeAllTimeMs >= 0 ? settings.totalRuntimeAllTimeMs : defaults.totalRuntimeAllTimeMs, totalRuntimeAllTimeMs: typeof settings.totalRuntimeAllTimeMs === "number" && settings.totalRuntimeAllTimeMs >= 0 ? settings.totalRuntimeAllTimeMs : defaults.totalRuntimeAllTimeMs,
@ -589,6 +593,37 @@ function asRecord(value: unknown): Record<string, unknown> | null {
return value as Record<string, unknown>; return value as Record<string, unknown>;
} }
function normalizeAudioStripSummary(raw: unknown): AudioStripSummary | undefined {
const parsed = asRecord(raw);
if (!parsed) {
return undefined;
}
const files = Array.isArray(parsed.files)
? parsed.files.slice(0, 100).flatMap((entry) => {
const file = asRecord(entry);
if (!file) {
return [];
}
const name = asText(file.name);
if (!name) {
return [];
}
const languages = asText(file.languages);
return [{ name, action: asText(file.action), reason: asText(file.reason), ...(languages ? { languages } : {}) }];
})
: [];
return {
at: clampNumber(parsed.at, 0, 0, Number.MAX_SAFE_INTEGER),
candidates: clampNumber(parsed.candidates, 0, 0, 1_000_000),
remuxed: clampNumber(parsed.remuxed, 0, 0, 1_000_000),
keptSingle: clampNumber(parsed.keptSingle, 0, 0, 1_000_000),
skippedNoGerman: clampNumber(parsed.skippedNoGerman, 0, 0, 1_000_000),
skippedNoTool: clampNumber(parsed.skippedNoTool, 0, 0, 1_000_000),
failed: clampNumber(parsed.failed, 0, 0, 1_000_000),
files
};
}
function readSettingsFile(filePath: string): AppSettings | null { function readSettingsFile(filePath: string): AppSettings | null {
try { try {
const parsed = JSON.parse(fs.readFileSync(filePath, "utf8")) as AppSettings; const parsed = JSON.parse(fs.readFileSync(filePath, "utf8")) as AppSettings;
@ -689,6 +724,7 @@ export function normalizeLoadedSession(raw: unknown): SessionState {
cancelled: Boolean(pkg.cancelled), cancelled: Boolean(pkg.cancelled),
enabled: pkg.enabled === undefined ? true : Boolean(pkg.enabled), enabled: pkg.enabled === undefined ? true : Boolean(pkg.enabled),
priority: VALID_PACKAGE_PRIORITIES.has(asText(pkg.priority)) ? asText(pkg.priority) as PackagePriority : "normal", priority: VALID_PACKAGE_PRIORITIES.has(asText(pkg.priority)) ? asText(pkg.priority) as PackagePriority : "normal",
audioStripSummary: normalizeAudioStripSummary(pkg.audioStripSummary),
downloadStartedAt: clampNumber(pkg.downloadStartedAt, 0, 0, Number.MAX_SAFE_INTEGER), downloadStartedAt: clampNumber(pkg.downloadStartedAt, 0, 0, Number.MAX_SAFE_INTEGER),
downloadCompletedAt: clampNumber(pkg.downloadCompletedAt, 0, 0, Number.MAX_SAFE_INTEGER), downloadCompletedAt: clampNumber(pkg.downloadCompletedAt, 0, 0, Number.MAX_SAFE_INTEGER),
createdAt: clampNumber(pkg.createdAt, now, 0, Number.MAX_SAFE_INTEGER), createdAt: clampNumber(pkg.createdAt, now, 0, Number.MAX_SAFE_INTEGER),

View File

@ -69,6 +69,7 @@ const api: ElectronApi = {
openPackageLog: (packageId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.OPEN_PACKAGE_LOG, packageId), openPackageLog: (packageId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.OPEN_PACKAGE_LOG, packageId),
openItemLog: (itemId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.OPEN_ITEM_LOG, itemId), openItemLog: (itemId: string): Promise<void> => ipcRenderer.invoke(IPC_CHANNELS.OPEN_ITEM_LOG, itemId),
getDebugSetupCheck: () => ipcRenderer.invoke(IPC_CHANNELS.GET_DEBUG_SETUP_CHECK), getDebugSetupCheck: () => ipcRenderer.invoke(IPC_CHANNELS.GET_DEBUG_SETUP_CHECK),
getRecentErrors: () => ipcRenderer.invoke(IPC_CHANNELS.GET_RECENT_ERRORS),
getTraceConfig: () => ipcRenderer.invoke(IPC_CHANNELS.GET_TRACE_CONFIG), getTraceConfig: () => ipcRenderer.invoke(IPC_CHANNELS.GET_TRACE_CONFIG),
setTraceEnabled: (enabled: boolean, note?: string, durationMinutes?: number) => ipcRenderer.invoke(IPC_CHANNELS.SET_TRACE_ENABLED, enabled, note, durationMinutes), setTraceEnabled: (enabled: boolean, note?: string, durationMinutes?: number) => ipcRenderer.invoke(IPC_CHANNELS.SET_TRACE_ENABLED, enabled, note, durationMinutes),
rotateDebugToken: (): Promise<{ path: string }> => ipcRenderer.invoke(IPC_CHANNELS.ROTATE_DEBUG_TOKEN), rotateDebugToken: (): Promise<{ path: string }> => ipcRenderer.invoke(IPC_CHANNELS.ROTATE_DEBUG_TOKEN),

View File

@ -5,6 +5,7 @@ import type {
AllDebridHostInfo, AllDebridHostInfo,
AppSettings, AppSettings,
AppTheme, AppTheme,
AudioStripSummary,
BandwidthScheduleEntry, BandwidthScheduleEntry,
DebugSetupCheckResult, DebugSetupCheckResult,
DebridFallbackProvider, DebridFallbackProvider,
@ -852,6 +853,7 @@ const emptySnapshot = (): UiSnapshot => ({
maxParallel: 4, maxParallelExtract: 2, extractCpuPriority: "high", retryLimit: 0, speedLimitEnabled: false, speedLimitKbps: 0, speedLimitMode: "global", maxParallel: 4, maxParallelExtract: 2, extractCpuPriority: "high", retryLimit: 0, speedLimitEnabled: false, speedLimitKbps: 0, speedLimitMode: "global",
updateRepo: "", autoUpdateCheck: true, clipboardWatch: false, minimizeToTray: false, updateRepo: "", autoUpdateCheck: true, clipboardWatch: false, minimizeToTray: false,
theme: "dark", collapseNewPackages: true, historyRetentionMode: "permanent", autoSortPackagesByProgress: true, autoSkipExtracted: false, hideExtractedItems: true, confirmDeleteSelection: true, backupIncludeDownloads: false, theme: "dark", collapseNewPackages: true, historyRetentionMode: "permanent", autoSortPackagesByProgress: true, autoSkipExtracted: false, hideExtractedItems: true, confirmDeleteSelection: true, backupIncludeDownloads: false,
notifyUrl: "", notifyOnPackageCompleted: false, notifyOnPackageFailed: false, notifyOnRunFinished: false,
accountListShowDetailedDebridLinkKeys: false, accountListShowDetailedDebridLinkKeys: false,
bandwidthSchedules: [], totalDownloadedAllTime: 0, totalCompletedFilesAllTime: 0, totalRuntimeAllTimeMs: 0, bandwidthSchedules: [], totalDownloadedAllTime: 0, totalCompletedFilesAllTime: 0, totalRuntimeAllTimeMs: 0,
columnOrder: ["name", "size", "progress", "hoster", "account", "prio", "status", "speed"], columnOrder: ["name", "size", "progress", "hoster", "account", "prio", "status", "speed"],
@ -984,6 +986,23 @@ function extractHoster(url: string): string {
} catch { return ""; } } catch { return ""; }
} }
function formatAudioStripSummary(summary: AudioStripSummary): { text: string; tooltip: string; attention: boolean } {
const parts: string[] = [];
const ok = summary.remuxed + summary.keptSingle;
if (ok > 0) parts.push(`${ok} OK`);
if (summary.skippedNoGerman > 0) parts.push(`${summary.skippedNoGerman} ohne DE-Tag`);
if (summary.skippedNoTool > 0) parts.push("ffmpeg fehlt");
if (summary.failed > 0) parts.push(`${summary.failed} Fehler`);
const tooltip = summary.files
.map((f) => `${f.name}: ${f.action} (${f.reason}${f.languages ? `, Spuren: ${f.languages}` : ""})`)
.join("\n");
return {
text: `Tonspur: ${parts.join(" · ") || "—"}`,
tooltip,
attention: summary.skippedNoGerman > 0 || summary.skippedNoTool > 0 || summary.failed > 0
};
}
const settingsSubTabs: { key: SettingsSubTab; label: string }[] = [ const settingsSubTabs: { key: SettingsSubTab; label: string }[] = [
{ key: "allgemein", label: "Allgemein" }, { key: "allgemein", label: "Allgemein" },
{ key: "accounts", label: "Accounts" }, { key: "accounts", label: "Accounts" },
@ -3914,6 +3933,32 @@ export function App(): ReactElement {
} }
}; };
const onShowRecentErrors = async (): Promise<void> => {
closeMenus();
try {
const entries = await window.rd.getRecentErrors();
const errorCount = entries.filter((e) => e.level === "ERROR").length;
const warnCount = entries.filter((e) => e.level === "WARN").length;
const details = entries.map((e) => `${e.ts} [${e.level}] ${e.message}`).join("\n");
const copy = await askConfirmPrompt({
title: "Letzte Fehler",
message: entries.length === 0
? "Keine Fehler oder Warnungen seit dem App-Start aufgezeichnet."
: `${errorCount} Fehler, ${warnCount} Warnungen (letzte ${entries.length})`,
confirmLabel: entries.length > 0 ? "In Zwischenablage kopieren" : "Schließen",
cancelLabel: "Schließen",
details: details || undefined,
detailsLabel: "Einträge anzeigen"
});
if (copy && entries.length > 0) {
await navigator.clipboard.writeText(details);
showToast("Fehlerliste kopiert", 2600);
}
} catch (error) {
showToast(`Fehler-Ansicht fehlgeschlagen: ${String(error)}`, 3000);
}
};
const onRotateDebugToken = async (): Promise<void> => { const onRotateDebugToken = async (): Promise<void> => {
closeMenus(); closeMenus();
const confirmed = await askConfirmPrompt({ const confirmed = await askConfirmPrompt({
@ -4321,6 +4366,9 @@ export function App(): ReactElement {
<button className="menu-dropdown-item" onClick={() => { void onToggleSupportTrace(); }}> <button className="menu-dropdown-item" onClick={() => { void onToggleSupportTrace(); }}>
<span>{supportTraceEnabled ? "Support-Trace deaktivieren" : "Support-Trace aktivieren"}</span> <span>{supportTraceEnabled ? "Support-Trace deaktivieren" : "Support-Trace aktivieren"}</span>
</button> </button>
<button className="menu-dropdown-item" onClick={() => { void onShowRecentErrors(); }}>
<span>Letzte Fehler anzeigen</span>
</button>
<button className="menu-dropdown-item" onClick={() => { void onRunDebugSetupCheck(); }}> <button className="menu-dropdown-item" onClick={() => { void onRunDebugSetupCheck(); }}>
<span>Debug-Setup prüfen</span> <span>Debug-Setup prüfen</span>
</button> </button>
@ -4909,6 +4957,12 @@ export function App(): ReactElement {
<label className="toggle-line"><input type="checkbox" checked={settingsDraft.minimizeToTray} onChange={(e) => setBool("minimizeToTray", e.target.checked)} /> In System Tray minimieren</label> <label className="toggle-line"><input type="checkbox" checked={settingsDraft.minimizeToTray} onChange={(e) => setBool("minimizeToTray", e.target.checked)} /> In System Tray minimieren</label>
<label className="toggle-line"><input type="checkbox" checked={settingsDraft.confirmDeleteSelection} onChange={(e) => setBool("confirmDeleteSelection", e.target.checked)} /> Vor dem Löschen bestätigen</label> <label className="toggle-line"><input type="checkbox" checked={settingsDraft.confirmDeleteSelection} onChange={(e) => setBool("confirmDeleteSelection", e.target.checked)} /> Vor dem Löschen bestätigen</label>
<label className="toggle-line"><input type="checkbox" checked={settingsDraft.backupIncludeDownloads} onChange={(e) => setBool("backupIncludeDownloads", e.target.checked)} /> Download-Liste in Sicherung mitsichern (Standard: nur Einstellungen)</label> <label className="toggle-line"><input type="checkbox" checked={settingsDraft.backupIncludeDownloads} onChange={(e) => setBool("backupIncludeDownloads", e.target.checked)} /> Download-Liste in Sicherung mitsichern (Standard: nur Einstellungen)</label>
<label>Benachrichtigungs-URL (ntfy/Webhook)</label>
<input value={settingsDraft.notifyUrl} placeholder="https://ntfy.sh/mein-topic" onChange={(e) => setText("notifyUrl", e.target.value)} />
<div className="hint">POST an diese URL bei den unten gewählten Ereignissen. Mit der ntfy-App aufs Handy: Topic-URL eintragen, Topic in der App abonnieren kein Account nötig.</div>
<label className="toggle-line"><input type="checkbox" checked={settingsDraft.notifyOnPackageCompleted} onChange={(e) => setBool("notifyOnPackageCompleted", e.target.checked)} /> Benachrichtigen wenn ein Paket fertig ist</label>
<label className="toggle-line"><input type="checkbox" checked={settingsDraft.notifyOnPackageFailed} onChange={(e) => setBool("notifyOnPackageFailed", e.target.checked)} /> Benachrichtigen wenn ein Paket fehlschlägt</label>
<label className="toggle-line"><input type="checkbox" checked={settingsDraft.notifyOnRunFinished} onChange={(e) => setBool("notifyOnRunFinished", e.target.checked)} /> Benachrichtigen wenn der Durchlauf beendet ist</label>
<label className="toggle-line"><input type="checkbox" checked={settingsDraft.theme === "light"} onChange={(e) => { <label className="toggle-line"><input type="checkbox" checked={settingsDraft.theme === "light"} onChange={(e) => {
const next = e.target.checked ? "light" : "dark"; const next = e.target.checked ? "light" : "dark";
settingsDraftRevisionRef.current += 1; settingsDraftRevisionRef.current += 1;
@ -6594,9 +6648,12 @@ const PackageCard = memo(function PackageCard({ pkg, items, packageSpeed, stripe
case "prio": return ( case "prio": return (
<span key={col} className={`pkg-col pkg-col-prio${pkg.priority === "high" ? " prio-high" : pkg.priority === "low" ? " prio-low" : ""}`}>{pkg.priority === "high" ? "Hoch" : pkg.priority === "low" ? "Niedrig" : ""}</span> <span key={col} className={`pkg-col pkg-col-prio${pkg.priority === "high" ? " prio-high" : pkg.priority === "low" ? " prio-low" : ""}`}>{pkg.priority === "high" ? "Hoch" : pkg.priority === "low" ? "Niedrig" : ""}</span>
); );
case "status": return ( case "status": {
<span key={col} className="pkg-col pkg-col-status">[{done}/{total}{done === total && total > 0 ? " - Done" : ""}{failed > 0 ? ` | ${failed} Fehler` : ""}{cancelled > 0 ? ` | ${cancelled} abgebr.` : ""}]{pkg.postProcessLabel ? ` - ${pkg.postProcessLabel}` : ""}</span> const audioStrip = pkg.audioStripSummary ? formatAudioStripSummary(pkg.audioStripSummary) : null;
return (
<span key={col} className="pkg-col pkg-col-status">[{done}/{total}{done === total && total > 0 ? " - Done" : ""}{failed > 0 ? ` | ${failed} Fehler` : ""}{cancelled > 0 ? ` | ${cancelled} abgebr.` : ""}]{pkg.postProcessLabel ? ` - ${pkg.postProcessLabel}` : ""}{audioStrip ? <span className={`pkg-audio-strip${audioStrip.attention ? " pkg-audio-strip-warn" : ""}`} title={audioStrip.tooltip}>{` · ${audioStrip.text}`}</span> : null}</span>
); );
}
case "speed": return ( case "speed": return (
<span key={col} className="pkg-col pkg-col-speed">{packageSpeed > 0 ? formatSpeedMbps(packageSpeed) : ""}</span> <span key={col} className="pkg-col pkg-col-speed">{packageSpeed > 0 ? formatSpeedMbps(packageSpeed) : ""}</span>
); );

View File

@ -736,6 +736,14 @@ body,
padding-right: 12px; padding-right: 12px;
} }
.pkg-audio-strip {
color: var(--muted);
}
.pkg-audio-strip-warn {
color: var(--danger);
}
.progress-size { .progress-size {
display: block; display: block;
position: relative; position: relative;

View File

@ -47,6 +47,7 @@ export const IPC_CHANNELS = {
OPEN_PACKAGE_LOG: "app:open-package-log", OPEN_PACKAGE_LOG: "app:open-package-log",
OPEN_ITEM_LOG: "app:open-item-log", OPEN_ITEM_LOG: "app:open-item-log",
GET_DEBUG_SETUP_CHECK: "app:get-debug-setup-check", GET_DEBUG_SETUP_CHECK: "app:get-debug-setup-check",
GET_RECENT_ERRORS: "app:get-recent-errors",
GET_TRACE_CONFIG: "app:get-trace-config", GET_TRACE_CONFIG: "app:get-trace-config",
SET_TRACE_ENABLED: "app:set-trace-enabled", SET_TRACE_ENABLED: "app:set-trace-enabled",
ROTATE_DEBUG_TOKEN: "app:rotate-debug-token", ROTATE_DEBUG_TOKEN: "app:rotate-debug-token",

View File

@ -66,6 +66,7 @@ export interface ElectronApi {
openPackageLog: (packageId: string) => Promise<void>; openPackageLog: (packageId: string) => Promise<void>;
openItemLog: (itemId: string) => Promise<void>; openItemLog: (itemId: string) => Promise<void>;
getDebugSetupCheck: () => Promise<DebugSetupCheckResult>; getDebugSetupCheck: () => Promise<DebugSetupCheckResult>;
getRecentErrors: () => Promise<Array<{ ts: string; level: string; message: string }>>;
getTraceConfig: () => Promise<SupportTraceConfig>; getTraceConfig: () => Promise<SupportTraceConfig>;
setTraceEnabled: (enabled: boolean, note?: string, durationMinutes?: number) => Promise<SupportTraceConfig>; setTraceEnabled: (enabled: boolean, note?: string, durationMinutes?: number) => Promise<SupportTraceConfig>;
rotateDebugToken: () => Promise<{ path: string }>; rotateDebugToken: () => Promise<{ path: string }>;

View File

@ -132,6 +132,10 @@ export interface AppSettings {
hideExtractedItems: boolean; hideExtractedItems: boolean;
confirmDeleteSelection: boolean; confirmDeleteSelection: boolean;
backupIncludeDownloads: boolean; backupIncludeDownloads: boolean;
notifyUrl: string;
notifyOnPackageCompleted: boolean;
notifyOnPackageFailed: boolean;
notifyOnRunFinished: boolean;
totalDownloadedAllTime: number; totalDownloadedAllTime: number;
totalCompletedFilesAllTime: number; totalCompletedFilesAllTime: number;
totalRuntimeAllTimeMs: number; totalRuntimeAllTimeMs: number;
@ -181,6 +185,24 @@ export interface DownloadItem {
onlineStatus?: "online" | "offline" | "checking"; onlineStatus?: "online" | "offline" | "checking";
} }
export interface AudioStripFileResult {
name: string;
action: string;
reason: string;
languages?: string;
}
export interface AudioStripSummary {
at: number;
candidates: number;
remuxed: number;
keptSingle: number;
skippedNoGerman: number;
skippedNoTool: number;
failed: number;
files: AudioStripFileResult[];
}
export interface PackageEntry { export interface PackageEntry {
id: string; id: string;
name: string; name: string;
@ -192,6 +214,7 @@ export interface PackageEntry {
enabled: boolean; enabled: boolean;
priority?: PackagePriority; priority?: PackagePriority;
postProcessLabel?: string; postProcessLabel?: string;
audioStripSummary?: AudioStripSummary;
downloadStartedAt?: number; downloadStartedAt?: number;
downloadCompletedAt?: number; downloadCompletedAt?: number;
createdAt: number; createdAt: number;

View File

@ -146,5 +146,20 @@ describe("keepGermanAudioOnly integration", () => {
expect(n).toBe(0); expect(n).toBe(0);
expect(mockedProcess).not.toHaveBeenCalled(); // bailed before touching any file expect(mockedProcess).not.toHaveBeenCalled(); // bailed before touching any file
expect(fs.readdirSync(extractDir)).toContain(DL_MKV); // untouched expect(fs.readdirSync(extractDir)).toContain(DL_MKV); // untouched
expect(pkg.audioStripSummary).toMatchObject({ candidates: 1, skippedNoTool: 1, remuxed: 0 });
expect(pkg.audioStripSummary.files[0]).toMatchObject({ name: DL_MKV, action: "skipped-no-tool" });
});
it("stores a per-package summary with counts and file details", async () => {
const { extractDir, manager, pkg } = setup(true);
stage(extractDir);
mockedProcess.mockResolvedValue({ action: "skipped-no-german", reason: "no-german-track", totalAudioTracks: 2, audioLanguages: ["eng", "fre"] } as VideoProcessResult);
await (manager as any).keepGermanAudioOnlyImpl(extractDir, pkg);
expect(pkg.audioStripSummary).toMatchObject({ candidates: 1, skippedNoGerman: 1, remuxed: 0, failed: 0 });
expect(pkg.audioStripSummary.files).toHaveLength(1);
expect(pkg.audioStripSummary.files[0]).toMatchObject({ name: DL_MKV, action: "skipped-no-german", reason: "no-german-track", languages: "eng,fre" });
expect(pkg.updatedAt).toBeGreaterThan(0); // bumped so the snapshot delta picks it up
}); });
}); });

53
tests/notify.test.ts Normal file
View File

@ -0,0 +1,53 @@
import { describe, expect, it, vi } from "vitest";
import { buildNotifyRequest, isNotifyUrlValid, sendNotification } from "../src/main/notify";
describe("isNotifyUrlValid", () => {
it("accepts http/https URLs", () => {
expect(isNotifyUrlValid("https://ntfy.sh/mein-topic")).toBe(true);
expect(isNotifyUrlValid("http://192.168.1.10:8080/hook")).toBe(true);
expect(isNotifyUrlValid(" https://ntfy.sh/topic ")).toBe(true);
});
it("rejects empty and non-http values", () => {
expect(isNotifyUrlValid("")).toBe(false);
expect(isNotifyUrlValid("ntfy.sh/topic")).toBe(false);
expect(isNotifyUrlValid("ftp://x")).toBe(false);
expect(isNotifyUrlValid("https:// mit leerzeichen")).toBe(false);
});
});
describe("buildNotifyRequest", () => {
it("builds an ntfy-style POST with title/priority/tags headers and message body", () => {
const req = buildNotifyRequest(" https://ntfy.sh/topic ", { title: "Paket fertig", message: "Show.S01\n5 Datei(en)", priority: "high", tags: "x" });
expect(req.url).toBe("https://ntfy.sh/topic");
expect(req.init.method).toBe("POST");
expect(req.init.body).toBe("Show.S01\n5 Datei(en)");
expect(req.init.headers).toMatchObject({ Title: "Paket fertig", Priority: "high", Tags: "x" });
});
it("omits default priority and empty tags", () => {
const req = buildNotifyRequest("https://ntfy.sh/topic", { title: "T", message: "M", priority: "default" });
expect(req.init.headers).not.toHaveProperty("Priority");
expect(req.init.headers).not.toHaveProperty("Tags");
});
});
describe("sendNotification", () => {
it("returns true on HTTP ok", async () => {
const fetchFn = vi.fn().mockResolvedValue(new Response("", { status: 200 }));
await expect(sendNotification("https://ntfy.sh/topic", { title: "T", message: "M" }, fetchFn)).resolves.toBe(true);
expect(fetchFn).toHaveBeenCalledTimes(1);
});
it("returns false on HTTP error without throwing", async () => {
const fetchFn = vi.fn().mockResolvedValue(new Response("", { status: 500 }));
await expect(sendNotification("https://ntfy.sh/topic", { title: "T", message: "M" }, fetchFn)).resolves.toBe(false);
});
it("returns false on network error without throwing", async () => {
const fetchFn = vi.fn().mockRejectedValue(new Error("offline"));
await expect(sendNotification("https://ntfy.sh/topic", { title: "T", message: "M" }, fetchFn)).resolves.toBe(false);
});
it("does not call fetch for an invalid URL", async () => {
const fetchFn = vi.fn();
await expect(sendNotification("", { title: "T", message: "M" }, fetchFn)).resolves.toBe(false);
await expect(sendNotification("kein-url", { title: "T", message: "M" }, fetchFn)).resolves.toBe(false);
expect(fetchFn).not.toHaveBeenCalled();
});
});