Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
71 changes: 71 additions & 0 deletions TheIntroDB.Tests/ScanSafetyTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,29 @@
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()
{
Expand Down Expand Up @@ -76,12 +99,12 @@
// this to five minutes would turn an exhausted daily budget into
// a probe loop (the 429-every-five-minutes behaviour).
response.Headers.Add("X-UsageLimit-Reset", "49000");
Assert.Equal(49000, Assert.IsType<int>(method.Invoke(null, new object[] { response.Headers, null })));

Check warning on line 102 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.

Check warning on line 102 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.

Check warning on line 102 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

Check warning on line 102 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

// Sanity bound: never wait longer than a day for the daily bucket.
response.Headers.Clear();
response.Headers.Add("X-UsageLimit-Reset", "999999");
Assert.Equal(86400, Assert.IsType<int>(method.Invoke(null, new object[] { response.Headers, null })));

Check warning on line 107 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.

Check warning on line 107 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.

Check warning on line 107 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

Check warning on line 107 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
}
}

Expand All @@ -97,7 +120,7 @@
{
// A broken/huge rate-limit reset must never disable lookups for days.
response.Headers.Add("X-RateLimit-Reset", "999999");
Assert.Equal(300, Assert.IsType<int>(method.Invoke(null, new object[] { response.Headers, null })));

Check warning on line 123 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.

Check warning on line 123 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.

Check warning on line 123 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

Check warning on line 123 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
}
}

Expand All @@ -113,7 +136,7 @@
{
// Fiber's limiter answers rate-limit 429s with Retry-After only.
response.Headers.RetryAfter = new RetryConditionHeaderValue(TimeSpan.FromSeconds(10));
Assert.Equal(10, Assert.IsType<int>(method.Invoke(null, new object[] { response.Headers, null })));

Check warning on line 139 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.

Check warning on line 139 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.

Check warning on line 139 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

Check warning on line 139 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
}
}

Expand All @@ -127,7 +150,7 @@

using (var response = new HttpResponseMessage())
{
Assert.Equal(300, Assert.IsType<int>(method.Invoke(null, new object[] { response.Headers, null })));

Check warning on line 153 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.

Check warning on line 153 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / test

Cannot convert null literal to non-nullable reference type.

Check warning on line 153 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.

Check warning on line 153 in TheIntroDB.Tests/ScanSafetyTests.cs

View workflow job for this annotation

GitHub Actions / build

Cannot convert null literal to non-nullable reference type.
}
}

Expand Down Expand Up @@ -182,6 +205,7 @@
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]
Expand Down Expand Up @@ -215,6 +239,53 @@
Assert.False(CountsTowardLimit(SegmentFetchResult.Success(System.Array.Empty<MediaSegmentData>())));
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)
Expand Down
31 changes: 23 additions & 8 deletions TheIntroDB/Api/MediaFetchResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,33 +10,48 @@ public class MediaFetchResult
public bool IsServerError { get; }
public bool IsClientError { get; }

public bool IsError => IsRateLimited || IsServerError || IsClientError || (!IsNotFound && Response == null);
/// <summary>
/// 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.
/// </summary>
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);

/// <summary>
/// Creates an unsupported-coordinates result: the API rejected the season/episode
/// numbers as out of range, so the answer is final for this item.
/// </summary>
public static MediaFetchResult Unsupported() =>
new(null, false, false, false, false, true);
}
}
55 changes: 54 additions & 1 deletion TheIntroDB/Api/TheIntroDbClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,12 +177,41 @@ public async Task<MediaFetchResult> 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<string, object>
{
["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)
Expand Down Expand Up @@ -330,6 +359,30 @@ public async Task<MediaFetchResult> GetMediaAsync(
return MediaFetchResult.Error();
}

/// <summary>
/// Classifies a non-success GET /media response as the API refusing the
/// season/episode numbers themselves rather than the request as a whole.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <param name="statusCode">The response status code.</param>
/// <param name="body">The response body, when one was read.</param>
/// <returns>True when the API rejected the season/episode range.</returns>
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;
}

/// <summary>
/// Builds the query string for a GET /media request.
/// </summary>
Expand Down
35 changes: 27 additions & 8 deletions TheIntroDB/Providers/SegmentFetchResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,24 @@ public class SegmentFetchResult
public bool WasApiAttempted { get; }
public bool IsLookupCompleted { get; }

/// <summary>
/// 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.
/// </summary>
public bool IsUnsupported { get; }

private SegmentFetchResult(
IReadOnlyList<MediaSegmentData> segments,
bool isRateLimited,
bool isError,
bool isServerError,
bool isClientError,
bool wasApiAttempted,
bool isLookupCompleted)
bool isLookupCompleted,
bool isUnsupported)
{
Segments = segments;
IsRateLimited = isRateLimited;
Expand All @@ -29,27 +39,36 @@ private SegmentFetchResult(
IsClientError = isClientError;
WasApiAttempted = wasApiAttempted;
IsLookupCompleted = isLookupCompleted;
IsUnsupported = isUnsupported;
}

public static SegmentFetchResult Success(IReadOnlyList<MediaSegmentData> 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<MediaSegmentData>(), false, false, false, false, true, true);
new(System.Array.Empty<MediaSegmentData>(), false, false, false, false, true, true, false);

public static SegmentFetchResult NotAttempted() =>
new(System.Array.Empty<MediaSegmentData>(), false, false, false, false, false, false);
new(System.Array.Empty<MediaSegmentData>(), false, false, false, false, false, false, false);

public static SegmentFetchResult RateLimited() =>
new(System.Array.Empty<MediaSegmentData>(), true, true, false, false, true, false);
new(System.Array.Empty<MediaSegmentData>(), true, true, false, false, true, false, false);

public static SegmentFetchResult Error() =>
new(System.Array.Empty<MediaSegmentData>(), false, true, false, false, true, false);
new(System.Array.Empty<MediaSegmentData>(), false, true, false, false, true, false, false);

public static SegmentFetchResult ServerError() =>
new(System.Array.Empty<MediaSegmentData>(), false, true, true, false, true, true);
new(System.Array.Empty<MediaSegmentData>(), false, true, true, false, true, true, false);

public static SegmentFetchResult ClientError() =>
new(System.Array.Empty<MediaSegmentData>(), false, true, false, true, true, false);
new(System.Array.Empty<MediaSegmentData>(), false, true, false, true, true, false, false);

/// <summary>
/// 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.
/// </summary>
public static SegmentFetchResult Unsupported() =>
new(System.Array.Empty<MediaSegmentData>(), false, false, false, false, true, false, true);
}
}
Loading
Loading