aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Directory.Packages.props2
-rw-r--r--Emby.Server.Implementations/Localization/Core/da.json20
-rw-r--r--Emby.Server.Implementations/Localization/Core/es-AR.json2
-rw-r--r--Emby.Server.Implementations/Localization/Core/fo.json2
-rw-r--r--Jellyfin.Server/Migrations/Routines/20260928120000_MigrateRatingLevels.cs2
-rw-r--r--MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs14
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs30
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieSimilarProvider.cs45
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesSimilarProvider.cs45
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs39
-rw-r--r--MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs10
-rw-r--r--tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs188
-rw-r--r--tests/Jellyfin.Server.Tests/Migrations/MigrateRatingLevelsTests.cs2
13 files changed, 108 insertions, 293 deletions
diff --git a/Directory.Packages.props b/Directory.Packages.props
index d533ad29e6..f65e8b17c0 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -81,7 +81,7 @@
<PackageVersion Include="System.Text.Json" Version="10.0.14" />
<PackageVersion Include="TagLibSharp" Version="2.3.0" />
<PackageVersion Include="z440.atl.core" Version="7.18.0" />
- <PackageVersion Include="TMDbLib" Version="3.0.0" />
+ <PackageVersion Include="TMDbLib" Version="4.0.0" />
<PackageVersion Include="UTF.Unknown" Version="2.7.0" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.1.5" />
<PackageVersion Include="xunit.v3" Version="3.2.2" />
diff --git a/Emby.Server.Implementations/Localization/Core/da.json b/Emby.Server.Implementations/Localization/Core/da.json
index 4c7d16a9a7..9cbb8bdaf3 100644
--- a/Emby.Server.Implementations/Localization/Core/da.json
+++ b/Emby.Server.Implementations/Localization/Core/da.json
@@ -27,8 +27,8 @@
"NameSeasonNumber": "Sæson {0}",
"NameSeasonUnknown": "Ukendt sæson",
"NewVersionIsAvailable": "En ny version af Jellyfin Server er tilgængelig.",
- "NotificationOptionApplicationUpdateAvailable": "Opdatering til applikationen er tilgængelig",
- "NotificationOptionApplicationUpdateInstalled": "Opdatering til applikationen blev installeret",
+ "NotificationOptionApplicationUpdateAvailable": "En opdatering til applikationen er tilgængelig",
+ "NotificationOptionApplicationUpdateInstalled": "Opdateringen til applikationen blev installeret",
"NotificationOptionAudioPlayback": "Lydafspilning påbegyndt",
"NotificationOptionAudioPlaybackStopped": "Lydafspilning stoppet",
"NotificationOptionCameraImageUploaded": "Kamerabillede uploadet",
@@ -68,8 +68,8 @@
"TaskUpdatePlugins": "Opdatér plugins",
"TaskCleanLogsDescription": "Sletter log-filer som er mere end {0} dage gamle.",
"TaskCleanLogs": "Ryd log-mappe",
- "TaskRefreshLibraryDescription": "Scanner dit mediebibliotek for nye filer og opdateret metadata.",
- "TaskRefreshLibrary": "Scan mediebibliotek",
+ "TaskRefreshLibraryDescription": "Skanner dit mediebibliotek for nye filer og opdaterede metadata.",
+ "TaskRefreshLibrary": "Skan mediebibliotek",
"TaskCleanCacheDescription": "Sletter cache-filer som systemet ikke længere bruger.",
"TaskCleanCache": "Ryd cache-mappe",
"TasksChannelsCategory": "Internetkanaler",
@@ -89,27 +89,27 @@
"Undefined": "Udefineret",
"Forced": "Tvunget",
"Default": "Standard",
- "TaskOptimizeDatabaseDescription": "Komprimerer databasen for at frigøre plads. Denne handling køres efter at have scannet mediebiblioteket, eller efter at have lavet ændringer til databasen.",
+ "TaskOptimizeDatabaseDescription": "Komprimerer databasen for at frigøre plads. Denne handling køres efter at have skannet mediebiblioteket eller efter at have lavet ændringer til databasen.",
"TaskOptimizeDatabase": "Optimér database",
"TaskKeyframeExtractorDescription": "Udtrækker rammer fra videofiler for at lave mere præcise HLS-playlister. Denne opgave kan tage lang tid.",
"TaskKeyframeExtractor": "Udtræk nøglerammer",
"External": "Ekstern",
"HearingImpaired": "Hørehæmmet",
- "TaskRefreshTrickplayImages": "Generer trickplay-billeder",
+ "TaskRefreshTrickplayImages": "Generér trickplay-billeder",
"TaskRefreshTrickplayImagesDescription": "Laver trickplay-billeder for videoer i aktiverede biblioteker.",
"TaskAudioNormalizationDescription": "Skanner filer for data vedrørende lydnormalisering.",
"TaskAudioNormalization": "Lydnormalisering",
"TaskDownloadMissingLyricsDescription": "Download sangtekster",
"TaskDownloadMissingLyrics": "Hent manglende sangtekster",
- "TaskExtractMediaSegments": "Scan for mediesegmenter",
- "TaskMoveTrickplayImages": "Migrer billedelokationer for trickplay-billeder",
- "TaskMoveTrickplayImagesDescription": "Flyt eksisterende trickplay-billeder jævnfør biblioteksindstillinger.",
+ "TaskExtractMediaSegments": "Skan for mediesegmenter",
+ "TaskMoveTrickplayImages": "Migrér billedlokationer for trickplay-billeder",
+ "TaskMoveTrickplayImagesDescription": "Flytter eksisterende trickplay-billeder i henhold til biblioteksindstillingerne.",
"TaskExtractMediaSegmentsDescription": "Udtrækker eller henter mediesegmenter fra plugins som understøtter MediaSegment.",
"CleanupUserDataTask": "Brugerdata oprydningsopgave",
"CleanupUserDataTaskDescription": "Rydder alle brugerdata (eks. visning- og favoritstatus) fra medier, der har været utilgængelige i mindst 90 dage.",
"LyricDownloadFailureFromForItem": "Sangtekster kunne ikke downloades fra {0} til {1}",
"Original": "Original",
- "NameExtraBehindTheScenes": "Bag scenerne",
+ "NameExtraBehindTheScenes": "Bag kulisserne",
"NameExtraClip": "Klip",
"NameExtraDeletedScene": "Slettet scene",
"NameExtraFeaturette": "Featurette",
diff --git a/Emby.Server.Implementations/Localization/Core/es-AR.json b/Emby.Server.Implementations/Localization/Core/es-AR.json
index a30abb9d4e..085166a963 100644
--- a/Emby.Server.Implementations/Localization/Core/es-AR.json
+++ b/Emby.Server.Implementations/Localization/Core/es-AR.json
@@ -94,7 +94,7 @@
"External": "Externo",
"TaskKeyframeExtractorDescription": "Extrae Fotogramas Clave de los archivos de vídeo para crear Listas de Reprodución HLS más precisas. Esta tarea puede durar mucho tiempo.",
"TaskKeyframeExtractor": "Extractor de Fotogramas Clave",
- "HearingImpaired": "Discapacidad Auditiva",
+ "HearingImpaired": "Discapacidad auditiva",
"TaskRefreshTrickplayImages": "Generar imágenes de Trickplay",
"TaskRefreshTrickplayImagesDescription": "Crea vistas previas de reproducción engañosa para videos en bibliotecas habilitadas.",
"TaskAudioNormalization": "Normalización de audio",
diff --git a/Emby.Server.Implementations/Localization/Core/fo.json b/Emby.Server.Implementations/Localization/Core/fo.json
index b6322e6561..5be132df2e 100644
--- a/Emby.Server.Implementations/Localization/Core/fo.json
+++ b/Emby.Server.Implementations/Localization/Core/fo.json
@@ -94,7 +94,7 @@
"TaskKeyframeExtractorDescription": "Úttekur lyklamyndir frá kykmynda-fílum til tess at byggja nágreiniligari HLS-spælilistar. Koyrslan kann taka langa tíð.",
"TaskOptimizeDatabaseDescription": "Trýstur dátugrunninin saman og loysur tóma goymslu. Koyrslan kann bøta um avrikið, eftir skanning ella aðrar broytingar í savninum ið elva til dátugrunnsbroytingar.",
"TaskRefreshChapterImagesDescription": "Ger smámyndir fyri kykmyndir ið hava kapitlar.",
- "TaskRefreshChapterImages": "Kapitlamyndaúttøkur",
+ "TaskRefreshChapterImages": "Kapittulmyndaúttøkur",
"NotificationOptionVideoPlayback": "Kykmyndaspæl byrjað",
"NotificationOptionVideoPlaybackStopped": "Kykmyndaspæl er steðgað",
"NotificationOptionAudioPlayback": "Ljóðspæl byrjað",
diff --git a/Jellyfin.Server/Migrations/Routines/20260928120000_MigrateRatingLevels.cs b/Jellyfin.Server/Migrations/Routines/20260928120000_MigrateRatingLevels.cs
index a2bf5bed9a..9772beacd9 100644
--- a/Jellyfin.Server/Migrations/Routines/20260928120000_MigrateRatingLevels.cs
+++ b/Jellyfin.Server/Migrations/Routines/20260928120000_MigrateRatingLevels.cs
@@ -55,7 +55,7 @@ internal class MigrateRatingLevels : IDatabaseMigrationRoutine
return Task.CompletedTask;
}
- private void PerformCore()
+ internal void PerformCore()
{
_logger.LogInformation("Recalculating parental rating levels based on rating string.");
using var context = _provider.CreateDbContext();
diff --git a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
index a751baf8b4..95095088c5 100644
--- a/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
+++ b/MediaBrowser.MediaEncoding/Encoder/MediaEncoder.cs
@@ -549,28 +549,28 @@ namespace MediaBrowser.MediaEncoding.Encoder
{
StartProcess(processWrapper);
using var reader = process.StandardOutput;
- await reader.BaseStream.CopyToAsync(memoryStream, cancellationToken).ConfigureAwait(false);
- memoryStream.Seek(0, SeekOrigin.Begin);
InternalMediaInfoResult result;
try
{
+ await reader.BaseStream.CopyToAsync(memoryStream, cancellationToken).ConfigureAwait(false);
+ memoryStream.Seek(0, SeekOrigin.Begin);
result = await JsonSerializer.DeserializeAsync<InternalMediaInfoResult>(
memoryStream,
_jsonSerializerOptions,
cancellationToken).ConfigureAwait(false);
+ if (result is null || (result.Streams is null && result.Format is null))
+ {
+ throw new FfmpegException("ffprobe failed - streams and format are both null.");
+ }
}
catch
{
+ // Cancellation while copying stdout must stop the probe before the wrapper unregisters it.
StopProcess(processWrapper, 100);
throw;
}
- if (result is null || (result.Streams is null && result.Format is null))
- {
- throw new FfmpegException("ffprobe failed - streams and format are both null.");
- }
-
if (result.Streams is not null)
{
// Normalize aspect ratio if invalid
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs
index 9501da7ec6..353c9011ec 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieProvider.cs
@@ -17,6 +17,8 @@ using MediaBrowser.Model.Providers;
using TMDbLib.Objects.Find;
using TMDbLib.Objects.General;
using TMDbLib.Objects.Search;
+using ReleaseDatesContainer = TMDbLib.Objects.Movies.ReleaseDatesContainer;
+using ReleaseDateType = TMDbLib.Objects.Movies.ReleaseDateType;
namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
{
@@ -223,22 +225,20 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
movie.CommunityRating = Convert.ToSingle(movieResult.VoteAverage);
- if (movieResult.Releases?.Countries is not null)
+ if (movieResult.ReleaseDates?.Results is not null)
{
- var releases = movieResult.Releases.Countries.Where(i => !string.IsNullOrWhiteSpace(i.Certification)).ToList();
+ var ourCertification = GetCertification(movieResult.ReleaseDates.Results, info.MetadataCountryCode);
- var ourRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, info.MetadataCountryCode, StringComparison.OrdinalIgnoreCase));
-
- if (ourRelease?.Certification is not null)
+ if (ourCertification is not null)
{
- movie.OfficialRating = TmdbUtils.BuildParentalRating(info.MetadataCountryCode, ourRelease.Certification);
+ movie.OfficialRating = TmdbUtils.BuildParentalRating(info.MetadataCountryCode, ourCertification);
}
else
{
- var usRelease = releases.FirstOrDefault(c => string.Equals(c.Iso_3166_1, "US", StringComparison.OrdinalIgnoreCase));
- if (usRelease?.Certification is not null)
+ var usCertification = GetCertification(movieResult.ReleaseDates.Results, "US");
+ if (usCertification is not null)
{
- movie.OfficialRating = usRelease.Certification;
+ movie.OfficialRating = usCertification;
}
}
}
@@ -392,6 +392,18 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies
return metadataResult;
}
+ private static string? GetCertification(IEnumerable<ReleaseDatesContainer> releases, string? countryCode)
+ {
+ var certified = releases
+ .FirstOrDefault(r => string.Equals(r.Iso_3166_1, countryCode, StringComparison.OrdinalIgnoreCase))?
+ .ReleaseDates?
+ .Where(r => !string.IsNullOrWhiteSpace(r.Certification))
+ .ToArray();
+
+ // A country lists one entry per release type; the theatrical one carries the rating that applies.
+ return (certified?.FirstOrDefault(r => r.Type == ReleaseDateType.Theatrical) ?? certified?.FirstOrDefault())?.Certification;
+ }
+
/// <inheritdoc />
public Task<HttpResponseMessage> GetImageResponse(string url, CancellationToken cancellationToken)
{
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieSimilarProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieSimilarProvider.cs
index 6a3c72d2fa..9ac50029e1 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieSimilarProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/Movies/TmdbMovieSimilarProvider.cs
@@ -3,10 +3,10 @@ using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading;
+using System.Threading.Tasks;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using Microsoft.Extensions.Logging;
using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
namespace MediaBrowser.Providers.Plugins.Tmdb.Movies;
@@ -17,17 +17,14 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.Movies;
public class TmdbMovieSimilarProvider : IRemoteSimilarItemsProvider<Movie>
{
private readonly TmdbClientManager _tmdbClientManager;
- private readonly ILogger<TmdbMovieSimilarProvider> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TmdbMovieSimilarProvider"/> class.
/// </summary>
/// <param name="tmdbClientManager">The TMDb client manager.</param>
- /// <param name="logger">The logger.</param>
- public TmdbMovieSimilarProvider(TmdbClientManager tmdbClientManager, ILogger<TmdbMovieSimilarProvider> logger)
+ public TmdbMovieSimilarProvider(TmdbClientManager tmdbClientManager)
{
_tmdbClientManager = tmdbClientManager;
- _logger = logger;
}
/// <inheritdoc/>
@@ -58,39 +55,15 @@ public class TmdbMovieSimilarProvider : IRemoteSimilarItemsProvider<Movie>
}
var providerName = MetadataProvider.Tmdb.ToString();
- var page = 1;
- var totalPages = 1;
-
- while (page <= totalPages && !cancellationToken.IsCancellationRequested)
+ await foreach (var recommendation in _tmdbClientManager
+ .GetMovieRecommendationsAsync(tmdbId, TmdbUtils.GetImageLanguagesParam(string.Empty), cancellationToken)
+ .ConfigureAwait(false))
{
- IReadOnlyList<TMDbLib.Objects.Search.SearchMovie> pageResults;
- try
- {
- (pageResults, totalPages) = await _tmdbClientManager
- .GetMovieRecommendationsPageAsync(tmdbId, page, TmdbUtils.GetImageLanguagesParam(string.Empty), cancellationToken)
- .ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogWarning(ex, "Failed to get recommended movies from TMDb for {TmdbId} page {Page}", tmdbId, page);
- yield break;
- }
-
- if (pageResults.Count == 0)
+ yield return new SimilarItemReference
{
- yield break;
- }
-
- foreach (var recommendation in pageResults)
- {
- yield return new SimilarItemReference
- {
- ProviderName = providerName,
- ProviderId = recommendation.Id.ToString(CultureInfo.InvariantCulture)
- };
- }
-
- page++;
+ ProviderName = providerName,
+ ProviderId = recommendation.Id.ToString(CultureInfo.InvariantCulture)
+ };
}
}
}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesSimilarProvider.cs b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesSimilarProvider.cs
index 40c7de05ad..bda5a69604 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesSimilarProvider.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TV/TmdbSeriesSimilarProvider.cs
@@ -3,11 +3,11 @@ using System.Collections.Generic;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Threading;
+using System.Threading.Tasks;
using MediaBrowser.Controller.Entities.TV;
using MediaBrowser.Controller.Library;
using MediaBrowser.Model.Configuration;
using MediaBrowser.Model.Entities;
-using Microsoft.Extensions.Logging;
namespace MediaBrowser.Providers.Plugins.Tmdb.TV;
@@ -17,17 +17,14 @@ namespace MediaBrowser.Providers.Plugins.Tmdb.TV;
public class TmdbSeriesSimilarProvider : IRemoteSimilarItemsProvider<Series>
{
private readonly TmdbClientManager _tmdbClientManager;
- private readonly ILogger<TmdbSeriesSimilarProvider> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="TmdbSeriesSimilarProvider"/> class.
/// </summary>
/// <param name="tmdbClientManager">The TMDb client manager.</param>
- /// <param name="logger">The logger.</param>
- public TmdbSeriesSimilarProvider(TmdbClientManager tmdbClientManager, ILogger<TmdbSeriesSimilarProvider> logger)
+ public TmdbSeriesSimilarProvider(TmdbClientManager tmdbClientManager)
{
_tmdbClientManager = tmdbClientManager;
- _logger = logger;
}
/// <inheritdoc/>
@@ -58,39 +55,15 @@ public class TmdbSeriesSimilarProvider : IRemoteSimilarItemsProvider<Series>
}
var providerName = MetadataProvider.Tmdb.ToString();
- var page = 1;
- var totalPages = 1;
-
- while (page <= totalPages && !cancellationToken.IsCancellationRequested)
+ await foreach (var recommendation in _tmdbClientManager
+ .GetSeriesRecommendationsAsync(tmdbId, TmdbUtils.GetImageLanguagesParam(string.Empty), cancellationToken)
+ .ConfigureAwait(false))
{
- IReadOnlyList<TMDbLib.Objects.Search.SearchTv> pageResults;
- try
- {
- (pageResults, totalPages) = await _tmdbClientManager
- .GetSeriesRecommendationsPageAsync(tmdbId, page, TmdbUtils.GetImageLanguagesParam(string.Empty), cancellationToken)
- .ConfigureAwait(false);
- }
- catch (Exception ex)
- {
- _logger.LogWarning(ex, "Failed to get recommended TV shows from TMDb for {TmdbId} page {Page}", tmdbId, page);
- yield break;
- }
-
- if (pageResults.Count == 0)
+ yield return new SimilarItemReference
{
- yield break;
- }
-
- foreach (var recommendation in pageResults)
- {
- yield return new SimilarItemReference
- {
- ProviderName = providerName,
- ProviderId = recommendation.Id.ToString(CultureInfo.InvariantCulture)
- };
- }
-
- page++;
+ ProviderName = providerName,
+ ProviderId = recommendation.Id.ToString(CultureInfo.InvariantCulture)
+ };
}
}
}
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs
index 7d119e8b84..3911d860f1 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbClientManager.cs
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.Globalization;
+using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using MediaBrowser.Model.Dto;
@@ -74,7 +75,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb
await EnsureClientConfigAsync().ConfigureAwait(false);
- var extraMethods = MovieMethods.Credits | MovieMethods.Releases | MovieMethods.Images | MovieMethods.Videos;
+ var extraMethods = MovieMethods.Credits | MovieMethods.ReleaseDates | MovieMethods.Images | MovieMethods.Videos;
if (!(Plugin.Instance?.Configuration.ExcludeTagsMovies).GetValueOrDefault())
{
extraMethods |= MovieMethods.Keywords;
@@ -251,7 +252,7 @@ namespace MediaBrowser.Providers.Plugins.Tmdb
/// <param name="countryCode">The country code, ISO 3166-1.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>The TMDb tv episode information or null if not found.</returns>
- public async Task<TvEpisode?> GetEpisodeAsync(int tvShowId, int seasonNumber, long episodeNumber, string? episodeGroup, string? language, string? imageLanguages, string? countryCode, CancellationToken cancellationToken)
+ public async Task<TvEpisode?> GetEpisodeAsync(int tvShowId, int seasonNumber, int episodeNumber, string? episodeGroup, string? language, string? imageLanguages, string? countryCode, CancellationToken cancellationToken)
{
var key = $"episode-{tvShowId.ToString(CultureInfo.InvariantCulture)}-s{seasonNumber.ToString(CultureInfo.InvariantCulture)}e{episodeNumber.ToString(CultureInfo.InvariantCulture)}-{episodeGroup}-{language}";
if (_memoryCache.TryGetValue(key, out TvEpisode? episode))
@@ -492,51 +493,37 @@ namespace MediaBrowser.Providers.Plugins.Tmdb
}
/// <summary>
- /// Gets a single page of recommended movies for a movie from the TMDb API.
+ /// Gets the recommended movies for a movie from the TMDb API, fetching further pages as the sequence is consumed.
/// </summary>
/// <param name="tmdbId">The TMDb id of the movie.</param>
- /// <param name="page">The page number to fetch (1-based).</param>
/// <param name="language">The language for results.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>A tuple containing the list of recommended movies and the total number of pages available.</returns>
- public async Task<(IReadOnlyList<SearchMovie> Results, int TotalPages)> GetMovieRecommendationsPageAsync(int tmdbId, int page, string? language, CancellationToken cancellationToken)
+ /// <returns>The recommended movies.</returns>
+ public async IAsyncEnumerable<SearchMovie> GetMovieRecommendationsAsync(int tmdbId, string? language, [EnumeratorCancellation] CancellationToken cancellationToken)
{
await EnsureClientConfigAsync().ConfigureAwait(false);
- var searchResults = await _tmDbClient
- .GetMovieRecommendationsAsync(tmdbId, language, page, cancellationToken)
- .ConfigureAwait(false);
-
- if (searchResults?.Results is null || searchResults.Results.Count == 0)
+ await foreach (var movie in _tmDbClient.GetMovieRecommendationsAllAsync(tmdbId, language, cancellationToken).ConfigureAwait(false))
{
- return ([], 0);
+ yield return movie;
}
-
- return (searchResults.Results, searchResults.TotalPages);
}
/// <summary>
- /// Gets a single page of recommended TV shows for a series from the TMDb API.
+ /// Gets the recommended TV shows for a series from the TMDb API, fetching further pages as the sequence is consumed.
/// </summary>
/// <param name="tmdbId">The TMDb id of the TV show.</param>
- /// <param name="page">The page number to fetch (1-based).</param>
/// <param name="language">The language for results.</param>
/// <param name="cancellationToken">The cancellation token.</param>
- /// <returns>A tuple containing the list of recommended TV shows and the total number of pages available.</returns>
- public async Task<(IReadOnlyList<SearchTv> Results, int TotalPages)> GetSeriesRecommendationsPageAsync(int tmdbId, int page, string? language, CancellationToken cancellationToken)
+ /// <returns>The recommended TV shows.</returns>
+ public async IAsyncEnumerable<SearchTv> GetSeriesRecommendationsAsync(int tmdbId, string? language, [EnumeratorCancellation] CancellationToken cancellationToken)
{
await EnsureClientConfigAsync().ConfigureAwait(false);
- var searchResults = await _tmDbClient
- .GetTvShowRecommendationsAsync(tmdbId, language, page, cancellationToken)
- .ConfigureAwait(false);
-
- if (searchResults?.Results is null || searchResults.Results.Count == 0)
+ await foreach (var series in _tmDbClient.GetTvShowRecommendationsAllAsync(tmdbId, language, cancellationToken).ConfigureAwait(false))
{
- return ([], 0);
+ yield return series;
}
-
- return (searchResults.Results, searchResults.TotalPages);
}
/// <summary>
diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs
index bd967b4041..f2e1975a08 100644
--- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs
+++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs
@@ -116,6 +116,16 @@ namespace MediaBrowser.Providers.Plugins.Tmdb
}
/// <summary>
+ /// Sets a numeric external id reported by TMDb, skipping the zero TMDb sends for "no id".
+ /// </summary>
+ /// <param name="instance">The item.</param>
+ /// <param name="provider">The provider the id belongs to.</param>
+ /// <param name="value">The id.</param>
+ /// <returns><c>true</c> if the id was set; otherwise, <c>false</c>.</returns>
+ public static bool TrySetProviderId(this IHasProviderIds instance, MetadataProvider provider, int? value)
+ => value > 0 && instance.TrySetProviderId(provider, value.Value.ToString(CultureInfo.InvariantCulture));
+
+ /// <summary>
/// Cleans the name according to TMDb requirements.
/// </summary>
/// <param name="name">The name of the entity.</param>
diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs
index 94672d5c7b..654e75f50d 100644
--- a/tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs
+++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs
@@ -26,162 +26,42 @@ using Xunit;
namespace Jellyfin.Server.Integration.Tests.Controllers;
-public sealed class ConfigurationControllerTests : IDisposable
+public sealed class ConfigurationControllerTests : IClassFixture<JellyfinApplicationFactory>
{
- private readonly Dictionary<string, object> _configurations = new()
- {
- [string.Empty] = new ServerConfiguration(),
- ["encoding"] = new EncodingOptions(),
- ["network"] = new NetworkConfiguration(),
- ["metadata"] = new MetadataConfiguration(),
- ["xbmcmetadata"] = new XbmcMetadataOptions(),
- ["livetv"] = new LiveTvOptions()
- };
-
- private readonly Mock<IServerConfigurationManager> _configurationManager = new();
- private readonly IHost _host;
- private readonly HttpClient _client;
-
- public ConfigurationControllerTests()
- {
- _configurationManager.Setup(manager => manager.Configuration)
- .Returns(() => (ServerConfiguration)_configurations[string.Empty]);
- _configurationManager.Setup(manager => manager.ReplaceConfiguration(It.IsAny<BaseApplicationConfiguration>()))
- .Callback<BaseApplicationConfiguration>(configuration => _configurations[string.Empty] = configuration);
- _configurationManager.Setup(manager => manager.GetConfiguration(It.IsAny<string>()))
- .Returns((string key) => _configurations[key]);
- _configurationManager.Setup(manager => manager.SaveConfiguration(It.IsAny<string>(), It.IsAny<object>()))
- .Callback<string, object>((key, configuration) => _configurations[key] = configuration);
-
- // Use the real API setup, but keep config in memory for these tests.
- _host = new HostBuilder().ConfigureWebHost(webHost => webHost
- .UseTestServer()
- .ConfigureServices(services =>
- {
- services.AddSingleton(_configurationManager.Object);
- services.AddAuthentication();
- services.AddAuthorization(options =>
- {
- options.AddPolicy(Policies.RequiresElevation, policy => policy.RequireAuthenticatedUser());
- });
- services.AddJellyfinApi(Array.Empty<Assembly>(), new NetworkConfiguration());
- })
- .Configure(app =>
- {
- app.UseRouting();
- app.Use((context, next) =>
- {
- context.User = new ClaimsPrincipal(new ClaimsIdentity("Test"));
- return next(context);
- });
- app.UseAuthorization();
- app.UseEndpoints(endpoints => endpoints.MapControllers());
- })).Start();
- _client = _host.GetTestClient();
- }
-
- [Theory]
- [InlineData("")]
- [InlineData("encoding")]
- [InlineData("network")]
- [InlineData("metadata")]
- [InlineData("xbmcmetadata")]
- [InlineData("livetv")]
- public async Task UpdateConfiguration_EmptyRequest_UsesInternalDefaults(string key)
- {
- await AssertMatchesLegacyDeserialization(key, "{}");
- }
+ private readonly JellyfinApplicationFactory _factory;
+ private static string? _accessToken;
- [Theory]
- [InlineData("", """
- {"ActivityLogRetentionDays":null,"QuickConnectAvailable":false,"MinResumePct":0,
- "SortRemoveWords":[],"TrickplayOptions":{"EnableHwAcceleration":true}}
- """)]
- [InlineData("encoding", """
- {"EnableHardwareEncoding":false,"EncodingThreadCount":0,"HardwareDecodingCodecs":[],
- "H264Crf":"19","EncoderPreset":"slow","VaapiDevice":null,"UnknownOption":true}
- """)]
- [InlineData("network", """
- {"CertificatePath":null,"CertificatePassword":null,"InternalHttpPort":"8097",
- "EnableRemoteAccess":false,"BaseUrl":"jellyfin/","KnownProxies":[]}
- """)]
- [InlineData("network", """
- {"BaseUrl":"","LocalNetworkSubnets":[],"LocalNetworkAddresses":[],"KnownProxies":[],
- "VirtualInterfaceNames":[],"PublishedServerUriBySubnet":[],"RemoteIPFilter":[]}
- """)]
- [InlineData("metadata", """{"UseFileCreationTimeForDateAdded":false}""")]
- [InlineData("xbmcmetadata", """{"UserId":"","ReleaseDateFormat":"yyyy-MM-dd","SaveImagePathsInNfo":false}""")]
- [InlineData("livetv", """
- {"GuideDays":"","RecordingPath":null,"SaveRecordingNFO":false,
- "TunerHosts":[{"Url":"http://tuner"}],"ListingProviders":[{"Type":"XmlTv"}]}
- """)]
- [InlineData("livetv", """{"TunerHosts":[],"ListingProviders":[],"MediaLocationsCreated":[]}""")]
- public async Task UpdateConfiguration_SuppliedProperties_MatchLegacyDeserialization(string key, string json)
+ public ConfigurationControllerTests(JellyfinApplicationFactory factory)
{
- await AssertMatchesLegacyDeserialization(key, json);
+ _factory = factory;
}
- [Theory]
- [InlineData("", "ServerName", "\"My server\"")]
- [InlineData("encoding", "H264Crf", "18")]
- [InlineData("network", "InternalHttpPort", "8097")]
- [InlineData("metadata", "UseFileCreationTimeForDateAdded", "false")]
- [InlineData("xbmcmetadata", "SaveImagePathsInNfo", "false")]
- [InlineData("livetv", "GuideDays", "7")]
- public async Task GetAndUpdateConfiguration_LowercaseRoute_RoundTripsConfiguration(string key, string property, string value)
+ [Fact]
+ public async Task GetConfiguration_Unauthorized_Unauthorized()
{
- using var response = await _client.GetAsync(GetUrl(key), TestContext.Current.CancellationToken);
- Assert.Equal(HttpStatusCode.OK, response.StatusCode);
- Assert.Equal(MediaTypeNames.Application.Json, response.Content.Headers.ContentType?.MediaType);
+ var client = _factory.CreateClient();
- var body = JsonNode.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken))!.AsObject();
- var expected = JsonSerializer.SerializeToNode(_configurations[key], JsonDefaults.Options)!.AsObject();
- Assert.True(JsonNode.DeepEquals(expected, body));
-
- body[property] = JsonNode.Parse(value);
- expected[property] = JsonNode.Parse(value);
- await PostConfiguration(key, body.ToJsonString());
-
- Assert.True(JsonNode.DeepEquals(expected, JsonSerializer.SerializeToNode(_configurations[key], JsonDefaults.Options)));
+ using var request = new HttpRequestMessage(HttpMethod.Get, GetUrl("encoding"));
+ using var response = await client.SendAsync(request, TestContext.Current.CancellationToken);
+ Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
}
[Fact]
public async Task UpdateConfiguration_CamelCaseProperties_AreApplied()
{
- await PostConfiguration("encoding", """{"h264Crf":18,"enableHardwareEncoding":false}""");
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client));
- var configuration = Assert.IsType<EncodingOptions>(_configurations["encoding"]);
- Assert.Equal(18, configuration.H264Crf);
- Assert.False(configuration.EnableHardwareEncoding);
- Assert.Equal(new EncodingOptions().H265Crf, configuration.H265Crf);
+ await PostConfiguration(client, "encoding", """{"h264Crf":18,"enableHardwareEncoding":false}""");
using var request = new HttpRequestMessage(HttpMethod.Get, GetUrl("encoding"));
request.Headers.Accept.ParseAdd(JsonDefaults.CamelCaseMediaType);
- using var response = await _client.SendAsync(request, TestContext.Current.CancellationToken);
+ using var response = await client.SendAsync(request, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var body = JsonNode.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken));
- Assert.Equal(18, body!["h264Crf"]!.GetValue<int>());
- }
-
- [Fact]
- public async Task UpdateConfiguration_OmittedProperties_ResetToDefaultsRatherThanCurrentValues()
- {
- await PostConfiguration("encoding", """{"H264Crf":18,"EnableHardwareEncoding":false}""");
- await AssertMatchesLegacyDeserialization("encoding", "{}");
- }
-
- [Fact]
- public async Task UpdateConfiguration_DefaultObjects_AreNotSharedBetweenRequests()
- {
- await PostConfiguration(string.Empty, "{}");
- var first = Assert.IsType<ServerConfiguration>(_configurations[string.Empty]);
- first.MetadataOptions[0].ItemType = "Changed";
- first.TrickplayOptions.WidthResolutions[0] = 123;
-
- await AssertMatchesLegacyDeserialization(string.Empty, "{}");
- var second = Assert.IsType<ServerConfiguration>(_configurations[string.Empty]);
- Assert.NotSame(first.MetadataOptions, second.MetadataOptions);
- Assert.NotSame(first.TrickplayOptions, second.TrickplayOptions);
+ Assert.NotNull(body);
+ Assert.NotNull(body["h264Crf"]);
+ Assert.Equal(18, body["h264Crf"]!.GetValue<int>());
}
[Theory]
@@ -203,18 +83,13 @@ public sealed class ConfigurationControllerTests : IDisposable
[InlineData("", """{"ServerName":null}""")]
public async Task UpdateConfiguration_InvalidRequest_DoesNotSave(string key, string json)
{
+ var client = _factory.CreateClient();
+ client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client));
+
using var content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json);
- using var response = await _client.PostAsync(GetUrl(key), content, TestContext.Current.CancellationToken);
+ using var response = await client.PostAsync(GetUrl(key), content, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
- _configurationManager.Verify(manager => manager.SaveConfiguration(It.IsAny<string>(), It.IsAny<object>()), Times.Never);
- _configurationManager.Verify(manager => manager.ReplaceConfiguration(It.IsAny<BaseApplicationConfiguration>()), Times.Never);
- }
-
- public void Dispose()
- {
- _client.Dispose();
- _host.Dispose();
}
private static string GetUrl(string key)
@@ -222,25 +97,10 @@ public sealed class ConfigurationControllerTests : IDisposable
return string.IsNullOrEmpty(key) ? "/System/Configuration" : "/System/Configuration/" + key;
}
- private async Task AssertMatchesLegacyDeserialization(string key, string json)
- {
- // Compare with how the old endpoint read the same JSON.
- var type = _configurations[key].GetType();
- var expected = JsonSerializer.Deserialize(json, type, JsonDefaults.Options);
-
- await PostConfiguration(key, json);
-
- var actual = _configurations[key];
- Assert.IsType(type, actual);
- Assert.True(JsonNode.DeepEquals(
- JsonSerializer.SerializeToNode(expected, type, JsonDefaults.Options),
- JsonSerializer.SerializeToNode(actual, type, JsonDefaults.Options)));
- }
-
- private async Task PostConfiguration(string key, string json)
+ private async Task PostConfiguration(HttpClient client, string key, string json)
{
using var content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json);
- using var response = await _client.PostAsync(GetUrl(key), content, TestContext.Current.CancellationToken);
+ using var response = await client.PostAsync(GetUrl(key), content, TestContext.Current.CancellationToken);
Assert.True(
response.StatusCode == HttpStatusCode.NoContent,
$"{response.StatusCode}: {await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken)}");
diff --git a/tests/Jellyfin.Server.Tests/Migrations/MigrateRatingLevelsTests.cs b/tests/Jellyfin.Server.Tests/Migrations/MigrateRatingLevelsTests.cs
index da7c72c98c..99f520b725 100644
--- a/tests/Jellyfin.Server.Tests/Migrations/MigrateRatingLevelsTests.cs
+++ b/tests/Jellyfin.Server.Tests/Migrations/MigrateRatingLevelsTests.cs
@@ -226,7 +226,7 @@ public sealed class MigrateRatingLevelsTests : IDisposable
var factory = new Mock<IDbContextFactory<JellyfinDbContext>>();
factory.Setup(f => f.CreateDbContext()).Returns(CreateDbContext);
- new MigrateRatingLevels(factory.Object, new StartupLogger<MigrateRatingLevels>(NullLogger<MigrateRatingLevels>.Instance), _localizationManager.Object, _libraryManager.Object, _appHost.Object).Perform();
+ new MigrateRatingLevels(factory.Object, new StartupLogger<MigrateRatingLevels>(NullLogger<MigrateRatingLevels>.Instance), _localizationManager.Object, _libraryManager.Object, _appHost.Object).PerformCore();
}
private JellyfinDbContext CreateDbContext() => new(