diff --git a/README.md b/README.md index a920adf..fac40d9 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ## Status -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.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). Neu außerdem: Selbst-Update über das Gitea-Repository ([docs/self-update.md](docs/self-update.md)). 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. @@ -98,7 +98,7 @@ Emby's `IJsonSerializer` ist **Newtonsoft**. `DeserializeFromString(body, typeof - [x] Erste Tools: `emby_server_info`, `emby_search`, `emby_now_playing`, `emby_get_item` - [x] Live-Deploy & Verifikation (Emby 4.9.5.0, Unraid) - [x] Dashboard-Config-Seite (Port, API-Key) -- [ ] Build-Pipeline + Deploy-Skript für Unraid +- [x] Release-Skript (`scripts/make-release.sh`) und Selbst-Update über `releases/latest.json` - [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 diff --git a/docs/self-update.md b/docs/self-update.md new file mode 100644 index 0000000..c668bee --- /dev/null +++ b/docs/self-update.md @@ -0,0 +1,52 @@ +# Selbst-Update (ab 1.5.0) + +Embys eigene Plugin-Updates gelten nur für Plugins aus dem offiziellen Emby-Katalog. +eMCPy aktualisiert sich deshalb selbst – auf demselben Weg wie Embys Updater: +neue DLL in den Plugin-Ordner legen und „Neustart erforderlich“ melden. +**Den Neustart löst du selbst aus** (Dashboard → Neustart), z. B. wenn niemand schaut. + +## Ablauf + +Geplante Aufgabe **„eMCPy: Nach Updates suchen“** (Kategorie Anwendung, Key `EmcpyUpdateCheck`), +täglich 04:00 und nach jedem Start, manuell unter *Geplante Aufgaben* startbar: + +1. `releases/latest.json` von der Update-URL laden (mit Gitea-Token). +2. Nur wenn die Version höher ist als die laufende: DLL vom **selben Host** laden. +3. Prüfen: SHA256 aus `latest.json`, Assemblyname `eMCPy`, Assemblyversion = Feedversion. +4. Bisherige DLL nach `data/emcpy/backup/` sichern (außerhalb des Plugin-Ordners, max. 3). +5. DLL atomar ersetzen, Neustart als erforderlich melden. + +Fehlschläge ändern nichts am installierten Plugin. Status steht im Emby-Log und in +`emby_plugins` → `emcpySelfUpdate` (`up_to_date`, `update_available`, +`installed_restart_pending`, `auth_required_or_not_found`, `checksum_mismatch`, …). + +## Einrichtung + +1. In Gitea: *Einstellungen → Anwendungen → Zugriffstoken*, Berechtigung `read:repository`. +2. Im Plugin unter *Automatische Updates* den Token eintragen. Die Update-URL ist + vorbelegt mit `https://git.casaderoll.de/michael/eMCPy/raw/branch/main/releases/latest.json`. +3. Optional „automatisch installieren“ abschalten → es wird nur gemeldet. + +Der Emby-Container muss `git.casaderoll.de` erreichen. Klappt das aus dem Docker-Netz +nicht (Hairpin-NAT), stattdessen die LAN-Adresse von Gitea per HTTP eintragen, +z. B. `http://192.168.1.2:/michael/eMCPy/raw/branch/main/releases/latest.json` +(HTTP ist nur zu privaten IPs erlaubt). + +## Sicherheit + +- Feed nur HTTPS bzw. HTTP zu privater IP, keine Weiterleitungen, DLL nur vom Feed-Host; + der Token wird nirgends sonst hin gesendet und nie ausgegeben. +- SHA256 schützt vor kaputten Downloads, **nicht** vor einem kompromittierten Gitea: + Wer in das Repository schreiben kann, kann Code auf dem Emby-Server ausführen. + Gitea-Konto entsprechend absichern. +- Nie Downgrades. Ein manueller Rollback wird erkannt; dann wird die neuere Version beim + nächsten Lauf erneut installiert – zum Festhalten einer alten Version + „automatisch installieren“ abschalten. +- `emby_run_task` kann diese Aufgabe standardmäßig nicht starten („update“ ist gesperrt). + +## Neues Release veröffentlichen + +1. `` in `src/eMCPy/eMCPy.csproj` erhöhen. +2. `scripts/make-release.sh "Änderungsnotiz"` – Tests, Build, `releases//`, `SHA256SUMS`, + `releases/latest.json`. +3. Committen und auf `main` pushen. Server holen die Version bei der nächsten Prüfung. diff --git a/releases/1.5.0/INSTALL.md b/releases/1.5.0/INSTALL.md index c5cda82..c12cf57 100644 --- a/releases/1.5.0/INSTALL.md +++ b/releases/1.5.0/INSTALL.md @@ -9,6 +9,12 @@ - Live TV, lesend: `emby_livetv_status`, `emby_livetv_channels`, `emby_livetv_guide`, `emby_livetv_recordings`. +Außerdem neu: **Selbst-Update** (siehe [docs/self-update.md](../../docs/self-update.md)) – +geplante Aufgabe „eMCPy: Nach Updates suchen“, prüft täglich `releases/latest.json`, installiert +geprüft und meldet „Neustart erforderlich“. Für das private Repo im Plugin einen Gitea-Token +mit `read:repository` eintragen. **Dies ist das letzte manuelle Update.** +JSON-RPC: Die `id` behält ihren Typ (vorher wurde aus `1` ein `"1"`). + 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. @@ -42,6 +48,8 @@ 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. +631 Assertions (372 Serieninventar, 97 Advanced, 40 Protokoll, 88 Admin/Live TV, +34 Selbst-Update/id), nur Test-Doubles für Aktionen und Downloads; HTTP-Smoke-Test: 49 Werkzeuge gelistet, Origin-Block, 405, ping. +Noch nicht auf dem Live-Server installiert; Live-TV-Abfragen und der Download aus Gitea +sind nur gegen Test-Doubles geprüft. Nach der Installation unter Geplante Aufgaben +„eMCPy: Nach Updates suchen“ einmal starten: erwartet ist Status `up_to_date`. diff --git a/releases/1.5.0/SHA256SUMS b/releases/1.5.0/SHA256SUMS index ef7c99e..6ef891b 100644 --- a/releases/1.5.0/SHA256SUMS +++ b/releases/1.5.0/SHA256SUMS @@ -1 +1 @@ -0ef04d721466f8dc4e6d832d9bfd5d6ed6c56520190e658cab2ead1423194ee0 eMCPy.dll +fc61bf002507f7c9016c1ead9c09494cb21588151aa1ef4daffc34112307089c eMCPy.dll diff --git a/releases/1.5.0/eMCPy.dll b/releases/1.5.0/eMCPy.dll index 4aee5bc..118bc23 100644 Binary files a/releases/1.5.0/eMCPy.dll and b/releases/1.5.0/eMCPy.dll differ diff --git a/releases/latest.json b/releases/latest.json new file mode 100644 index 0000000..c104046 --- /dev/null +++ b/releases/latest.json @@ -0,0 +1,7 @@ +{ + "version": "1.5.0", + "url": "1.5.0/eMCPy.dll", + "sha256": "fc61bf002507f7c9016c1ead9c09494cb21588151aa1ef4daffc34112307089c", + "minServerVersion": "4.9.0.0", + "notes": "Admin-, Aufgaben- und Live-TV-Werkzeuge, Selbst-Update, Sicherheits- und Protokollfixes." +} diff --git a/scripts/make-release.sh b/scripts/make-release.sh new file mode 100755 index 0000000..fa62d9c --- /dev/null +++ b/scripts/make-release.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Baut ein Release und aktualisiert den Update-Feed für das eMCPy-Selbst-Update. +# scripts/make-release.sh "Kurze Änderungsnotiz" +# Version kommt aus src/eMCPy/eMCPy.csproj (). Vorher dort erhöhen. +# Danach committen und pushen; Server mit eMCPy >= 1.5.0 holen die Version bei der nächsten Prüfung. +set -euo pipefail +cd "$(dirname "$0")/.." +notes="${1:-}" +version="$(sed -n 's:.*\(.*\).*:\1:p' src/eMCPy/eMCPy.csproj | head -1)" +[ -n "$version" ] || { echo "Version nicht gefunden" >&2; exit 1; } +if [ -e "releases/$version/eMCPy.dll" ]; then echo "releases/$version existiert bereits – Version erhöhen." >&2; exit 1; fi + +dotnet run --project tests/eMCPy.Tests +rm -rf dist +dotnet publish src/eMCPy/eMCPy.csproj -c Release -o dist >/dev/null +mkdir -p "releases/$version" +cp dist/eMCPy.dll "releases/$version/eMCPy.dll" +if command -v sha256sum >/dev/null; then sha="$(sha256sum "releases/$version/eMCPy.dll" | cut -d' ' -f1)"; else sha="$(shasum -a 256 "releases/$version/eMCPy.dll" | cut -d' ' -f1)"; fi +echo "$sha eMCPy.dll" > "releases/$version/SHA256SUMS" + +python3 - "$version" "$sha" "$notes" <<'PY' +import json, sys +version, sha, notes = sys.argv[1:4] +feed = {"version": version, "url": f"{version}/eMCPy.dll", "sha256": sha, "minServerVersion": "4.9.0.0", "notes": notes} +with open("releases/latest.json", "w", encoding="utf-8") as f: + json.dump(feed, f, ensure_ascii=False, indent=2); f.write("\n") +PY +[ -e "releases/$version/INSTALL.md" ] || printf '# eMCPy %s\n\n%s\n\nInstallation automatisch über „eMCPy: Nach Updates suchen“ (danach Emby neu starten) oder manuell: DLL nach plugins/ kopieren, Emby neu starten.\n' "$version" "$notes" > "releases/$version/INSTALL.md" +echo "Release $version gebaut, SHA256 $sha, releases/latest.json aktualisiert." diff --git a/src/eMCPy/Configuration/configPage.html b/src/eMCPy/Configuration/configPage.html index ea179fa..12e894c 100644 --- a/src/eMCPy/Configuration/configPage.html +++ b/src/eMCPy/Configuration/configPage.html @@ -104,6 +104,32 @@ +

Automatische Updates

+ +
+ +
Geplante Aufgabe „eMCPy: Nach Updates suchen“ (täglich 04:00 und nach dem Start, unter Geplante Aufgaben auch manuell startbar).
+
+ +
+ +
Die DLL wird geprüft (SHA256, Name, Version) und ersetzt; Emby meldet danach „Neustart erforderlich“. Den Neustart löst du selbst aus. Aus = nur melden.
+
+ +
+ + +
HTTPS-Adresse von releases/latest.json im Repository (HTTP nur zu einer LAN-IP).
+
+ +
+ + +
Für private Repositories nötig: in Gitea unter Einstellungen → Anwendungen einen Token mit read:repository erstellen. Wird nur an den Host der Update-URL gesendet.
+
+
Status wird geladen …
diff --git a/src/eMCPy/Configuration/configPage.js b/src/eMCPy/Configuration/configPage.js index 29b3352..5ccec3e 100644 --- a/src/eMCPy/Configuration/configPage.js +++ b/src/eMCPy/Configuration/configPage.js @@ -86,6 +86,10 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) { view.querySelector('#serverUrl').value = config.ServerUrl || ''; view.querySelector('#allowedOrigins').value = config.AllowedOrigins || ''; view.querySelector('#allowedTaskKeys').value = config.AllowedTaskKeys || ''; + view.querySelector('#enableAutoUpdate').checked = config.EnableAutoUpdate !== false; + view.querySelector('#autoInstallUpdates').checked = config.AutoInstallUpdates !== false; + view.querySelector('#updateFeedUrl').value = config.UpdateFeedUrl || ''; + view.querySelector('#updateToken').value = config.UpdateToken || ''; this.checkServerStatus(view, config); loading.hide(); }).catch(() => { @@ -116,6 +120,10 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) { config.ServerUrl = view.querySelector('#serverUrl').value.trim(); config.AllowedOrigins = view.querySelector('#allowedOrigins').value.trim(); config.AllowedTaskKeys = view.querySelector('#allowedTaskKeys').value.trim(); + config.EnableAutoUpdate = view.querySelector('#enableAutoUpdate').checked; + config.AutoInstallUpdates = view.querySelector('#autoInstallUpdates').checked; + config.UpdateFeedUrl = view.querySelector('#updateFeedUrl').value.trim(); + config.UpdateToken = view.querySelector('#updateToken').value.trim(); updatePluginConfiguration(config).then(result => { loading.hide(); diff --git a/src/eMCPy/Mcp/AdminOperations.cs b/src/eMCPy/Mcp/AdminOperations.cs index ac44c13..bce379f 100644 --- a/src/eMCPy/Mcp/AdminOperations.cs +++ b/src/eMCPy/Mcp/AdminOperations.cs @@ -282,10 +282,25 @@ namespace eMCPy.Mcp updateStatus, updates, currentInstallations = installing, + emcpySelfUpdate = SelfUpdateInfo(), note = "Nur lesend. Plugin-Updates installiert die Aufgabe für Plugin-Updates (standardmäßig gesperrt)." }; } + object SelfUpdateInfo() + { + var cfg = s.Configuration(); + var st = s.StateDirectory == null ? null : Update.SelfUpdater.ReadStatus(s.StateDirectory); + return new + { + enabled = cfg.EnableAutoUpdate, + autoInstall = cfg.AutoInstallUpdates, + tokenConfigured = !string.IsNullOrWhiteSpace(cfg.UpdateToken), + taskKey = Update.UpdateTask.TaskKey, + lastCheck = st == null ? null : new { checkedAt = st.CheckedAt, state = st.State, message = st.Message, runningVersion = st.RunningVersion, availableVersion = st.AvailableVersion, installedVersion = st.InstalledVersion, backupFile = st.BackupFile, notes = st.Notes } + }; + } + // ---------- Geräte ---------- public object Devices(ToolArgs a) diff --git a/src/eMCPy/Mcp/McpToolRegistry.cs b/src/eMCPy/Mcp/McpToolRegistry.cs index b9a9e0f..93f1011 100644 --- a/src/eMCPy/Mcp/McpToolRegistry.cs +++ b/src/eMCPy/Mcp/McpToolRegistry.cs @@ -1099,17 +1099,36 @@ namespace eMCPy.Mcp ["result"] = result }; if (id.ValueKind != JsonValueKind.Undefined) - d["id"] = id; + d["id"] = IdValue(id); return d; } + /// + /// JSON-RPC verlangt dieselbe id (inkl. Typ) in der Antwort. Embys Serializer gibt ein + /// JsonElement als Text aus (1 → "1"), daher hier in einen einfachen .NET-Wert umwandeln. + /// + public static object IdValue(JsonElement id) + { + switch (id.ValueKind) + { + case JsonValueKind.Number: + if (id.TryGetInt64(out var l)) return l; + if (id.TryGetDecimal(out var m)) return m; + return id.GetDouble(); + case JsonValueKind.String: + return id.GetString(); + default: + return null; + } + } + private static object RpcError(JsonElement id, int code, string message) { return new Dictionary { ["jsonrpc"] = "2.0", ["error"] = new { code, message }, - ["id"] = id + ["id"] = IdValue(id) }; } } diff --git a/src/eMCPy/PluginConfiguration.cs b/src/eMCPy/PluginConfiguration.cs index 15b28ef..5c69cc5 100644 --- a/src/eMCPy/PluginConfiguration.cs +++ b/src/eMCPy/PluginConfiguration.cs @@ -37,5 +37,17 @@ namespace eMCPy /// Gesetzt = ausschließlich diese Keys (auch sonst gesperrte). /// public string AllowedTaskKeys { get; set; } = string.Empty; + + /// Tägliche Prüfung auf neue eMCPy-Versionen (geplante Aufgabe „eMCPy: Nach Updates suchen“). + public bool EnableAutoUpdate { get; set; } = true; + + /// true = neue Version geprüft installieren und Neustart melden; false = nur melden. + public bool AutoInstallUpdates { get; set; } = true; + + /// URL zu releases/latest.json (HTTPS, oder HTTP zu privater LAN-IP). + public string UpdateFeedUrl { get; set; } = "https://git.casaderoll.de/michael/eMCPy/raw/branch/main/releases/latest.json"; + + /// Gitea-Zugriffstoken mit Leserecht auf das Repository (nötig, da privat). Wird nie ausgegeben. + public string UpdateToken { get; set; } = string.Empty; } } diff --git a/src/eMCPy/Update/SelfUpdater.cs b/src/eMCPy/Update/SelfUpdater.cs new file mode 100644 index 0000000..6b63dec --- /dev/null +++ b/src/eMCPy/Update/SelfUpdater.cs @@ -0,0 +1,224 @@ +using System; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Reflection; +using System.Security.Cryptography; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading; +using eMCPy.Mcp; + +namespace eMCPy.Update +{ + /// Inhalt von releases/latest.json im eMCPy-Repository. + public sealed class UpdateFeed + { + [JsonPropertyName("version")] public string Version { get; set; } + [JsonPropertyName("url")] public string Url { get; set; } + [JsonPropertyName("sha256")] public string Sha256 { get; set; } + [JsonPropertyName("minServerVersion")] public string MinServerVersion { get; set; } + [JsonPropertyName("notes")] public string Notes { get; set; } + } + + public sealed class UpdateStatus + { + public DateTimeOffset CheckedAt { get; set; } + public string State { get; set; } + public string Message { get; set; } + public string RunningVersion { get; set; } + public string AvailableVersion { get; set; } + public string InstalledVersion { get; set; } + public string Sha256 { get; set; } + public string Notes { get; set; } + public string BackupFile { get; set; } + } + + /// + /// Selbst-Update wie Embys eigener Plugin-Updater: neue DLL prüfen, in den Plugin-Ordner legen, + /// Neustart als erforderlich melden. Der Neustart selbst bleibt beim Admin. + /// Sicherheitsregeln: Feed nur per HTTPS (oder HTTP auf privater/Loopback-IP), DLL nur vom selben + /// Host wie der Feed (der Token geht nur dorthin), keine Weiterleitungen, Größenlimits, + /// SHA256 aus dem Feed, Assemblyname/-version müssen passen, nur höhere Versionen. + /// + public sealed class SelfUpdater + { + public const string StatusFileName = "update-status.json"; + const long MaxFeedBytes = 64 * 1024, MaxDllBytes = 20 * 1024 * 1024; + static readonly object Gate = new object(); + + readonly HttpMessageHandler handler; + readonly Func config; + readonly string assemblyPath, stateDirectory; + readonly Version running, server; + readonly Action notifyRestart; + readonly Action log; + + public SelfUpdater(HttpMessageHandler handler, Func config, string assemblyPath, Version running, + Version server, string stateDirectory, Action notifyRestart, Action log = null) + { + this.handler = handler; this.config = config; this.assemblyPath = assemblyPath; this.running = running; + this.server = server; this.stateDirectory = stateDirectory; this.notifyRestart = notifyRestart; this.log = log ?? (_ => { }); + } + + public static UpdateStatus ReadStatus(string stateDirectory) + { + try + { + var path = Path.Combine(stateDirectory, StatusFileName); + return File.Exists(path) ? JsonSerializer.Deserialize(File.ReadAllText(path)) : null; + } + catch { return null; } + } + + public UpdateStatus Run(CancellationToken ct) + { + lock (Gate) + { + UpdateStatus status; + try { status = RunCore(ct); } + catch (OperationCanceledException) { status = Status("error", "Zeitüberschreitung oder abgebrochen."); } + catch (UpdateException ex) { status = Status(ex.State, ex.Message); } + catch (Exception ex) { status = Status("error", "Update fehlgeschlagen: " + ex.GetType().Name); } + Save(status); + log("[eMCPy] Update-Prüfung: " + status.State + " – " + status.Message); + return status; + } + } + + UpdateStatus RunCore(CancellationToken ct) + { + var cfg = config(); + if (!cfg.EnableAutoUpdate) return Status("disabled", "Update-Prüfung ist deaktiviert."); + if (string.IsNullOrWhiteSpace(cfg.UpdateFeedUrl)) return Status("not_configured", "Keine Update-URL konfiguriert."); + var feedUri = ValidateFeedUrl(cfg.UpdateFeedUrl.Trim()); + + // Bereits installiert, Neustart steht noch aus → nichts erneut herunterladen. + var previous = ReadStatus(stateDirectory); + if (previous?.State == "installed_restart_pending" && Version.TryParse(previous.InstalledVersion, out var pending) && pending > running && OnDiskVersion() == Normalize(pending)) + return Status("installed_restart_pending", "Version " + previous.InstalledVersion + " ist installiert; Emby-Neustart erforderlich.", previous.InstalledVersion, previous.InstalledVersion); + + using var client = CreateClient(cfg.UpdateToken); + var feedBytes = Download(client, feedUri, MaxFeedBytes, ct); + UpdateFeed feed; + try { feed = JsonSerializer.Deserialize(feedBytes); } + catch (JsonException) { throw new UpdateException("invalid_feed", "latest.json ist kein gültiges JSON."); } + if (feed == null || !Version.TryParse(feed.Version, out var available)) throw new UpdateException("invalid_feed", "latest.json ohne gültige Version."); + var sha = (feed.Sha256 ?? "").Trim().ToLowerInvariant(); + if (sha.Length != 64 || !sha.All(Uri.IsHexDigit)) throw new UpdateException("invalid_feed", "latest.json ohne gültigen SHA256-Wert."); + + if (Normalize(available) <= Normalize(running)) + return Status("up_to_date", "Aktuell (" + running.ToString(3) + ").", feed.Version, notes: feed.Notes); + if (!string.IsNullOrWhiteSpace(feed.MinServerVersion) && Version.TryParse(feed.MinServerVersion, out var minServer) && server != null && server < minServer) + return Status("server_too_old", "Version " + feed.Version + " benötigt Emby " + feed.MinServerVersion + ".", feed.Version, notes: feed.Notes); + if (!cfg.AutoInstallUpdates) + return Status("update_available", "Version " + feed.Version + " verfügbar; automatische Installation ist aus.", feed.Version, sha: sha, notes: feed.Notes); + + if (string.IsNullOrWhiteSpace(feed.Url)) throw new UpdateException("invalid_feed", "latest.json ohne url."); + var dllUri = new Uri(feedUri, feed.Url); + if (dllUri.Scheme != feedUri.Scheme || !string.Equals(dllUri.Host, feedUri.Host, StringComparison.OrdinalIgnoreCase) || dllUri.Port != feedUri.Port) + throw new UpdateException("invalid_feed", "DLL muss vom selben Host wie latest.json kommen."); + + var dll = Download(client, dllUri, MaxDllBytes, ct); + var actual = Convert.ToHexString(SHA256.HashData(dll)).ToLowerInvariant(); + if (actual != sha) throw new UpdateException("checksum_mismatch", "SHA256 der heruntergeladenen DLL passt nicht zu latest.json."); + + var pluginDir = Path.GetDirectoryName(assemblyPath) ?? throw new UpdateException("error", "Plugin-Pfad unbekannt."); + var temp = Path.Combine(pluginDir, Path.GetFileName(assemblyPath) + ".download"); + File.WriteAllBytes(temp, dll); + try + { + AssemblyName name; + try { name = AssemblyName.GetAssemblyName(temp); } + catch (BadImageFormatException) { throw new UpdateException("invalid_assembly", "Download ist keine .NET-Assembly."); } + if (!string.Equals(name.Name, "eMCPy", StringComparison.Ordinal) || name.Version == null || Normalize(name.Version) != Normalize(available)) + throw new UpdateException("invalid_assembly", "Assembly passt nicht (Name/Version " + name.Name + " " + name.Version + ")."); + + var backupDir = Path.Combine(stateDirectory, "backup"); + Directory.CreateDirectory(backupDir); + var backup = Path.Combine(backupDir, "eMCPy-" + running.ToString(3) + ".dll"); + if (File.Exists(assemblyPath)) File.Copy(assemblyPath, backup, true); + foreach (var old in new DirectoryInfo(backupDir).GetFiles("eMCPy-*.dll").OrderByDescending(f => f.LastWriteTimeUtc).Skip(3)) old.Delete(); + + // Atomarer Austausch im selben Verzeichnis; die laufende Version bleibt bis zum Neustart geladen. + File.Move(temp, assemblyPath, true); + notifyRestart?.Invoke(); + return Status("installed_restart_pending", "Version " + feed.Version + " installiert; Emby-Neustart erforderlich.", feed.Version, feed.Version, sha, feed.Notes, Path.GetFileName(backup)); + } + finally { if (File.Exists(temp)) File.Delete(temp); } + } + + Version OnDiskVersion() + { + try { var v = AssemblyName.GetAssemblyName(assemblyPath).Version; return v == null ? null : Normalize(v); } catch { return null; } + } + + static Version Normalize(Version v) => new Version(v.Major, Math.Max(0, v.Minor), Math.Max(0, v.Build)); + + public static Uri ValidateFeedUrl(string url) + { + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) throw new UpdateException("not_configured", "Update-URL ist ungültig."); + if (!string.IsNullOrEmpty(uri.UserInfo)) throw new UpdateException("not_configured", "Update-URL darf keine Zugangsdaten enthalten; Token-Feld verwenden."); + if (uri.Scheme == Uri.UriSchemeHttps) return uri; + if (uri.Scheme == Uri.UriSchemeHttp && IPAddress.TryParse(uri.Host.Trim('[', ']'), out var ip) && OriginPolicy.IsPrivateOrLoopback(ip)) return uri; + throw new UpdateException("not_configured", "Update-URL muss HTTPS sein (HTTP nur zu privater LAN-IP)."); + } + + HttpClient CreateClient(string token) + { + var client = handler != null + ? new HttpClient(handler, false) + : new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }, true); + client.Timeout = TimeSpan.FromSeconds(60); + client.DefaultRequestHeaders.UserAgent.ParseAdd("eMCPy/" + running.ToString(3)); + if (!string.IsNullOrWhiteSpace(token)) client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("token", token.Trim()); + return client; + } + + static byte[] Download(HttpClient client, Uri uri, long maxBytes, CancellationToken ct) + { + using var response = client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, ct).GetAwaiter().GetResult(); + var code = (int)response.StatusCode; + if (code == 401 || code == 403 || code == 404) + throw new UpdateException("auth_required_or_not_found", "HTTP " + code + " von " + uri.Host + ": Gitea-Token fehlt/ungültig oder Datei nicht vorhanden."); + if (code >= 300 && code < 400) throw new UpdateException("error", "Weiterleitung wird nicht verfolgt (HTTP " + code + ")."); + if (!response.IsSuccessStatusCode) throw new UpdateException("error", "HTTP " + code + " von " + uri.Host + "."); + if (response.Content.Headers.ContentLength > maxBytes) throw new UpdateException("error", "Datei zu groß."); + using var stream = response.Content.ReadAsStreamAsync(ct).GetAwaiter().GetResult(); + using var buffer = new MemoryStream(); + var chunk = new byte[81920]; int read; + while ((read = stream.ReadAsync(chunk, 0, chunk.Length, ct).GetAwaiter().GetResult()) > 0) + { + buffer.Write(chunk, 0, read); + if (buffer.Length > maxBytes) throw new UpdateException("error", "Datei zu groß."); + } + return buffer.ToArray(); + } + + UpdateStatus Status(string state, string message, string available = null, string installed = null, string sha = null, string notes = null, string backup = null) => new UpdateStatus + { + CheckedAt = DateTimeOffset.UtcNow, State = state, Message = message, RunningVersion = running.ToString(3), + AvailableVersion = available, InstalledVersion = installed, Sha256 = sha, Notes = notes, BackupFile = backup + }; + + void Save(UpdateStatus status) + { + try + { + Directory.CreateDirectory(stateDirectory); + var path = Path.Combine(stateDirectory, StatusFileName); + File.WriteAllText(path + ".tmp", JsonSerializer.Serialize(status)); + File.Move(path + ".tmp", path, true); + } + catch { } + } + + sealed class UpdateException : Exception + { + public string State { get; } + public UpdateException(string state, string message) : base(message) { State = state; } + } + } +} diff --git a/src/eMCPy/Update/UpdateTask.cs b/src/eMCPy/Update/UpdateTask.cs new file mode 100644 index 0000000..2092dd6 --- /dev/null +++ b/src/eMCPy/Update/UpdateTask.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Tasks; + +namespace eMCPy.Update +{ + /// + /// Geplante Aufgabe im Emby-Dashboard (Geplante Aufgaben → Anwendung). + /// Täglich und nach dem Start; kann dort auch manuell ausgelöst werden. + /// + public class UpdateTask : IScheduledTask, IConfigurableScheduledTask + { + public const string TaskKey = "EmcpyUpdateCheck"; + readonly ILogger logger; + + public UpdateTask(ILogManager logManager) { logger = logManager.GetLogger("eMCPy"); } + + public string Name => "eMCPy: Nach Updates suchen"; + public string Key => TaskKey; + public string Description => "Prüft das eMCPy-Repository auf eine neuere Version, installiert sie geprüft und meldet den erforderlichen Neustart."; + public string Category => "Application"; + public bool IsHidden => false; + public bool IsEnabled => true; + public bool IsLogged => true; + + public Task Execute(CancellationToken cancellationToken, IProgress progress) + { + var plugin = Plugin.Instance ?? throw new InvalidOperationException("eMCPy-Plugin nicht geladen."); + progress?.Report(5); + var updater = Create(plugin, msg => logger.Info(msg)); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + timeout.CancelAfter(TimeSpan.FromMinutes(3)); + var status = updater.Run(timeout.Token); + progress?.Report(100); + if (status.State == "error" || status.State == "checksum_mismatch" || status.State == "invalid_assembly" || status.State == "invalid_feed") + logger.Warn("[eMCPy] Update nicht installiert: " + status.Message); + return Task.CompletedTask; + } + + public static SelfUpdater Create(Plugin plugin, Action log) => new SelfUpdater( + null, + () => plugin.Configuration, + plugin.AssemblyFilePath, + typeof(UpdateTask).Assembly.GetName().Version ?? new Version(0, 0, 0), + plugin.ServerAppHost?.ApplicationVersion, + plugin.StateDirectory, + () => plugin.ServerAppHost?.NotifyPendingRestart(), + log); + + public IEnumerable GetDefaultTriggers() => new[] + { + new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerDaily, TimeOfDayTicks = TimeSpan.FromHours(4).Ticks }, + new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerStartup } + }; + } +} diff --git a/tests/eMCPy.Tests/Program.cs b/tests/eMCPy.Tests/Program.cs index 324ecf5..c747722 100644 --- a/tests/eMCPy.Tests/Program.cs +++ b/tests/eMCPy.Tests/Program.cs @@ -136,6 +136,7 @@ Check(typeof(SeriesInventory).Assembly.GetName().Version.ToString(3)=="1.5.0", " AdvancedTests.Run(); ProtocolTests.Run(); AdminTests.Run(); +UpdateTests.Run(); InventoryReplay.Run(); Console.WriteLine($"PASS: {passed} assertions; 35 episodes in 5 pages, no per-episode detail lookup."); diff --git a/tests/eMCPy.Tests/UpdateTests.cs b/tests/eMCPy.Tests/UpdateTests.cs new file mode 100644 index 0000000..607f286 --- /dev/null +++ b/tests/eMCPy.Tests/UpdateTests.cs @@ -0,0 +1,135 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using eMCPy; +using eMCPy.Mcp; +using eMCPy.Update; + +public static class UpdateTests +{ + sealed class FakeHttp : HttpMessageHandler + { + public readonly Dictionary> Routes = new Dictionary>(); + public readonly List Requests = new List(); + protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) + { + Requests.Add(request); + return Task.FromResult(Routes.TryGetValue(request.RequestUri.AbsoluteUri, out var r) ? r() : new HttpResponseMessage(HttpStatusCode.NotFound)); + } + } + + public static void Run() + { + int assertions = 0; + void Check(bool ok, string msg) { if (!ok) throw new Exception(msg); assertions++; } + + // ---- JSON-RPC id behält den Typ ---- + Check(McpToolRegistry.IdValue(JsonDocument.Parse("1").RootElement) is long l && l == 1, "Numeric id stays number"); + Check(McpToolRegistry.IdValue(JsonDocument.Parse("\"abc\"").RootElement) as string == "abc", "String id stays string"); + Check(McpToolRegistry.IdValue(JsonDocument.Parse("1.5").RootElement) is decimal, "Fractional id stays number"); + Check(McpToolRegistry.IdValue(JsonDocument.Parse("null").RootElement) == null, "Null id"); + var reg = new McpToolRegistry(null, null); + var resp = (Dictionary)reg.HandleRequest("{\"jsonrpc\":\"2.0\",\"id\":42,\"method\":\"ping\"}"); + Check(resp["id"] is long id42 && id42 == 42, "Response carries plain numeric id (not JsonElement)"); + + // ---- Selbst-Update ---- + var root = Path.Combine(Path.GetTempPath(), "emcpy-update-" + Guid.NewGuid()); + var plugins = Path.Combine(root, "plugins"); var state = Path.Combine(root, "data", "emcpy"); + Directory.CreateDirectory(plugins); + try + { + var target = Path.Combine(plugins, "eMCPy.dll"); + var newDll = File.ReadAllBytes(typeof(Plugin).Assembly.Location); // echte eMCPy-Assembly 1.5.0 + string Sha(byte[] b) => Convert.ToHexString(SHA256.HashData(b)).ToLowerInvariant(); + const string feedUrl = "https://git.example/michael/eMCPy/raw/branch/main/releases/latest.json"; + const string dllUrl = "https://git.example/michael/eMCPy/raw/branch/main/releases/1.5.0/eMCPy.dll"; + var cfg = new PluginConfiguration { UpdateFeedUrl = feedUrl, UpdateToken = "gitea-secret-token" }; + var http = new FakeHttp(); int restarts = 0; + void Reset() { File.WriteAllText(target, "OLD"); if (Directory.Exists(state)) Directory.Delete(state, true); http.Requests.Clear(); http.Routes.Clear(); restarts = 0; } + HttpResponseMessage Json(object o) => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonSerializer.Serialize(o), Encoding.UTF8, "application/json") }; + HttpResponseMessage Bytes(byte[] b) => new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(b) }; + void Feed(string version, string url, string sha, string minServer = null) => http.Routes[feedUrl] = () => Json(new { version, url, sha256 = sha, minServerVersion = minServer, notes = "Test" }); + SelfUpdater Updater(string running = "1.4.1") => new SelfUpdater(http, () => cfg, target, Version.Parse(running), new Version(4, 9, 5, 0), state, () => restarts++); + UpdateStatus Go(string running = "1.4.1") => Updater(running).Run(CancellationToken.None); + bool Untouched() => File.ReadAllText(target) == "OLD" && !File.Exists(target + ".download") && restarts == 0; + + Reset(); cfg.EnableAutoUpdate = false; + Check(Go().State == "disabled" && http.Requests.Count == 0, "Disabled makes no requests"); + cfg.EnableAutoUpdate = true; + + foreach (var bad in new[] { "http://git.example/latest.json", "ftp://x/latest.json", "https://user:pw@git.example/latest.json", "kein url" }) + { Reset(); cfg.UpdateFeedUrl = bad; Check(Go().State == "not_configured" && http.Requests.Count == 0, "Rejected feed URL: " + bad); } + Check(SelfUpdater.ValidateFeedUrl("http://192.168.1.2:3000/x/latest.json") != null, "HTTP to LAN IP allowed"); + cfg.UpdateFeedUrl = feedUrl; + + Reset(); + var missing = Go(); + Check(missing.State == "auth_required_or_not_found", "404 explained as token/file problem"); + Check(http.Requests[0].Headers.Authorization?.Scheme == "token" && http.Requests[0].Headers.Authorization?.Parameter == "gitea-secret-token", "Gitea token header sent to feed host"); + Check(!File.ReadAllText(Path.Combine(state, SelfUpdater.StatusFileName)).Contains("gitea-secret-token"), "Token never stored in status"); + + Reset(); http.Routes[feedUrl] = () => new HttpResponseMessage(HttpStatusCode.Found) { Headers = { Location = new Uri("https://evil.example/") } }; + Check(Go().State == "error" && http.Requests.Count == 1, "Redirect not followed"); + + Reset(); http.Routes[feedUrl] = () => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("") }; + Check(Go().State == "invalid_feed", "Non-JSON feed rejected"); + + Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(newDll)); + Check(Go("1.5.0").State == "up_to_date" && http.Requests.Count == 1, "Same version: no download"); + Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(newDll)); + Check(Go("1.6.0").State == "up_to_date" && Untouched(), "Never downgrade"); + + Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(newDll), "9.0.0.0"); + Check(Go().State == "server_too_old" && Untouched(), "Server version requirement"); + + Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", "abc"); + Check(Go().State == "invalid_feed", "Invalid sha in feed"); + + Reset(); cfg.AutoInstallUpdates = false; Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(newDll)); + var notify = Go(); + Check(notify.State == "update_available" && notify.AvailableVersion == "1.5.0" && Untouched() && http.Requests.Count == 1, "Notify-only mode does not download"); + cfg.AutoInstallUpdates = true; + + Reset(); Feed("1.5.0", "https://evil.example/eMCPy.dll", Sha(newDll)); + Check(Go().State == "invalid_feed" && http.Requests.Count == 1 && Untouched(), "DLL from other host refused, token not sent there"); + + Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(newDll)); http.Routes[dllUrl] = () => Bytes(Encoding.UTF8.GetBytes("tampered")); + Check(Go().State == "checksum_mismatch" && Untouched(), "Checksum mismatch leaves plugin untouched"); + + var junk = Encoding.UTF8.GetBytes("not an assembly at all"); + Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(junk)); http.Routes[dllUrl] = () => Bytes(junk); + Check(Go().State == "invalid_assembly" && Untouched(), "Non-assembly refused even with matching sha"); + + Reset(); Feed("1.6.0", "1.5.0/eMCPy.dll", Sha(newDll)); http.Routes[dllUrl] = () => Bytes(newDll); + Check(Go().State == "invalid_assembly" && Untouched(), "Assembly version must match feed version"); + + Reset(); Feed("1.5.0", "1.5.0/eMCPy.dll", Sha(newDll)); http.Routes[dllUrl] = () => Bytes(newDll); + var installed = Go(); + Check(installed.State == "installed_restart_pending" && installed.InstalledVersion == "1.5.0", "Update installed"); + Check(File.ReadAllBytes(target).SequenceEqual(newDll) && !File.Exists(target + ".download"), "Plugin DLL replaced atomically"); + Check(restarts == 1, "Pending restart reported once"); + Check(File.ReadAllText(Path.Combine(state, "backup", "eMCPy-1.4.1.dll")) == "OLD", "Previous DLL backed up outside plugins folder"); + Check(Directory.GetFiles(plugins).Length == 1, "No extra DLLs in plugins folder"); + int before = http.Requests.Count; + var again = Go(); + Check(again.State == "installed_restart_pending" && http.Requests.Count == before && restarts == 1, "No re-download while restart pending"); + File.WriteAllText(target, "OLD"); // Admin hat manuell zurückgerollt + Check(Go().State == "installed_restart_pending" && http.Requests.Count > before, "Manual rollback detected, update re-applied"); + Check(SelfUpdater.ReadStatus(state).State == "installed_restart_pending", "Status persisted for emby_plugins"); + + for (int i = 0; i < 5; i++) { File.WriteAllText(target, "OLD"); if (File.Exists(Path.Combine(state, SelfUpdater.StatusFileName))) File.Delete(Path.Combine(state, SelfUpdater.StatusFileName)); Go("1.4." + (10 + i)); } + Check(Directory.GetFiles(Path.Combine(state, "backup")).Length <= 3, "At most 3 backups kept"); + + Console.WriteLine($"PASS update: {assertions} assertions."); + } + finally { if (Directory.Exists(root)) Directory.Delete(root, true); } + } +}