diff --git a/README.md b/README.md index 48cad60..a920adf 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ## Status -Version **1.4.2** (gebaut, noch nicht installiert): Sicherheits- und Protokollfix – Browser-Zugriff nur von LAN-/erlaubten Origins, Listen-Adresse wird verwendet, `ping`/Notifications/Versionsaushandlung. Werkzeuge und Ausgaben unverändert. [Installierbares Paket 1.4.2](releases/1.4.2/INSTALL.md) +Version **1.5.0** (gebaut, noch nicht installiert): 49 Werkzeuge. Neu: geplante Aufgaben auflisten/auslösen/abbrechen (z. B. EPG aktualisieren, Bibliotheken scannen), Aktivitätsprotokoll, geschwärztes Server-Log, Plugins, Geräte, Speicherplatz sowie Live TV lesend (Tuner/EPG-Quellen, Sender mit EPG-Status, Programm, Aufnahmen). Enthält die Sicherheits- und Protokollfixes aus 1.4.2. Details: [Admin- und Live-TV-Werkzeuge](docs/admin-livetv.md), [Installierbares Paket 1.5.0](releases/1.5.0/INSTALL.md) Version **1.4.1** (installiert und Serieninventar live geprüft): 37 MCP-Werkzeuge für Serienbestand, kombinierte Suche, Sammeldetails, Bild-/Sprach-/Metadaten-/FSK-Prüfung, Provider-Folgenabgleich, Änderungsvergleich und Diagnosen. Gezielte Schreibaktionen sind standardmäßig deaktiviert und starten als Vorschau. @@ -12,7 +12,8 @@ Version **1.4.1** (installiert und Serieninventar live geprüft): 37 MCP-Werkzeu - [Neue Werkzeuge, Bildprüfung, FSK-Ablauf und Testgrenzen](docs/advanced-tools.md) - [Serienbestand und bisherige Live-Abnahme](docs/series-inventory.md) -- [Installierbares Paket 1.4.2](releases/1.4.2/INSTALL.md) · [1.4.1](releases/1.4.1/INSTALL.md) +- [Installierbares Paket 1.5.0](releases/1.5.0/INSTALL.md) · [1.4.2](releases/1.4.2/INSTALL.md) · [1.4.1](releases/1.4.1/INSTALL.md) +- [Admin- und Live-TV-Werkzeuge](docs/admin-livetv.md) - Serieninventar: `detail="compact"` für Bestandsvergleiche; ohne Parameter/full bisherige Ausgabe. 278 reale Episoden: 75,49 % weniger Zeichen, lokal und im aktiven MCP bestätigt. ## Konzept @@ -99,6 +100,8 @@ Emby's `IJsonSerializer` ist **Newtonsoft**. `DeserializeFromString(body, typeof - [x] Dashboard-Config-Seite (Port, API-Key) - [ ] Build-Pipeline + Deploy-Skript für Unraid - [x] Bibliotheks-/Medienwerkzeuge und paginierter Serienbestand +- [x] Geplante Aufgaben, Admin-Übersicht, Live TV lesend (1.5.0) +- [ ] Live TV schreibend (Aufnahmen planen/abbrechen), Untertitel-Download, Sammlungen/Playlists ## Lizenz diff --git a/docs/admin-livetv.md b/docs/admin-livetv.md new file mode 100644 index 0000000..016483f --- /dev/null +++ b/docs/admin-livetv.md @@ -0,0 +1,59 @@ +# Admin- und Live-TV-Werkzeuge (1.5.0) + +12 neue Werkzeuge, insgesamt 49. Nur `emby_run_task` und `emby_cancel_task` verändern etwas; +sie folgen demselben Ablauf wie die übrigen Schreibwerkzeuge: Standard `dryRun=true`, +Ausführung nur mit Plugin-Schreibfreigabe, gesetztem API-Key und `confirm=true`, +Eintrag in `actions.jsonl`. + +## Geplante Aufgaben + +| Werkzeug | Zweck | +|---|---| +| `emby_tasks` | Alle Aufgaben mit Key, Kategorie, Status, Fortschritt, letztem Ergebnis, `runAllowed` | +| `emby_run_task` | Genau eine Aufgabe in die Warteschlange stellen, nur wenn sie `Idle` ist | +| `emby_cancel_task` | Genau eine laufende Aufgabe abbrechen | + +Typische Aufgaben: EPG/Guide aktualisieren (liest bei M3U/XMLTV auch Sender neu ein), +alle Bibliotheken scannen, Kapitelbilder extrahieren, Untertitel herunterladen. + +**Freigabe:** Ohne Eintrag unter *Erlaubte Aufgaben* sind alle Aufgaben erlaubt, deren Key +oder Name nicht `restart`, `shutdown`, `backup`, `restore`, `delete`, `remove`, `uninstall` +oder `update` enthält (also z. B. keine Plugin-/Server-Updates). Ist die Liste gesetzt, +sind ausschließlich die dort eingetragenen Keys erlaubt – auch sonst gesperrte. +Die exakten Keys liefert `emby_tasks`. + +## Admin (nur lesend) + +| Werkzeug | Zweck | +|---|---| +| `emby_activity_log` | Aktivitätsprotokoll (Logins inkl. Fehlversuche, Wiedergaben, Plugin-Ereignisse), filterbar nach Schweregrad, Benutzer/System, Text, Zeitpunkt | +| `emby_server_log` | Jüngste Einträge des Server-Logs (letzte 4 MB), mehrzeilige Exceptions zusammengefasst, Level-/Textfilter, Auswahl älterer Logdateien nur per exaktem Namen | +| `emby_plugins` | Installierte Plugins, Server-Version/Update-Status, laufende Installationen; `checkUpdates=true` fragt den Emby-Katalog ab | +| `emby_devices` | Geräte/Clients mit App, Version, letztem Benutzer, letzter Aktivität, IP | +| `emby_storage` | Freier/gesamter Speicher für Bibliotheks-, Daten-, Cache-, Log-, Temp-, Transcoding- und Aufnahmepfade; optional Verzeichnisgrößen (nie Bibliotheken) | + +**Schwärzung im Server-Log:** `api_key`, `X-Emby-Token`, `X-Api-Key`, `token`, `password`, +`secret`, `Authorization`-Header, `Bearer`-Tokens und `user:pass@` in URLs werden durch +`***` ersetzt. Das ist musterbasiert; ungewöhnlich formatierte Geheimnisse können durchrutschen. + +## Live TV (nur lesend) + +| Werkzeug | Zweck | +|---|---| +| `emby_livetv_status` | Tuner/M3U- und EPG-Quellen, EPG-Zeitraum, Senderzahl, Sender ohne aktuelles Programm, aktive Aufnahme, Task-Key zum EPG-Aktualisieren | +| `emby_livetv_channels` | Sender nach Nummer mit jetzt/als Nächstes, Programmanzahl 24 h, EPG-Status `ok`/`gap_now`/`no_programs_next_24h` | +| `emby_livetv_guide` | Programm für Sender und Zeitfenster (≤ 72 h), Text- und Kategoriefilter | +| `emby_livetv_recordings` | Geplante Aufnahmen und Serien-Aufnahmeregeln | + +Von Tunern und EPG-Quellen werden nur Typ, Name und **Schema + Host** ausgegeben +(lokale Dateien nur mit Dateinamen). URL-Pfade, Query-Parameter, Benutzer, Passwörter, +User-Agent und Provider-Optionen werden nie ausgegeben, weil IPTV-Anbieter dort Zugangsdaten führen. + +**Annahme zur Live-Abnahme:** Sendungen werden über `ParentId` dem Sender zugeordnet +(so liegen Programme in Emby 4.9 im SDK; ein eigenes `ChannelId`-Feld gibt es dort nicht). +`scripts/verify-live-admin.php` prüft das gegen den echten Server. + +## Live-Abnahme + +`php scripts/verify-live-admin.php` auf dem Emby-Host, ausschließlich lesend +(Aufgaben nur als Vorschau). Gibt keine Tokens, Loginhalte oder Tuner-URLs aus. diff --git a/releases/1.5.0/INSTALL.md b/releases/1.5.0/INSTALL.md new file mode 100644 index 0000000..c5cda82 --- /dev/null +++ b/releases/1.5.0/INSTALL.md @@ -0,0 +1,47 @@ +# eMCPy 1.5.0 + +12 neue Werkzeuge (insgesamt 49), Details in [docs/admin-livetv.md](../../docs/admin-livetv.md): + +- Geplante Aufgaben: `emby_tasks`, `emby_run_task`, `emby_cancel_task` + (z. B. EPG/Guide aktualisieren, alle Bibliotheken scannen). +- Admin, lesend: `emby_activity_log`, `emby_server_log` (geschwärzt), `emby_plugins`, + `emby_devices`, `emby_storage`. +- Live TV, lesend: `emby_livetv_status`, `emby_livetv_channels`, `emby_livetv_guide`, + `emby_livetv_recordings`. + +Enthält alle Änderungen aus 1.4.2 (Origin-Prüfung, Listen-Adresse, JSON-RPC-Fixes); +1.4.2 muss nicht separat installiert werden. Bestehende Werkzeuge und Ausgaben unverändert. + +DLL gebaut (net6.0, `dotnet publish -c Release`), SHA256SUMS prüfen. Nur eMCPy.dll +installieren. Konfiguration bleibt erhalten; neue Felder *Erlaubte Origins* und +*Erlaubte Aufgaben* sind leer. + +## Vor dem Update beachten + +- Dashboard über eine Domain? Unter *Erlaubte Origins* eintragen (sonst 403 im Status-Check). +- *Listen-Adresse* für Docker auf `0.0.0.0` lassen. +- `emby_run_task`/`emby_cancel_task` brauchen wie alle Schreibwerkzeuge Schreibfreigabe, + API-Key und `confirm=true`. Ohne *Erlaubte Aufgaben* sind Neustart/Update/Backup/Restore/ + Löschen gesperrt; mit gesetzter Liste nur die eingetragenen Keys. +- Neue Dienste (Aktivität, Geräte, Live TV, Installation, Konfiguration) werden optional + aufgelöst; fehlt einer, melden nur die betroffenen Werkzeuge „nicht verfügbar“. + +## Installation + +Ohne laufende MCP-Anfragen, Wiedergaben oder Aufnahmen: Emby kontrolliert stoppen, +vorhandene DLL außerhalb des Pluginpfades sichern, neue DLL bei gleichen Rechten nach +`/mnt/nvme-storage/appdata/Emby/plugins/` kopieren, Emby starten. Plugin-Seite öffnen +(Version 1.5.0, Status grün). Dann ausschließlich lesend: + + php scripts/verify-live-admin.php + php scripts/verify-live-mcp.php + +`verify-live-admin.php` prüft u. a. 49 Werkzeuge, Log-Schwärzung, keine Tuner-Zugangsdaten +und die Zuordnung Programm → Sender (ParentId) gegen echte Daten. +Rollback: Emby stoppen, gesicherte DLL zurückkopieren, starten. + +## Lokal geprüft + +597 Assertions (372 Serieninventar, 97 Advanced, 40 Protokoll, 88 Admin/Live TV), nur +Test-Doubles für Aktionen; HTTP-Smoke-Test: 49 Werkzeuge gelistet, Origin-Block, 405, ping. +Noch nicht auf dem Live-Server installiert; Live-TV-Abfragen sind nur gegen Test-Doubles geprüft. diff --git a/releases/1.5.0/SHA256SUMS b/releases/1.5.0/SHA256SUMS new file mode 100644 index 0000000..ef7c99e --- /dev/null +++ b/releases/1.5.0/SHA256SUMS @@ -0,0 +1 @@ +0ef04d721466f8dc4e6d832d9bfd5d6ed6c56520190e658cab2ead1423194ee0 eMCPy.dll diff --git a/releases/1.5.0/eMCPy.dll b/releases/1.5.0/eMCPy.dll new file mode 100644 index 0000000..4aee5bc Binary files /dev/null and b/releases/1.5.0/eMCPy.dll differ diff --git a/scripts/verify-live-admin.php b/scripts/verify-live-admin.php new file mode 100644 index 0000000..eb67891 --- /dev/null +++ b/scripts/verify-live-admin.php @@ -0,0 +1,72 @@ +McpPort.'/mcp'); + curl_setopt_array($c, [CURLOPT_RETURNTRANSFER=>true, CURLOPT_POST=>true, + CURLOPT_HTTPHEADER=>['Content-Type: application/json','X-Api-Key: '.(string)$x->ApiKey], + CURLOPT_POSTFIELDS=>json_encode(['jsonrpc'=>'2.0','id'=>$calls,'method'=>$method,'params'=>$params]),CURLOPT_TIMEOUT=>90]); + $body = curl_exec($c); $code = curl_getinfo($c, CURLINFO_HTTP_CODE); curl_close($c); + if ($code !== 200) throw new RuntimeException('MCP request failed: HTTP '.$code); + $r = json_decode($body,true,512,JSON_THROW_ON_ERROR); + if (isset($r['error'])) throw new RuntimeException('MCP JSON-RPC error'); + return $r['result']; +} +function requireTrue($ok,$message) { if (!$ok) throw new RuntimeException($message); } +function callTool($name,$args) { + $r=rpc('tools/call',['name'=>$name,'arguments'=>(object)$args]); + requireTrue(empty($r['isError']), 'MCP tool failed: '.$name.' – '.($r['content'][0]['text'] ?? '')); + return json_decode($r['content'][0]['text'],true,512,JSON_THROW_ON_ERROR); +} +$init=rpc('initialize',['protocolVersion'=>'2025-06-18']); +requireTrue($init['serverInfo']['version']==='1.5.0','Expected active 1.5.0'); +requireTrue($init['protocolVersion']==='2025-06-18','Protocol negotiation'); +requireTrue(rpc('ping',(object)[])==[],'ping'); +$tools=array_column(rpc('tools/list',(object)[])['tools'],'name'); +requireTrue(count($tools)===49,'Expected 49 tools, got '.count($tools)); + +$tasks=callTool('emby_tasks',[]); +requireTrue($tasks['total']>0,'Scheduled tasks visible'); +echo "Tasks: {$tasks['total']} (categories: ".implode(', ',$tasks['categories']).")\n"; +foreach ($tasks['tasks'] as $t) echo sprintf(" %-28s %-14s %-8s %s\n",$t['key'],$t['category'],$t['state'],$t['runAllowed']?'allowed':'blocked'); +$idle=array_values(array_filter($tasks['tasks'],fn($t)=>$t['runAllowed']&&$t['state']==='Idle')); +if ($idle) { $p=callTool('emby_run_task',['key'=>$idle[0]['key']]); requireTrue($p['dryRun']===true&&$p['status']==='preview','Run preview only'); } + +$act=callTool('emby_activity_log',['limit'=>20]); +echo "Activity entries: {$act['total']}\n"; +$log=callTool('emby_server_log',['lines'=>50,'level'=>'Warn']); +requireTrue($log['file']!==null,'Server log found'); +$raw=json_encode($log); +requireTrue(!preg_match('/(api_key|X-Emby-Token|password)=(?!\*\*\*)[^&\s"]+/i',$raw),'Log redaction'); +echo "Log {$log['file']}: {$log['returned']} Warn/Error entries returned\n"; +$plugins=callTool('emby_plugins',[]); +echo "Plugins: ".count($plugins['plugins'])." on Emby {$plugins['serverVersion']}\n"; +$dev=callTool('emby_devices',['limit'=>50]); +echo "Devices: {$dev['total']}\n"; +$st=callTool('emby_storage',[]); +foreach ($st['locations'] as $l) echo sprintf(" %-40s %s %s\n",implode(',',$l['roles']),$l['status'],isset($l['percentFree'])?$l['percentFree'].'% frei':''); + +$tv=callTool('emby_livetv_status',[]); +$tvRaw=json_encode($tv); +foreach ($tv['tuners'] as $t) requireTrue(!str_contains((string)$t['source'],'@')&&!str_contains((string)$t['source'],'?'),'Tuner source host only'); +requireTrue(!preg_match('/password|username/i',$tvRaw),'No tuner/EPG credentials'); +echo "Live TV: {$tv['channels']} channels, {$tv['channelsWithoutProgramNow']} without current program, guide until ".($tv['guideRange']['end'] ?? 'n/a').", refresh task ".($tv['refreshGuideTaskKey'] ?? 'n/a')."\n"; +if ($tv['channels']>0) { + $ch=callTool('emby_livetv_channels',['limit'=>10]); + requireTrue($ch['returned']>0,'Channels page'); + $first=$ch['channels'][0]; + echo "First channel: {$first['number']} {$first['name']} – {$first['guideStatus']}\n"; + $g=callTool('emby_livetv_guide',['channelId'=>$first['id'],'hours'=>6]); + echo "Guide entries next 6h on first channel: {$g['total']}\n"; + if ($first['guideStatus']!=='no_programs_next_24h') requireTrue($g['total']>0,'Program ParentId maps to channel (guide vs channels consistent)'); +} +$rec=callTool('emby_livetv_recordings',[]); +echo "Timers: ".count($rec['timers']).", series timers: ".count($rec['seriesTimers'])."\n"; +echo "PASS live admin/livetv acceptance ({$calls} calls, read-only).\n"; diff --git a/src/eMCPy/Configuration/configPage.html b/src/eMCPy/Configuration/configPage.html index c2749ea..ea179fa 100644 --- a/src/eMCPy/Configuration/configPage.html +++ b/src/eMCPy/Configuration/configPage.html @@ -36,7 +36,7 @@
-
Standardmäßig aus. Erlaubt Altersfreigabe, Gesehen-Status, Pause und Refresh/Scan. +
Standardmäßig aus. Erlaubt Altersfreigabe, Gesehen-Status, Pause, Refresh/Scan sowie geplante Aufgaben starten/abbrechen (z. B. EPG aktualisieren). Benötigt einen gesetzten MCP-API-Key; Aktionen starten als Vorschau und erfordern explizite Bestätigung. Keine Lösch- oder Neustartwerkzeuge. Diese Freigabe lässt den MCP-Listener weiterlaufen.
@@ -95,6 +95,15 @@
+
+ + +
+ Task-Keys (kommagetrennt, siehe Werkzeug emby_tasks), die emby_run_task starten darf. + Leer = alle Aufgaben außer Neustart, Update, Backup/Restore und Löschen. Gesetzt = ausschließlich diese Keys. +
+
+
Status wird geladen …
diff --git a/src/eMCPy/Configuration/configPage.js b/src/eMCPy/Configuration/configPage.js index 90c0e10..29b3352 100644 --- a/src/eMCPy/Configuration/configPage.js +++ b/src/eMCPy/Configuration/configPage.js @@ -85,6 +85,7 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) { view.querySelector('#mcpUrl').value = config.McpUrl || ''; view.querySelector('#serverUrl').value = config.ServerUrl || ''; view.querySelector('#allowedOrigins').value = config.AllowedOrigins || ''; + view.querySelector('#allowedTaskKeys').value = config.AllowedTaskKeys || ''; this.checkServerStatus(view, config); loading.hide(); }).catch(() => { @@ -114,6 +115,7 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) { config.McpUrl = view.querySelector('#mcpUrl').value.trim(); config.ServerUrl = view.querySelector('#serverUrl').value.trim(); config.AllowedOrigins = view.querySelector('#allowedOrigins').value.trim(); + config.AllowedTaskKeys = view.querySelector('#allowedTaskKeys').value.trim(); updatePluginConfiguration(config).then(result => { loading.hide(); diff --git a/src/eMCPy/Mcp/AdminOperations.cs b/src/eMCPy/Mcp/AdminOperations.cs new file mode 100644 index 0000000..ac44c13 --- /dev/null +++ b/src/eMCPy/Mcp/AdminOperations.cs @@ -0,0 +1,364 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using System.Threading; +using MediaBrowser.Model.Tasks; + +namespace eMCPy.Mcp +{ + /// + /// Geplante Aufgaben (auflisten/auslösen/abbrechen), Aktivitätsprotokoll, Server-Log, + /// Plugins, Geräte und Speicherplatz. + /// + public sealed class AdminOperations + { + readonly EmbyServices s; + static readonly object TaskLock = new object(); + public AdminOperations(EmbyServices services) { s = services; } + + // ---------- Geplante Aufgaben ---------- + + // Ohne explizite Freigabeliste gesperrt: alles, was den Server neu startet, aktualisiert, + // sichert/wiederherstellt oder Daten löscht. + static readonly Regex DeniedTask = new Regex(@"restart|shutdown|backup|restore|delete|remove|uninstall|update", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + static string Key(IScheduledTaskWorker t) => t.ScheduledTask?.Key ?? t.Id; + + HashSet ExplicitAllowList() + { + var raw = s.Configuration().AllowedTaskKeys ?? string.Empty; + return new HashSet(raw.Split(new[] { ',', ';', ' ', '\n', '\r', '\t' }, StringSplitOptions.RemoveEmptyEntries), StringComparer.OrdinalIgnoreCase); + } + + public (bool allowed, string reason) TaskPolicy(IScheduledTaskWorker t) + { + var allow = ExplicitAllowList(); + if (allow.Count > 0) + return allow.Contains(Key(t)) || allow.Contains(t.Id) ? (true, "in_allowed_task_keys") : (false, "not_in_allowed_task_keys"); + return DeniedTask.IsMatch(Key(t) + " " + t.Name) ? (false, "blocked_by_default_restart_update_backup_delete") : (true, "default_allowed"); + } + + IScheduledTaskWorker[] Workers() => s.Tasks?.ScheduledTasks ?? throw new ToolOperationException("Aufgabenverwaltung nicht verfügbar."); + + IScheduledTaskWorker FindTask(string key) => + Workers().FirstOrDefault(t => string.Equals(Key(t), key, StringComparison.OrdinalIgnoreCase) || string.Equals(t.Id, key, StringComparison.OrdinalIgnoreCase)) + ?? throw new ToolInputException("Aufgabe nicht gefunden. Schlüssel aus emby_tasks verwenden."); + + object TaskRow(IScheduledTaskWorker t) + { + var policy = TaskPolicy(t); var last = t.LastExecutionResult; + return new + { + key = Key(t), + id = t.Id, + name = t.Name, + category = t.Category, + description = t.Description, + state = t.State.ToString(), + progress = t.CurrentProgress, + triggers = t.Triggers?.Length ?? 0, + lastResult = last == null ? null : new { status = last.Status.ToString(), startUtc = last.StartTimeUtc, endUtc = last.EndTimeUtc, error = last.ErrorMessage }, + runAllowed = policy.allowed, + policy = policy.reason + }; + } + + public object Tasks(ToolArgs a) + { + var category = a.Text("category"); var query = a.Text("query"); + var rows = Workers() + .Where(t => category == null || string.Equals(t.Category, category, StringComparison.OrdinalIgnoreCase)) + .Where(t => query == null || (t.Name ?? "").IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0 || Key(t).IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0) + .OrderBy(t => t.Category).ThenBy(t => t.Name) + .Select(TaskRow).ToArray(); + return new + { + total = rows.Length, + categories = Workers().Select(t => t.Category).Where(c => c != null).Distinct().OrderBy(c => c).ToArray(), + allowListActive = ExplicitAllowList().Count > 0, + tasks = rows + }; + } + + public object RunTask(ToolArgs a) + { + bool dry = a.Bool("dryRun", true); if (!dry) ToolSupport.RequireWrite(s, a); + lock (TaskLock) + { + var t = FindTask(a.Text("key")); + var policy = TaskPolicy(t); + if (!policy.allowed) throw new ToolOperationException("Aufgabe ist gesperrt (" + policy.reason + "). Freigabe nur über 'Erlaubte Aufgaben' im Plugin."); + if (t.State != TaskState.Idle) throw new ToolOperationException("Aufgabe läuft bereits oder wird abgebrochen (" + t.State + ")."); + var preview = new { key = Key(t), name = t.Name, category = t.Category, state = t.State.ToString(), lastResult = t.LastExecutionResult?.Status.ToString() }; + if (dry) return new { dryRun = true, task = preview, status = "preview" }; + var operationId = Guid.NewGuid().ToString(); + ManagementOperations.Journal(s, new { operationId, time = DateTimeOffset.UtcNow, action = "run_task", key = Key(t), name = t.Name }); + s.Tasks.QueueScheduledTask(t.ScheduledTask, new TaskOptions()); + return new { dryRun = false, operationId, task = preview, status = "queued", complete = false, note = "Fortschritt mit emby_tasks prüfen." }; + } + } + + public object CancelTask(ToolArgs a) + { + bool dry = a.Bool("dryRun", true); if (!dry) ToolSupport.RequireWrite(s, a); + lock (TaskLock) + { + var t = FindTask(a.Text("key")); + if (t.State != TaskState.Running) throw new ToolOperationException("Aufgabe läuft nicht (" + t.State + ")."); + var preview = new { key = Key(t), name = t.Name, state = t.State.ToString(), progress = t.CurrentProgress }; + if (dry) return new { dryRun = true, task = preview, status = "preview" }; + var operationId = Guid.NewGuid().ToString(); + ManagementOperations.Journal(s, new { operationId, time = DateTimeOffset.UtcNow, action = "cancel_task", key = Key(t), name = t.Name }); + s.Tasks.Cancel(t); + return new { dryRun = false, operationId, task = preview, status = "cancel_requested", complete = false }; + } + } + + // ---------- Aktivitätsprotokoll ---------- + + public object Activity(ToolArgs a) + { + if (s.Activity == null) throw new ToolOperationException("Aktivitätsprotokoll nicht verfügbar."); + int start = a.Int("start", 0), limit = a.Int("limit", 50); + var since = a.Date("since"); var query = a.Text("query"); var severity = a.Text("minSeverity"); + bool? hasUser = a.Has("hasUserId") ? a.Bool("hasUserId") : (bool?)null; + var result = s.Activity.GetActivityLogEntries(since, hasUser, start, limit, true, CancellationToken.None); + var entries = result.Items ?? Array.Empty(); + int minRank = SeverityRank(severity); + var page = entries + .Where(e => SeverityRank(e.Severity.ToString()) >= minRank) + .Where(e => query == null || (e.Name + " " + e.ShortOverview + " " + e.Overview + " " + e.Type).IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0) + .Select(e => new { id = e.Id, date = e.Date, type = e.Type, severity = e.Severity.ToString(), name = e.Name, shortOverview = e.ShortOverview, overview = Truncate(e.Overview, 1000), userId = e.UserId, itemId = e.ItemId }) + .ToArray(); + long next = (long)start + entries.Length; + return new + { + total = result.TotalRecordCount, + scanned = entries.Length, + returned = page.Length, + hasMore = next < result.TotalRecordCount, + nextStart = next < result.TotalRecordCount ? (int?)next : null, + note = "Filter (minSeverity/query) wirken auf die gescannte Seite; nextStart folgen.", + entries = page + }; + } + + static int SeverityRank(string severity) => (severity ?? "").ToLowerInvariant() switch + { + "debug" => 0, "info" => 1, "warn" => 2, "warning" => 2, "error" => 3, "fatal" => 4, _ => 0 + }; + + // ---------- Server-Log ---------- + + static readonly Regex LogStart = new Regex(@"^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:[.,]\d+)?\s+(\w+)\s", RegexOptions.CultureInvariant); + static readonly Regex[] Secrets = + { + new Regex(@"(?i)(api_?key|x-emby-token|x-mediabrowser-token|x-api-key|access_?token|token|password|passwd|pw|secret)(\s*[=:]\s*|""\s*:\s*"")[^\s&""',;}]+"), + new Regex(@"(?i)(authorization\s*[=:]\s*)(bearer|basic|mediabrowser|emby)?\s*[^\r\n]+"), + new Regex(@"(?i)(bearer\s+)[A-Za-z0-9._~+/=-]+"), + new Regex(@"(?i)(://)[^/\s:@]+:[^/\s@]+@") + }; + + public static string Redact(string text) + { + if (string.IsNullOrEmpty(text)) return text; + text = Secrets[0].Replace(text, m => m.Groups[1].Value + m.Groups[2].Value + "***"); + text = Secrets[1].Replace(text, m => m.Groups[1].Value + "***"); + text = Secrets[2].Replace(text, m => m.Groups[1].Value + "***"); + text = Secrets[3].Replace(text, "://***@"); + return text; + } + + string LogDirectory() => s.ServerConfig?.ApplicationPaths?.LogDirectoryPath ?? throw new ToolOperationException("Log-Verzeichnis nicht verfügbar."); + + FileInfo[] LogFiles() + { + var dir = new DirectoryInfo(LogDirectory()); + if (!dir.Exists) return Array.Empty(); + return dir.GetFiles().Where(f => f.Extension.Equals(".txt", StringComparison.OrdinalIgnoreCase) || f.Extension.Equals(".log", StringComparison.OrdinalIgnoreCase)) + .OrderByDescending(f => f.LastWriteTimeUtc).Take(30).ToArray(); + } + + public object ServerLog(ToolArgs a) + { + var files = LogFiles(); + var requested = a.Text("file"); + FileInfo file; + if (requested != null) + file = files.FirstOrDefault(f => f.Name == requested) ?? throw new ToolInputException("Unbekannte Logdatei; Namen aus 'files' verwenden."); + else + file = files.FirstOrDefault(f => f.Name.StartsWith("embyserver", StringComparison.OrdinalIgnoreCase)) ?? files.FirstOrDefault(); + var fileList = files.Select(f => new { name = f.Name, size = f.Length, modifiedUtc = f.LastWriteTimeUtc }).ToArray(); + if (file == null) return new { file = (string)null, files = fileList, entries = Array.Empty() }; + + int count = a.Int("lines", 100); int minRank = SeverityRank(a.Text("level")); var query = a.Text("query"); + var text = ReadTail(file.FullName, 4 * 1024 * 1024, out bool truncated); + var entries = ParseLog(text); + var matches = entries + .Where(e => SeverityRank(e.level) >= minRank) + .Where(e => query == null || e.text.IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0) + .ToList(); + var page = matches.Skip(Math.Max(0, matches.Count - count)).Select(e => new { level = e.level, text = Redact(Truncate(e.text, 4000)) }).ToArray(); + return new + { + file = file.Name, + fileSize = file.Length, + scannedBytesFromEnd = Math.Min(file.Length, 4L * 1024 * 1024), + olderContentNotScanned = truncated, + matchedInScan = matches.Count, + returned = page.Length, + redaction = "Tokens, API-Keys, Passwörter und URL-Zugangsdaten werden ersetzt.", + files = fileList, + entries = page + }; + } + + static string ReadTail(string path, long maxBytes, out bool truncated) + { + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + truncated = fs.Length > maxBytes; + if (truncated) fs.Seek(-maxBytes, SeekOrigin.End); + using var reader = new StreamReader(fs, Encoding.UTF8, true); + var text = reader.ReadToEnd(); + if (truncated) { var nl = text.IndexOf('\n'); text = nl >= 0 ? text.Substring(nl + 1) : string.Empty; } + return text; + } + + public static List<(string level, string text)> ParseLog(string text) + { + var result = new List<(string level, string text)>(); + StringBuilder current = null; string level = null; int continuation = 0; + foreach (var raw in text.Split('\n')) + { + var line = raw.TrimEnd('\r'); + var m = LogStart.Match(line); + if (m.Success) + { + if (current != null) result.Add((level, current.ToString())); + current = new StringBuilder(line); level = m.Groups[1].Value; continuation = 0; + } + else if (current != null && line.Length > 0 && continuation++ < 40) current.Append('\n').Append(line); + } + if (current != null) result.Add((level, current.ToString())); + return result; + } + + // ---------- Plugins ---------- + + public object Plugins(ToolArgs a) + { + var plugins = (s.Host?.Plugins ?? Array.Empty()) + .Select(p => new { id = p.Id.ToString(), name = p.Name, version = p.Version?.ToString(), file = Path.GetFileName(p.AssemblyFilePath) }) + .OrderBy(p => p.name).ToArray(); + object updates = null; string updateStatus = "not_checked"; + if (a.Bool("checkUpdates")) + { + if (s.Installation == null || s.Host?.ApplicationVersion == null) updateStatus = "unavailable"; + else + { + try + { + using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + var found = s.Installation.GetAvailablePluginUpdates(s.Host.ApplicationVersion, timeout.Token).GetAwaiter().GetResult() ?? Array.Empty(); + updates = found.Select(u => new { name = u.name, guid = u.guid, version = u.versionStr, classification = u.classification.ToString(), timestamp = u.timestamp, infoUrl = u.infoUrl }).ToArray(); + updateStatus = "checked"; + } + catch (OperationCanceledException) { updateStatus = "timeout"; } + catch (Exception) { updateStatus = "failed"; } + } + } + var installing = s.Installation?.CurrentInstallations?.Select(x => new { name = x.Item1?.Name, version = x.Item1?.Version, progress = x.Item1?.PercentComplete }).ToArray(); + return new + { + serverVersion = s.Host?.ApplicationVersion?.ToString(), + serverUpdateAvailable = s.Host?.HasUpdateAvailable, + availableServerVersion = s.Host?.AvailableVersion?.ToString(), + pendingRestart = s.Host?.HasPendingRestart, + plugins, + updateStatus, + updates, + currentInstallations = installing, + note = "Nur lesend. Plugin-Updates installiert die Aufgabe für Plugin-Updates (standardmäßig gesperrt)." + }; + } + + // ---------- Geräte ---------- + + public object Devices(ToolArgs a) + { + if (s.Devices == null) throw new ToolOperationException("Geräteverwaltung nicht verfügbar."); + int start = a.Int("start", 0), limit = a.Int("limit", 50); + var result = s.Devices.GetDevices(new MediaBrowser.Model.Devices.DeviceQuery { StartIndex = start, Limit = limit }, CancellationToken.None); + var items = result.Items ?? Array.Empty(); + DateTimeOffset? activeSince = a.Has("activeWithinDays") ? DateTimeOffset.UtcNow.AddDays(-a.Int("activeWithinDays", 30)) : (DateTimeOffset?)null; + var page = items.Where(d => activeSince == null || d.DateLastActivity >= activeSince) + .Select(d => new { id = d.InternalId.ToString(), name = d.Name, app = d.AppName, appVersion = d.AppVersion, lastUser = d.LastUserName, lastUserId = d.LastUserId, lastActivity = d.DateLastActivity, ipAddress = d.IpAddress?.ToString() }) + .ToArray(); + long next = (long)start + items.Length; + return new { total = result.TotalRecordCount, scanned = items.Length, returned = page.Length, hasMore = next < result.TotalRecordCount, nextStart = next < result.TotalRecordCount ? (int?)next : null, devices = page }; + } + + // ---------- Speicherplatz ---------- + + public object Storage(ToolArgs a) + { + var targets = new List<(string role, string path)>(); + var paths = s.ServerConfig?.ApplicationPaths; + if (paths != null) + { + targets.Add(("data", paths.DataPath)); targets.Add(("cache", paths.CachePath)); targets.Add(("logs", paths.LogDirectoryPath)); + targets.Add(("temp", paths.TempDirectory)); targets.Add(("plugins", paths.PluginsPath)); + } + try { if (s.ServerConfig?.GetConfiguration("encoding") is MediaBrowser.Model.Configuration.EncodingOptions enc && !string.IsNullOrWhiteSpace(enc.TranscodingTempPath)) targets.Add(("transcoding", enc.TranscodingTempPath)); } catch { } + try { if (s.ServerConfig?.GetConfiguration("livetv") is MediaBrowser.Model.LiveTv.LiveTvOptions tv) { targets.Add(("recordings", tv.RecordingPath)); targets.Add(("movieRecordings", tv.MovieRecordingPath)); targets.Add(("seriesRecordings", tv.SeriesRecordingPath)); } } catch { } + foreach (var folder in s.Library?.GetVirtualFolders() ?? new List()) + foreach (var location in folder.Locations ?? Array.Empty()) targets.Add(("library:" + folder.Name, location)); + + bool sizes = a.Bool("includeDirectorySizes"); + var rows = targets.Where(t => !string.IsNullOrWhiteSpace(t.path)).GroupBy(t => t.path).Select(g => + { + var path = g.Key; var roles = g.Select(x => x.role).Distinct().ToArray(); + if (!Directory.Exists(path)) return (object)new { roles, path, status = "missing_or_not_accessible" }; + try + { + var drive = new DriveInfo(path); + object size = null; + if (sizes && roles.Any(r => !r.StartsWith("library:"))) size = DirectorySize(path); + return new + { + roles, + path, + status = "ok", + totalBytes = drive.TotalSize, + freeBytes = drive.AvailableFreeSpace, + percentFree = drive.TotalSize > 0 ? Math.Round(100.0 * drive.AvailableFreeSpace / drive.TotalSize, 1) : (double?)null, + directorySize = size + }; + } + catch (Exception) { return new { roles, path, status = "not_measurable" }; } + }).ToArray(); + return new { note = "Werte pro Pfad; mehrere Pfade können auf demselben Dateisystem liegen. Bibliotheksgrößen werden nie rekursiv gezählt.", locations = rows }; + } + + static object DirectorySize(string path) + { + long bytes = 0; int files = 0; var watch = System.Diagnostics.Stopwatch.StartNew(); bool complete = true; + try + { + foreach (var f in new DirectoryInfo(path).EnumerateFiles("*", new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint })) + { + bytes += f.Length; + if (++files >= 200000 || watch.ElapsedMilliseconds > 10000) { complete = false; break; } + } + } + catch { complete = false; } + return new { bytes, files, complete }; + } + + static string Truncate(string text, int max) => text == null || text.Length <= max ? text : text.Substring(0, max) + "…"; + } +} diff --git a/src/eMCPy/Mcp/AdvancedSchemas.cs b/src/eMCPy/Mcp/AdvancedSchemas.cs index 80d6a3f..e53f044 100644 --- a/src/eMCPy/Mcp/AdvancedSchemas.cs +++ b/src/eMCPy/Mcp/AdvancedSchemas.cs @@ -68,6 +68,67 @@ namespace eMCPy.Mcp list.Add(Tool("emby_refresh_item", "Stellt einen nichtrekursiven Metadaten-Refresh eines Items in Embys Queue. Kein Ersetzen aller Bilder/Metadaten, kein Neustart. Standard Vorschau; queued bedeutet nicht abgeschlossen.", p, new[] { "id" }, true)); p = Action(); p["libraryId"] = Str("Konkrete Bibliothek aus emby_library_folders."); list.Add(Tool("emby_scan_library", "Stellt die rekursive Validierung einer einzelnen Bibliothek in Embys Refresh-Queue (ValidationOnly, kein vollständiger Metadatenersatz). Standard Vorschau; Fortschritt in server_diagnostics, queued ist nicht abgeschlossen.", p, new[] { "libraryId" }, true)); + // ---- 1.5.0: Aufgaben ---- + p = new Dictionary { ["category"] = Str("Optional: exakte Kategorie, z.B. Library oder Live TV."), ["query"] = Str("Optionaler Teil von Name oder Key.") }; + list.Add(Tool("emby_tasks", "Geplante Aufgaben mit Key, Kategorie, Status, Fortschritt, letztem Ergebnis und ob emby_run_task sie auslösen darf (z.B. EPG/Guide aktualisieren, alle Bibliotheken scannen, Kapitelbilder, Untertitel).", p)); + p = Action(); p["key"] = Str("Task-Key aus emby_tasks."); + list.Add(Tool("emby_run_task", "Stellt genau eine geplante Aufgabe in Embys Warteschlange, nur wenn sie gerade nicht läuft. Neustart/Update/Backup/Restore/Löschen sind ohne Freigabeliste gesperrt. Standard Vorschau; queued bedeutet nicht abgeschlossen, Fortschritt in emby_tasks.", p, new[] { "key" }, true)); + p = Action(); p["key"] = Str("Task-Key einer laufenden Aufgabe aus emby_tasks."); + list.Add(Tool("emby_cancel_task", "Bricht genau eine laufende geplante Aufgabe ab. Standard Vorschau.", p, new[] { "key" }, true)); + // ---- 1.5.0: Admin ---- + p = new Dictionary + { + ["since"] = Str("Optional: ISO-Zeitstempel mit Zeitzone."), + ["minSeverity"] = Str("Optional: Mindest-Schweregrad.", "Info", "Warn", "Error", "Fatal"), + ["hasUserId"] = Bool("Optional: true nur Benutzeraktionen (Login, Wiedergabe), false nur Systemereignisse."), + ["query"] = Str("Optionaler Text in Name/Beschreibung/Typ."), + ["start"] = Int("Startposition, Standard 0.", 0, int.MaxValue), + ["limit"] = Int("Einträge pro Seite, Standard 50, höchstens 200.", 1, 200) + }; + list.Add(Tool("emby_activity_log", "Emby-Aktivitätsprotokoll, neueste zuerst: Anmeldungen inkl. fehlgeschlagener, Wiedergaben, Plugin-Installationen, Aufgabenfehler, Bibliotheksereignisse.", p)); + p = new Dictionary + { + ["lines"] = Int("Anzahl jüngster Logeinträge, Standard 100, höchstens 500.", 1, 500), + ["level"] = Str("Optional: Mindest-Level.", "Debug", "Info", "Warn", "Error", "Fatal"), + ["query"] = Str("Optionaler Text, z.B. Pluginname oder Fehlermeldung."), + ["file"] = Str("Optional: exakter Dateiname aus files; Standard aktuelles embyserver-Log.") + }; + list.Add(Tool("emby_server_log", "Jüngste Einträge des Emby-Server-Logs (letzte 4 MB), mehrzeilige Exceptions zusammengefasst, filterbar nach Level/Text. Tokens, API-Keys, Passwörter und URL-Zugangsdaten werden geschwärzt.", p)); + p = new Dictionary { ["checkUpdates"] = Bool("Standard false. true fragt verfügbare Plugin-Updates beim Emby-Katalog ab (Internetzugriff).") }; + list.Add(Tool("emby_plugins", "Installierte Plugins mit Version, Server-Version/-Update-Status, laufende Installationen und optional verfügbare Plugin-Updates. Nur lesend.", p)); + p = new Dictionary + { + ["activeWithinDays"] = Int("Optional: nur Geräte mit Aktivität in den letzten N Tagen.", 1, 3650), + ["start"] = Int("Startposition, Standard 0.", 0, int.MaxValue), + ["limit"] = Int("Geräte pro Seite, Standard 50, höchstens 200.", 1, 200) + }; + list.Add(Tool("emby_devices", "Registrierte Geräte/Clients mit App, Version, letztem Benutzer, letzter Aktivität und IP. Keine Zugangsdaten.", p)); + p = new Dictionary { ["includeDirectorySizes"] = Bool("Standard false. true zählt Größe von Cache/Logs/Temp/Transcoding (max. 200000 Dateien/10 s je Pfad), nie Bibliotheken.") }; + list.Add(Tool("emby_storage", "Freier/gesamter Speicher für Bibliothekspfade, Daten, Cache, Logs, Temp, Transcoding und Aufnahmepfade.", p)); + // ---- 1.5.0: Live TV (lesend) ---- + list.Add(Tool("emby_livetv_status", "Live-TV-Überblick: Tuner/M3U-Quellen und EPG-Quellen (nur Host, keine Zugangsdaten), EPG-Zeitraum, Senderzahl, Sender ohne aktuelles Programm, aktive Aufnahme und Task-Key zum EPG-Aktualisieren.", new Dictionary())); + p = new Dictionary + { + ["query"] = Str("Optional: Teil des Sendernamens oder exakte Sendernummer."), + ["onlyWithoutGuide"] = Bool("Standard false. true nur Sender ohne Programm jetzt/nächste 24 h."), + ["start"] = Int("Startposition, Standard 0.", 0, int.MaxValue), + ["limit"] = Int("Sender pro Seite, Standard 50, höchstens 200.", 1, 200) + }; + list.Add(Tool("emby_livetv_channels", "Sender nach Nummer sortiert mit jetzt/als Nächstes laufender Sendung, Programmanzahl der nächsten 24 h und EPG-Status (ok, gap_now, no_programs_next_24h).", p)); + p = new Dictionary + { + ["channelId"] = Str("Optional: Sender-ID aus emby_livetv_channels."), + ["channelIds"] = new { type = "array", description = "Optional: bis zu 50 Sender-IDs.", minItems = 1, maxItems = 50, uniqueItems = true, items = Str("Sender-ID") }, + ["from"] = Str("Optional: Beginn als ISO-Zeitstempel mit Zeitzone, Standard jetzt."), + ["hours"] = Int("Zeitfenster in Stunden, Standard 6, höchstens 72.", 1, 72), + ["query"] = Str("Optional: Text in Titel/Serienname."), + ["category"] = Str("Optional: Kategorie.", "movie", "series", "sports", "news", "kids"), + ["includeOverview"] = Bool("Standard false; true liefert gekürzte Beschreibung."), + ["start"] = Int("Startposition, Standard 0.", 0, int.MaxValue), + ["limit"] = Int("Sendungen pro Seite, Standard 100, höchstens 500.", 1, 500) + }; + list.Add(Tool("emby_livetv_guide", "TV-Programm (EPG) für Sender und Zeitfenster, z.B. 'Was läuft heute Abend', 'Wann kommt der Tatort', Filme/Sport filtern.", p)); + list.Add(Tool("emby_livetv_recordings", "Geplante Aufnahmen (Timer) mit Status und Serien-Aufnahmeregeln. Nur lesend.", new Dictionary())); return list; } diff --git a/src/eMCPy/Mcp/AdvancedTools.cs b/src/eMCPy/Mcp/AdvancedTools.cs index ffd5583..bce20bd 100644 --- a/src/eMCPy/Mcp/AdvancedTools.cs +++ b/src/eMCPy/Mcp/AdvancedTools.cs @@ -12,7 +12,7 @@ namespace eMCPy.Mcp { var definition = AdvancedSchemas.Get(name); AdvancedSchemas.Validate(definition, arguments); - var a = new ToolArgs(arguments); var library = new LibraryOperations(services); var management = new ManagementOperations(services); + var a = new ToolArgs(arguments); var library = new LibraryOperations(services); var management = new ManagementOperations(services); var admin = new AdminOperations(services); var tv = new LiveTvOperations(services); return name switch { "emby_search_advanced" => library.Search(a), @@ -34,6 +34,18 @@ namespace eMCPy.Mcp "emby_pause_session" => management.Pause(a), "emby_refresh_item" => management.Refresh(a, false), "emby_scan_library" => management.Refresh(a, true), + "emby_tasks" => admin.Tasks(a), + "emby_run_task" => admin.RunTask(a), + "emby_cancel_task" => admin.CancelTask(a), + "emby_activity_log" => admin.Activity(a), + "emby_server_log" => admin.ServerLog(a), + "emby_plugins" => admin.Plugins(a), + "emby_devices" => admin.Devices(a), + "emby_storage" => admin.Storage(a), + "emby_livetv_status" => tv.Status(), + "emby_livetv_channels" => tv.ChannelList(a), + "emby_livetv_guide" => tv.Guide(a), + "emby_livetv_recordings" => tv.Recordings(), _ => throw new ToolInputException("Werkzeug ohne Implementierung.") }; } diff --git a/src/eMCPy/Mcp/LiveTvOperations.cs b/src/eMCPy/Mcp/LiveTvOperations.cs new file mode 100644 index 0000000..456e954 --- /dev/null +++ b/src/eMCPy/Mcp/LiveTvOperations.cs @@ -0,0 +1,201 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.LiveTv; +using MediaBrowser.Model.Querying; + +namespace eMCPy.Mcp +{ + /// + /// Live TV / Internet-TV, nur lesend: Tuner, EPG-Quellen, Sender mit EPG-Abdeckung, + /// Programm und geplante Aufnahmen. EPG-Aktualisierung über emby_run_task. + /// Zugangsdaten von Tunern/EPG-Quellen (URLs, Benutzer, Passwörter, Optionen) werden nie ausgegeben. + /// + public sealed class LiveTvOperations + { + readonly EmbyServices s; + public LiveTvOperations(EmbyServices services) { s = services; } + + LiveTvOptions Options() + { + try { return s.ServerConfig?.GetConfiguration("livetv") as LiveTvOptions; } catch { return null; } + } + + /// Nur Schema + Host (+Port) einer Tuner-/EPG-URL; Pfade/Query können Zugangsdaten enthalten. + public static string HostOnly(string value) + { + if (string.IsNullOrWhiteSpace(value)) return null; + if (Uri.TryCreate(value, UriKind.Absolute, out var uri)) + // Bewusst ohne GetLeftPart(Authority): das behielte user:pass@. + return uri.IsFile ? "local:" + System.IO.Path.GetFileName(uri.LocalPath) + : uri.Scheme + "://" + uri.Host + (uri.IsDefaultPort ? "" : ":" + uri.Port); + return "local:" + System.IO.Path.GetFileName(value); + } + + static string RefreshTaskKey(EmbyServices s) => + s.Tasks?.ScheduledTasks?.FirstOrDefault(t => (t.ScheduledTask?.Key ?? "").IndexOf("guide", StringComparison.OrdinalIgnoreCase) >= 0 + || (t.Name ?? "").IndexOf("guide", StringComparison.OrdinalIgnoreCase) >= 0) is MediaBrowser.Model.Tasks.IScheduledTaskWorker w ? (w.ScheduledTask?.Key ?? w.Id) : null; + + List Channels() + { + var q = new InternalItemsQuery { IncludeItemTypes = new[] { "TvChannel" }, Recursive = true }; + return s.Library.GetItemsResult(q).Items.ToList(); + } + + static double SortNumber(BaseItem c) => + c is LiveTvChannel ch && double.TryParse((ch.Number ?? "").Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture, out var n) ? n : double.MaxValue; + + static string Number(BaseItem c) => (c as LiveTvChannel)?.Number; + + List Programs(long[] channelIds, DateTimeOffset from, DateTimeOffset to, int? startIndex = null, int? limit = null) + { + var q = new InternalItemsQuery + { + IncludeItemTypes = new[] { "Program" }, + Recursive = true, + MinEndDate = from, + MaxStartDate = to, + OrderBy = new[] { (ItemSortBy.StartDate, SortOrder.Ascending), (ItemSortBy.SortName, SortOrder.Ascending) } + }; + if (channelIds != null && channelIds.Length > 0) q.ParentIds = channelIds; + if (startIndex.HasValue) q.StartIndex = startIndex; + if (limit.HasValue) q.Limit = limit; + return s.Library.GetItemsResult(q).Items.OfType().ToList(); + } + + static object ProgramRow(LiveTvProgram p, bool overview) => new + { + id = p.InternalId.ToString(CultureInfo.InvariantCulture), + channelId = p.ParentId.ToString(CultureInfo.InvariantCulture), + title = p.Name, + seriesName = p.SeriesName, + start = p.StartDate, + end = p.EndDate, + isMovie = p.IsMovie, isSeries = p.IsSeries, isSports = p.IsSports, isNews = p.IsNews, isKids = p.IsKids, + isNew = p.IsNew, isRepeat = p.IsRepeat, isLive = p.IsLive, isPremiere = p.IsPremiere, + officialRating = p.OfficialRating, + overview = overview ? Truncate(p.Overview, 400) : null + }; + + public object Status() + { + var options = Options(); + var guide = Try(() => s.LiveTv?.GetGuideInfo()); + var channels = Channels(); + var now = DateTimeOffset.UtcNow; + int withGuideNow = channels.Count == 0 ? 0 : Programs(null, now, now).Select(p => p.ParentId).Distinct().Count(); + return new + { + tuners = (options?.TunerHosts ?? Array.Empty()).Select(t => new + { + id = t.Id, type = t.Type, name = t.FriendlyName, source = HostOnly(t.Url), tunerCount = t.TunerCount, + importGuideData = t.ImportGuideData, importFavoritesOnly = t.ImportFavoritesOnly, allowHardwareTranscoding = t.AllowHWTranscoding + }).ToArray(), + guideProviders = (options?.ListingProviders ?? Array.Empty()).Select(p => new + { + id = p.Id, type = p.Type, name = p.Name, source = HostOnly(p.Path), country = p.Country, + enabledTuners = p.EnabledTuners?.Length ?? 0, channelMappings = p.ChannelMappings?.Length ?? 0 + }).ToArray(), + guideDays = options?.GuideDays, + guideRange = guide == null ? null : new { start = guide.StartDate, end = guide.EndDate, daysAhead = Math.Round((guide.EndDate - now).TotalDays, 1) }, + channels = channels.Count, + channelsWithProgramNow = withGuideNow, + channelsWithoutProgramNow = channels.Count - withGuideNow, + hasActiveRecording = Try(() => (bool?)s.LiveTv?.HasActiveRecording), + recordingPath = options?.RecordingPath, + refreshGuideTaskKey = RefreshTaskKey(s), + note = "EPG und Senderliste aktualisieren: emby_run_task mit refreshGuideTaskKey. Zugangsdaten werden nicht ausgegeben." + }; + } + + public object ChannelList(ToolArgs a) + { + int start = a.Int("start", 0), limit = a.Int("limit", 50); var query = a.Text("query"); bool onlyWithoutGuide = a.Bool("onlyWithoutGuide"); + var now = DateTimeOffset.UtcNow; + var all = Channels().Where(c => query == null || (c.Name ?? "").IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0 || Number(c) == query) + .OrderBy(SortNumber).ThenBy(c => c.Name, StringComparer.OrdinalIgnoreCase).ToList(); + var page = all.Skip(start).Take(limit).ToList(); + var programs = page.Count == 0 ? new List() : Programs(page.Select(c => c.InternalId).ToArray(), now, now.AddHours(24)); + var byChannel = programs.GroupBy(p => p.ParentId).ToDictionary(g => g.Key, g => g.OrderBy(p => p.StartDate).ToList()); + var rows = page.Select(c => + { + byChannel.TryGetValue(c.InternalId, out var list); list ??= new List(); + var current = list.FirstOrDefault(p => p.StartDate <= now && (p.EndDate ?? DateTimeOffset.MaxValue) > now); + var next = list.FirstOrDefault(p => p.StartDate > now); + return new + { + id = c.InternalId.ToString(CultureInfo.InvariantCulture), + number = Number(c), + name = c.Name, + mediaType = (c as LiveTvChannel)?.ChannelMediaType, + isFavorite = (c as LiveTvChannel)?.IsFavorite, + programsNext24h = list.Count, + guideStatus = list.Count == 0 ? "no_programs_next_24h" : current == null ? "gap_now" : "ok", + now = current == null ? null : new { title = current.Name, start = current.StartDate, end = current.EndDate }, + next = next == null ? null : new { title = next.Name, start = next.StartDate, end = next.EndDate }, + guideUntil = list.Count == 0 ? null : list.Max(p => p.EndDate) + }; + }).Where(r => !onlyWithoutGuide || r.guideStatus != "ok").ToArray(); + long nextStart = (long)start + page.Count; + return new + { + total = all.Count, scanned = page.Count, returned = rows.Length, + hasMore = nextStart < all.Count, nextStart = nextStart < all.Count ? (int?)nextStart : null, + note = onlyWithoutGuide ? "onlyWithoutGuide filtert die gescannte Seite; nextStart folgen." : null, + channels = rows + }; + } + + public object Guide(ToolArgs a) + { + var ids = a.Strings("channelIds").Concat(a.Has("channelId") ? new[] { a.Text("channelId") } : Array.Empty()) + .Select(id => ToolSupport.Id(s.Library, id)).Distinct().ToArray(); + var from = a.Date("from") ?? DateTimeOffset.UtcNow; var hours = a.Int("hours", 6); + int start = a.Int("start", 0), limit = a.Int("limit", 100); var query = a.Text("query"); var category = a.Text("category"); + var all = Programs(ids, from, from.AddHours(hours)) + .Where(p => query == null || (p.Name + " " + p.SeriesName).IndexOf(query, StringComparison.OrdinalIgnoreCase) >= 0) + .Where(p => category == null || category switch { "movie" => p.IsMovie, "series" => p.IsSeries, "sports" => p.IsSports, "news" => p.IsNews, "kids" => p.IsKids, _ => true }) + .ToList(); + var page = all.Skip(start).Take(limit).Select(p => ProgramRow(p, a.Bool("includeOverview"))).ToArray(); + long next = (long)start + page.Length; + var channelNames = ids.Length == 0 ? null : ids.Select(id => s.Library.GetItemById(id)).Where(c => c != null) + .Select(c => new { id = c.InternalId.ToString(CultureInfo.InvariantCulture), number = Number(c), name = c.Name }).ToArray(); + return new + { + from, to = from.AddHours(hours), channels = channelNames, + total = all.Count, returned = page.Length, hasMore = next < all.Count, nextStart = next < all.Count ? (int?)next : null, + programs = page + }; + } + + public object Recordings() + { + if (s.LiveTv == null) throw new ToolOperationException("Live TV nicht verfügbar."); + var timers = s.LiveTv.GetTimers(new TimerQuery()).Items ?? Array.Empty(); + var series = s.LiveTv.GetSeriesTimers(new SeriesTimerQuery()).Items ?? Array.Empty(); + return new + { + hasActiveRecording = Try(() => (bool?)s.LiveTv.HasActiveRecording), + timers = timers.OrderBy(t => t.StartDate).Select(t => new + { + id = t.Id, name = t.Name, channelId = t.ChannelId, channelNumber = t.ChannelNumber, channelName = t.ChannelName, + start = t.StartDate, end = t.EndDate, status = t.Status.ToString(), seriesTimerId = t.SeriesTimerId, + prePaddingSeconds = t.PrePaddingSeconds, postPaddingSeconds = t.PostPaddingSeconds, keepUntil = t.KeepUntil.ToString() + }).ToArray(), + seriesTimers = series.Select(t => new + { + id = t.Id, name = t.Name, channelName = t.ChannelName, recordAnyChannel = t.RecordAnyChannel, recordAnyTime = t.RecordAnyTime, + recordNewOnly = t.RecordNewOnly, skipEpisodesInLibrary = t.SkipEpisodesInLibrary, keepUpTo = t.KeepUpTo, + days = t.Days?.Select(d => d.ToString()).ToArray(), keepUntil = t.KeepUntil.ToString() + }).ToArray() + }; + } + + static T Try(Func f) { try { return f(); } catch { return default; } } + static string Truncate(string text, int max) => text == null || text.Length <= max ? text : text.Substring(0, max) + "…"; + } +} diff --git a/src/eMCPy/Mcp/ManagementOperations.cs b/src/eMCPy/Mcp/ManagementOperations.cs index 82ae375..4239de2 100644 --- a/src/eMCPy/Mcp/ManagementOperations.cs +++ b/src/eMCPy/Mcp/ManagementOperations.cs @@ -66,7 +66,8 @@ namespace eMCPy.Mcp }).ToArray() }; } - void Journal(object entry) + void Journal(object entry) => Journal(s, entry); + internal static void Journal(EmbyServices s, object entry) { Directory.CreateDirectory(s.StateDirectory); var path = Path.Combine(s.StateDirectory, "actions.jsonl"); diff --git a/src/eMCPy/Mcp/ToolSupport.cs b/src/eMCPy/Mcp/ToolSupport.cs index 0b0b953..5ec2458 100644 --- a/src/eMCPy/Mcp/ToolSupport.cs +++ b/src/eMCPy/Mcp/ToolSupport.cs @@ -32,6 +32,12 @@ namespace eMCPy.Mcp public IFileSystem FileSystem; public MediaBrowser.Controller.Drawing.IImageProcessor Images; public IServerApplicationHost Host; + // Optional (per TryResolve); fehlen sie, melden die betroffenen Werkzeuge "nicht verfügbar". + public MediaBrowser.Controller.Configuration.IServerConfigurationManager ServerConfig; + public MediaBrowser.Model.Activity.IActivityManager Activity; + public MediaBrowser.Common.Updates.IInstallationManager Installation; + public MediaBrowser.Controller.Devices.IDeviceManager Devices; + public MediaBrowser.Controller.LiveTv.ILiveTvManager LiveTv; public Func Configuration; public string StateDirectory; } diff --git a/src/eMCPy/PluginConfiguration.cs b/src/eMCPy/PluginConfiguration.cs index 061c703..15b28ef 100644 --- a/src/eMCPy/PluginConfiguration.cs +++ b/src/eMCPy/PluginConfiguration.cs @@ -30,5 +30,12 @@ namespace eMCPy /// LAN-IPs/localhost und der Origin der ServerUrl sind immer erlaubt. /// public string AllowedOrigins { get; set; } = string.Empty; + + /// + /// Optional: kommagetrennte Task-Keys, die emby_run_task auslösen darf. + /// Leer = alle Aufgaben außer Neustart/Update/Backup/Restore/Löschen. + /// Gesetzt = ausschließlich diese Keys (auch sonst gesperrte). + /// + public string AllowedTaskKeys { get; set; } = string.Empty; } } diff --git a/src/eMCPy/ServiceRegistrar.cs b/src/eMCPy/ServiceRegistrar.cs index 9381cee..ab95fe2 100644 --- a/src/eMCPy/ServiceRegistrar.cs +++ b/src/eMCPy/ServiceRegistrar.cs @@ -36,12 +36,24 @@ namespace eMCPy FileSystem = fileSystem, Images = imageProcessor, Host = serverAppHost, + // Zusätzliche Dienste bewusst per TryResolve statt Konstruktor: + // fehlt einer, bleiben alle übrigen Werkzeuge funktionsfähig. + ServerConfig = Resolve(serverAppHost), + Activity = Resolve(serverAppHost), + Installation = Resolve(serverAppHost), + Devices = Resolve(serverAppHost), + LiveTv = Resolve(serverAppHost), Configuration = () => Plugin.Instance.Configuration, StateDirectory = Plugin.Instance.StateDirectory }; } } + static T Resolve(IServerApplicationHost host) where T : class + { + try { return host?.TryResolve(); } catch { return null; } + } + public void Run() { } public void Dispose() { } diff --git a/src/eMCPy/eMCPy.csproj b/src/eMCPy/eMCPy.csproj index c47951b..7baf3c9 100644 --- a/src/eMCPy/eMCPy.csproj +++ b/src/eMCPy/eMCPy.csproj @@ -3,9 +3,9 @@ net6.0 eMCPy eMCPy - 1.4.2 - 1.4.2 - 1.4.2 + 1.5.0 + 1.5.0 + 1.5.0 false CS1591 diff --git a/tests/eMCPy.Tests/AdminTests.cs b/tests/eMCPy.Tests/AdminTests.cs new file mode 100644 index 0000000..e03a619 --- /dev/null +++ b/tests/eMCPy.Tests/AdminTests.cs @@ -0,0 +1,258 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using eMCPy; +using eMCPy.Mcp; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.Activity; +using MediaBrowser.Model.Devices; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.LiveTv; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Querying; +using MediaBrowser.Model.Tasks; + +public static class AdminTests +{ + public static void Run() + { + int assertions = 0; + void Check(bool ok, string msg) { if (!ok) throw new Exception(msg); assertions++; } + void Fails(Action f, string msg) { bool t = false; try { f(); } catch (ArgumentException) { t = true; } catch (InvalidOperationException) { t = true; } Check(t, msg); } + + var cfg = new PluginConfiguration(); + var state = Path.Combine(Path.GetTempPath(), "emcpy-admin-" + Guid.NewGuid()); + var logs = Path.Combine(state, "logs"); Directory.CreateDirectory(logs); + try + { + // ---------- Aufgaben ---------- + IScheduledTaskWorker Worker(string key, string name, string category, Func st) + { + var task = Fake.Make((m, a) => m.Name switch { "get_Key" => key, "get_Name" => name, "get_Category" => category, _ => null }); + return Fake.Make((m, a) => m.Name switch + { + "get_ScheduledTask" => task, "get_Name" => name, "get_Category" => category, "get_Id" => "id-" + key, + "get_State" => st(), "get_Description" => "desc", "get_CurrentProgress" => (double?)null, "get_Triggers" => new TaskTriggerInfo[0], + "get_LastExecutionResult" => new TaskResult { Status = TaskCompletionStatus.Completed }, _ => null + }); + } + var guideState = TaskState.Idle; + var workers = new[] + { + Worker("RefreshGuide", "Refresh Guide", "Live TV", () => guideState), + Worker("RefreshLibrary", "Scan media library", "Library", () => TaskState.Idle), + Worker("PluginUpdates", "Check for plugin updates", "Application", () => TaskState.Idle), + Worker("DatabaseBackup", "Backup database", "Maintenance", () => TaskState.Idle) + }; + int queued = 0, cancelled = 0; + var services = new EmbyServices { Configuration = () => cfg, StateDirectory = state }; + services.Tasks = Fake.Make((m, a) => + { + if (m.Name == "get_ScheduledTasks") return workers; + if (m.Name == "QueueScheduledTask" && a.Length == 2 && a[0] is IScheduledTask t) { Check(t.Key == "RefreshGuide" || t.Key == "PluginUpdates", "Only intended task queued"); queued++; return null; } + if (m.Name == "Cancel") { cancelled++; return null; } + throw new Exception("Unexpected task call " + m.Name); + }); + var tools = new AdvancedTools(services); + JsonElement Run(string name, object args) => JsonSerializer.SerializeToElement(tools.Execute(name, JsonSerializer.SerializeToElement(args))); + + var list = Run("emby_tasks", new { }); + Check(list.GetProperty("total").GetInt32() == 4, "All tasks listed"); + bool Allowed(JsonElement l, string key) => l.GetProperty("tasks").EnumerateArray().Single(t => t.GetProperty("key").GetString() == key).GetProperty("runAllowed").GetBoolean(); + Check(Allowed(list, "RefreshGuide") && Allowed(list, "RefreshLibrary"), "Guide and library scan allowed by default"); + Check(!Allowed(list, "PluginUpdates") && !Allowed(list, "DatabaseBackup"), "Update and backup blocked by default"); + Check(Run("emby_tasks", new { category = "Live TV" }).GetProperty("total").GetInt32() == 1, "Category filter"); + + Check(Run("emby_run_task", new { key = "RefreshGuide" }).GetProperty("dryRun").GetBoolean() && queued == 0, "Run preview is readonly"); + Fails(() => Run("emby_run_task", new { key = "RefreshGuide", dryRun = false, confirm = true }), "Run needs write enable"); + cfg.EnableWriteTools = true; + Fails(() => Run("emby_run_task", new { key = "RefreshGuide", dryRun = false, confirm = true }), "Run needs API key"); + cfg.ApiKey = "synthetic-key"; + Fails(() => Run("emby_run_task", new { key = "RefreshGuide", dryRun = false }), "Run needs confirm"); + Fails(() => Run("emby_run_task", new { key = "DatabaseBackup", dryRun = false, confirm = true }), "Blocked task refused"); + Fails(() => Run("emby_run_task", new { key = "Nope" }), "Unknown task refused"); + var ran = Run("emby_run_task", new { key = "RefreshGuide", dryRun = false, confirm = true }); + Check(queued == 1 && ran.GetProperty("status").GetString() == "queued", "Task queued once"); + Check(File.ReadAllText(Path.Combine(state, "actions.jsonl")).Contains("run_task"), "Task run journaled"); + guideState = TaskState.Running; + Fails(() => Run("emby_run_task", new { key = "RefreshGuide", dryRun = false, confirm = true }), "Running task not queued twice"); + Run("emby_cancel_task", new { key = "RefreshGuide" }); Check(cancelled == 0, "Cancel preview readonly"); + Run("emby_cancel_task", new { key = "RefreshGuide", dryRun = false, confirm = true }); Check(cancelled == 1, "Cancel sent once"); + guideState = TaskState.Idle; + Fails(() => Run("emby_cancel_task", new { key = "RefreshGuide", dryRun = false, confirm = true }), "Idle task cannot be cancelled"); + cfg.AllowedTaskKeys = "PluginUpdates"; + var restricted = Run("emby_tasks", new { }); + Check(Allowed(restricted, "PluginUpdates") && !Allowed(restricted, "RefreshGuide"), "Explicit allow list overrides defaults"); + Run("emby_run_task", new { key = "PluginUpdates", dryRun = false, confirm = true }); Check(queued == 2, "Allow-listed task queued"); + cfg.AllowedTaskKeys = ""; cfg.EnableWriteTools = false; + + // ---------- Aktivitätsprotokoll ---------- + services.Activity = Fake.Make((m, a) => + { + Check(a.Length == 6, "Activity overload with total count"); + return new QueryResult + { + TotalRecordCount = 5, + Items = new[] + { + new ActivityLogEntry { Id = 1, Name = "Login failed for admin", Type = "AuthenticationFailed", Severity = LogSeverity.Error, Date = DateTimeOffset.UtcNow }, + new ActivityLogEntry { Id = 2, Name = "Michael started playback", Type = "VideoPlayback", Severity = LogSeverity.Info, Date = DateTimeOffset.UtcNow } + } + }; + }); + var act = Run("emby_activity_log", new { limit = 2 }); + Check(act.GetProperty("returned").GetInt32() == 2 && act.GetProperty("hasMore").GetBoolean() && act.GetProperty("nextStart").GetInt32() == 2, "Activity pagination"); + Check(Run("emby_activity_log", new { minSeverity = "Warn" }).GetProperty("returned").GetInt32() == 1, "Severity filter"); + Check(Run("emby_activity_log", new { query = "playback" }).GetProperty("returned").GetInt32() == 1, "Activity text filter"); + Fails(() => Run("emby_activity_log", new { since = "yesterday" }), "Activity since needs ISO timestamp"); + + // ---------- Server-Log ---------- + var paths = Fake.Make((m, a) => m.Name switch + { + "get_LogDirectoryPath" => logs, "get_DataPath" => state, "get_CachePath" => state, "get_TempDirectory" => state, "get_PluginsPath" => Path.Combine(state, "missing"), _ => null + }); + services.ServerConfig = Fake.Make((m, a) => m.Name == "get_ApplicationPaths" ? paths : m.Name == "GetConfiguration" ? LiveTvConfig((string)a[0]) : null); + File.WriteAllText(Path.Combine(logs, "embyserver.txt"), string.Join("\n", new[] + { + "2026-11-22 20:00:00.001 Info Main: Startup complete", + "2026-11-22 20:00:01.002 Info HttpServer: HTTP GET http://192.168.1.2:8096/emby/Items?api_key=SECRETKEY123&X-Emby-Token=TOKEN999", + "2026-11-22 20:00:02.003 Error LiveTV: Error refreshing guide", + "\tSystem.Net.HttpRequestException: 401 for http://iptvuser:iptvpass@iptv.example/xmltv.php?password=PW1", + "\t at Emby.LiveTv.Refresh()", + "2026-11-22 20:00:03.004 Warn Auth: Authorization: MediaBrowser Client=\"x\", Token=\"TOKEN777\"", + "2026-11-22 20:00:04.005 Debug Main: noise" + })); + File.WriteAllText(Path.Combine(logs, "secret.conf"), "not a log"); + var log = Run("emby_server_log", new { }); + var raw = log.GetRawText(); + Check(log.GetProperty("returned").GetInt32() == 5, "All log entries parsed (multi-line merged)"); + Check(!raw.Contains("SECRETKEY123") && !raw.Contains("TOKEN999") && !raw.Contains("iptvpass") && !raw.Contains("PW1") && !raw.Contains("TOKEN777"), "Secrets redacted in log"); + Check(raw.Contains("Error refreshing guide") && raw.Contains("Emby.LiveTv.Refresh"), "Exception stack kept"); + Check(!log.GetProperty("files").EnumerateArray().Any(f => f.GetProperty("name").GetString() == "secret.conf"), "Only .txt/.log files listed"); + var errors = Run("emby_server_log", new { level = "Error" }); + Check(errors.GetProperty("returned").GetInt32() == 1 && errors.GetProperty("entries")[0].GetProperty("level").GetString() == "Error", "Level filter"); + Check(Run("emby_server_log", new { level = "Warn" }).GetProperty("returned").GetInt32() == 2, "Warn includes Error"); + Check(Run("emby_server_log", new { lines = 1 }).GetProperty("entries")[0].GetProperty("text").GetString().Contains("noise"), "Newest entries returned"); + Check(Run("emby_server_log", new { query = "guide" }).GetProperty("returned").GetInt32() == 1, "Log text filter"); + Fails(() => Run("emby_server_log", new { file = "../secret.conf" }), "No path traversal"); + Fails(() => Run("emby_server_log", new { file = "secret.conf" }), "Only listed log files"); + Fails(() => Run("emby_server_log", new { lines = 501 }), "Line limit enforced"); + Check(AdminOperations.Redact("Authorization: Bearer abc.def") == "Authorization: ***", "Authorization header redacted"); + Check(AdminOperations.Redact("password=hunter2&x=1") == "password=***&x=1", "Query password redacted"); + Check(AdminOperations.Redact("\"Password\":\"hunter2\"").Contains("***") && !AdminOperations.Redact("\"Password\":\"hunter2\"").Contains("hunter2"), "JSON password redacted"); + + // ---------- Plugins / Geräte / Speicher ---------- + services.Host = Fake.Make((m, a) => m.Name switch + { + "get_Plugins" => new MediaBrowser.Common.Plugins.IPlugin[0], "get_ApplicationVersion" => new Version(4, 9, 5, 0), "get_HasUpdateAvailable" => false, "get_HasPendingRestart" => false, _ => null + }); + var plugins = Run("emby_plugins", new { }); + Check(plugins.GetProperty("serverVersion").GetString() == "4.9.5.0" && plugins.GetProperty("updateStatus").GetString() == "not_checked", "Plugins without internet by default"); + Check(Run("emby_plugins", new { checkUpdates = true }).GetProperty("updateStatus").GetString() == "unavailable", "Missing installation manager reported honestly"); + + services.Devices = Fake.Make((m, a) => + { + var q = (DeviceQuery)a[0]; Check(q.Limit == 2 && q.StartIndex == 0, "Device paging passed through"); + return new QueryResult { TotalRecordCount = 3, Items = new[] { new DeviceInfo { InternalId = 1, Name = "TV", AppName = "Emby for Android TV", DateLastActivity = DateTimeOffset.UtcNow }, new DeviceInfo { InternalId = 2, Name = "Old", DateLastActivity = DateTimeOffset.UtcNow.AddDays(-400) } } }; + }); + var devices = Run("emby_devices", new { limit = 2, activeWithinDays = 30 }); + Check(devices.GetProperty("returned").GetInt32() == 1 && devices.GetProperty("hasMore").GetBoolean(), "Device activity filter and paging"); + + var library = new List(); + var channels = new[] { new LiveTvChannel { InternalId = 501, Name = "Das Erste", Number = "1" }, new LiveTvChannel { InternalId = 502, Name = "ZDF", Number = "2" }, new LiveTvChannel { InternalId = 510, Name = "Ohne EPG", Number = "10" } }; + var now = DateTimeOffset.UtcNow; + var programs = new[] + { + new LiveTvProgram { InternalId = 601, ParentId = 501, Name = "Tagesschau", StartDate = now.AddMinutes(-10), EndDate = now.AddMinutes(5), IsNews = true }, + new LiveTvProgram { InternalId = 602, ParentId = 501, Name = "Tatort", StartDate = now.AddMinutes(5), EndDate = now.AddMinutes(95), IsSeries = true, Overview = new string('x', 1000) }, + new LiveTvProgram { InternalId = 603, ParentId = 502, Name = "Fußball", StartDate = now.AddHours(2), EndDate = now.AddHours(4), IsSports = true }, + new LiveTvProgram { InternalId = 604, ParentId = 502, Name = "Spielfilm", StartDate = now.AddHours(30), EndDate = now.AddHours(32), IsMovie = true } + }; + int programQueries = 0; + services.Library = Fake.Make((m, a) => + { + switch (m.Name) + { + case "GetItemsResult": + var q = (InternalItemsQuery)a[0]; + if (q.IncludeItemTypes.SequenceEqual(new[] { "TvChannel" })) return new QueryResult { Items = channels.Cast().Reverse().ToArray() }; + Check(q.IncludeItemTypes.SequenceEqual(new[] { "Program" }) && q.MinEndDate.HasValue && q.MaxStartDate.HasValue, "Program query bounded by time window"); + programQueries++; + return new QueryResult { Items = programs.Where(p => (q.ParentIds == null || q.ParentIds.Length == 0 || q.ParentIds.Contains(p.ParentId)) && p.EndDate > q.MinEndDate && p.StartDate <= q.MaxStartDate).Cast().ToArray() }; + case "GetItemById": return channels.FirstOrDefault(c => c.InternalId == (long)a[0]); + case "GetVirtualFolders": return new List { new VirtualFolderInfo { Name = "Filme", Locations = new[] { state, Path.Combine(state, "gone") } } }; + default: throw new Exception("Unexpected library call " + m.Name); + } + }); + var storage = Run("emby_storage", new { includeDirectorySizes = true }); + var locs = storage.GetProperty("locations").EnumerateArray().ToArray(); + var stateRow = locs.Single(l => l.GetProperty("path").GetString() == state); + Check(stateRow.GetProperty("status").GetString() == "ok" && stateRow.GetProperty("totalBytes").GetInt64() > 0, "Storage measured"); + Check(stateRow.GetProperty("roles").EnumerateArray().Any(r => r.GetString() == "library:Filme") && stateRow.GetProperty("roles").EnumerateArray().Any(r => r.GetString() == "data"), "Same path merged with roles"); + Check(stateRow.GetProperty("directorySize").GetProperty("files").GetInt32() >= 1, "Non-library sizes counted"); + Check(locs.Any(l => l.GetProperty("status").GetString() == "missing_or_not_accessible"), "Missing path reported"); + + // ---------- Live TV ---------- + int timerCalls = 0; + services.LiveTv = Fake.Make((m, a) => m.Name switch + { + "GetGuideInfo" => new GuideInfo { StartDate = now.AddDays(-1), EndDate = now.AddDays(7) }, + "get_HasActiveRecording" => (object)false, + "GetTimers" => (timerCalls++ >= 0 ? new QueryResult { Items = new[] { new TimerInfoDto { Id = "t1", Name = "Tatort", ChannelName = "Das Erste", StartDate = now.AddMinutes(5), EndDate = now.AddMinutes(95) } } } : null), + "GetSeriesTimers" => new QueryResult { Items = new[] { new SeriesTimerInfoDto { Id = "s1", Name = "Tatort", RecordNewOnly = true, Days = new[] { DayOfWeek.Sunday } } } }, + _ => throw new Exception("Unexpected live tv call " + m.Name) + }); + var status = Run("emby_livetv_status", new { }); + var statusRaw = status.GetRawText(); + Check(status.GetProperty("channels").GetInt32() == 3 && status.GetProperty("channelsWithProgramNow").GetInt32() == 1, "EPG coverage now"); + Check(status.GetProperty("tuners")[0].GetProperty("source").GetString() == "http://iptv.example:8080", "Tuner shows host only"); + Check(!statusRaw.Contains("iptvuser") && !statusRaw.Contains("geheim") && !statusRaw.Contains("get.php") && !statusRaw.Contains("epguser") && !statusRaw.Contains("Mozilla"), "No tuner/EPG credentials or options"); + Check(status.GetProperty("guideProviders")[0].GetProperty("source").GetString() == "https://epg.example", "Guide provider host only"); + Check(status.GetProperty("refreshGuideTaskKey").GetString() == "RefreshGuide", "Guide refresh task discovered"); + + var ch = Run("emby_livetv_channels", new { }); + Check(ch.GetProperty("channels")[0].GetProperty("name").GetString() == "Das Erste" && ch.GetProperty("channels")[2].GetProperty("number").GetString() == "10", "Channels sorted numerically"); + Check(ch.GetProperty("channels")[0].GetProperty("now").GetProperty("title").GetString() == "Tagesschau" && ch.GetProperty("channels")[0].GetProperty("next").GetProperty("title").GetString() == "Tatort", "Now/next"); + Check(ch.GetProperty("channels")[1].GetProperty("guideStatus").GetString() == "gap_now" && ch.GetProperty("channels")[2].GetProperty("guideStatus").GetString() == "no_programs_next_24h", "Guide status per channel"); + var noGuide = Run("emby_livetv_channels", new { onlyWithoutGuide = true }); + Check(noGuide.GetProperty("returned").GetInt32() == 2, "Only channels with guide problems"); + Check(Run("emby_livetv_channels", new { query = "2" }).GetProperty("channels")[0].GetProperty("name").GetString() == "ZDF", "Exact number search"); + int before = programQueries; Run("emby_livetv_channels", new { limit = 2 }); Check(programQueries == before + 1, "One bulk program query per channel page"); + + var guide = Run("emby_livetv_guide", new { channelId = "501", hours = 3, includeOverview = true }); + Check(guide.GetProperty("total").GetInt32() == 2 && guide.GetProperty("programs")[1].GetProperty("overview").GetString().Length <= 401, "Guide per channel, overview truncated"); + Check(Run("emby_livetv_guide", new { hours = 6, category = "sports" }).GetProperty("programs")[0].GetProperty("title").GetString() == "Fußball", "Category filter"); + Check(Run("emby_livetv_guide", new { hours = 72, query = "film" }).GetProperty("total").GetInt32() == 1, "Guide text filter and wider window"); + Fails(() => Run("emby_livetv_guide", new { hours = 73 }), "Guide window bounded"); + Fails(() => Run("emby_livetv_guide", new { from = "heute" }), "Guide from needs ISO timestamp"); + + var rec = Run("emby_livetv_recordings", new { }); + Check(rec.GetProperty("timers")[0].GetProperty("name").GetString() == "Tatort" && rec.GetProperty("seriesTimers")[0].GetProperty("days")[0].GetString() == "Sunday", "Timers and series timers"); + + Check(LiveTvOperations.HostOnly("/config/m3u/sender.m3u") == "local:sender.m3u", "Local tuner file shows name only"); + + // ---------- Schemas ---------- + foreach (var name in new[] { "emby_tasks", "emby_run_task", "emby_cancel_task", "emby_activity_log", "emby_server_log", "emby_plugins", "emby_devices", "emby_storage", "emby_livetv_status", "emby_livetv_channels", "emby_livetv_guide", "emby_livetv_recordings" }) + Check(AdvancedSchemas.IsKnown(name), "Schema registered: " + name); + var defs = JsonSerializer.SerializeToElement(AdvancedSchemas.Definitions()); + bool Destructive(string n) => defs.EnumerateArray().Single(d => d.GetProperty("name").GetString() == n).GetProperty("annotations").GetProperty("destructiveHint").GetBoolean(); + Check(Destructive("emby_run_task") && Destructive("emby_cancel_task") && !Destructive("emby_server_log") && !Destructive("emby_livetv_guide"), "Annotations mark only task actions as writes"); + + Console.WriteLine($"PASS admin/livetv: {assertions} assertions; only test doubles used."); + } + finally { if (Directory.Exists(state)) Directory.Delete(state, true); } + + object LiveTvConfig(string key) => key == "livetv" ? new LiveTvOptions + { + GuideDays = 7, + TunerHosts = new[] { new TunerHostInfo { Id = "tuner1", Type = "m3u", FriendlyName = "IPTV", Url = "http://iptvuser:geheim@iptv.example:8080/get.php?username=iptvuser&password=geheim", TunerCount = 2, UserAgent = "Mozilla/5.0", ProviderOptions = "{\"password\":\"geheim\"}" } }, + ListingProviders = new[] { new ListingsProviderInfo { Id = "epg1", Type = "xmltv", Name = "XMLTV", Path = "https://epg.example/xmltv.php?username=epguser&password=geheim", Username = "epguser", Password = "geheim" } } + } : throw new InvalidOperationException("no config " + key); + } +} diff --git a/tests/eMCPy.Tests/Program.cs b/tests/eMCPy.Tests/Program.cs index 7c36754..324ecf5 100644 --- a/tests/eMCPy.Tests/Program.cs +++ b/tests/eMCPy.Tests/Program.cs @@ -132,9 +132,10 @@ foreach(var t in tools.EnumerateArray()) if(t.GetProperty("inputSchema").GetProp rows.Clear(); var emptySeries=Run(new {seriesId="100"}); Check(emptySeries.GetProperty("total").GetInt32()==0 && emptySeries.GetProperty("returned").GetInt32()==0 && !emptySeries.GetProperty("hasMore").GetBoolean(), "Empty series"); -Check(typeof(SeriesInventory).Assembly.GetName().Version.ToString(3)=="1.4.2", "Release version"); +Check(typeof(SeriesInventory).Assembly.GetName().Version.ToString(3)=="1.5.0", "Release version"); AdvancedTests.Run(); ProtocolTests.Run(); +AdminTests.Run(); InventoryReplay.Run(); Console.WriteLine($"PASS: {passed} assertions; 35 episodes in 5 pages, no per-episode detail lookup.");