diff --git a/src/eMCPy/Configuration/configPage.html b/src/eMCPy/Configuration/configPage.html index 5dc1774..c82c94b 100644 --- a/src/eMCPy/Configuration/configPage.html +++ b/src/eMCPy/Configuration/configPage.html @@ -67,6 +67,16 @@ +
+ + +
+ Basis-URL für Bild-Links und andere generierte URLs. In Docker (Bridge-Netzwerk) wichtig: + hier die LAN-URL eintragen, z. B. http://192.168.1.2:8096. + Leer = automatische Erkennung (kann in Docker die Container-IP liefern). +
+
+
Status wird geladen …
diff --git a/src/eMCPy/Configuration/configPage.js b/src/eMCPy/Configuration/configPage.js index e74bdac..00fb6c0 100644 --- a/src/eMCPy/Configuration/configPage.js +++ b/src/eMCPy/Configuration/configPage.js @@ -82,6 +82,7 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) { view.querySelector('#listenAddress').value = config.ListenAddress || '0.0.0.0'; view.querySelector('#apiKey').value = config.ApiKey || ''; view.querySelector('#mcpUrl').value = config.McpUrl || ''; + view.querySelector('#serverUrl').value = config.ServerUrl || ''; this.checkServerStatus(view, config); loading.hide(); }).catch(() => { @@ -105,6 +106,7 @@ define(['baseView', 'loading', 'toast'], function (BaseView, loading, toast) { config.ListenAddress = view.querySelector('#listenAddress').value.trim() || '0.0.0.0'; config.ApiKey = view.querySelector('#apiKey').value.trim(); config.McpUrl = view.querySelector('#mcpUrl').value.trim(); + config.ServerUrl = view.querySelector('#serverUrl').value.trim(); updatePluginConfiguration(config).then(result => { loading.hide(); diff --git a/src/eMCPy/Mcp/McpToolRegistry.cs b/src/eMCPy/Mcp/McpToolRegistry.cs index 428e31a..9fc27ae 100644 --- a/src/eMCPy/Mcp/McpToolRegistry.cs +++ b/src/eMCPy/Mcp/McpToolRegistry.cs @@ -3,9 +3,14 @@ using System.Reflection; using System.Collections.Generic; using System.Linq; using System.Text.Json; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Session; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Querying; using MediaBrowser.Model.Serialization; namespace eMCPy.Mcp @@ -104,6 +109,48 @@ namespace eMCPy.Mcp case "emby_get_item": result = ToolGetItem(hasArgs ? args : default); break; + // ---- NEU: Codec / Media ---- + case "emby_media_info": + result = ToolMediaInfo(hasArgs ? args : default); + break; + case "emby_codec_inventory": + result = ToolCodecInventory(hasArgs ? args : default); + break; + case "emby_find_by_codec": + result = ToolFindByCodec(hasArgs ? args : default); + break; + // ---- NEU: Bilder / Cover ---- + case "emby_item_images": + result = ToolItemImages(hasArgs ? args : default); + break; + case "emby_image_url": + result = ToolImageUrl(hasArgs ? args : default); + break; + // ---- NEU: Bibliothek ---- + case "emby_library_stats": + result = ToolLibraryStats(); + break; + case "emby_library_browse": + result = ToolLibraryBrowse(hasArgs ? args : default); + break; + case "emby_library_folders": + result = ToolLibraryFolders(); + break; + case "emby_recently_added": + result = ToolRecentlyAdded(hasArgs ? args : default); + break; + case "emby_next_up": + result = ToolNextUp(hasArgs ? args : default); + break; + case "emby_random": + result = ToolRandom(hasArgs ? args : default); + break; + case "emby_top_rated": + result = ToolTopRated(hasArgs ? args : default); + break; + case "emby_missing_metadata": + result = ToolMissingMetadata(hasArgs ? args : default); + break; default: return RpcError(id, -32602, "Unbekanntes Tool: " + name); } @@ -133,6 +180,16 @@ namespace eMCPy.Mcp return null; } + private static int? ArgInt(JsonElement args, string key) + { + if (args.ValueKind == JsonValueKind.Object && args.TryGetProperty(key, out var v)) + { + if (v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var i)) return i; + if (v.ValueKind == JsonValueKind.String && int.TryParse(v.GetString(), out var i2)) return i2; + } + return null; + } + // ---------- Tool-Definitionen ---------- private List GetToolDefinitions() @@ -154,7 +211,7 @@ namespace eMCPy.Mcp type = "object", properties = new { - query = new { type = "string", description = "Suchbegriff (Titel,_actor, Genre …)" }, + query = new { type = "string", description = "Suchbegriff (Titel, actor, Genre …)" }, type = new { type = "string", description = "Optional: Movie, Series, Music – leer = alle Typen" } }, required = new[] { "query" } @@ -179,10 +236,311 @@ namespace eMCPy.Mcp }, required = new[] { "id" } } + }, + new + { + name = "emby_media_info", + description = "Liefert technische Details (Codec) eines Items: Video-/Audio-Codec, Auflösung, Bitrate, Profile, Level, Container, Audio-Sprachen, Untertitel.", + inputSchema = new + { + type = "object", + properties = new + { + id = new { type = "string", description = "Item-ID als GUID" } + }, + required = new[] { "id" } + } + }, + new + { + name = "emby_codec_inventory", + description = "Scannt die Mediathek und zählt Items pro Video-Codec (H264, H265, …) und Audio-Codec (AAC, AC3, …).", + inputSchema = new + { + type = "object", + properties = new + { + type = new { type = "string", description = "Optional: Movie, Series, Music – leer = alle" }, + limit = new { type = "integer", description = "Max. Items zu scannen (Default 500, 0 = alle)" } + } + } + }, + new + { + name = "emby_find_by_codec", + description = "Findet alle Items mit einem bestimmten Video- oder Audio-Codec (z. B. 'hevc' für H265, 'h264', 'ac3', 'dts').", + inputSchema = new + { + type = "object", + properties = new + { + codec = new { type = "string", description = "Codec-Name (z. B. h264, hevc, av1, aac, ac3, dts)" }, + kind = new { type = "string", description = "video (Default) oder audio" }, + type = new { type = "string", description = "Optional: Movie, Series, Music" }, + limit = new { type = "integer", description = "Max. Ergebnisse (Default 50)" } + }, + required = new[] { "codec" } + } + }, + new + { + name = "emby_item_images", + description = "Listet alle verfügbaren Bilder/Cover eines Items (Primary, Backdrop, Logo, Banner, Art, Box, …) mit Größe und URL.", + inputSchema = new + { + type = "object", + properties = new + { + id = new { type = "string", description = "Item-ID als GUID" } + }, + required = new[] { "id" } + } + }, + new + { + name = "emby_image_url", + description = "Liefert die direkte URL zu einem bestimmten Bild eines Items (z. B. Poster, Backdrop, Logo).", + inputSchema = new + { + type = "object", + properties = new + { + id = new { type = "string", description = "Item-ID als GUID" }, + imageType = new { type = "string", description = "Bildtyp: Primary, Backdrop, Logo, Banner, Art, Box, Thumb, Disc (Default: Primary)" }, + maxWidth = new { type = "integer", description = "Optionale Breite in Pixeln" }, + maxHeight = new { type = "integer", description = "Optionale Höhe in Pixeln" } + }, + required = new[] { "id" } + } + }, + new + { + name = "emby_library_stats", + description = "Liefert Statistiken zur Mediathek: Anzahl Items pro Typ (Filme, Serien, Musik, Fotos) und Gesamtzahl.", + inputSchema = new { type = "object", properties = new Dictionary() } + }, + new + { + name = "emby_library_browse", + description = "Durchsucht die Mediathek nach Typ (Movie, Series, Album, Artist, Season, Episode, Song, Video, Photo) mit Pagination.", + inputSchema = new + { + type = "object", + properties = new + { + type = new { type = "string", description = "Item-Typ: Movie, Series, Album, Artist, Season, Episode, Song, Video, Photo (Default: Movie)" }, + start = new { type = "integer", description = "Startindex (Default 0)" }, + limit = new { type = "integer", description = "Anzahl Ergebnisse (Default 20, max 100)" }, + sortBy = new { type = "string", description = "Sortierung: Name, DateCreated, DateModified, PremiereDate, CommunityRating (Default: Name)" } + } + } + }, + new + { + name = "emby_library_folders", + description = "Listet die Top-Level-Bibliotheken (z. B. Filme, Serien, Musik) mit Typ und Item-Anzahl.", + inputSchema = new { type = "object", properties = new Dictionary() } + }, + new + { + name = "emby_recently_added", + description = "Listet die zuletzt hinzugefügten Items der Mediathek.", + inputSchema = new + { + type = "object", + properties = new + { + type = new { type = "string", description = "Optional: Movie, Series, Music – leer = alle" }, + limit = new { type = "integer", description = "Anzahl (Default 20)" } + } + } + }, + new + { + name = "emby_next_up", + description = "Listet die nächsten Episoden, die als Nächstes anstehen (Fortsetzen).", + inputSchema = new + { + type = "object", + properties = new + { + limit = new { type = "integer", description = "Anzahl (Default 20)" } + } + } + }, + new + { + name = "emby_random", + description = "Liefert ein zufälliges Item eines Typs (z. B. für 'Spiel mir einen zufälligen Film').", + inputSchema = new + { + type = "object", + properties = new + { + type = new { type = "string", description = "Item-Typ: Movie, Series, Album, Song, Video (Default: Movie)" } + } + } + }, + new + { + name = "emby_top_rated", + description = "Listet die bestbewerteten Items (Community-Rating) eines Typs.", + inputSchema = new + { + type = "object", + properties = new + { + type = new { type = "string", description = "Item-Typ: Movie, Series, Album (Default: Movie)" }, + limit = new { type = "integer", description = "Anzahl (Default 20)" } + } + } + }, + new + { + name = "emby_missing_metadata", + description = "Findet Items ohne primäres Bild (Poster/Cover) – nützlich für Wartung.", + inputSchema = new + { + type = "object", + properties = new + { + type = new { type = "string", description = "Optional: Movie, Series, Music – leer = alle" }, + limit = new { type = "integer", description = "Max. Ergebnisse (Default 50)" } + } + } } }; } + // ---------- Helper ---------- + + private string GetVersion() + { + return typeof(McpToolRegistry).Assembly.GetName().Version?.ToString(3) ?? "0.0.0"; + } + + private string GetServerUrl() + { + // 1. Explizit konfigurierte Server-URL (wichtig in Docker: LAN-URL) + var cfg = Plugin.Instance?.Configuration; + if (cfg != null && !string.IsNullOrWhiteSpace(cfg.ServerUrl)) + return cfg.ServerUrl.TrimEnd('/'); + + var host = Plugin.Instance?.ServerAppHost; + int port = host?.HttpPort ?? 8096; + + // 1. Erste lokale IPv4-LAN-Adresse (für externe Agenten im LAN). + // Docker-Interface-IPs (172.17.x.x, 172.18.x.x, 10.x.x.x) werden bevorzugt übersprungen. + try + { + var allIps = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces() + .Where(ni => ni.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up && + ni.NetworkInterfaceType != System.Net.NetworkInformation.NetworkInterfaceType.Loopback) + .SelectMany(ni => ni.GetIPProperties().UnicastAddresses) + .Where(ua => ua.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) + .Select(ua => ua.Address.ToString()) + .Where(ip => !ip.StartsWith("127.")) + .ToList(); + + // Bevorzugt: IPs außerhalb des Docker-Netzwerks (172.17-31.x.x, 10.x.x.x) + var lanIp = allIps.FirstOrDefault(ip => + !ip.StartsWith("172.17.") && !ip.StartsWith("172.18.") && + !ip.StartsWith("172.19.") && !ip.StartsWith("172.20.") && + !ip.StartsWith("172.21.") && !ip.StartsWith("172.22.") && + !ip.StartsWith("172.23.") && !ip.StartsWith("172.24.") && + !ip.StartsWith("172.25.") && !ip.StartsWith("172.26.") && + !ip.StartsWith("172.27.") && !ip.StartsWith("172.28.") && + !ip.StartsWith("172.29.") && !ip.StartsWith("172.30.") && + !ip.StartsWith("172.31.") && !ip.StartsWith("10.")); + if (lanIp == null) lanIp = allIps.FirstOrDefault(); + + if (!string.IsNullOrEmpty(lanIp)) + return $"http://{lanIp}:{port}"; + } + catch { } + + // 2. Fallback: lokale API-URL + try + { + if (host != null) + { + var url = host.GetLocalApiUrl((string)null); + if (!string.IsNullOrEmpty(url)) return url.TrimEnd('/'); + } + } + catch { } + + return $"http://localhost:{port}"; + } + + private Guid? GetFirstUserId() + { + try + { + var users = Users.GetUserList(new UserQuery()); + if (users != null && users.Length > 0) + return users[0].Id; + } + catch { } + return null; + } + + private BaseItem ResolveItem(string id) + { + if (string.IsNullOrEmpty(id)) return null; + if (Guid.TryParse(id, out var guid)) + return Library.GetItemById(guid); + return null; + } + + private ImageType ParseImageType(string s) + { + if (string.IsNullOrEmpty(s)) return ImageType.Primary; + try { return (ImageType)Enum.Parse(typeof(ImageType), s, true); } + catch { return ImageType.Primary; } + } + + private static object ItemSummary(BaseItem item) + { + var d = new Dictionary + { + ["id"] = item.Id.ToString(), + ["name"] = item.Name, + ["type"] = item.GetType().Name, + ["mediaType"] = item.MediaType + }; + if (item.ProductionYear.HasValue) d["year"] = item.ProductionYear.Value; + if (item.CommunityRating.HasValue) d["communityRating"] = item.CommunityRating.Value; + if (item.RunTimeTicks.HasValue) d["runtimeMinutes"] = (int)(item.RunTimeTicks.Value / TimeSpan.TicksPerMinute); + if (item.Overview != null) d["overview"] = item.Overview.Length > 200 ? item.Overview.Substring(0, 200) + "…" : item.Overview; + if (item.Genres != null && item.Genres.Length > 0) d["genres"] = item.Genres; + if (item.Studios != null && item.Studios.Length > 0) d["studios"] = item.Studios; + if (item.OfficialRating != null) d["officialRating"] = item.OfficialRating; + return d; + } + + private static object StreamSummary(MediaStream s) + { + var d = new Dictionary + { + ["type"] = s.Type.ToString(), + ["codec"] = s.Codec, + ["index"] = s.Index + }; + if (s.Width.HasValue) d["width"] = s.Width.Value; + if (s.Height.HasValue) d["height"] = s.Height.Value; + if (s.BitRate.HasValue) d["bitrate"] = s.BitRate.Value; + if (s.Profile != null) d["profile"] = s.Profile; + if (s.Level.HasValue) d["level"] = s.Level.Value; + if (s.Language != null) d["language"] = s.Language; + if (s.Channels.HasValue) d["channels"] = s.Channels.Value; + if (s.SampleRate.HasValue) d["sampleRate"] = s.SampleRate.Value; + if (s.DisplayTitle != null) d["displayTitle"] = s.DisplayTitle; + if (s.IsDefault) d["isDefault"] = true; + if (s.IsForced) d["isForced"] = true; + return d; + } + // ---------- Tool-Implementierungen ---------- private object ToolServerInfo() @@ -190,128 +548,525 @@ namespace eMCPy.Mcp var cfg = Plugin.Instance?.Configuration; return new { - server = "Emby", - plugin = "eMCPy", + serverName = "Emby", + embyVersion = "4.9.5.0", + pluginName = "eMCPy", + pluginVersion = GetVersion(), mcpEnabled = cfg?.EnableMcpServer ?? false, - mcpPort = cfg?.McpPort ?? 0, - userCount = Users?.GetUserCount(new MediaBrowser.Model.Querying.UserQuery()) ?? 0 + mcpPort = cfg?.McpPort ?? 8097, + userCount = Users.GetUserCount(new UserQuery()), + tools = GetToolDefinitions().Count }; } private object ToolSearch(JsonElement args) { var query = ArgString(args, "query"); - if (string.IsNullOrWhiteSpace(query)) - return new { error = "Parameter 'query' fehlt" }; - - if (Library == null) - return new { error = "LibraryManager noch nicht verfügbar (Server startet?)" }; + if (string.IsNullOrEmpty(query)) + throw new ArgumentException("query ist erforderlich"); var type = ArgString(args, "type"); - - var results = new List(); - var queryResult = Library.GetItemsResult(new MediaBrowser.Controller.Entities.InternalItemsQuery + var q = new InternalItemsQuery { SearchTerm = query, + Recursive = true, Limit = 20 - }); - foreach (var item in queryResult.Items) + }; + if (!string.IsNullOrEmpty(type)) + q.IncludeItemTypes = new[] { type }; + + var result = Library.GetItemsResult(q); + return new { - if (!string.IsNullOrEmpty(type) && - !string.Equals(item.MediaType, type, StringComparison.OrdinalIgnoreCase)) - continue; - - results.Add(new - { - id = item.Id.ToString(), - name = item.Name, - type = item.MediaType, - path = item.Path - }); - } - - return new { query, type, count = results.Count, results }; + query, + total = result.TotalRecordCount, + items = result.Items.Select(ItemSummary).ToArray() + }; } private object ToolNowPlaying() { - if (Sessions == null) - return new { error = "SessionManager noch nicht verfügbar (Server startet?)" }; - - var list = Sessions.Sessions - .Where(s => s.NowPlayingItem != null) + var sessions = Sessions.Sessions; + var playing = sessions + .Where(s => s.PlayState?.IsPaused == false && s.PlayState?.PositionTicks > 0) .Select(s => new { - session = s.Id, - user = s.UserName, - client = s.Client, - device = s.DeviceName, - item = s.NowPlayingItem.Name, - itemType = s.NowPlayingItem.Type, - itemId = s.NowPlayingItem.Id, - positionSeconds = s.PlayState != null ? (long)(s.PlayState.PositionTicks / TimeSpan.TicksPerSecond) : 0, - paused = s.PlayState?.IsPaused ?? false + sessionName = s.Client, + deviceName = s.DeviceName, + userName = s.UserName, + nowPlaying = s.NowPlayingItem?.Name, + nowPlayingType = s.NowPlayingItem?.GetType().Name, + positionSeconds = (int)(s.PlayState?.PositionTicks / TimeSpan.TicksPerSecond ?? 0), + isPaused = s.PlayState?.IsPaused ?? false }) - .ToList(); + .ToArray(); - return new { count = list.Count, nowPlaying = list }; + return new + { + activeSessions = playing.Length, + sessions = playing + }; } private object ToolGetItem(JsonElement args) { var id = ArgString(args, "id"); - if (string.IsNullOrWhiteSpace(id)) - return new { error = "Parameter 'id' fehlt" }; - if (Library == null) - return new { error = "LibraryManager noch nicht verfügbar (Server startet?)" }; - - if (!Guid.TryParse(id, out var guid)) - return new { error = "Ungültige GUID: " + id }; - - var item = Library.GetItemById(guid); + var item = ResolveItem(id); if (item == null) - return new { found = false, id }; + throw new ArgumentException("Item nicht gefunden: " + id); + + var result = ItemSummary(item); + var dict = result as Dictionary; + if (dict != null) + { + // Zusätzliche Details + if (item.ProviderIds != null && item.ProviderIds.Count > 0) + { + var providers = new Dictionary(); + foreach (var kv in item.ProviderIds) + providers[kv.Key] = kv.Value; + dict["providerIds"] = providers; + } + if (item.Path != null) dict["path"] = item.Path; + if (item.DateCreated != default) dict["dateCreated"] = item.DateCreated.ToString("yyyy-MM-dd"); + if (item.DateModified != default) dict["dateModified"] = item.DateModified.ToString("yyyy-MM-dd"); + } + return result; + } + + // ---- NEU: Codec / Media ---- + + private object ToolMediaInfo(JsonElement args) + { + var id = ArgString(args, "id"); + var item = ResolveItem(id); + if (item == null) + throw new ArgumentException("Item nicht gefunden: " + id); + + List streams; + try { streams = item.GetMediaStreams(); } + catch { streams = null; } + if (streams == null) streams = new List(); + var videoStreams = streams.Where(s => s.Type == MediaStreamType.Video).Select(StreamSummary).ToArray(); + var audioStreams = streams.Where(s => s.Type == MediaStreamType.Audio).Select(StreamSummary).ToArray(); + var subtitleStreams = streams.Where(s => s.Type == MediaStreamType.Subtitle).Select(StreamSummary).ToArray(); + var imageStreams = streams.Where(s => s.Type == MediaStreamType.EmbeddedImage).Select(StreamSummary).ToArray(); + + // MediaSources für Container-Info + object mediaSources = null; + try + { + var sources = item.GetMediaSources(false, false, null); + if (sources != null && sources.Count > 0) + { + mediaSources = sources.Select(ms => new + { + id = ms.Id, + container = ms.Container, + bitrate = ms.Bitrate, + isRemote = ms.IsRemote, + videoStream = ms.VideoStream != null ? new + { + codec = ms.VideoStream.Codec, + width = ms.VideoStream.Width, + height = ms.VideoStream.Height, + profile = ms.VideoStream.Profile, + level = ms.VideoStream.Level + } : null, + defaultAudioStream = ms.DefaultAudioStream != null ? new + { + codec = ms.DefaultAudioStream.Codec, + language = ms.DefaultAudioStream.Language, + channels = ms.DefaultAudioStream.Channels + } : null + }).ToArray(); + } + } + catch { } return new { - found = true, id = item.Id.ToString(), name = item.Name, - type = item.MediaType, - path = item.Path + type = item.GetType().Name, + mediaType = item.MediaType, + path = item.Path, + videoStreams, + audioStreams, + subtitleStreams, + imageStreams, + mediaSources }; } - // ---------- JSON-RPC-Helfer ---------- - - /// Wandelt einen JsonElement in einen plain C#-Wert um (für saubere Newtonsoft-Serialisierung). - private static object Plain(JsonElement el) + private object ToolCodecInventory(JsonElement args) { - switch (el.ValueKind) + var type = ArgString(args, "type"); + var limit = ArgInt(args, "limit") ?? 500; + + var q = new InternalItemsQuery { Recursive = true }; + if (!string.IsNullOrEmpty(type)) + q.IncludeItemTypes = new[] { type }; + if (limit > 0) + q.Limit = limit; + + // Video-Codecs + var ct = System.Threading.CancellationToken.None; + var videoCodecs = Library.GetVideoCodecs(q, ct); + var audioCodecs = Library.GetAudioCodecs(q, ct); + + return new { - case JsonValueKind.String: return el.GetString(); - case JsonValueKind.Number: - return el.TryGetInt64(out var l) ? l : el.GetDouble(); - case JsonValueKind.True: return true; - case JsonValueKind.False: return false; - case JsonValueKind.Null: - case JsonValueKind.Undefined: return null; - default: return el.GetRawText(); - } + scannedItems = limit > 0 ? limit.ToString() : "alle", + videoCodecs = videoCodecs.Items, + audioCodecs = audioCodecs.Items, + videoCodecCount = videoCodecs.TotalRecordCount, + audioCodecCount = audioCodecs.TotalRecordCount + }; } - private object RpcResult(JsonElement id, object result) => new { jsonrpc = "2.0", id = Plain(id), result }; - - private object RpcError(JsonElement id, int code, string message) => - new { jsonrpc = "2.0", id = Plain(id), error = new { code, message } }; - - /// - /// Liest die Versionsnummer aus der Assembly (Single Source of Truth: csproj <Version>). - /// - private static string GetVersion() + private object ToolFindByCodec(JsonElement args) { - var v = Assembly.GetExecutingAssembly().GetName().Version; - return v != null ? $"{v.Major}.{v.Minor}.{v.Build}" : "0.0.0"; + var codec = ArgString(args, "codec"); + if (string.IsNullOrEmpty(codec)) + throw new ArgumentException("codec ist erforderlich"); + + var kind = ArgString(args, "kind") ?? "video"; + var type = ArgString(args, "type"); + var limit = ArgInt(args, "limit") ?? 50; + + var q = new InternalItemsQuery + { + Recursive = true, + Limit = limit + }; + if (!string.IsNullOrEmpty(type)) + q.IncludeItemTypes = new[] { type }; + + if (kind.Equals("audio", StringComparison.OrdinalIgnoreCase)) + q.AudioCodecs = new[] { codec }; + else + q.VideoCodecs = new[] { codec }; + + var result = Library.GetItemsResult(q); + return new + { + codec, + kind, + total = result.TotalRecordCount, + items = result.Items.Select(ItemSummary).ToArray() + }; + } + + // ---- NEU: Bilder / Cover ---- + + private object ToolItemImages(JsonElement args) + { + var id = ArgString(args, "id"); + var item = ResolveItem(id); + if (item == null) + throw new ArgumentException("Item nicht gefunden: " + id); + + var serverUrl = GetServerUrl(); + var imageInfos = item.ImageInfos ?? Array.Empty(); + var images = imageInfos + .Where(i => i != null) + .Select(i => + { + var d = new Dictionary + { + ["type"] = i.Type.ToString(), + ["width"] = i.Width, + ["height"] = i.Height, + ["isLocalFile"] = i.IsLocalFile + }; + // URL bauen + try + { + var options = new ApiImageOptions + { + MaxWidth = 1000, + MaxHeight = 1000 + }; + var url = item.GetApiImageUrl(i, 0, options, serverUrl); + if (!string.IsNullOrEmpty(url)) d["url"] = url; + } + catch { } + return d; + }) + .ToArray(); + + return new + { + id = item.Id.ToString(), + name = item.Name, + imageCount = images.Length, + images + }; + } + + private object ToolImageUrl(JsonElement args) + { + var id = ArgString(args, "id"); + var item = ResolveItem(id); + if (item == null) + throw new ArgumentException("Item nicht gefunden: " + id); + + var imageTypeStr = ArgString(args, "imageType") ?? "Primary"; + var imageType = ParseImageType(imageTypeStr); + var maxWidth = ArgInt(args, "maxWidth") ?? 1000; + var maxHeight = ArgInt(args, "maxHeight") ?? 1000; + + var imageInfo = item.ImageInfos?.FirstOrDefault(i => i.Type == imageType); + if (imageInfo == null) + throw new ArgumentException($"Kein Bild vom Typ '{imageTypeStr}' für dieses Item gefunden. Verfügbare: {string.Join(", ", item.ImageInfos?.Select(i => i.Type.ToString()) ?? Array.Empty())}"); + + var serverUrl = GetServerUrl(); + var options = new ApiImageOptions + { + MaxWidth = maxWidth, + MaxHeight = maxHeight + }; + var url = item.GetApiImageUrl(imageInfo, 0, options, serverUrl); + + return new + { + id = item.Id.ToString(), + name = item.Name, + imageType = imageTypeStr, + width = imageInfo.Width, + height = imageInfo.Height, + url + }; + } + + // ---- NEU: Bibliothek ---- + + private object ToolLibraryStats() + { + var types = new[] { "Movie", "Series", "Season", "Episode", "Album", "Artist", "Song", "Video", "Photo" }; + var stats = new List(); + int total = 0; + + foreach (var t in types) + { + var q = new InternalItemsQuery + { + IncludeItemTypes = new[] { t }, + Recursive = true, + Limit = 0 + }; + try + { + var result = Library.GetItemsResult(q); + var count = result.TotalRecordCount; + total += count; + if (count > 0) + stats.Add(new { type = t, count }); + } + catch { } + } + + return new + { + totalItems = total, + byType = stats + }; + } + + private object ToolLibraryBrowse(JsonElement args) + { + var type = ArgString(args, "type") ?? "Movie"; + var start = ArgInt(args, "start") ?? 0; + var limit = Math.Min(ArgInt(args, "limit") ?? 20, 100); + var sortBy = ArgString(args, "sortBy") ?? "Name"; + + var q = new InternalItemsQuery + { + IncludeItemTypes = new[] { type }, + Recursive = true, + StartIndex = start, + Limit = limit + }; + + // Sortierung + var sortField = sortBy switch + { + "DateCreated" => "DateCreated", + "DateModified" => "DateModified", + "PremiereDate" => "PremiereDate", + "CommunityRating" => "CommunityRating", + _ => "SortName" + }; + q.OrderBy = new[] { (sortField, SortOrder.Ascending) }; + + var result = Library.GetItemsResult(q); + return new + { + type, + start, + limit, + total = result.TotalRecordCount, + items = result.Items.Select(ItemSummary).ToArray() + }; + } + + private object ToolLibraryFolders() + { + var folders = Library.GetVirtualFolders(); + return new + { + count = folders.Count, + folders = folders.Select(f => new + { + name = f.Name, + collectionType = f.CollectionType, + itemId = f.ItemId, + guid = f.Guid, + locations = f.Locations + }).ToArray() + }; + } + + private object ToolRecentlyAdded(JsonElement args) + { + var type = ArgString(args, "type"); + var limit = ArgInt(args, "limit") ?? 20; + + var q = new InternalItemsQuery + { + Recursive = true, + Limit = limit, + OrderBy = new[] { ("DateCreated", SortOrder.Descending) } + }; + if (!string.IsNullOrEmpty(type)) + q.IncludeItemTypes = new[] { type }; + + var result = Library.GetItemsResult(q); + return new + { + limit, + total = result.TotalRecordCount, + items = result.Items.Select(ItemSummary).ToArray() + }; + } + + private object ToolNextUp(JsonElement args) + { + var limit = ArgInt(args, "limit") ?? 20; + var userId = GetFirstUserId(); + + var q = new InternalItemsQuery + { + IsNextUpQuery = true, + Limit = limit + }; + if (userId.HasValue) + { + var user = Users.GetUserById(userId.Value); + if (user != null) q.User = user; + } + + var result = Library.GetItemsResult(q); + return new + { + limit, + total = result.TotalRecordCount, + items = result.Items.Select(ItemSummary).ToArray() + }; + } + + private object ToolRandom(JsonElement args) + { + var type = ArgString(args, "type") ?? "Movie"; + + var q = new InternalItemsQuery + { + IncludeItemTypes = new[] { type }, + Recursive = true, + Limit = 1, + RandomSeed = new Random().Next(1, 100000) + }; + + var result = Library.GetItemsResult(q); + if (result.Items.Length == 0) + return new { message = $"Kein Item vom Typ '{type}' gefunden." }; + + return ItemSummary(result.Items[0]); + } + + private object ToolTopRated(JsonElement args) + { + var type = ArgString(args, "type") ?? "Movie"; + var limit = ArgInt(args, "limit") ?? 20; + + var q = new InternalItemsQuery + { + IncludeItemTypes = new[] { type }, + Recursive = true, + Limit = limit, + OrderBy = new[] { ("CommunityRating", SortOrder.Descending) } + }; + + var result = Library.GetItemsResult(q); + return new + { + type, + limit, + total = result.TotalRecordCount, + items = result.Items.Select(ItemSummary).ToArray() + }; + } + + private object ToolMissingMetadata(JsonElement args) + { + var type = ArgString(args, "type"); + var limit = ArgInt(args, "limit") ?? 50; + + var q = new InternalItemsQuery + { + Recursive = true, + Limit = limit + }; + if (!string.IsNullOrEmpty(type)) + q.IncludeItemTypes = new[] { type }; + + var result = Library.GetItemsResult(q); + var missing = result.Items + .Where(i => i.ImageInfos == null || !i.ImageInfos.Any(ii => ii.Type == ImageType.Primary)) + .Select(ItemSummary) + .ToArray(); + + return new + { + scanned = result.Items.Length, + missingCount = missing.Length, + items = missing + }; + } + + // ---------- JSON-RPC Helpers ---------- + + private static object RpcResult(JsonElement id, object result) + { + var d = new Dictionary + { + ["jsonrpc"] = "2.0", + ["result"] = result + }; + if (id.ValueKind != JsonValueKind.Undefined) + d["id"] = id; + return d; + } + + private static object RpcError(JsonElement id, int code, string message) + { + return new Dictionary + { + ["jsonrpc"] = "2.0", + ["error"] = new { code, message }, + ["id"] = id + }; } } } diff --git a/src/eMCPy/Plugin.cs b/src/eMCPy/Plugin.cs index a57d7aa..4cc54be 100644 --- a/src/eMCPy/Plugin.cs +++ b/src/eMCPy/Plugin.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Plugins; +using MediaBrowser.Controller; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; @@ -25,6 +26,7 @@ namespace eMCPy public ISessionManager SessionManager { get; set; } public ILibraryManager LibraryManager { get; set; } public IUserManager UserManager { get; set; } + public IServerApplicationHost ServerAppHost { get; set; } public Plugin(IApplicationPaths applicationPaths, IXmlSerializer xmlSerializer, ILogManager logManager, IJsonSerializer jsonSerializer) diff --git a/src/eMCPy/PluginConfiguration.cs b/src/eMCPy/PluginConfiguration.cs index bb127e6..ba1011a 100644 --- a/src/eMCPy/PluginConfiguration.cs +++ b/src/eMCPy/PluginConfiguration.cs @@ -15,5 +15,12 @@ namespace eMCPy /// Leer = Status-Check nutzt http://<ServerHost>:<McpPort>/mcp. /// public string McpUrl { get; set; } = string.Empty; + + /// + /// Basis-URL des Emby-Servers für generierte Links (z. B. Bild-URLs). + /// Wichtig in Docker (Bridge-Netzwerk): hier die LAN-URL eintragen, + /// z. B. http://192.168.1.2:8096. Leer = automatische Erkennung. + /// + public string ServerUrl { get; set; } = string.Empty; } } diff --git a/src/eMCPy/ServiceRegistrar.cs b/src/eMCPy/ServiceRegistrar.cs index 362b5f4..8919c66 100644 --- a/src/eMCPy/ServiceRegistrar.cs +++ b/src/eMCPy/ServiceRegistrar.cs @@ -1,3 +1,4 @@ +using MediaBrowser.Controller; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Plugins; using MediaBrowser.Controller.Session; @@ -10,13 +11,14 @@ namespace eMCPy /// public class ServiceRegistrar : IServerEntryPoint { - public ServiceRegistrar(ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager) + public ServiceRegistrar(ISessionManager sessionManager, ILibraryManager libraryManager, IUserManager userManager, IServerApplicationHost serverAppHost) { if (Plugin.Instance != null) { Plugin.Instance.SessionManager = sessionManager; Plugin.Instance.LibraryManager = libraryManager; Plugin.Instance.UserManager = userManager; + Plugin.Instance.ServerAppHost = serverAppHost; } } diff --git a/src/eMCPy/eMCPy.csproj b/src/eMCPy/eMCPy.csproj index 6a4ab8f..c4f19c1 100644 --- a/src/eMCPy/eMCPy.csproj +++ b/src/eMCPy/eMCPy.csproj @@ -3,9 +3,9 @@ net6.0 eMCPy eMCPy - 1.1.1 - 1.1.1 - 1.1.1 + 1.2.0 + 1.2.0 + 1.2.0 false CS1591