diff options
17 files changed, 140 insertions, 287 deletions
diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 4a63fa3148..7588620481 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -253,6 +253,7 @@ - [klizas](https://github.com/klizas) - [p27ZuH6CNAdzr](https://github.com/p27ZuH6CNAdzr) - [mysticalsoap](https://github.com/mysticalsoap) + - [LoicBl0ndeau](https://github.com/LoicBl0ndeau) # Emby Contributors 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/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/lt-LT.json b/Emby.Server.Implementations/Localization/Core/lt-LT.json index 8546d5a21f..27442245dc 100644 --- a/Emby.Server.Implementations/Localization/Core/lt-LT.json +++ b/Emby.Server.Implementations/Localization/Core/lt-LT.json @@ -10,7 +10,7 @@ "Folders": "Aplankai", "Genres": "Žanrai", "HeaderContinueWatching": "Žiūrėti toliau", - "HeaderFavoriteEpisodes": "Mėgstamos serijos", + "HeaderFavoriteEpisodes": "Mėgstami epizodai", "HeaderFavoriteShows": "Mėgstami serialai", "HeaderLiveTV": "Tiesioginė TV", "HeaderNextUp": "Toliau", diff --git a/Emby.Server.Implementations/Plugins/PluginManager.cs b/Emby.Server.Implementations/Plugins/PluginManager.cs index f7ad9b9498..392493264c 100644 --- a/Emby.Server.Implementations/Plugins/PluginManager.cs +++ b/Emby.Server.Implementations/Plugins/PluginManager.cs @@ -415,7 +415,7 @@ namespace Emby.Server.Implementations.Plugins TargetAbi = versionInfo.TargetAbi ?? string.Empty, Timestamp = string.IsNullOrEmpty(versionInfo.Timestamp) ? DateTime.MinValue : DateTime.Parse(versionInfo.Timestamp, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal), Version = versionInfo.Version, - Status = status == PluginStatus.Disabled ? PluginStatus.Disabled : PluginStatus.Active, // Keep disabled state. + Status = status is PluginStatus.Disabled or PluginStatus.Superseded ? status : PluginStatus.Active, // Keep disabled and superseded states. AutoUpdate = true, ImagePath = imagePath }; diff --git a/Emby.Server.Implementations/Updates/InstallationManager.cs b/Emby.Server.Implementations/Updates/InstallationManager.cs index cccdb3e6aa..8fd4b83e78 100644 --- a/Emby.Server.Implementations/Updates/InstallationManager.cs +++ b/Emby.Server.Implementations/Updates/InstallationManager.cs @@ -503,9 +503,9 @@ namespace Emby.Server.Implementations.Updates var plugins = _pluginManager.Plugins; foreach (var plugin in plugins) { - // Don't auto update when plugin marked not to, or when it's disabled or pending removal. + // Don't auto update when plugin marked not to, or when it's disabled, superseded or pending removal. if (plugin.Manifest?.AutoUpdate == false - || plugin.Manifest?.Status is PluginStatus.Disabled or PluginStatus.Deleted) + || plugin.Manifest?.Status is PluginStatus.Disabled or PluginStatus.Superseded or PluginStatus.Deleted) { continue; } diff --git a/Jellyfin.Api/Controllers/TvShowsController.cs b/Jellyfin.Api/Controllers/TvShowsController.cs index 6b0f10e02a..4b4d06abde 100644 --- a/Jellyfin.Api/Controllers/TvShowsController.cs +++ b/Jellyfin.Api/Controllers/TvShowsController.cs @@ -275,11 +275,13 @@ public class TvShowsController : BaseJellyfinApiController .ToList(); } + Video? requestedVersion = null; if (startItemId.HasValue) { // The start item may be an alternate version, which is not part of the episode listing; start from its primary episode instead. var startId = startItemId.Value; - if (_libraryManager.GetItemById<Video>(startId)?.PrimaryVersionId is { } primaryVersionId) + requestedVersion = _libraryManager.GetItemById<Video>(startId); + if (requestedVersion?.PrimaryVersionId is { } primaryVersionId) { startId = primaryVersionId; } @@ -295,6 +297,19 @@ public class TvShowsController : BaseJellyfinApiController episodes = UserViewBuilder.FilterForAdjacency(episodes, adjacentTo.Value).ToList(); } + // The start item may be an alternate version, which is not part of the episode listing. + // Put it back at the position of its primary episode so clients that use this + // listing as a play queue start with the version the user selected. + if (requestedVersion is not null + && requestedVersion.PrimaryVersionId is { } requestedPrimaryId) + { + var primaryIndex = episodes.FindIndex(i => i.Id.Equals(requestedPrimaryId)); + if (primaryIndex >= 0) + { + episodes[primaryIndex] = requestedVersion; + } + } + if (sortBy == ItemSortBy.Random) { episodes.Shuffle(); 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.Implementations.Tests/Plugins/PluginManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs index ee41b968e1..9c50c5b1ac 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Plugins/PluginManagerTests.cs @@ -239,6 +239,28 @@ namespace Jellyfin.Server.Implementations.Tests.Plugins Assert.Equivalent(expectedManifest, result); } + [Theory] + [InlineData(PluginStatus.Active)] + [InlineData(PluginStatus.Disabled)] + [InlineData(PluginStatus.Superseded)] + public async Task PopulateManifest_CatalogRefresh_PreservesPersistedStatus(PluginStatus status) + { + var packageInfo = GenerateTestPackage(); + var pluginManager = new PluginManager(new NullLogger<PluginManager>(), null!, null!, null!, new Version(1, 0)); + var manifest = new PluginManifest + { + Id = packageInfo.Id, + Name = packageInfo.Name, + Version = packageInfo.Versions[0].Version, + Status = status + }; + + Assert.True(pluginManager.SaveManifest(manifest, _pluginPath)); + Assert.True(await pluginManager.PopulateManifest(packageInfo, new Version(1, 0), _pluginPath, status)); + + Assert.Equal(status, pluginManager.LoadManifest(_pluginPath).Manifest.Status); + } + [Fact] public async Task PopulateManifest_ExistingImage_IsNotDownloaded() { 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( |
