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); } }