diff --git a/README.md b/README.md index f8acf00..53a16b3 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ The series' **display order** is sent with every episode lookup, so a show set t IMDb and TMDB ids are less accurate for TV episodes: those requests are always read in that provider's numbering. +**Year-based season numbers work.** Some series (e.g. *Tagesschau*) number their seasons by year, so Emby passes a season such as `2024` to the API, which accepts a season up to `9999`. If the API a server talks to still caps a season at `1000` (an older deployment), those episodes are refused with `Invalid season. Must be between 0 and 1000`: the plugin then says so once per series instead of once per episode, stops re-asking for them until Emby restarts, and leaves the segments it already has alone. + ## Configuration TheIntroDB plugin includes some configuration options to adjust and improve your experience. diff --git a/TheIntroDB.Tests/ScanSafetyTests.cs b/TheIntroDB.Tests/ScanSafetyTests.cs index 74e1946..365dc4b 100644 --- a/TheIntroDB.Tests/ScanSafetyTests.cs +++ b/TheIntroDB.Tests/ScanSafetyTests.cs @@ -37,6 +37,29 @@ public void BudgetEnforcesExactLimit() Assert.Equal(2, budget.Used); } + [Fact] + public void CachedSkipsDoNotSpendTheLookupBudget() + { + // The scanner reserves a lookup before calling the provider and cancels it when + // the result reports no API attempt — the not-found cache hit, and an address + // already refused as out of range in this session. So a cached skip must come + // back as NotAttempted: a cached hit that claimed WasApiAttempted would spend + // MaxLookupsPerRun on the same items every run and never reach the rest of the + // library (a review finding on this PR). Only a real HTTP 400 may return + // Unsupported, which is deliberately attempted. + Assert.False(SegmentFetchResult.NotAttempted().WasApiAttempted); + Assert.True(SegmentFetchResult.Unsupported().WasApiAttempted); + + var budget = new ScanLookupBudget(2); + Assert.True(budget.TryBeginLookup()); + budget.CancelLatestLookup(); + Assert.Equal(0, budget.Used); + + Assert.True(budget.TryBeginLookup()); + Assert.True(budget.TryBeginLookup()); + Assert.False(budget.TryBeginLookup()); + } + [Fact] public void RateLimitRetryCountsAgainstBudget() { @@ -182,6 +205,7 @@ public static IEnumerable IncompleteLookupResults() yield return new object[] { SegmentFetchResult.Error() }; yield return new object[] { SegmentFetchResult.RateLimited() }; yield return new object[] { SegmentFetchResult.ClientError() }; + yield return new object[] { SegmentFetchResult.Unsupported() }; } [Fact] @@ -215,6 +239,53 @@ public void FailureLimitCountsOnlyTransportFailures() Assert.False(CountsTowardLimit(SegmentFetchResult.Success(System.Array.Empty()))); Assert.False(CountsTowardLimit(SegmentFetchResult.RateLimited())); Assert.False(CountsTowardLimit(SegmentFetchResult.NotAttempted())); + Assert.False(CountsTowardLimit(SegmentFetchResult.Unsupported())); + } + + [Fact] + public void UnsupportedCoordinatesNeitherCompleteTheLookupNorLookLikeAFailure() + { + // jellyfin-plugin#39: an out-of-range season (a year-based season number) is + // final for the API version, so the scan must skip the item without counting + // it toward the abort limit, without treating it as a completed 404 (which + // would make the scan write an empty segment list over what is stored), and + // without classifying it as an error. + var result = SegmentFetchResult.Unsupported(); + Assert.True(result.IsUnsupported); + Assert.True(result.WasApiAttempted); + Assert.False(result.IsLookupCompleted); + Assert.False(result.IsError); + Assert.False(result.IsClientError); + Assert.False(result.IsServerError); + Assert.False(result.IsRateLimited); + Assert.Empty(result.Segments); + } + + [Fact] + public void UnsupportedApiResultIsNotAnErrorOrANotFound() + { + var result = TheIntroDB.Api.MediaFetchResult.Unsupported(); + Assert.True(result.IsUnsupported); + Assert.False(result.IsError); + Assert.False(result.IsNotFound); + Assert.False(result.IsClientError); + Assert.False(result.IsServerError); + } + + [Theory] + [InlineData(400, "{\"error\":\"Invalid season. Must be between 0 and 1000\"}", true)] // jellyfin-plugin#39: S2024 + [InlineData(400, "{\"error\":\"Invalid episode. Must be between 0 and 10000\"}", true)] + [InlineData(400, "{\"error\":\"invalid season. must be between 0 and 1000\"}", true)] + [InlineData(400, "{\"error\":\"Invalid season format: abc\"}", false)] // a client bug, not a range + [InlineData(400, "{\"error\":\"Invalid tvdb_id format\"}", false)] + [InlineData(400, "{\"error\":\"no submissions for this media\"}", false)] + [InlineData(404, "{\"error\":\"no submissions for this media\"}", false)] + [InlineData(500, "{\"error\":\"internal\"}", false)] + [InlineData(400, "", false)] + [InlineData(400, " ", false)] + public void OnlyTheSeasonOrEpisodeRangeIsClassifiedAsUnsupportedCoordinates(int statusCode, string body, bool expected) + { + Assert.Equal(expected, TheIntroDB.Api.TheIntroDbClient.IsUnsupportedCoordinateRejection(statusCode, body)); } private static bool CountsTowardLimit(SegmentFetchResult result) diff --git a/TheIntroDB/Api/MediaFetchResult.cs b/TheIntroDB/Api/MediaFetchResult.cs index 7089f9e..86d6adf 100644 --- a/TheIntroDB/Api/MediaFetchResult.cs +++ b/TheIntroDB/Api/MediaFetchResult.cs @@ -10,33 +10,48 @@ public class MediaFetchResult public bool IsServerError { get; } public bool IsClientError { get; } - public bool IsError => IsRateLimited || IsServerError || IsClientError || (!IsNotFound && Response == null); + /// + /// Gets a value indicating whether the API refused the item's season/episode + /// numbers themselves as out of range. Final, not transient: the coordinates + /// cannot be expressed on this API version, so retrying cannot help. + /// + public bool IsUnsupported { get; } - private MediaFetchResult(MediaResponse response, bool isRateLimited, bool isNotFound, bool isServerError, bool isClientError) + public bool IsError => IsRateLimited || IsServerError || IsClientError || (!IsNotFound && !IsUnsupported && Response == null); + + private MediaFetchResult(MediaResponse response, bool isRateLimited, bool isNotFound, bool isServerError, bool isClientError, bool isUnsupported) { Response = response; IsRateLimited = isRateLimited; IsNotFound = isNotFound; IsServerError = isServerError; IsClientError = isClientError; + IsUnsupported = isUnsupported; } public static MediaFetchResult Success(MediaResponse response) => - new(response, false, false, false, false); + new(response, false, false, false, false, false); public static MediaFetchResult NotFound() => - new(null, false, true, false, false); + new(null, false, true, false, false, false); public static MediaFetchResult RateLimited() => - new(null, true, false, false, false); + new(null, true, false, false, false, false); public static MediaFetchResult Error() => - new(null, false, false, false, false); + new(null, false, false, false, false, false); public static MediaFetchResult ServerError() => - new(null, false, false, true, false); + new(null, false, false, true, false, false); public static MediaFetchResult ClientError() => - new(null, false, false, false, true); + new(null, false, false, false, true, false); + + /// + /// Creates an unsupported-coordinates result: the API rejected the season/episode + /// numbers as out of range, so the answer is final for this item. + /// + public static MediaFetchResult Unsupported() => + new(null, false, false, false, false, true); } } diff --git a/TheIntroDB/Api/TheIntroDbClient.cs b/TheIntroDB/Api/TheIntroDbClient.cs index 76d4ad0..244bc4d 100644 --- a/TheIntroDB/Api/TheIntroDbClient.cs +++ b/TheIntroDB/Api/TheIntroDbClient.cs @@ -177,12 +177,41 @@ public async Task GetMediaAsync( if (!response.IsSuccessStatusCode) { - var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + var rawBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + var body = rawBody; if (!string.IsNullOrEmpty(body) && body.Length > 500) { body = body.Substring(0, 500) + "..."; } + if (IsUnsupportedCoordinateRejection((int)response.StatusCode, rawBody)) + { + // The season/episode numbers themselves are outside the range + // /media accepts (jellyfin-plugin#39: Emby hands a year-based + // season number such as 2024 straight through, and the API caps + // a season at 1000). Nothing about the caller's key or identity + // is wrong and no retry can express those coordinates, so this + // is final — and logged at debug, because the provider says it + // once per series instead of once per episode per scan. + _logger.Debug( + "TheIntroDB API rejected the season/episode coordinates as out of range: {0}", + string.IsNullOrEmpty(body) ? "(empty)" : body); + TrackUsage(trackUsage, + "theintrodb_api_media_fetch", + new Dictionary + { + ["host"] = "emby", + ["result"] = "unsupported_coordinates", + ["status"] = (int)response.StatusCode, + ["media_type"] = isMovie ? "movie" : "episode", + ["has_tmdb"] = hasTmdb ? 1 : 0, + ["has_tvdb"] = hasTvdb ? 1 : 0, + ["has_imdb"] = hasImdb ? 1 : 0, + ["has_theintrodb_api_key"] = !string.IsNullOrWhiteSpace(config.ApiKey) ? 1 : 0 + }); + return MediaFetchResult.Unsupported(); + } + _logger.Warn("TheIntroDB API error response body: {0}", string.IsNullOrEmpty(body) ? "(empty)" : body); if ((int)response.StatusCode == 404) @@ -330,6 +359,30 @@ public async Task GetMediaAsync( return MediaFetchResult.Error(); } + /// + /// Classifies a non-success GET /media response as the API refusing the + /// season/episode numbers themselves rather than the request as a whole. + /// + /// + /// Emby numbers a year-based season series by year (Tagesschau S2024E196), and + /// the API caps a season at 1000. Only the range message counts — a malformed + /// season ("Invalid season format") is a client bug and stays a loud error. + /// Matching the message prefix keeps it correct if the API moves the bounds. + /// + /// The response status code. + /// The response body, when one was read. + /// True when the API rejected the season/episode range. + internal static bool IsUnsupportedCoordinateRejection(int statusCode, string body) + { + if (statusCode != 400 || string.IsNullOrWhiteSpace(body)) + { + return false; + } + + return body.IndexOf("Invalid season. Must be between", StringComparison.OrdinalIgnoreCase) >= 0 + || body.IndexOf("Invalid episode. Must be between", StringComparison.OrdinalIgnoreCase) >= 0; + } + /// /// Builds the query string for a GET /media request. /// diff --git a/TheIntroDB/Providers/SegmentFetchResult.cs b/TheIntroDB/Providers/SegmentFetchResult.cs index 93b2a9e..444830d 100644 --- a/TheIntroDB/Providers/SegmentFetchResult.cs +++ b/TheIntroDB/Providers/SegmentFetchResult.cs @@ -13,6 +13,15 @@ public class SegmentFetchResult public bool WasApiAttempted { get; } public bool IsLookupCompleted { get; } + /// + /// Gets a value indicating whether the API refused the item's season/episode + /// numbers as out of range (a year-based season number, jellyfin-plugin#39). + /// Final for the item, and deliberately neither a completed lookup nor a + /// failure: the scan must leave the item's stored segments alone and must not + /// advance the consecutive-failure counter. + /// + public bool IsUnsupported { get; } + private SegmentFetchResult( IReadOnlyList segments, bool isRateLimited, @@ -20,7 +29,8 @@ private SegmentFetchResult( bool isServerError, bool isClientError, bool wasApiAttempted, - bool isLookupCompleted) + bool isLookupCompleted, + bool isUnsupported) { Segments = segments; IsRateLimited = isRateLimited; @@ -29,27 +39,36 @@ private SegmentFetchResult( IsClientError = isClientError; WasApiAttempted = wasApiAttempted; IsLookupCompleted = isLookupCompleted; + IsUnsupported = isUnsupported; } public static SegmentFetchResult Success(IReadOnlyList segments) => - new(segments, false, false, false, false, true, true); + new(segments, false, false, false, false, true, true, false); public static SegmentFetchResult NotFound() => - new(System.Array.Empty(), false, false, false, false, true, true); + new(System.Array.Empty(), false, false, false, false, true, true, false); public static SegmentFetchResult NotAttempted() => - new(System.Array.Empty(), false, false, false, false, false, false); + new(System.Array.Empty(), false, false, false, false, false, false, false); public static SegmentFetchResult RateLimited() => - new(System.Array.Empty(), true, true, false, false, true, false); + new(System.Array.Empty(), true, true, false, false, true, false, false); public static SegmentFetchResult Error() => - new(System.Array.Empty(), false, true, false, false, true, false); + new(System.Array.Empty(), false, true, false, false, true, false, false); public static SegmentFetchResult ServerError() => - new(System.Array.Empty(), false, true, true, false, true, true); + new(System.Array.Empty(), false, true, true, false, true, true, false); public static SegmentFetchResult ClientError() => - new(System.Array.Empty(), false, true, false, true, true, false); + new(System.Array.Empty(), false, true, false, true, true, false, false); + + /// + /// Creates an unsupported-coordinates result: the API refused the season/episode + /// numbers as out of range, so nothing can be fetched for this item and nothing + /// should be retried from the scan's point of view. + /// + public static SegmentFetchResult Unsupported() => + new(System.Array.Empty(), false, false, false, false, true, false, true); } } diff --git a/TheIntroDB/Providers/TheIntroDbSegmentProvider.cs b/TheIntroDB/Providers/TheIntroDbSegmentProvider.cs index 8df7b76..e98dfa8 100644 --- a/TheIntroDB/Providers/TheIntroDbSegmentProvider.cs +++ b/TheIntroDB/Providers/TheIntroDbSegmentProvider.cs @@ -30,6 +30,18 @@ public class TheIntroDbSegmentProvider private static readonly System.Collections.Concurrent.ConcurrentDictionary _orderSkipsLogged = new System.Collections.Concurrent.ConcurrentDictionary(); + // One warning per series whose season/episode numbers the API refuses, not one + // per episode of it (jellyfin-plugin#39). Static for the same reason as above. + private static readonly System.Collections.Concurrent.ConcurrentDictionary _coordinateSkipsLogged = + new System.Collections.Concurrent.ConcurrentDictionary(); + + // Addresses the API has refused as out of range during this session. A 400 + // spends rate-limit budget like any other request, so a year-based season must + // not be re-asked once per item per scan; the session boundary keeps a fixed API + // from being skipped forever once it starts accepting those numbers. + private static readonly System.Collections.Concurrent.ConcurrentDictionary _unsupportedCoordinates = + new System.Collections.Concurrent.ConcurrentDictionary(); + private readonly ILibraryManager _libraryManager; private readonly ILogger _logger; @@ -190,6 +202,23 @@ public async Task GetMediaSegmentsAsync( config.EnableIntro, config.EnableRecap, config.EnableCredits, config.EnablePreview, config.IgnoreMediaWithExistingSegments); var lookupKey = BuildNotFoundKey(isMovie, tmdbId, tvdbId, imdbId, season, episode, mapping, tvdbEpisodeId); + + if (_unsupportedCoordinates.ContainsKey(lookupKey)) + { + // This address was already refused as out of range in this session + // (jellyfin-plugin#39: a year-based season number the API caps). + // Re-asking would spend rate-limit budget on a known 400 for every item + // of every scan, so skip the request and leave the stored segments alone. + // + // NotAttempted, not Unsupported: no request went out, so the scan must + // cancel the lookup it reserved (the scanner refunds exactly when + // WasApiAttempted is false, like the not-found cache hit below). Claiming + // an attempt here would spend MaxLookupsPerRun on the same cached items + // every run and never reach the rest of the library. + _logger.Debug("Skipping {0}: TheIntroDB rejected its season/episode range in this session", item.Name); + return SegmentFetchResult.NotAttempted(); + } + if (TheIntroDbNotFoundCache.Instance.TryGetHit(lookupKey)) { _logger.Debug("Skipping {0}: known not found in TheIntroDB (cached 404)", item.Name); @@ -229,6 +258,24 @@ public async Task GetMediaSegmentsAsync( return SegmentFetchResult.ServerError(); } + if (mediaResult.IsUnsupported) + { + // The API refused the item's season/episode numbers as out of range + // (jellyfin-plugin#39: Emby passes a year-based season number such as + // 2024 straight through, and the API caps a season at 1000). Those + // coordinates cannot be expressed on this API version, so the outcome is + // final for the item: say it once per series, stop asking for the rest of + // the session, and return without touching anything the item already has. + var coordinatesSeries = (item as Episode)?.Series; + LogCoordinatesSkipOnce( + coordinatesSeries == null ? itemId : coordinatesSeries.Id, + coordinatesSeries == null ? item.Name : coordinatesSeries.Name, + season, + episode); + _unsupportedCoordinates[lookupKey] = 0; + return SegmentFetchResult.Unsupported(); + } + if (mediaResult.IsClientError) { _logger.Warn("TheIntroDB API rejected the request for {0} (client error). Skipping item.", item.Name); @@ -425,6 +472,26 @@ private void LogOrderSkipOnce(Guid itemId, string name) } } + /// + /// Logs a series whose season/episode numbers the API refuses, once per series + /// rather than once per episode (jellyfin-plugin#39). + /// + /// Emby id of the series being skipped (the episode's id when there is no series). + /// Series name, for the log line. + /// The season number the API refused. + /// The episode number the API refused. + private void LogCoordinatesSkipOnce(Guid itemId, string name, int? season, int? episode) + { + if (_coordinateSkipsLogged.TryAdd(itemId, 0)) + { + _logger.Warn( + "Skipping {0}: TheIntroDB rejected S{1}E{2} as out of range. An API that caps a season at 1000 refuses year-based season numbers (e.g. S2024); existing segments are kept.", + name, + season, + episode); + } + } + private static int? GetTmdbId(BaseItem item) { if (item?.ProviderIds is null) diff --git a/TheIntroDB/Services/TheIntroDbLibraryScanner.cs b/TheIntroDB/Services/TheIntroDbLibraryScanner.cs index c9fd8e0..a71fad7 100644 --- a/TheIntroDB/Services/TheIntroDbLibraryScanner.cs +++ b/TheIntroDB/Services/TheIntroDbLibraryScanner.cs @@ -221,6 +221,17 @@ public async Task ScanLibraryAsync( continue; } + if (result.IsUnsupported) + { + // The API refused this item's season/episode range (a year-based + // season number, jellyfin-plugin#39). The provider warned once + // for the series, and the answer is final for this API version, + // so there is nothing to write, nothing to retry and nothing to + // count as a failure: the item's stored segments stay as they are. + processed++; + continue; + } + if (!result.IsLookupCompleted) { if (ShouldCountTowardFailureLimit(result)) @@ -363,7 +374,8 @@ private static bool IsParkedBeyondRetryWindow() /// counter that aborts the scan. Only genuine "API may be down" signals count /// (transport failures after retries — ). /// Server (5xx) and client (4xx) responses prove the API is reachable and - /// answering, so they never abort the scan. + /// answering, so they never abort the scan — and neither does an out-of-range + /// season/episode answer, which is a property of the item's coordinates. /// private static bool ShouldCountTowardFailureLimit(SegmentFetchResult result) { @@ -371,7 +383,8 @@ private static bool ShouldCountTowardFailureLimit(SegmentFetchResult result) && !result.IsLookupCompleted && !result.IsServerError && !result.IsClientError - && !result.IsRateLimited; + && !result.IsRateLimited + && !result.IsUnsupported; } private static BaseItem[] OrderItemsForScan(