Author SHA1 Message Date
Mikei386andClaude Opus 5.5 7c7d384933 feat: self-update from Gitea and JSON-RPC id type fix (1.5.0)
- Scheduled task "eMCPy: Nach Updates suchen" (daily + startup) reads
  releases/latest.json, downloads only newer versions from the same host,
  verifies SHA256, assembly name and version, backs up the old DLL outside
  the plugins folder, swaps atomically and reports a pending restart.
  HTTPS (or HTTP to private IPs) only, no redirects, size limits, Gitea
  token sent only to the feed host and never stored or returned.
- Config page section for auto update; status in emby_plugins.
- scripts/make-release.sh builds releases/<v> and the update feed.
- JSON-RPC responses keep the request id's type (Emby's serializer turned
  numeric ids into strings).
- 1.5.0 package rebuilt (not yet installed anywhere).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 10:42:46 +01:00
16 changed files with 603 additions and 8 deletions

No files matched your search

+2 -2
View File
@@ -4,7 +4,7 @@
## Status ## 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. 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] Erste Tools: `emby_server_info`, `emby_search`, `emby_now_playing`, `emby_get_item`
- [x] Live-Deploy & Verifikation (Emby 4.9.5.0, Unraid) - [x] Live-Deploy & Verifikation (Emby 4.9.5.0, Unraid)
- [x] Dashboard-Config-Seite (Port, API-Key) - [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] Bibliotheks-/Medienwerkzeuge und paginierter Serienbestand
- [x] Geplante Aufgaben, Admin-Übersicht, Live TV lesend (1.5.0) - [x] Geplante Aufgaben, Admin-Übersicht, Live TV lesend (1.5.0)
- [ ] Live TV schreibend (Aufnahmen planen/abbrechen), Untertitel-Download, Sammlungen/Playlists - [ ] Live TV schreibend (Aufnahmen planen/abbrechen), Untertitel-Download, Sammlungen/Playlists
+52
View File
@@ -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:<Gitea-HTTP-Port>/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. `<Version>` in `src/eMCPy/eMCPy.csproj` erhöhen.
2. `scripts/make-release.sh "Änderungsnotiz"` – Tests, Build, `releases/<v>/`, `SHA256SUMS`,
`releases/latest.json`.
3. Committen und auf `main` pushen. Server holen die Version bei der nächsten Prüfung.
+11 -3
View File
@@ -9,6 +9,12 @@
- Live TV, lesend: `emby_livetv_status`, `emby_livetv_channels`, `emby_livetv_guide`, - Live TV, lesend: `emby_livetv_status`, `emby_livetv_channels`, `emby_livetv_guide`,
`emby_livetv_recordings`. `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); 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. 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 ## Lokal geprüft
597 Assertions (372 Serieninventar, 97 Advanced, 40 Protokoll, 88 Admin/Live TV), nur 631 Assertions (372 Serieninventar, 97 Advanced, 40 Protokoll, 88 Admin/Live TV,
Test-Doubles für Aktionen; HTTP-Smoke-Test: 49 Werkzeuge gelistet, Origin-Block, 405, ping. 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 sind nur gegen Test-Doubles geprüft. 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`.
+1 -1
View File
@@ -1 +1 @@
0ef04d721466f8dc4e6d832d9bfd5d6ed6c56520190e658cab2ead1423194ee0 eMCPy.dll fc61bf002507f7c9016c1ead9c09494cb21588151aa1ef4daffc34112307089c eMCPy.dll
Binary file not shown.
+7
View File
@@ -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."
}
+29
View File
@@ -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 (<Version>). 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:.*<Version>\(.*\)</Version>.*:\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."
+26
View File
@@ -104,6 +104,32 @@
</div> </div>
</div> </div>
<h2>Automatische Updates</h2>
<div class="checkboxContainer">
<label><input is="emby-checkbox" type="checkbox" id="enableAutoUpdate" />
<span>Täglich nach neuen eMCPy-Versionen suchen</span></label>
<div class="fieldDescription">Geplante Aufgabe „eMCPy: Nach Updates suchen“ (täglich 04:00 und nach dem Start, unter Geplante Aufgaben auch manuell startbar).</div>
</div>
<div class="checkboxContainer" style="margin-top: 1em;">
<label><input is="emby-checkbox" type="checkbox" id="autoInstallUpdates" />
<span>Neue Version automatisch installieren</span></label>
<div class="fieldDescription">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.</div>
</div>
<div class="inputContainer" style="margin-top: 1em;">
<label class="inputLabel" for="updateFeedUrl">Update-URL (latest.json)</label>
<input is="emby-input" type="text" id="updateFeedUrl" />
<div class="fieldDescription">HTTPS-Adresse von <code>releases/latest.json</code> im Repository (HTTP nur zu einer LAN-IP).</div>
</div>
<div class="inputContainer" style="margin-top: 1em;">
<label class="inputLabel" for="updateToken">Gitea-Token (Leserecht)</label>
<input is="emby-input" type="password" id="updateToken" autocomplete="off" />
<div class="fieldDescription">Für private Repositories nötig: in Gitea unter Einstellungen → Anwendungen einen Token mit <code>read:repository</code> erstellen. Wird nur an den Host der Update-URL gesendet.</div>
</div>
<div class="emcpy-status pending" id="serverStatus"> <div class="emcpy-status pending" id="serverStatus">
Status wird geladen … Status wird geladen …
</div> </div>
+8
View File
@@ -86,6 +86,10 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) {
view.querySelector('#serverUrl').value = config.ServerUrl || ''; view.querySelector('#serverUrl').value = config.ServerUrl || '';
view.querySelector('#allowedOrigins').value = config.AllowedOrigins || ''; view.querySelector('#allowedOrigins').value = config.AllowedOrigins || '';
view.querySelector('#allowedTaskKeys').value = config.AllowedTaskKeys || ''; 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); this.checkServerStatus(view, config);
loading.hide(); loading.hide();
}).catch(() => { }).catch(() => {
@@ -116,6 +120,10 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) {
config.ServerUrl = view.querySelector('#serverUrl').value.trim(); config.ServerUrl = view.querySelector('#serverUrl').value.trim();
config.AllowedOrigins = view.querySelector('#allowedOrigins').value.trim(); config.AllowedOrigins = view.querySelector('#allowedOrigins').value.trim();
config.AllowedTaskKeys = view.querySelector('#allowedTaskKeys').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 => { updatePluginConfiguration(config).then(result => {
loading.hide(); loading.hide();
+15
View File
@@ -282,10 +282,25 @@ namespace eMCPy.Mcp
updateStatus, updateStatus,
updates, updates,
currentInstallations = installing, currentInstallations = installing,
emcpySelfUpdate = SelfUpdateInfo(),
note = "Nur lesend. Plugin-Updates installiert die Aufgabe für Plugin-Updates (standardmäßig gesperrt)." 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 ---------- // ---------- Geräte ----------
public object Devices(ToolArgs a) public object Devices(ToolArgs a)
+21 -2
View File
@@ -1099,17 +1099,36 @@ namespace eMCPy.Mcp
["result"] = result ["result"] = result
}; };
if (id.ValueKind != JsonValueKind.Undefined) if (id.ValueKind != JsonValueKind.Undefined)
d["id"] = id; d["id"] = IdValue(id);
return d; return d;
} }
/// <summary>
/// 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.
/// </summary>
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) private static object RpcError(JsonElement id, int code, string message)
{ {
return new Dictionary<string, object> return new Dictionary<string, object>
{ {
["jsonrpc"] = "2.0", ["jsonrpc"] = "2.0",
["error"] = new { code, message }, ["error"] = new { code, message },
["id"] = id ["id"] = IdValue(id)
}; };
} }
} }
+12
View File
@@ -37,5 +37,17 @@ namespace eMCPy
/// Gesetzt = ausschließlich diese Keys (auch sonst gesperrte). /// Gesetzt = ausschließlich diese Keys (auch sonst gesperrte).
/// </summary> /// </summary>
public string AllowedTaskKeys { get; set; } = string.Empty; public string AllowedTaskKeys { get; set; } = string.Empty;
/// <summary>Tägliche Prüfung auf neue eMCPy-Versionen (geplante Aufgabe „eMCPy: Nach Updates suchen“).</summary>
public bool EnableAutoUpdate { get; set; } = true;
/// <summary>true = neue Version geprüft installieren und Neustart melden; false = nur melden.</summary>
public bool AutoInstallUpdates { get; set; } = true;
/// <summary>URL zu releases/latest.json (HTTPS, oder HTTP zu privater LAN-IP).</summary>
public string UpdateFeedUrl { get; set; } = "https://git.casaderoll.de/michael/eMCPy/raw/branch/main/releases/latest.json";
/// <summary>Gitea-Zugriffstoken mit Leserecht auf das Repository (nötig, da privat). Wird nie ausgegeben.</summary>
public string UpdateToken { get; set; } = string.Empty;
} }
} }
+224
View File
@@ -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
{
/// <summary>Inhalt von releases/latest.json im eMCPy-Repository.</summary>
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; }
}
/// <summary>
/// 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.
/// </summary>
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<PluginConfiguration> config;
readonly string assemblyPath, stateDirectory;
readonly Version running, server;
readonly Action notifyRestart;
readonly Action<string> log;
public SelfUpdater(HttpMessageHandler handler, Func<PluginConfiguration> config, string assemblyPath, Version running,
Version server, string stateDirectory, Action notifyRestart, Action<string> 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<UpdateStatus>(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<UpdateFeed>(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; }
}
}
}
+59
View File
@@ -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
{
/// <summary>
/// Geplante Aufgabe im Emby-Dashboard (Geplante Aufgaben → Anwendung).
/// Täglich und nach dem Start; kann dort auch manuell ausgelöst werden.
/// </summary>
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<double> 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<string> 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<TaskTriggerInfo> GetDefaultTriggers() => new[]
{
new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerDaily, TimeOfDayTicks = TimeSpan.FromHours(4).Ticks },
new TaskTriggerInfo { Type = TaskTriggerInfo.TriggerStartup }
};
}
}
+1
View File
@@ -136,6 +136,7 @@ Check(typeof(SeriesInventory).Assembly.GetName().Version.ToString(3)=="1.5.0", "
AdvancedTests.Run(); AdvancedTests.Run();
ProtocolTests.Run(); ProtocolTests.Run();
AdminTests.Run(); AdminTests.Run();
UpdateTests.Run();
InventoryReplay.Run(); InventoryReplay.Run();
Console.WriteLine($"PASS: {passed} assertions; 35 episodes in 5 pages, no per-episode detail lookup."); Console.WriteLine($"PASS: {passed} assertions; 35 episodes in 5 pages, no per-episode detail lookup.");
+135
View File
@@ -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<string, Func<HttpResponseMessage>> Routes = new Dictionary<string, Func<HttpResponseMessage>>();
public readonly List<HttpRequestMessage> Requests = new List<HttpRequestMessage>();
protected override Task<HttpResponseMessage> 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<string, object>)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("<html>") };
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); }
}
}