diff options
173 files changed, 11330 insertions, 1219 deletions
diff --git a/.github/workflows/openapi-workflow-run.yml b/.github/workflows/openapi-workflow-run.yml index cb6d2ef84b..aaf8192be1 100644 --- a/.github/workflows/openapi-workflow-run.yml +++ b/.github/workflows/openapi-workflow-run.yml @@ -50,7 +50,16 @@ jobs: path: openapi-report run-id: ${{ github.event.workflow_run.id }} github-token: ${{ secrets.GITHUB_TOKEN }} + - name: Check Result + id: check_file + run: | + if grep -q "No differences. Specifications are equivalent" ${{ steps.download_report.outputs.download-path }}/openapi-report.md; then + echo "comment=false" >> $GITHUB_ENV + else + echo "comment=true" >> $GITHUB_ENV + fi - name: Push Comment + if: env.comment == 'true' uses: thollander/actions-comment-pull-request@24bffb9b452ba05a4f3f77933840a6a841d1b32b # v3.0.1 with: github-token: ${{ secrets.JF_BOT_TOKEN }} diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index a01162a3b4..4a63fa3148 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -252,6 +252,7 @@ - [Daniel Aquino](https://github.com/chino) - [klizas](https://github.com/klizas) - [p27ZuH6CNAdzr](https://github.com/p27ZuH6CNAdzr) + - [mysticalsoap](https://github.com/mysticalsoap) # Emby Contributors diff --git a/Emby.Naming/ExternalFiles/ExternalPathParser.cs b/Emby.Naming/ExternalFiles/ExternalPathParser.cs index 1f16161282..f08cbf1cf7 100644 --- a/Emby.Naming/ExternalFiles/ExternalPathParser.cs +++ b/Emby.Naming/ExternalFiles/ExternalPathParser.cs @@ -104,18 +104,14 @@ namespace Emby.Naming.ExternalFiles if (culture is not null && pathInfo.Language is null) { - pathInfo.Language = culture.Name.Contains('-', StringComparison.OrdinalIgnoreCase) - ? culture.Name - : culture.ThreeLetterISOLanguageName; + pathInfo.Language = GetLanguageCode(culture); extraString = extraString.Replace(currentSlice, string.Empty, StringComparison.OrdinalIgnoreCase); } else if (culture is not null && pathInfo.Language == "hin") { // Hindi language code "hi" collides with a hearing impaired flag - use as Hindi only if no other language is set pathInfo.IsHearingImpaired = true; - pathInfo.Language = culture.Name.Contains('-', StringComparison.OrdinalIgnoreCase) - ? culture.Name - : culture.ThreeLetterISOLanguageName; + pathInfo.Language = GetLanguageCode(culture); extraString = extraString.Replace(currentSlice, string.Empty, StringComparison.OrdinalIgnoreCase); } else if (_namingOptions.MediaHearingImpairedFlags.Any(s => currentSliceWithoutSeparator.Equals(s, StringComparison.OrdinalIgnoreCase))) @@ -136,5 +132,17 @@ namespace Emby.Naming.ExternalFiles return pathInfo; } + + private static string? GetLanguageCode(CultureDto culture) + { + var tag = culture.TwoLetterISOLanguageName; + if (tag.Contains('-', StringComparison.Ordinal)) + { + return tag; + } + + return culture.ThreeLetterISOLanguageNames.FirstOrDefault(n => !n.Equals(tag, StringComparison.OrdinalIgnoreCase)) + ?? culture.ThreeLetterISOLanguageName; + } } } diff --git a/Emby.Server.Implementations/ApplicationHost.cs b/Emby.Server.Implementations/ApplicationHost.cs index 1a54565863..51aa71081f 100644 --- a/Emby.Server.Implementations/ApplicationHost.cs +++ b/Emby.Server.Implementations/ApplicationHost.cs @@ -728,7 +728,7 @@ namespace Emby.Server.Implementations _pluginManager.CreatePlugins(); Resolve<ILibraryManager>().AddParts( - GetExports<IResolverIgnoreRule>(), + GetExports<IResolverIgnoreRule>(type => ServiceProvider.GetService(type) ?? CreateInstanceSafe(type)), GetExports<IItemResolver>(), GetExports<IIntroProvider>(), GetExports<IBaseItemComparer>(), diff --git a/Emby.Server.Implementations/Library/DotIgnoreIgnoreRule.cs b/Emby.Server.Implementations/Library/DotIgnoreIgnoreRule.cs index 023c1e8915..0d63049372 100644 --- a/Emby.Server.Implementations/Library/DotIgnoreIgnoreRule.cs +++ b/Emby.Server.Implementations/Library/DotIgnoreIgnoreRule.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.IO; +using System.Linq; using System.Text.RegularExpressions; using BitFaster.Caching.Lru; using MediaBrowser.Controller.Entities; @@ -16,10 +17,14 @@ namespace Emby.Server.Implementations.Library; public class DotIgnoreIgnoreRule : IResolverIgnoreRule { private static readonly bool IsWindows = OperatingSystem.IsWindows(); + private static readonly StringComparison PathComparison = IsWindows ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; private readonly FastConcurrentLru<string, IgnoreFileCacheEntry> _directoryCache; private readonly FastConcurrentLru<string, ParsedIgnoreCacheEntry> _rulesCache; + private Func<IEnumerable<string>>? _libraryRootsProvider; + private volatile string[]? _libraryRoots; + /// <summary> /// Initializes a new instance of the <see cref="DotIgnoreIgnoreRule"/> class. /// </summary> @@ -40,11 +45,23 @@ public class DotIgnoreIgnoreRule : IResolverIgnoreRule public bool ShouldIgnore(FileSystemMetadata fileInfo, BaseItem? parent) => IsIgnoredInternal(fileInfo, parent); /// <summary> - /// Clears the directory lookup cache. The parsed rules cache is not cleared + /// Sets the provider of library root paths. The search for a .ignore file stops at the + /// outermost library root containing the path instead of walking up to the filesystem root. + /// </summary> + /// <param name="libraryRootsProvider">The library root paths provider.</param> + public void SetLibraryRootsProvider(Func<IEnumerable<string>> libraryRootsProvider) + { + _libraryRootsProvider = libraryRootsProvider; + ClearDirectoryCache(); + } + + /// <summary> + /// Clears the directory lookup cache and the library roots. The parsed rules cache is not cleared /// as it validates file modification time on each access. /// </summary> public void ClearDirectoryCache() { + _libraryRoots = null; _directoryCache.Clear(); } @@ -164,7 +181,9 @@ public class DotIgnoreIgnoreRule : IResolverIgnoreRule return null; } - // Walk up the directory tree to find .ignore file using DirectoryInfo.Parent + // Walk up the directory tree to find .ignore file using DirectoryInfo.Parent, + // never leaving the library: probing above it can hit autofs or network mounts (#17364) + var stopDirectory = GetOutermostLibraryRoot(startDir.FullName); var checkedDirs = new List<string> { directory }; for (var current = startDir; current is not null; current = current.Parent) @@ -203,6 +222,11 @@ public class DotIgnoreIgnoreRule : IResolverIgnoreRule { checkedDirs.Add(currentPath); } + + if (stopDirectory is not null && IsSamePath(currentPath, stopDirectory)) + { + break; + } } // No .ignore file found - cache null result for all directories @@ -215,6 +239,58 @@ public class DotIgnoreIgnoreRule : IResolverIgnoreRule return null; } + private string? GetOutermostLibraryRoot(string path) + { + string? outermost = null; + foreach (var root in GetLibraryRoots()) + { + if ((outermost is null || root.Length < outermost.Length) + && IsSameOrChildPath(path, root)) + { + outermost = root; + } + } + + return outermost; + } + + private string[] GetLibraryRoots() + { + var roots = _libraryRoots; + if (roots is not null) + { + return roots; + } + + var provider = _libraryRootsProvider; + if (provider is null) + { + return []; + } + + roots = provider() + .Where(r => !string.IsNullOrEmpty(r)) + .Select(r => Path.TrimEndingDirectorySeparator(Path.GetFullPath(r))) + .ToArray(); + _libraryRoots = roots; + return roots; + } + + private static bool IsSameOrChildPath(string path, string root) + { + if (IsSamePath(path, root)) + { + return true; + } + + // A filesystem root such as "/" keeps its trailing separator after trimming + return path.StartsWith(root, PathComparison) + && (Path.EndsInDirectorySeparator(root) || path[root.Length] == Path.DirectorySeparatorChar); + } + + private static bool IsSamePath(string path1, string path2) + => Path.TrimEndingDirectorySeparator(path1.AsSpan()).Equals(Path.TrimEndingDirectorySeparator(path2.AsSpan()), PathComparison); + private ParsedIgnoreCacheEntry? GetParsedRules(FileInfo ignoreFile) { if (!ignoreFile.Exists) diff --git a/Emby.Server.Implementations/Library/LibraryManager.cs b/Emby.Server.Implementations/Library/LibraryManager.cs index 16616dd328..359b0f1d0c 100644 --- a/Emby.Server.Implementations/Library/LibraryManager.cs +++ b/Emby.Server.Implementations/Library/LibraryManager.cs @@ -184,6 +184,7 @@ namespace Emby.Server.Implementations.Library _peopleRepository = peopleRepository; _pathManager = pathManager; _dotIgnoreIgnoreRule = dotIgnoreIgnoreRule; + _dotIgnoreIgnoreRule.SetLibraryRootsProvider(GetLibraryRootPaths); _localization = localization; _directoryService = directoryService; _extraResolver = new ExtraResolver(loggerFactory.CreateLogger<ExtraResolver>(), namingOptions, directoryService); @@ -1627,23 +1628,7 @@ namespace Emby.Server.Implementations.Library { Name = Path.GetFileName(dir), - Locations = _fileSystem.GetFilePaths(dir, false) - .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCase)) - .Select(i => - { - try - { - return _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(i)); - } - catch (Exception ex) - { - _logger.LogError(ex, "Error resolving shortcut file {File}", i); - return null; - } - }) - .Where(i => i is not null) - .Order() - .ToArray(), + Locations = GetVirtualFolderLocations(dir).Order().ToArray(), CollectionType = GetCollectionType(dir) }; @@ -1671,6 +1656,40 @@ namespace Emby.Server.Implementations.Library return info; } + private IEnumerable<string> GetVirtualFolderLocations(string dir) + { + return _fileSystem.GetFilePaths(dir, false) + .Where(i => Path.GetExtension(i.AsSpan()).Equals(ShortcutFileExtension, StringComparison.OrdinalIgnoreCase)) + .Select(i => + { + try + { + return _appHost.ExpandVirtualPath(_fileSystem.ResolveShortcut(i)); + } + catch (Exception ex) + { + _logger.LogError(ex, "Error resolving shortcut file {File}", i); + return null; + } + }) + .OfType<string>(); + } + + // Reads the .mblink files directly; going through RootFolder.Children would re-enter the resolver. + private IEnumerable<string> GetLibraryRootPaths() + { + // root/default only exists once the user root folder or a library has been created + var userViewsPath = _configurationManager.ApplicationPaths.DefaultUserViewsPath; + if (!_fileSystem.DirectoryExists(userViewsPath)) + { + return []; + } + + return _fileSystem.GetDirectoryPaths(userViewsPath) + .SelectMany(GetVirtualFolderLocations) + .ToList(); + } + private CollectionTypeOptions? GetCollectionType(string path) { var files = _fileSystem.GetFilePaths(path, [".collection"], true, false); @@ -3750,6 +3769,7 @@ namespace Emby.Server.Implementations.Library public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex, bool removeOnFailure) { + HttpRequestException? lastHttpException = null; foreach (var url in image.Path.Split('|')) { try @@ -3781,6 +3801,7 @@ namespace Emby.Server.Implementations.Library && (ex.StatusCode.Value == HttpStatusCode.NotFound || ex.StatusCode.Value == HttpStatusCode.Forbidden)) { _logger.LogDebug(ex, "Error downloading image {Url}", url); + lastHttpException = ex; continue; } @@ -3795,13 +3816,17 @@ namespace Emby.Server.Implementations.Library await item.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false); } - throw new InvalidOperationException(string.Format( - CultureInfo.InvariantCulture, - "Unable to convert any {0} image url in \"{1}\" to a local file for {2} ({3})", - image.Type, - image.Path, - item.Name, - item.Id)); + // Keep the rejection as the inner exception: callers such as the Live TV guide need the + // status code to tell a missing image from a provider that is refusing us. + throw new InvalidOperationException( + string.Format( + CultureInfo.InvariantCulture, + "Unable to convert any {0} image url in \"{1}\" to a local file for {2} ({3})", + image.Type, + image.Path, + item.Name, + item.Id), + lastHttpException); } public async Task AddVirtualFolder(string name, CollectionTypeOptions? collectionType, LibraryOptions options, bool refreshLibrary) @@ -4200,6 +4225,30 @@ namespace Emby.Server.Implementations.Library } /// <inheritdoc /> + public IReadOnlyList<int> GetYears(InternalItemsQuery query) + { + if (query.User is not null) + { + AddUserToQuery(query, query.User); + } + + SetTopParentOrAncestorIds(query); + return _itemRepository.GetYears(query); + } + + /// <inheritdoc /> + public IReadOnlyList<string> GetOfficialRatings(InternalItemsQuery query) + { + if (query.User is not null) + { + AddUserToQuery(query, query.User); + } + + SetTopParentOrAncestorIds(query); + return _itemRepository.GetOfficialRatings(query); + } + + /// <inheritdoc /> public IReadOnlyList<string> GetTagNames(InternalItemsQuery query) { if (query.User is not null) diff --git a/Emby.Server.Implementations/Library/MediaSourceManager.cs b/Emby.Server.Implementations/Library/MediaSourceManager.cs index e9bba05839..4513cefde8 100644 --- a/Emby.Server.Implementations/Library/MediaSourceManager.cs +++ b/Emby.Server.Implementations/Library/MediaSourceManager.cs @@ -481,13 +481,7 @@ namespace Emby.Server.Implementations.Library return []; } - var culture = _localizationManager.FindLanguageInfo(language); - if (culture is not null) - { - return culture.Name.Contains('-', StringComparison.OrdinalIgnoreCase) ? [culture.Name] : culture.ThreeLetterISOLanguageNames; - } - - return [language]; + return _localizationManager.GetMediaStreamLanguageCodes(language); } private void SetDefaultSubtitleStreamIndex(MediaSourceInfo source, UserItemData userData, User user, bool allowRememberingSelection) diff --git a/Emby.Server.Implementations/Library/MediaStreamSelector.cs b/Emby.Server.Implementations/Library/MediaStreamSelector.cs index 631179ffcf..31e36af3b8 100644 --- a/Emby.Server.Implementations/Library/MediaStreamSelector.cs +++ b/Emby.Server.Implementations/Library/MediaStreamSelector.cs @@ -46,6 +46,7 @@ namespace Emby.Server.Implementations.Library .ThenByDescending(x => x.IsDefault) .ThenByDescending(x => !x.IsForced && MatchesPreferredLanguage(x.Language, preferredLanguages)) .ThenByDescending(x => x.IsForced && MatchesPreferredLanguage(x.Language, preferredLanguages)) + .ThenBy(x => GetLanguageRank(x.Language, preferredLanguages)) .ThenByDescending(x => x.IsForced && IsLanguageUndefined(x.Language)) .ThenByDescending(x => x.IsForced) .ToList(); @@ -158,6 +159,13 @@ namespace Emby.Server.Implementations.Library preferredLanguages.Contains(language, StringComparison.OrdinalIgnoreCase); } + // Earlier preferences win among matches: a pt-br preference lists [pt-br, por] and must pick the pt-br track. + private static int GetLanguageRank(string language, IReadOnlyList<string> preferredLanguages) + { + var index = preferredLanguages.FindIndex(x => string.Equals(x, language, StringComparison.OrdinalIgnoreCase)); + return index == -1 ? int.MaxValue : index; + } + private static bool IsLanguageUndefined(string language) { // Check for null, empty, or known placeholders diff --git a/Emby.Server.Implementations/Library/Search/SqlSearchProvider.cs b/Emby.Server.Implementations/Library/Search/SqlSearchProvider.cs index a5ea02df51..dd96f75893 100644 --- a/Emby.Server.Implementations/Library/Search/SqlSearchProvider.cs +++ b/Emby.Server.Implementations/Library/Search/SqlSearchProvider.cs @@ -136,7 +136,7 @@ public class SqlSearchProvider : IInternalSearchProvider dbQuery = ApplyTypeFilter(dbQuery, query.IncludeItemTypes, query.ExcludeItemTypes); dbQuery = ApplyMediaTypeFilter(dbQuery, query.MediaTypes); - dbQuery = ApplyParentFilter(dbQuery, query.ParentId); + dbQuery = ApplyParentFilter(dbContext, dbQuery, query.ParentId); dbQuery = ApplyUserAccessFilter(dbContext, dbQuery, query); dbQuery = ExcludeVersionsOfMatchedPrimaries(dbQuery); @@ -205,6 +205,7 @@ public class SqlSearchProvider : IInternalSearchProvider } private static IQueryable<BaseItemEntity> ApplyParentFilter( + JellyfinDbContext context, IQueryable<BaseItemEntity> query, Guid? parentId) { @@ -214,7 +215,10 @@ public class SqlSearchProvider : IInternalSearchProvider } var pid = parentId.Value; - return query.Where(e => e.ParentId == pid || e.Parents!.Any(p => p.ParentItemId == pid)); + var descendantIds = context.AncestorIds + .Where(a => a.ParentItemId == pid) + .Select(a => a.ItemId); + return query.Where(e => e.ParentId == pid || descendantIds.Contains(e.Id)); } private static IQueryable<BaseItemEntity> ExcludeVersionsOfMatchedPrimaries(IQueryable<BaseItemEntity> query) diff --git a/Emby.Server.Implementations/Localization/Core/be.json b/Emby.Server.Implementations/Localization/Core/be.json index c5b1213096..23d2ffe45f 100644 --- a/Emby.Server.Implementations/Localization/Core/be.json +++ b/Emby.Server.Implementations/Localization/Core/be.json @@ -9,7 +9,7 @@ "Collections": "Калекцыі", "Default": "Прадвызначана", "FailedLoginAttemptWithUserName": "Няўдалая спроба ўваходу з {0}", - "Folders": "Папкі", + "Folders": "Тэчки", "Favorites": "Абранае", "External": "Знешні", "Genres": "Жанры", @@ -22,7 +22,7 @@ "Movies": "Фільмы", "Music": "Музыка", "MusicVideos": "Музычныя кліпы", - "NameInstallFailed": "Усталяванне {0} не атрымалася", + "NameInstallFailed": "Усталяванне {0} не ўдалося", "NameSeasonNumber": "Сезон {0}", "NotificationOptionApplicationUpdateAvailable": "Даступна абнаўленне праграмы", "NotificationOptionPluginInstalled": "Плагін усталяваны", @@ -65,7 +65,7 @@ "NotificationOptionUserLockedOut": "Карыстальнік заблакіраваны", "NotificationOptionVideoPlayback": "Пачалося прайграванне відэа", "NotificationOptionVideoPlaybackStopped": "Прайграванне відэа спынена", - "ScheduledTaskFailedWithName": "{0} не атрымалася", + "ScheduledTaskFailedWithName": "{0} не ўдалося", "Shows": "Шоу", "StartupEmbyServerIsLoading": "Jellyfin Server загружаецца. Калі ласка, паўтарыце спробу крыху пазней.", "SubtitleDownloadFailureFromForItem": "Субцітры для {1} не ўдалося спампаваць з {0}", @@ -84,7 +84,7 @@ "TaskCleanCache": "Ачысціць кэш", "TaskCleanCacheDescription": "Выдаляе файлы кэша, якія больш не патрэбныя сістэме.", "TaskRefreshChapterImages": "Вынуць выявы раздзелаў", - "TaskRefreshLibrary": "Сканаваць бібліятэку", + "TaskRefreshLibrary": "Сканаваць медыятэку", "TaskRefreshLibraryDescription": "Сканіруе вашу медыятэку на наяўнасць новых файлаў і абнаўляе метаданыя.", "TaskCleanLogs": "Ачысціць журнал", "TaskRefreshPeople": "Абнавіць выканаўцаў", @@ -94,20 +94,20 @@ "TaskCleanTranscodeDescription": "Выдаляе перакадзіраваныя файлы, старэйшыя за адзін дзень.", "TaskRefreshChannels": "Абнавіць каналы", "TaskDownloadMissingSubtitles": "Спампаваць адсутныя субцітры", - "TaskKeyframeExtractorDescription": "Выдае ключавыя кадры з відэафайлаў для стварэння больш дакладных плэй-лістоў HLS. Гэта задача можа выконвацца доўга.", + "TaskKeyframeExtractorDescription": "Выдае ключавыя кадры з відэафайлаў для стварэння больш дакладных плэйлістоў HLS. Гэта задача можа выконвацца доўга.", "TaskRefreshTrickplayImages": "Стварыць выявы Trickplay", "TaskRefreshTrickplayImagesDescription": "Стварае перадпрагляды відэаролікаў для Trickplay у падключаных бібліятэках.", "TaskAudioNormalizationDescription": "Скануе файлы на прадмет нармалізацыі гуку.", "TaskAudioNormalization": "Нармалізацыя гуку", - "TaskExtractMediaSegmentsDescription": "Выдае або атрымлівае медыясегменты з убудоў з падтрымкай MediaSegment.", + "TaskExtractMediaSegmentsDescription": "Выдае або атрымлівае медыясегменты з плагінаў з падтрымкай MediaSegment.", "TaskMoveTrickplayImagesDescription": "Перамяшчае існуючыя файлы trickplay у адпаведнасці з наладамі бібліятэкі.", - "TaskDownloadMissingLyrics": "Спампаваць адсутныя тэксты песняў", - "TaskDownloadMissingLyricsDescription": "Спампоўвае тэксты для песняў", - "TaskExtractMediaSegments": "Сканіраванне медыя-сегмента", + "TaskDownloadMissingLyrics": "Спампаваць адсутныя тэксты песень", + "TaskDownloadMissingLyricsDescription": "Спампоўвае тэксты песень", + "TaskExtractMediaSegments": "Сканаванне медыясегментаў", "TaskMoveTrickplayImages": "Перанесці месцазнаходжанне выявы Trickplay", "CleanupUserDataTask": "Задача па ачыстцы даных карыстальніка", - "CleanupUserDataTaskDescription": "Ачышчае ўсе даныя карыстальніка (стан прагляду, абранае і г.д.) для медыяфайлаў, што адсутнічаюць больш за 90 дзён.", - "LyricDownloadFailureFromForItem": "Не ўдалося загрузіць тэкст песні з {0} для {1}", + "CleanupUserDataTaskDescription": "Ачышчае ўсе даныя карыстальніка (стан прагляду, абранае і г.д.) для медыя, якія адсутнічаюць больш за 90 дзён.", + "LyricDownloadFailureFromForItem": "Не ўдалося спампаваць тэксты песень з {0} для {1}", "NameExtraDeletedScene": "Выдаленая сцэна", "NameExtraInterview": "Інтэрв'ю", "NameExtraNumbered": "{0} {1}", @@ -115,8 +115,11 @@ "NameExtraTrailer": "Трэйлер", "NameExtraBehindTheScenes": "За кулісамі", "NameExtraClip": "Кліп", - "NameExtraFeaturette": "Кароткаметражка", + "NameExtraFeaturette": "Фічарэт", "NameExtraSample": "Прыклад", "NameExtraShort": "Кароткаметражка", - "NameExtraThemeSong": "Тэматычная песня" + "NameExtraThemeSong": "Фонавая музыка", + "NameExtraThemeVideo": "Фонавае відэа", + "Original": "Арыгінал", + "NameExtraUnknown": "Дадаткова" } diff --git a/Emby.Server.Implementations/Localization/Core/fo.json b/Emby.Server.Implementations/Localization/Core/fo.json index b9964b02b8..5be132df2e 100644 --- a/Emby.Server.Implementations/Localization/Core/fo.json +++ b/Emby.Server.Implementations/Localization/Core/fo.json @@ -1,5 +1,5 @@ { - "Artists": "Tónlistafólk", + "Artists": "Listafólk", "Collections": "Samlingar", "Default": "Forsett", "External": "Ytri", @@ -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/Emby.Server.Implementations/Localization/Core/hr.json b/Emby.Server.Implementations/Localization/Core/hr.json index c7e2b5f5e9..596a7fa6be 100644 --- a/Emby.Server.Implementations/Localization/Core/hr.json +++ b/Emby.Server.Implementations/Localization/Core/hr.json @@ -4,7 +4,7 @@ "AuthenticationSucceededWithUserName": "{0} uspješno ovjerena", "Books": "Knjige", "ChapterNameValue": "Poglavlje {0}", - "Collections": "Zbirke", + "Collections": "Kolekcije", "FailedLoginAttemptWithUserName": "Neuspješan pokušaj prijave od {0}", "Favorites": "Favoriti", "Folders": "Mape", @@ -25,8 +25,8 @@ "MusicVideos": "Glazbeni spotovi", "NameInstallFailed": "{0} neuspješnih instalacija", "NameSeasonNumber": "Sezona {0}", - "NameSeasonUnknown": "Sezona nepoznata", - "NewVersionIsAvailable": "Nova verzija Jellyfin servera je dostupna za preuzimanje.", + "NameSeasonUnknown": "Nepoznata sezona", + "NewVersionIsAvailable": "Nova verzija Jellyfin poslužitelja je dostupna za preuzimanje.", "NotificationOptionApplicationUpdateAvailable": "Dostupno je ažuriranje aplikacije", "NotificationOptionApplicationUpdateInstalled": "Instalirano je ažuriranje aplikacije", "NotificationOptionAudioPlayback": "Reprodukcija glazbe započela", @@ -38,7 +38,7 @@ "NotificationOptionPluginInstalled": "Dodatak instaliran", "NotificationOptionPluginUninstalled": "Dodatak deinstaliran", "NotificationOptionPluginUpdateInstalled": "Instalirano ažuriranje dodatka", - "NotificationOptionServerRestartRequired": "Ponovno pokrenite server", + "NotificationOptionServerRestartRequired": "Ponovno pokrenite poslužitelj", "NotificationOptionTaskFailed": "Greška zakazanog zadatka", "NotificationOptionUserLockedOut": "Korisnik zaključan", "NotificationOptionVideoPlayback": "Reprodukcija videa započela", @@ -49,7 +49,7 @@ "PluginUpdatedWithName": "{0} je ažurirano", "ScheduledTaskFailedWithName": "{0} neuspjelo", "Shows": "Emisije", - "StartupEmbyServerIsLoading": "Jellyfin server se učitava. Pokušajte ponovo uskoro.", + "StartupEmbyServerIsLoading": "Jellyfin poslužitelj se učitava. Pokušajte ponovno uskoro.", "SubtitleDownloadFailureFromForItem": "Titlovi nisu uspješno preuzeti od {0} za {1}", "TvShows": "TV emisije", "UserCreatedWithName": "Korisnik {0} je kreiran", @@ -57,13 +57,13 @@ "UserDownloadingItemWithValues": "{0} preuzima {1}", "UserLockedOutWithName": "Korisnik {0} je zaključan", "UserOfflineFromDevice": "{0} prekinuo vezu od {1}", - "UserOnlineFromDevice": "{0} povezan od {1}", + "UserOnlineFromDevice": "{0} povezan sa {1}", "UserPasswordChangedWithName": "Lozinka je promijenjena za korisnika {0}", "UserStartedPlayingItemWithValues": "{0} je pokrenuo reprodukciju {1} na {2}", "UserStoppedPlayingItemWithValues": "{0} je završio reprodukciju {1} na {2}", "VersionNumber": "Verzija {0}", - "TaskRefreshLibraryDescription": "Skenira biblioteku medija radi novih datoteka i osvježava metapodatke.", - "TaskRefreshLibrary": "Skeniraj biblioteku medija", + "TaskRefreshLibraryDescription": "Pretražuje biblioteku medija radi novih datoteka i osvježava metapodatke.", + "TaskRefreshLibrary": "Pretraži biblioteku medija", "TaskRefreshChapterImagesDescription": "Kreira sličice za videozapise koji imaju poglavlja.", "TaskRefreshChapterImages": "Izdvoji slike poglavlja", "TaskCleanCacheDescription": "Briše nepotrebne datoteke iz predmemorije.", @@ -80,7 +80,7 @@ "TaskUpdatePlugins": "Ažuriraj dodatke", "TaskRefreshPeopleDescription": "Ažurira metapodatke za glumce i redatelje u biblioteci medija.", "TaskRefreshPeople": "Osvježi osobe", - "TaskCleanLogsDescription": "Briše zapise dnevnika koji su stariji od {0} dana.", + "TaskCleanLogsDescription": "Briše dnevnik zapisa koji su stariji od {0} dana.", "TaskCleanLogs": "Očisti mapu dnevnika zapisa", "TasksChannelsCategory": "Internet kanali", "TasksLibraryCategory": "Biblioteka", @@ -90,19 +90,19 @@ "Forced": "Forsirani", "Default": "Zadano", "TaskOptimizeDatabase": "Optimiziraj bazu podataka", - "External": "Eksterni", - "TaskKeyframeExtractorDescription": "Izvlačenje ključnih okvira iz videozapisa za stvaranje objektivnije HLS liste za reprodukciju. Pokretanje ovog zadatka može potrajati.", - "TaskKeyframeExtractor": "Izvoditelj ključnog okvira", + "External": "Vanjski", + "TaskKeyframeExtractorDescription": "Izvlačenje ključnih kadrova iz videozapisa za stvaranje preciznije HLS liste za reprodukciju. Ovaj zadatak može potrajati duže.", + "TaskKeyframeExtractor": "Ekstraktor ključnih kadrova", "TaskOptimizeDatabaseDescription": "Sažima bazu podataka i uklanja prazan prostor. Pokretanje ovog zadatka, može poboljšati performanse nakon provođenja indeksiranja biblioteke ili provođenja drugih promjena koje utječu na bazu podataka.", "HearingImpaired": "Oštećen sluh", "TaskRefreshTrickplayImages": "Generiraj slike brzog pregledavanja", "TaskRefreshTrickplayImagesDescription": "Stvara preglede brzog pregledavanja za videa u aktiviranim bibliotekama.", "TaskAudioNormalization": "Normalizacija zvuka", - "TaskAudioNormalizationDescription": "Skenira datoteke u potrazi za podacima o normalizaciji zvuka.", - "TaskExtractMediaSegments": "Skeniranje dijelova medija", + "TaskAudioNormalizationDescription": "Pretražuje datoteke u potrazi za podacima o normalizaciji zvuka.", + "TaskExtractMediaSegments": "Pretraživanje dijelova medija", "TaskDownloadMissingLyrics": "Preuzmi tekstove koji nedostaju", "TaskDownloadMissingLyricsDescription": "Preuzmi tekstove pjesama", - "TaskExtractMediaSegmentsDescription": "Izvlači ili pribavlja dijelove medija iz omogućenih media pluginova.", + "TaskExtractMediaSegmentsDescription": "Izvlači ili preuzima dijelove medija s omogućenim medija dodatcima.", "TaskMoveTrickplayImages": "Premjesti mjesto slika brzog pregledavanja", "TaskMoveTrickplayImagesDescription": "Premješta postojeće datoteke brzog pregledavanja u postavke biblioteke.", "CleanupUserDataTask": "Zadatak čišćenja korisničkih podataka", @@ -111,15 +111,15 @@ "LyricDownloadFailureFromForItem": "Preuzimanje tekstova pjesmi od {0} za {1} nije uspjelo", "NameExtraBehindTheScenes": "Iza kulisa", "NameExtraClip": "Klip", - "NameExtraDeletedScene": "Obrisana Scena", + "NameExtraDeletedScene": "Obrisana scena", "NameExtraFeaturette": "Promotivni video", "NameExtraInterview": "Intervju", "NameExtraNumbered": "{0} {1}", "NameExtraSample": "Uzorak", "NameExtraScene": "Scena", "NameExtraShort": "Kratki film", - "NameExtraThemeSong": "Glavna Pjesma", - "NameExtraThemeVideo": "Tema videa", + "NameExtraThemeSong": "Pjesma teme", + "NameExtraThemeVideo": "Video teme", "NameExtraTrailer": "Trailer", "NameExtraUnknown": "Dodatno" } diff --git a/Emby.Server.Implementations/Localization/Core/hy.json b/Emby.Server.Implementations/Localization/Core/hy.json index 09f1bfe79c..2505226972 100644 --- a/Emby.Server.Implementations/Localization/Core/hy.json +++ b/Emby.Server.Implementations/Localization/Core/hy.json @@ -19,8 +19,8 @@ "VersionNumber": "Տարբերակ {0}", "TasksMaintenanceCategory": "Սպասարկում", "TasksChannelsCategory": "Ինտերնետային ալիքներ", - "TaskRefreshPeople": "Թարմացնել մարդկանց", - "TaskRefreshChannels": "Թարմացնել ալիքները", + "TaskRefreshPeople": "Թարմացնել Մարդկանց", + "TaskRefreshChannels": "Թարմացնել Ալիքները", "TaskDownloadMissingSubtitles": "Ներբեռնել պակասող ենթագրերը", "AppDeviceValues": "Հավելված` {0}, Սարք `{1}", "ChapterNameValue": "Գլուխ {0}", @@ -39,5 +39,87 @@ "Latest": "Վերջինը", "LyricDownloadFailureFromForItem": "Չհաջողվեց ներբեռնել {1}-ի երգի բառերը {0}-ից", "MixedContent": "Խառը բովանդակություն", - "CleanupUserDataTaskDescription": "Մաքրում է օգտատիրոջ բոլոր տվյալները (դիտման կարգավիճակ, «սիրելի» նշում և այլն) այն մեդիաֆայլերից, որոնք առնվազն 90 օր է՝ առկա չեն։" + "CleanupUserDataTaskDescription": "Մաքրում է օգտատիրոջ բոլոր տվյալները (դիտման կարգավիճակ, «սիրելի» նշում և այլն) այն մեդիաֆայլերից, որոնք առնվազն 90 օր է՝ առկա չեն։", + "MusicVideos": "երաժշտական տեսահոլովակներ", + "NameExtraDeletedScene": "ջնջված տեսարան", + "NameExtraInterview": "Հարցազրույց", + "NameExtraSample": "Նմուշ", + "NameExtraScene": "Տեսարան", + "NameExtraShort": "Կարճ", + "NameExtraThemeSong": "Թեմատիկ երգ", + "NameExtraThemeVideo": "Թեմատիկ տեսահոլովակ", + "NameExtraTrailer": "Թրեյլեր", + "NameExtraUnknown": "Ավելին", + "NameInstallFailed": "{0} տեղադրումը ձախողվեց", + "NameSeasonUnknown": "Անհայտ սեզոն", + "NewVersionIsAvailable": "Jellyfin սերվերի թարմացված տարբերակը հասանելի է տեղադրման համար:", + "NotificationOptionApplicationUpdateAvailable": "Հավելվածի թարմացումը հասանելի է", + "NotificationOptionApplicationUpdateInstalled": "Հավելվածը թարմացված է", + "NotificationOptionAudioPlayback": "Աուդիոյի նվագարկումը սկսված է", + "NotificationOptionAudioPlaybackStopped": "Աուդիոյի նվագարկումը կանգնեցված է", + "NotificationOptionCameraImageUploaded": "տեսախցիկի նկարը ներբեռնված է", + "NotificationOptionInstallationFailed": "Տեղադրման խնդիր", + "NotificationOptionNewLibraryContent": "Նոր բովանդակություն ավելացվեց", + "HearingImpaired": "Լսողության խանգարումներ ունեցողների համար", + "NameExtraBehindTheScenes": "Կադրից Դուրս", + "NameExtraClip": "Հատված", + "NameExtraFeaturette": "Կարճամետրաժ ակնարկ", + "Original": "Բնօրինակ", + "NotificationOptionPluginError": "Փլագինի խափանում", + "NotificationOptionPluginInstalled": "Փլագինը տեղադրված է", + "NotificationOptionPluginUninstalled": "Փլագինը հեռացված է", + "NotificationOptionPluginUpdateInstalled": "Փլագինը թարմացումը տեղադրված է", + "NotificationOptionServerRestartRequired": "Սերվերի վերամեկնարկում է հարկավոր", + "NotificationOptionTaskFailed": "Պլանավորած առաջադրանքի խափանում", + "NotificationOptionUserLockedOut": "Օգտատերը արգելափակված է", + "NotificationOptionVideoPlayback": "Տեսանյութի նվագարկումը սկսված է", + "NotificationOptionVideoPlaybackStopped": "Տեսանյութի նվագարկումը կանգնեցված է", + "PluginUninstalledWithName": "{0} հեռացված է", + "PluginUpdatedWithName": "{0} թարմացված է", + "ScheduledTaskFailedWithName": "{0} խափանվել է", + "Shows": "Սերիալ", + "StartupEmbyServerIsLoading": "Jellyfin Սերվերը հեռվում է, խնդրում ենք փորձել մի փոքր ուշ։", + "SubtitleDownloadFailureFromForItem": "Ենթագրերը չհաջողվեց ներմուծել {0} {1} համար", + "Undefined": "Չսահմանված", + "UserCreatedWithName": "{0} Օգտատերը ստեղծված է", + "UserDeletedWithName": "{0} Օգտատերը հեռացված է", + "UserDownloadingItemWithValues": "{0} ներմուծում է {1}", + "UserLockedOutWithName": "{0} Օգտատերը արգելափակված է", + "UserOfflineFromDevice": "{0} անջատվել է {1}", + "UserOnlineFromDevice": "{0} ցանցում է {1}-ից", + "UserPasswordChangedWithName": "Գաղտնաբառը փոխված է {0} օգտատերի համար", + "UserStartedPlayingItemWithValues": "{0}-ը նվագարկում է «{1}» {2}-ում", + "UserStoppedPlayingItemWithValues": "{0}-ը վերջացրեց նվագարկումը «{1}» {2}-ում", + "TaskCleanActivityLogDescription": "Ջնջում է ակտիվության մատյանի՝ սահմանված ժամկետից հին գրառումները։", + "TaskCleanCache": "Մաքրել քեշի պանակը", + "TaskCleanCacheDescription": "Ջնջում է քեշի ֆայլերը որոնք այլևս հարկավոր չեն համակարգին:", + "TaskRefreshChapterImages": "Արդյունահանել Գլուխների Պատկերները", + "TaskRefreshChapterImagesDescription": "Ստեղծում է մանրանկարներ տեսանյութերի համար որոնք ունեն նկարներ:", + "TaskAudioNormalization": "Աուդիոյի նորմալացում", + "TaskAudioNormalizationDescription": "Ականավորում է ֆայլերը աուդիոյի նորմալացման տվյալների համար:", + "TaskRefreshLibrary": "Սկանավորել Մեդիա Գրադարանը", + "TaskRefreshLibraryDescription": "Ականավորում է Ձեր մեդիա Գրադարանը նոր և թարմացված մետադատայի համար:", + "TaskCleanLogs": "Մաքրել Մատյանի Պանակը", + "TaskCleanLogsDescription": "Ջնջում է մատյանի ֆայլերը որոնք մնացել են ավելի քան {0} օր։", + "TaskRefreshPeopleDescription": "Թարմացնում է մետադատան դերասանների և դիրեկտորների համար Ձեր մեդիա Գրադարանում։", + "TaskRefreshTrickplayImages": "Գեներացնել Trickplay Նկարներ", + "TaskRefreshTrickplayImagesDescription": "Ստեղծում է trickplay նախասրտում տեսանյութերի համար նշված գրադարաններում:", + "TaskUpdatePlugins": "Թարմացնել Փլագինները", + "TaskUpdatePluginsDescription": "Ներմուծում և տեղադրում է թարմացումները Փլագինների համար որոնք նշված են ինքնուրույն թարմացվել։", + "TaskCleanTranscode": "Մաքրել Տրանսկոդի Պանակը", + "TaskCleanTranscodeDescription": "Ջնջում է տրանսկոդի ֆայլերը որոնք ավելի քան մեկ օր են։", + "TaskRefreshChannelsDescription": "Թարմացնում է ինտերնետ ալիքի ինֆորմացիան:", + "TaskDownloadMissingLyrics": "Ներմուծել փակասող երգի տեքստը", + "TaskDownloadMissingLyricsDescription": "Ներմուծում է երգի տեքստի երգի համար", + "TaskDownloadMissingSubtitlesDescription": "Հիմնված մետադատայի կարգավորման որոնում է ինտերնետում պակասող ենթագրերը։", + "TaskOptimizeDatabase": "Օպտիմալացնել տվյալների բազան", + "TaskOptimizeDatabaseDescription": "Սեղմում է տվյալների բազան և ազատում է տեղ հիշողության մեջ։ Այս առաջադրանքի գործարկումը գրադարանի սկանավորումից կամ այլ փոփոխություններից հետո, որոնք ազդում են տվյալների բազայի վրա, կարող է բարելավել արտադրողականությունը։", + "TaskKeyframeExtractor": "Բանալի Կադրերի Արդյունահանիչ", + "TaskKeyframeExtractorDescription": "Արդյունահանում է բանալի կադրերը տեսանյութերի ֆայլերից, որպեսզի ստեղծել ավելի ճշգրիտ HLS նվագացանկ։ Այս առաջադրանքը կատարելը կարող է տևել երկար ժամանակ։", + "TaskExtractMediaSegments": "Մեդիայի Սեգմենտի Սկանավորում", + "TaskExtractMediaSegmentsDescription": "Արդյունահանում է կամ ստանում է մեդիայի սեգմենտները MediaSegment միացված Փլագինից։", + "TaskMoveTrickplayImages": "Տեղափոխել Trickplay Պատկերի Տեղադրությունը", + "TaskMoveTrickplayImagesDescription": "Տեղափոխում է գոյություն ունեցող trickplay ֆայլերը ըստ գրադարանի կարգավորումներից։", + "CleanupUserDataTask": "Օգտատերի տվյալների մաքրման գործողություն", + "NameExtraNumbered": "{0} {1}" } diff --git a/Emby.Server.Implementations/Localization/Core/id.json b/Emby.Server.Implementations/Localization/Core/id.json index 3502ec39ad..3fb410bc3c 100644 --- a/Emby.Server.Implementations/Localization/Core/id.json +++ b/Emby.Server.Implementations/Localization/Core/id.json @@ -108,5 +108,18 @@ "TaskDownloadMissingLyrics": "Unduh Lirik yang Hilang", "CleanupUserDataTask": "Tugas Pembersihan Data Pengguna", "LyricDownloadFailureFromForItem": "Lirik gagal di download dari {0} untuk {1}", - "Original": "Asli" + "Original": "Asli", + "NameExtraBehindTheScenes": "Dibalik Layar", + "NameExtraClip": "klip", + "NameExtraDeletedScene": "adegan yang dihapus", + "NameExtraFeaturette": "film pendek", + "NameExtraInterview": "wawancara", + "NameExtraSample": "contoh", + "NameExtraScene": "adegan", + "NameExtraShort": "pendek", + "NameExtraThemeSong": "lagu tema", + "NameExtraThemeVideo": "Tema video", + "NameExtraTrailer": "cuplikan", + "NameExtraUnknown": "tambahan", + "NameExtraNumbered": "{0} {1}" } diff --git a/Emby.Server.Implementations/Localization/Core/ka.json b/Emby.Server.Implementations/Localization/Core/ka.json index f7ca19d7f0..04a1ab582c 100644 --- a/Emby.Server.Implementations/Localization/Core/ka.json +++ b/Emby.Server.Implementations/Localization/Core/ka.json @@ -37,7 +37,7 @@ "Favorites": "რჩეულები", "Folders": "საქაღალდეები", "HeaderFavoriteShows": "რჩეული სერიალები", - "HeaderLiveTV": "ცოცხალი ტელევიზია", + "HeaderLiveTV": "პირდაპირი ტელევიზია", "HeaderNextUp": "შემდეგი", "HomeVideos": "სახლის ვიდეოები", "NameSeasonNumber": "სეზონი {0}", diff --git a/Emby.Server.Implementations/Localization/Core/lt-LT.json b/Emby.Server.Implementations/Localization/Core/lt-LT.json index 20c4c4a61c..8546d5a21f 100644 --- a/Emby.Server.Implementations/Localization/Core/lt-LT.json +++ b/Emby.Server.Implementations/Localization/Core/lt-LT.json @@ -52,7 +52,7 @@ "StartupEmbyServerIsLoading": "Jellyfin Server kraunasi. Netrukus pabandykite dar kartą.", "SubtitleDownloadFailureFromForItem": "{1} subtitrai buvo nesėkmingai parsiųsti iš {0}", "TvShows": "TV serialai", - "UserCreatedWithName": "Buvo sukurtas {0} naudotojas", + "UserCreatedWithName": "Buvo sukurtas naudotojas {0}", "UserDeletedWithName": "Naudotojas {0} ištrintas", "UserDownloadingItemWithValues": "{0} siunčiasi {1}", "UserLockedOutWithName": "Naudotojas {0} užblokuotas", diff --git a/Emby.Server.Implementations/Localization/Core/lv.json b/Emby.Server.Implementations/Localization/Core/lv.json index 52f1eecbe4..9d00507cc7 100644 --- a/Emby.Server.Implementations/Localization/Core/lv.json +++ b/Emby.Server.Implementations/Localization/Core/lv.json @@ -120,5 +120,6 @@ "NameExtraShort": "Īsfilma", "NameExtraThemeSong": "Motīvu dziesma", "NameExtraThemeVideo": "Tēmas video", - "NameExtraTrailer": "Treileris" + "NameExtraTrailer": "Treileris", + "NameExtraUnknown": "Papildu" } diff --git a/Emby.Server.Implementations/Localization/Core/mk.json b/Emby.Server.Implementations/Localization/Core/mk.json index daf8112eef..9b07d847aa 100644 --- a/Emby.Server.Implementations/Localization/Core/mk.json +++ b/Emby.Server.Implementations/Localization/Core/mk.json @@ -15,7 +15,7 @@ "NotificationOptionPluginError": "Грешка на додаток", "NotificationOptionNewLibraryContent": "Додадена нова содржина", "NotificationOptionInstallationFailed": "Неуспешна Инсталација", - "NotificationOptionCameraImageUploaded": "Слика од камера поставена", + "NotificationOptionCameraImageUploaded": "Слика од камера прикачена", "NotificationOptionAudioPlaybackStopped": "Аудио стопирано", "NotificationOptionAudioPlayback": "Аудио стартувано", "NotificationOptionApplicationUpdateInstalled": "Надоградбата на Апликацијата е иснталирана", @@ -105,5 +105,7 @@ "TaskMoveTrickplayImages": "Мигрирај ја локацијата на сликата од Trickplay", "TaskMoveTrickplayImagesDescription": "Ги преместува постоечките датотеки за трикплеј според поставките на библиотеката.", "CleanupUserDataTask": "Задача за чистење на кориснички податоци", - "CleanupUserDataTaskDescription": "Ги чисти сите кориснички податоци (состојба на гледање, статус на омилени итн.) од медиуми што повеќе не се присутни најмалку 90 дена." + "CleanupUserDataTaskDescription": "Ги чисти сите кориснички податоци (состојба на гледање, статус на омилени итн.) од медиуми што повеќе не се присутни најмалку 90 дена.", + "NameExtraShort": "Кратко", + "NameExtraUnknown": "Дополнително" } diff --git a/Emby.Server.Implementations/Localization/Core/nb.json b/Emby.Server.Implementations/Localization/Core/nb.json index 6da32f56a0..f97b9b8a7d 100644 --- a/Emby.Server.Implementations/Localization/Core/nb.json +++ b/Emby.Server.Implementations/Localization/Core/nb.json @@ -119,5 +119,7 @@ "NameExtraTrailer": "Trailer", "LyricDownloadFailureFromForItem": "Kunne ikke laste ned sangtekster fra {0} for {1}", "NameExtraClip": "Klipp", - "NameExtraShort": "Kortfilm" + "NameExtraShort": "Kortfilm", + "NameExtraUnknown": "Ekstra", + "Original": "Original" } diff --git a/Emby.Server.Implementations/Localization/Core/sw.json b/Emby.Server.Implementations/Localization/Core/sw.json index c117a0eae2..735182f0c2 100644 --- a/Emby.Server.Implementations/Localization/Core/sw.json +++ b/Emby.Server.Implementations/Localization/Core/sw.json @@ -1,5 +1,6 @@ { "Artists": "Wasanii", "Books": "Vitabu", - "Collections": "Mikusanyiko" + "Collections": "Mikusanyiko", + "HeaderContinueWatching": "Endelea Kutazama" } diff --git a/Emby.Server.Implementations/Localization/Core/zh-CN.json b/Emby.Server.Implementations/Localization/Core/zh-CN.json index 7c61ce6f17..fce89050e2 100644 --- a/Emby.Server.Implementations/Localization/Core/zh-CN.json +++ b/Emby.Server.Implementations/Localization/Core/zh-CN.json @@ -6,7 +6,7 @@ "ChapterNameValue": "章节 {0}", "Collections": "合集", "FailedLoginAttemptWithUserName": "来自 {0} 的登录失败", - "Favorites": "收藏夹", + "Favorites": "收藏", "Folders": "文件夹", "Genres": "类型", "HeaderContinueWatching": "继续观看", diff --git a/Emby.Server.Implementations/Localization/LocalizationManager.cs b/Emby.Server.Implementations/Localization/LocalizationManager.cs index 7af545c550..c11a0bcc63 100644 --- a/Emby.Server.Implementations/Localization/LocalizationManager.cs +++ b/Emby.Server.Implementations/Localization/LocalizationManager.cs @@ -53,6 +53,16 @@ namespace Emby.Server.Implementations.Localization private FrozenDictionary<string, string> _iso6392BtoT = null!; + // Jellyfin's own pre-12.0 codes for region qualified languages and the legacy OpenSubtitles + // ones, still stored in existing configuration and common in file names (movie.pob.srt). + private static readonly FrozenDictionary<string, string> _legacyLanguageAliases = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) + { + { "pob", "pt-br" }, + { "pb", "pt-br" }, + { "pop", "pt-pt" }, + { "es-mx", "es-419" }, + }.ToFrozenDictionary(StringComparer.OrdinalIgnoreCase); + /// <summary> /// Initializes a new instance of the <see cref="LocalizationManager" /> class. /// </summary> @@ -170,6 +180,7 @@ namespace Emby.Server.Implementations.Localization { List<CultureDto> list = []; Dictionary<string, string> iso6392BtoTdict = new Dictionary<string, string>(); + HashSet<string> claimedCodes = new HashSet<string>(StringComparer.OrdinalIgnoreCase); using var stream = _assembly.GetManifestResourceStream(CulturesPath); if (stream is null) @@ -223,6 +234,16 @@ namespace Emby.Server.Implementations.Localization iso6392BtoTdict.TryAdd(parts[1], parts[0]); } + // Variants (pt-br, es-419, zh-cn, ze, ...) share the ISO 639-2 code of their base + // language, but clients key their language pickers on ThreeLetterISOLanguageName and + // would collapse them onto one option. The first entry to claim a code keeps it, which + // is the same one FindLanguageInfo resolves that code to; the rest fall back to their + // own tag. + if (!claimedCodes.Add(parts[0]) && !string.IsNullOrEmpty(twoCharName)) + { + threeLetterNames = [twoCharName, .. threeLetterNames]; + } + list.Add(new CultureDto(name, displayname, twoCharName, threeLetterNames)); } @@ -244,6 +265,11 @@ namespace Emby.Server.Implementations.Localization language, static (lang, cultures) => { + if (_legacyLanguageAliases.TryGetValue(lang, out var alias)) + { + lang = alias; + } + // TODO language should ideally be a ReadOnlySpan but moq cannot mock ref structs for (var i = 0; i < cultures.Count; i++) { diff --git a/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs index c4bda96371..27d9955b09 100644 --- a/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs +++ b/Emby.Server.Implementations/QuickConnect/QuickConnectManager.cs @@ -219,10 +219,10 @@ namespace Emby.Server.Implementations.QuickConnect { if (expireAll || timestamp < minTime) { - _logger.LogDebug("Removing expired secret {Secret}", secret); + _logger.LogDebug("Removing expired secret."); if (!_authorizedSecrets.TryRemove(secret, out _)) { - _logger.LogWarning("Secret {Secret} already expired", secret); + _logger.LogWarning("Secret already expired."); } } } diff --git a/Emby.Server.Implementations/Session/SessionManager.cs b/Emby.Server.Implementations/Session/SessionManager.cs index dd71f843e8..91401eea6b 100644 --- a/Emby.Server.Implementations/Session/SessionManager.cs +++ b/Emby.Server.Implementations/Session/SessionManager.cs @@ -1837,7 +1837,7 @@ namespace Emby.Server.Implementations.Session { CheckDisposed(); - _logger.LogInformation("Logging out access token {0}", device.AccessToken); + _logger.LogInformation("Logging out {0} ({1}) for user {2}", device.DeviceName, device.DeviceId, device.UserId); await _deviceManager.DeleteDevice(device).ConfigureAwait(false); diff --git a/Jellyfin.Api/Controllers/ConfigurationController.cs b/Jellyfin.Api/Controllers/ConfigurationController.cs index ecd667b2e8..e40bb8453c 100644 --- a/Jellyfin.Api/Controllers/ConfigurationController.cs +++ b/Jellyfin.Api/Controllers/ConfigurationController.cs @@ -1,14 +1,12 @@ -using System; using System.ComponentModel.DataAnnotations; -using System.Net.Mime; -using System.Text.Json; -using Jellyfin.Api.Attributes; -using Jellyfin.Extensions.Json; +using Jellyfin.Api.Helpers; using MediaBrowser.Common.Api; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; using MediaBrowser.Controller.Configuration; -using MediaBrowser.Controller.MediaEncoding; using MediaBrowser.Model.Branding; using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.LiveTv; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -24,21 +22,14 @@ namespace Jellyfin.Api.Controllers; public class ConfigurationController : BaseJellyfinApiController { private readonly IServerConfigurationManager _configurationManager; - private readonly IMediaEncoder _mediaEncoder; - - private readonly JsonSerializerOptions _serializerOptions = JsonDefaults.Options; /// <summary> /// Initializes a new instance of the <see cref="ConfigurationController"/> class. /// </summary> /// <param name="configurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param> - /// <param name="mediaEncoder">Instance of the <see cref="IMediaEncoder"/> interface.</param> - public ConfigurationController( - IServerConfigurationManager configurationManager, - IMediaEncoder mediaEncoder) + public ConfigurationController(IServerConfigurationManager configurationManager) { _configurationManager = configurationManager; - _mediaEncoder = mediaEncoder; } /// <summary> @@ -48,9 +39,9 @@ public class ConfigurationController : BaseJellyfinApiController /// <returns>Application configuration.</returns> [HttpGet("Configuration")] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult<ServerConfiguration> GetConfiguration() + public ActionResult<ServerConfigurationDto> GetConfiguration() { - return _configurationManager.Configuration; + return ConfigurationMapper.MapToDto(_configurationManager.Configuration); } /// <summary> @@ -62,61 +53,158 @@ public class ConfigurationController : BaseJellyfinApiController [HttpPost("Configuration")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult UpdateConfiguration([FromBody, Required] ServerConfiguration configuration) + public ActionResult UpdateConfiguration([FromBody, Required] ServerConfigurationDto configuration) { - _configurationManager.ReplaceConfiguration(configuration); + _configurationManager.ReplaceConfiguration(ConfigurationMapper.MapToInternal(configuration)); return NoContent(); } /// <summary> - /// Gets a named configuration. + /// Gets a default MetadataOptions object. /// </summary> - /// <param name="key">Configuration key.</param> - /// <response code="200">Configuration returned.</response> - /// <returns>Configuration.</returns> - [HttpGet("Configuration/{key}")] + /// <response code="200">Metadata options returned.</response> + /// <returns>Default MetadataOptions.</returns> + [HttpGet("Configuration/MetadataOptions/Default")] + [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesFile(MediaTypeNames.Application.Json)] - public ActionResult<object> GetNamedConfiguration([FromRoute, Required] string key) + public ActionResult<MetadataOptions> GetDefaultMetadataOptions() { - return _configurationManager.GetConfiguration(key); + return new MetadataOptions(); } /// <summary> - /// Updates named configuration. + /// Gets encoding configuration. /// </summary> - /// <param name="key">Configuration key.</param> - /// <param name="configuration">Configuration.</param> - /// <response code="204">Named configuration updated.</response> + /// <response code="200">Encoding configuration returned.</response> + /// <returns>Encoding configuration.</returns> + [HttpGet("Configuration/Encoding")] + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult<EncodingOptionsDto> GetEncodingConfiguration() + { + return ConfigurationMapper.MapToDto(_configurationManager.GetConfiguration<EncodingOptions>("encoding")); + } + + /// <summary> + /// Updates encoding configuration. + /// </summary> + /// <param name="configuration">Encoding configuration.</param> + /// <response code="204">Encoding configuration updated.</response> /// <returns>Update status.</returns> - [HttpPost("Configuration/{key}")] + [HttpPost("Configuration/Encoding")] [Authorize(Policy = Policies.RequiresElevation)] [ProducesResponseType(StatusCodes.Status204NoContent)] - public ActionResult UpdateNamedConfiguration([FromRoute, Required] string key, [FromBody, Required] JsonDocument configuration) + public ActionResult UpdateEncodingConfiguration([FromBody, Required] EncodingOptionsDto configuration) { - var configurationType = _configurationManager.GetConfigurationType(key); - var deserializedConfiguration = configuration.Deserialize(configurationType, _serializerOptions); + _configurationManager.SaveConfiguration("encoding", ConfigurationMapper.MapToInternal(configuration)); + return NoContent(); + } - if (deserializedConfiguration is null) - { - throw new ArgumentException("Body doesn't contain a valid configuration"); - } + /// <summary> + /// Gets network configuration. + /// </summary> + /// <response code="200">Network configuration returned.</response> + /// <returns>Network configuration.</returns> + [HttpGet("Configuration/Network")] + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult<NetworkConfigurationDto> GetNetworkConfiguration() + { + return ConfigurationMapper.MapToDto(_configurationManager.GetConfiguration<NetworkConfiguration>("network")); + } - _configurationManager.SaveConfiguration(key, deserializedConfiguration); + /// <summary> + /// Updates network configuration. + /// </summary> + /// <param name="configuration">Network configuration.</param> + /// <response code="204">Network configuration updated.</response> + /// <returns>Update status.</returns> + [HttpPost("Configuration/Network")] + [Authorize(Policy = Policies.RequiresElevation)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult UpdateNetworkConfiguration([FromBody, Required] NetworkConfigurationDto configuration) + { + _configurationManager.SaveConfiguration("network", ConfigurationMapper.MapToInternal(configuration)); return NoContent(); } /// <summary> - /// Gets a default MetadataOptions object. + /// Gets metadata configuration. /// </summary> - /// <response code="200">Metadata options returned.</response> - /// <returns>Default MetadataOptions.</returns> - [HttpGet("Configuration/MetadataOptions/Default")] + /// <response code="200">Metadata configuration returned.</response> + /// <returns>Metadata configuration.</returns> + [HttpGet("Configuration/Metadata")] + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult<MetadataConfigurationDto> GetMetadataConfiguration() + { + return ConfigurationMapper.MapToDto(_configurationManager.GetConfiguration<MetadataConfiguration>("metadata")); + } + + /// <summary> + /// Updates metadata configuration. + /// </summary> + /// <param name="configuration">Metadata configuration.</param> + /// <response code="204">Metadata configuration updated.</response> + /// <returns>Update status.</returns> + [HttpPost("Configuration/Metadata")] [Authorize(Policy = Policies.RequiresElevation)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult UpdateMetadataConfiguration([FromBody, Required] MetadataConfigurationDto configuration) + { + _configurationManager.SaveConfiguration("metadata", ConfigurationMapper.MapToInternal(configuration)); + return NoContent(); + } + + /// <summary> + /// Gets XbmcMetadata configuration. + /// </summary> + /// <response code="200">XbmcMetadata configuration returned.</response> + /// <returns>XbmcMetadata configuration.</returns> + [HttpGet("Configuration/XbmcMetadata")] [ProducesResponseType(StatusCodes.Status200OK)] - public ActionResult<MetadataOptions> GetDefaultMetadataOptions() + public ActionResult<XbmcMetadataOptionsDto> GetXbmcMetadataConfiguration() { - return new MetadataOptions(); + return ConfigurationMapper.MapToDto(_configurationManager.GetConfiguration<XbmcMetadataOptions>("xbmcmetadata")); + } + + /// <summary> + /// Updates XbmcMetadata configuration. + /// </summary> + /// <param name="configuration">XbmcMetadata configuration.</param> + /// <response code="204">XbmcMetadata configuration updated.</response> + /// <returns>Update status.</returns> + [HttpPost("Configuration/XbmcMetadata")] + [Authorize(Policy = Policies.RequiresElevation)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult UpdateXbmcMetadataConfiguration([FromBody, Required] XbmcMetadataOptionsDto configuration) + { + _configurationManager.SaveConfiguration("xbmcmetadata", ConfigurationMapper.MapToInternal(configuration)); + return NoContent(); + } + + /// <summary> + /// Gets LiveTv configuration. + /// </summary> + /// <response code="200">LiveTv configuration returned.</response> + /// <returns>LiveTv configuration.</returns> + [HttpGet("Configuration/LiveTv")] + [ProducesResponseType(StatusCodes.Status200OK)] + public ActionResult<LiveTvOptionsDto> GetLiveTvConfiguration() + { + return ConfigurationMapper.MapToDto(_configurationManager.GetConfiguration<LiveTvOptions>("livetv")); + } + + /// <summary> + /// Updates LiveTv configuration. + /// </summary> + /// <param name="configuration">LiveTv configuration.</param> + /// <response code="204">LiveTv configuration updated.</response> + /// <returns>Update status.</returns> + [HttpPost("Configuration/LiveTv")] + [Authorize(Policy = Policies.RequiresElevation)] + [ProducesResponseType(StatusCodes.Status204NoContent)] + public ActionResult UpdateLiveTvConfiguration([FromBody, Required] LiveTvOptionsDto configuration) + { + _configurationManager.SaveConfiguration("livetv", ConfigurationMapper.MapToInternal(configuration)); + return NoContent(); } /// <summary> @@ -131,7 +219,7 @@ public class ConfigurationController : BaseJellyfinApiController public ActionResult UpdateBrandingConfiguration([FromBody, Required] BrandingOptionsDto configuration) { // Get the current branding configuration to preserve SplashscreenLocation - var currentBranding = (BrandingOptions)_configurationManager.GetConfiguration("branding"); + var currentBranding = _configurationManager.GetConfiguration<BrandingOptions>("branding"); // Update only the properties from BrandingOptionsDto currentBranding.LoginDisclaimer = configuration.LoginDisclaimer; diff --git a/Jellyfin.Api/Controllers/DynamicHlsController.cs b/Jellyfin.Api/Controllers/DynamicHlsController.cs index 6df76de0b4..a57cd568ce 100644 --- a/Jellyfin.Api/Controllers/DynamicHlsController.cs +++ b/Jellyfin.Api/Controllers/DynamicHlsController.cs @@ -1431,9 +1431,7 @@ public class DynamicHlsController : BaseJellyfinApiController throw new ArgumentException("StartTimeTicks is not allowed."); } - // CTS lifecycle is managed internally. - var cancellationTokenSource = new CancellationTokenSource(); - var cancellationToken = cancellationTokenSource.Token; + var cancellationToken = HttpContext.RequestAborted; var state = await StreamingHelpers.GetStreamingState( streamingRequest, @@ -1455,91 +1453,136 @@ public class DynamicHlsController : BaseJellyfinApiController var segmentExtension = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer); - // Keep segment selection and transcoding replacement under the same playlist lock. - // An out-of-order request must not replace a job while another request is using its output. - using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false)) + TranscodingJob? job = null; + TranscodingJob? jobToWaitFor = null; + CancellationTokenSource? cancellationTokenSource = null; + try { - TranscodingJob? job; - var startTranscoding = false; - if (System.IO.File.Exists(segmentPath)) + while (true) { - job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); - _logger.LogDebug("returning {0} [it exists]", segmentPath); - return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false); - } + // Readers must be able to acquire the lock while a replacement waits for them to finish. + await WaitForActiveTranscodingRequests(jobToWaitFor, cancellationToken).ConfigureAwait(false); - var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension); - var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength; - - if (segmentId == -1) - { - _logger.LogDebug("Starting transcoding because fmp4 init file is being requested"); - startTranscoding = true; - segmentId = 0; - } - else if (currentTranscodingIndex is null) - { - _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null"); - startTranscoding = true; - } - else if (segmentId < currentTranscodingIndex.Value) - { - _logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", segmentId, currentTranscodingIndex); - startTranscoding = true; - } - else if (segmentId - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange) - { - _logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", segmentId - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, segmentId); - startTranscoding = true; - } - - if (startTranscoding) - { - // If the playlist doesn't already exist, startup ffmpeg - try + // Selection, reader registration and replacement remain atomic per playlist. + using (await _transcodeManager.LockAsync(playlistPath, cancellationToken).ConfigureAwait(false)) { - var currentJob = _transcodeManager.GetTranscodingJob(playlistPath, TranscodingJobType); - await WaitForActiveTranscodingRequests(currentJob, cancellationToken).ConfigureAwait(false); + var startTranscoding = false; + if (System.IO.File.Exists(segmentPath)) + { + job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); + _logger.LogDebug("returning {0} [it exists]", segmentPath); + break; + } - await _transcodeManager.KillTranscodingJobs(streamingRequest.DeviceId, streamingRequest.PlaySessionId, p => false) - .ConfigureAwait(false); + var currentTranscodingIndex = GetCurrentTranscodingIndex(playlistPath, segmentExtension); + var segmentGapRequiringTranscodingChange = 24 / state.SegmentLength; - if (currentTranscodingIndex.HasValue) + if (segmentId == -1) + { + _logger.LogDebug("Starting transcoding because fmp4 init file is being requested"); + startTranscoding = true; + } + else if (currentTranscodingIndex is null) { - await DeleteLastFile(playlistPath, segmentExtension, 0).ConfigureAwait(false); + _logger.LogDebug("Starting transcoding because currentTranscodingIndex=null"); + startTranscoding = true; + } + else if (segmentId < currentTranscodingIndex.Value) + { + _logger.LogDebug("Starting transcoding because requestedIndex={0} and currentTranscodingIndex={1}", segmentId, currentTranscodingIndex); + startTranscoding = true; + } + else if (segmentId - currentTranscodingIndex.Value > segmentGapRequiringTranscodingChange) + { + _logger.LogDebug("Starting transcoding because segmentGap is {0} and max allowed gap is {1}. requestedIndex={2}", segmentId - currentTranscodingIndex.Value, segmentGapRequiringTranscodingChange, segmentId); + startTranscoding = true; } - streamingRequest.StartTimeTicks = streamingRequest.CurrentRuntimeTicks; + if (startTranscoding) + { + jobToWaitFor = _transcodeManager.GetTranscodingJob(playlistPath, TranscodingJobType); + if (jobToWaitFor?.ActiveRequestCount > 0) + { + continue; + } + + try + { + await _transcodeManager.KillTranscodingJobs(streamingRequest.DeviceId, streamingRequest.PlaySessionId, p => false) + .ConfigureAwait(false); + + if (currentTranscodingIndex.HasValue) + { + await DeleteLastFile(playlistPath, segmentExtension, 0).ConfigureAwait(false); + } + + // Preserve the init request's identity until replacement is actually selected. + if (segmentId == -1) + { + segmentId = 0; + } + + streamingRequest.StartTimeTicks = streamingRequest.CurrentRuntimeTicks; + state.WaitForPath = segmentPath; + + // The shared FFmpeg job must outlive cancellation of any one HTTP request. + cancellationTokenSource = new CancellationTokenSource(); + job = await _transcodeManager.StartFfMpeg( + state, + playlistPath, + GetCommandLineArguments(playlistPath, state, false, segmentId), + Request.HttpContext.User.GetUserId(), + TranscodingJobType, + cancellationTokenSource).ConfigureAwait(false); + } + catch + { + if (cancellationTokenSource is not null) + { + var startedJob = state.TranscodingJob ?? _transcodeManager.GetTranscodingJob(playlistPath, TranscodingJobType); + if (startedJob?.CancellationTokenSource == cancellationTokenSource) + { + job = startedJob; + } + } + + state.Dispose(); + throw; + } + } + else + { + job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); + if (job?.TranscodingThrottler is not null) + { + await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false); + } + } - state.WaitForPath = segmentPath; - job = await _transcodeManager.StartFfMpeg( - state, - playlistPath, - GetCommandLineArguments(playlistPath, state, false, segmentId), - Request.HttpContext.User.GetUserId(), - TranscodingJobType, - cancellationTokenSource).ConfigureAwait(false); + _logger.LogDebug("returning {0} [general case]", segmentPath); + job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); + break; } - catch - { - state.Dispose(); - throw; - } - - // await WaitForMinimumSegmentCount(playlistPath, 1, cancellationTokenSource.Token).ConfigureAwait(false); } - else + + return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false); + } + catch + { + // OnCompleted is only registered once a response is ready. + if (job is not null) { - job = _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); - if (job?.TranscodingThrottler is not null) - { - await job.TranscodingThrottler.UnpauseTranscoding().ConfigureAwait(false); - } + _transcodeManager.OnTranscodeEndRequest(job); } - _logger.LogDebug("returning {0} [general case]", segmentPath); - job ??= _transcodeManager.OnTranscodeBeginRequest(playlistPath, TranscodingJobType); - return await GetSegmentResult(state, playlistPath, segmentPath, segmentExtension, segmentId, job, cancellationToken).ConfigureAwait(false); + throw; + } + finally + { + if (job is null) + { + cancellationTokenSource?.Dispose(); + } } } @@ -1930,6 +1973,7 @@ public class DynamicHlsController : BaseJellyfinApiController TranscodingJob? transcodingJob, CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); var segmentExists = System.IO.File.Exists(segmentPath); if (segmentExists) { @@ -1999,6 +2043,7 @@ public class DynamicHlsController : BaseJellyfinApiController private ActionResult GetSegmentResult(StreamState state, string segmentPath, int segmentIndex, TranscodingJob? transcodingJob) { var segmentEndingPositionTicks = state.Request.CurrentRuntimeTicks + state.Request.ActualSegmentLengthTicks; + var result = FileStreamResponseHelpers.GetStaticFileResult(segmentPath, MimeTypes.GetMimeType(segmentPath)); Response.OnCompleted(() => { @@ -2013,7 +2058,7 @@ public class DynamicHlsController : BaseJellyfinApiController return Task.CompletedTask; }); - return FileStreamResponseHelpers.GetStaticFileResult(segmentPath, MimeTypes.GetMimeType(segmentPath)); + return result; } private int? GetCurrentTranscodingIndex(string playlist, string segmentExtension) diff --git a/Jellyfin.Api/Controllers/FilterController.cs b/Jellyfin.Api/Controllers/FilterController.cs index b9ca45cc1c..e0fb231df5 100644 --- a/Jellyfin.Api/Controllers/FilterController.cs +++ b/Jellyfin.Api/Controllers/FilterController.cs @@ -82,7 +82,8 @@ public class FilterController : BaseJellyfinApiController IncludeItemTypes = includeItemTypes, Recursive = true, EnableTotalRecordCount = false, - AncestorIds = [folder.Id], + // Let LibraryManager scope virtual roots to the user's accessible libraries. + AncestorIds = folder is UserRootFolder or AggregateFolder ? [] : [folder.Id], DtoOptions = new DtoOptions { Fields = [], @@ -160,8 +161,7 @@ public class FilterController : BaseJellyfinApiController var streamLanguageQuery = new InternalItemsQuery(user) { - // It's possible that different langauges are only available on alternative versions. - // To fetch them all, owned items are included. + // Include alternate versions that may have additional languages. IncludeOwnedItems = true, IncludeItemTypes = includeItemTypes, DtoOptions = new DtoOptions @@ -178,7 +178,7 @@ public class FilterController : BaseJellyfinApiController IsSeries = isSeries }; - var tagQuery = new InternalItemsQuery(user) + var itemQuery = new InternalItemsQuery(user) { IncludeItemTypes = includeItemTypes, DtoOptions = new DtoOptions @@ -197,22 +197,23 @@ public class FilterController : BaseJellyfinApiController if ((recursive ?? true) || parentItem is UserView || parentItem is ICollectionFolder) { - var ancestorIds = parentItem is null ? Array.Empty<Guid>() : new[] { parentItem.Id }; + // Let LibraryManager scope virtual roots to the user's accessible libraries. + Guid[] ancestorIds = parentItem is null or UserRootFolder or AggregateFolder ? [] : [parentItem.Id]; genreQuery.AncestorIds = ancestorIds; streamLanguageQuery.AncestorIds = ancestorIds; - tagQuery.AncestorIds = ancestorIds; + itemQuery.AncestorIds = ancestorIds; } else { genreQuery.Parent = parentItem; streamLanguageQuery.Parent = parentItem; - tagQuery.Parent = parentItem; + itemQuery.Parent = parentItem; } if ((includeItemTypes.Contains(BaseItemKind.Series) || includeItemTypes.Contains(BaseItemKind.Season)) && !includeItemTypes.Contains(BaseItemKind.Episode)) { - // streams are joined on epsiodes not shows or seasons + // Series and season languages come from their episodes. streamLanguageQuery.IncludeItemTypes = [.. includeItemTypes, BaseItemKind.Episode]; } @@ -237,7 +238,9 @@ public class FilterController : BaseJellyfinApiController }).ToArray(); } - filters.Tags = _libraryManager.GetTagNames(tagQuery); + filters.Tags = _libraryManager.GetTagNames(itemQuery); + filters.Years = _libraryManager.GetYears(itemQuery); + filters.OfficialRatings = _libraryManager.GetOfficialRatings(itemQuery); if (includeItemTypes.Contains(BaseItemKind.Movie) || includeItemTypes.Contains(BaseItemKind.Series) diff --git a/Jellyfin.Api/Controllers/ImageController.cs b/Jellyfin.Api/Controllers/ImageController.cs index d492a2f5ba..f04d24cbcc 100644 --- a/Jellyfin.Api/Controllers/ImageController.cs +++ b/Jellyfin.Api/Controllers/ImageController.cs @@ -21,6 +21,7 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Drawing; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Providers; using MediaBrowser.Model.Branding; using MediaBrowser.Model.Drawing; @@ -50,6 +51,7 @@ public class ImageController : BaseJellyfinApiController private readonly ILogger<ImageController> _logger; private readonly IServerConfigurationManager _serverConfigurationManager; private readonly IApplicationPaths _appPaths; + private readonly ISchedulesDirectService _schedulesDirectService; /// <summary> /// Initializes a new instance of the <see cref="ImageController"/> class. @@ -62,6 +64,7 @@ public class ImageController : BaseJellyfinApiController /// <param name="logger">Instance of the <see cref="ILogger{ImageController}"/> interface.</param> /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param> /// <param name="appPaths">Instance of the <see cref="IApplicationPaths"/> interface.</param> + /// <param name="schedulesDirectService">Instance of the <see cref="ISchedulesDirectService"/> interface.</param> public ImageController( IUserManager userManager, ILibraryManager libraryManager, @@ -70,7 +73,8 @@ public class ImageController : BaseJellyfinApiController IFileSystem fileSystem, ILogger<ImageController> logger, IServerConfigurationManager serverConfigurationManager, - IApplicationPaths appPaths) + IApplicationPaths appPaths, + ISchedulesDirectService schedulesDirectService) { _userManager = userManager; _libraryManager = libraryManager; @@ -80,6 +84,7 @@ public class ImageController : BaseJellyfinApiController _logger = logger; _serverConfigurationManager = serverConfigurationManager; _appPaths = appPaths; + _schedulesDirectService = schedulesDirectService; } private static CryptoStream GetFromBase64Stream(Stream inputStream) @@ -1893,7 +1898,13 @@ public class ImageController : BaseJellyfinApiController if (!imageInfo.IsLocalFile && item is not null) { - imageInfo = await _libraryManager.ConvertImageToLocal(item, imageInfo, imageIndex ?? 0).ConfigureAwait(false); + var localImage = await _schedulesDirectService.ConvertImageToLocal(item, imageInfo, imageIndex ?? 0).ConfigureAwait(false); + if (localImage is null) + { + return NotFound(); + } + + imageInfo = localImage; } var options = new ImageProcessingOptions diff --git a/Jellyfin.Api/Controllers/SuggestionsController.cs b/Jellyfin.Api/Controllers/SuggestionsController.cs index 9c5515dd92..79f2f4b123 100644 --- a/Jellyfin.Api/Controllers/SuggestionsController.cs +++ b/Jellyfin.Api/Controllers/SuggestionsController.cs @@ -67,16 +67,10 @@ public class SuggestionsController : BaseJellyfinApiController [FromQuery] int? limit, [FromQuery] bool enableTotalRecordCount = false) { - User? user; - if (userId.IsNullOrEmpty()) - { - user = null; - } - else - { - var requestUserId = RequestHelpers.GetUserId(User, userId); - user = _userManager.GetUserById(requestUserId); - } + var requestUserId = RequestHelpers.GetUserId(User, userId); + User? user = requestUserId.IsEmpty() + ? null + : _userManager.GetUserById(requestUserId); var dtoOptions = new DtoOptions(); var result = _libraryManager.GetItemsResult(new InternalItemsQuery(user) diff --git a/Jellyfin.Api/Helpers/ConfigurationJsonTypeInfoModifier.cs b/Jellyfin.Api/Helpers/ConfigurationJsonTypeInfoModifier.cs new file mode 100644 index 0000000000..83cccd0678 --- /dev/null +++ b/Jellyfin.Api/Helpers/ConfigurationJsonTypeInfoModifier.cs @@ -0,0 +1,48 @@ +using System.Text.Json.Serialization.Metadata; +using MediaBrowser.Common.Net; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.LiveTv; + +namespace Jellyfin.Api.Helpers; + +/// <summary> +/// Keeps config defaults out of the DTOs. +/// </summary> +public static class ConfigurationJsonTypeInfoModifier +{ + /// <summary> + /// Fills in defaults from the internal config before reading the request. + /// </summary> + /// <remarks> + /// Missing fields keep their defaults. Values sent by the client, including null, replace them. + /// Use a new config each time so requests don't share arrays or other objects. + /// </remarks> + /// <param name="typeInfo">The JSON type information.</param> + public static void Modify(JsonTypeInfo typeInfo) + { + if (typeInfo.Type == typeof(ServerConfigurationDto)) + { + typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new ServerConfiguration()); + } + else if (typeInfo.Type == typeof(EncodingOptionsDto)) + { + typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new EncodingOptions()); + } + else if (typeInfo.Type == typeof(NetworkConfigurationDto)) + { + typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new NetworkConfiguration()); + } + else if (typeInfo.Type == typeof(MetadataConfigurationDto)) + { + typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new MetadataConfiguration()); + } + else if (typeInfo.Type == typeof(XbmcMetadataOptionsDto)) + { + typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new XbmcMetadataOptions()); + } + else if (typeInfo.Type == typeof(LiveTvOptionsDto)) + { + typeInfo.CreateObject = static () => ConfigurationMapper.MapToDto(new LiveTvOptions()); + } + } +} diff --git a/Jellyfin.Api/Helpers/ConfigurationMapper.cs b/Jellyfin.Api/Helpers/ConfigurationMapper.cs new file mode 100644 index 0000000000..8cfb847177 --- /dev/null +++ b/Jellyfin.Api/Helpers/ConfigurationMapper.cs @@ -0,0 +1,454 @@ +using MediaBrowser.Common.Net; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.LiveTv; + +namespace Jellyfin.Api.Helpers; + +/// <summary> +/// Helper for mapping between configuration DTOs and their internal counterparts. +/// </summary> +public static class ConfigurationMapper +{ + /// <summary> + /// Maps a <see cref="ServerConfiguration"/> to a <see cref="ServerConfigurationDto"/>. + /// </summary> + /// <param name="config">The <see cref="ServerConfiguration"/>.</param> + /// <returns>The <see cref="ServerConfigurationDto"/>.</returns> + public static ServerConfigurationDto MapToDto(ServerConfiguration config) + { + return new ServerConfigurationDto + { + LogFileRetentionDays = config.LogFileRetentionDays, + IsStartupWizardCompleted = config.IsStartupWizardCompleted, + CachePath = config.CachePath, + PreviousVersionStr = config.PreviousVersionStr, + EnableMetrics = config.EnableMetrics, + EnableNormalizedItemByNameIds = config.EnableNormalizedItemByNameIds, + IsPortAuthorized = config.IsPortAuthorized, + QuickConnectAvailable = config.QuickConnectAvailable, + EnableCaseSensitiveItemIds = config.EnableCaseSensitiveItemIds, + DisableLiveTvChannelUserDataName = config.DisableLiveTvChannelUserDataName, + MetadataPath = config.MetadataPath, + PreferredMetadataLanguage = config.PreferredMetadataLanguage, + MetadataCountryCode = config.MetadataCountryCode, + SortReplaceCharacters = config.SortReplaceCharacters, + SortRemoveCharacters = config.SortRemoveCharacters, + SortRemoveWords = config.SortRemoveWords, + MinResumePct = config.MinResumePct, + MaxResumePct = config.MaxResumePct, + MinResumeDurationSeconds = config.MinResumeDurationSeconds, + MinAudiobookResume = config.MinAudiobookResume, + MaxAudiobookResume = config.MaxAudiobookResume, + InactiveSessionThreshold = config.InactiveSessionThreshold, + LibraryMonitorDelay = config.LibraryMonitorDelay, + LibraryUpdateDuration = config.LibraryUpdateDuration, + CacheSize = config.CacheSize, + ImageSavingConvention = config.ImageSavingConvention, + MetadataOptions = config.MetadataOptions, + SkipDeserializationForBasicTypes = config.SkipDeserializationForBasicTypes, + ServerName = config.ServerName, + UICulture = config.UICulture, + SaveMetadataHidden = config.SaveMetadataHidden, + ContentTypes = config.ContentTypes, + RemoteClientBitrateLimit = config.RemoteClientBitrateLimit, + EnableFolderView = config.EnableFolderView, + EnableGroupingMoviesIntoCollections = config.EnableGroupingMoviesIntoCollections, + EnableGroupingShowsIntoCollections = config.EnableGroupingShowsIntoCollections, + DisplaySpecialsWithinSeasons = config.DisplaySpecialsWithinSeasons, + CodecsUsed = config.CodecsUsed, + PluginRepositories = config.PluginRepositories, + EnableExternalContentInSuggestions = config.EnableExternalContentInSuggestions, + ImageExtractionTimeoutMs = config.ImageExtractionTimeoutMs, + PathSubstitutions = config.PathSubstitutions, + EnableSlowResponseWarning = config.EnableSlowResponseWarning, + SlowResponseThresholdMs = config.SlowResponseThresholdMs, + CorsHosts = config.CorsHosts, + ActivityLogRetentionDays = config.ActivityLogRetentionDays, + LibraryScanFanoutConcurrency = config.LibraryScanFanoutConcurrency, + LibraryMetadataRefreshConcurrency = config.LibraryMetadataRefreshConcurrency, + AllowClientLogUpload = config.AllowClientLogUpload, + DummyChapterDuration = config.DummyChapterDuration, + ChapterImageResolution = config.ChapterImageResolution, + ParallelImageEncodingLimit = config.ParallelImageEncodingLimit, + CastReceiverApplications = config.CastReceiverApplications, + TrickplayOptions = config.TrickplayOptions, + EnableLegacyAuthorization = config.EnableLegacyAuthorization, + }; + } + + /// <summary> + /// Maps a <see cref="ServerConfigurationDto"/> to a <see cref="ServerConfiguration"/>. + /// </summary> + /// <param name="dto">The <see cref="ServerConfigurationDto"/>.</param> + /// <returns>The <see cref="ServerConfiguration"/>.</returns> + public static ServerConfiguration MapToInternal(ServerConfigurationDto dto) + { + return new ServerConfiguration + { + LogFileRetentionDays = dto.LogFileRetentionDays, + IsStartupWizardCompleted = dto.IsStartupWizardCompleted, + CachePath = dto.CachePath, + PreviousVersionStr = dto.PreviousVersionStr, + EnableMetrics = dto.EnableMetrics, + EnableNormalizedItemByNameIds = dto.EnableNormalizedItemByNameIds, + IsPortAuthorized = dto.IsPortAuthorized, + QuickConnectAvailable = dto.QuickConnectAvailable, + EnableCaseSensitiveItemIds = dto.EnableCaseSensitiveItemIds, + DisableLiveTvChannelUserDataName = dto.DisableLiveTvChannelUserDataName, + MetadataPath = dto.MetadataPath, + PreferredMetadataLanguage = dto.PreferredMetadataLanguage, + MetadataCountryCode = dto.MetadataCountryCode, + SortReplaceCharacters = dto.SortReplaceCharacters, + SortRemoveCharacters = dto.SortRemoveCharacters, + SortRemoveWords = dto.SortRemoveWords, + MinResumePct = dto.MinResumePct, + MaxResumePct = dto.MaxResumePct, + MinResumeDurationSeconds = dto.MinResumeDurationSeconds, + MinAudiobookResume = dto.MinAudiobookResume, + MaxAudiobookResume = dto.MaxAudiobookResume, + InactiveSessionThreshold = dto.InactiveSessionThreshold, + LibraryMonitorDelay = dto.LibraryMonitorDelay, + LibraryUpdateDuration = dto.LibraryUpdateDuration, + CacheSize = dto.CacheSize, + ImageSavingConvention = dto.ImageSavingConvention, + MetadataOptions = dto.MetadataOptions, + SkipDeserializationForBasicTypes = dto.SkipDeserializationForBasicTypes, + ServerName = dto.ServerName, + UICulture = dto.UICulture, + SaveMetadataHidden = dto.SaveMetadataHidden, + ContentTypes = dto.ContentTypes, + RemoteClientBitrateLimit = dto.RemoteClientBitrateLimit, + EnableFolderView = dto.EnableFolderView, + EnableGroupingMoviesIntoCollections = dto.EnableGroupingMoviesIntoCollections, + EnableGroupingShowsIntoCollections = dto.EnableGroupingShowsIntoCollections, + DisplaySpecialsWithinSeasons = dto.DisplaySpecialsWithinSeasons, + CodecsUsed = dto.CodecsUsed, + PluginRepositories = dto.PluginRepositories, + EnableExternalContentInSuggestions = dto.EnableExternalContentInSuggestions, + ImageExtractionTimeoutMs = dto.ImageExtractionTimeoutMs, + PathSubstitutions = dto.PathSubstitutions, + EnableSlowResponseWarning = dto.EnableSlowResponseWarning, + SlowResponseThresholdMs = dto.SlowResponseThresholdMs, + CorsHosts = dto.CorsHosts, + ActivityLogRetentionDays = dto.ActivityLogRetentionDays, + LibraryScanFanoutConcurrency = dto.LibraryScanFanoutConcurrency, + LibraryMetadataRefreshConcurrency = dto.LibraryMetadataRefreshConcurrency, + AllowClientLogUpload = dto.AllowClientLogUpload, + DummyChapterDuration = dto.DummyChapterDuration, + ChapterImageResolution = dto.ChapterImageResolution, + ParallelImageEncodingLimit = dto.ParallelImageEncodingLimit, + CastReceiverApplications = dto.CastReceiverApplications, + TrickplayOptions = dto.TrickplayOptions, + EnableLegacyAuthorization = dto.EnableLegacyAuthorization, + }; + } + + /// <summary> + /// Maps an <see cref="EncodingOptions"/> to an <see cref="EncodingOptionsDto"/>. + /// </summary> + /// <param name="options">The <see cref="EncodingOptions"/>.</param> + /// <returns>The <see cref="EncodingOptionsDto"/>.</returns> + public static EncodingOptionsDto MapToDto(EncodingOptions options) + { + return new EncodingOptionsDto + { + EncodingThreadCount = options.EncodingThreadCount, + TranscodingTempPath = options.TranscodingTempPath, + FallbackFontPath = options.FallbackFontPath, + EnableFallbackFont = options.EnableFallbackFont, + EnableAudioVbr = options.EnableAudioVbr, + DownMixAudioBoost = options.DownMixAudioBoost, + DownMixStereoAlgorithm = options.DownMixStereoAlgorithm, + MaxMuxingQueueSize = options.MaxMuxingQueueSize, + EnableThrottling = options.EnableThrottling, + ThrottleDelaySeconds = options.ThrottleDelaySeconds, + EnableSegmentDeletion = options.EnableSegmentDeletion, + SegmentKeepSeconds = options.SegmentKeepSeconds, + HardwareAccelerationType = options.HardwareAccelerationType, + EncoderAppPath = options.EncoderAppPath, + EncoderAppPathDisplay = options.EncoderAppPathDisplay, + VaapiDevice = options.VaapiDevice, + QsvDevice = options.QsvDevice, + EnableTonemapping = options.EnableTonemapping, + EnableVppTonemapping = options.EnableVppTonemapping, + EnableVideoToolboxTonemapping = options.EnableVideoToolboxTonemapping, + TonemappingAlgorithm = options.TonemappingAlgorithm, + TonemappingMode = options.TonemappingMode, + TonemappingRange = options.TonemappingRange, + TonemappingDesat = options.TonemappingDesat, + TonemappingPeak = options.TonemappingPeak, + TonemappingParam = options.TonemappingParam, + VppTonemappingBrightness = options.VppTonemappingBrightness, + VppTonemappingContrast = options.VppTonemappingContrast, + H264Crf = options.H264Crf, + H265Crf = options.H265Crf, + EncoderPreset = options.EncoderPreset, + DeinterlaceDoubleRate = options.DeinterlaceDoubleRate, + DeinterlaceMethod = options.DeinterlaceMethod, + EnableDecodingColorDepth10Hevc = options.EnableDecodingColorDepth10Hevc, + EnableDecodingColorDepth10Vp9 = options.EnableDecodingColorDepth10Vp9, + EnableDecodingColorDepth10HevcRext = options.EnableDecodingColorDepth10HevcRext, + EnableDecodingColorDepth12HevcRext = options.EnableDecodingColorDepth12HevcRext, + EnableEnhancedNvdecDecoder = options.EnableEnhancedNvdecDecoder, + PreferSystemNativeHwDecoder = options.PreferSystemNativeHwDecoder, + EnableIntelLowPowerH264HwEncoder = options.EnableIntelLowPowerH264HwEncoder, + EnableIntelLowPowerHevcHwEncoder = options.EnableIntelLowPowerHevcHwEncoder, + EnableHardwareEncoding = options.EnableHardwareEncoding, + AllowHevcEncoding = options.AllowHevcEncoding, + AllowAv1Encoding = options.AllowAv1Encoding, + EnableSubtitleExtraction = options.EnableSubtitleExtraction, + SubtitleExtractionTimeoutMinutes = options.SubtitleExtractionTimeoutMinutes, + HardwareDecodingCodecs = options.HardwareDecodingCodecs, + AllowOnDemandMetadataBasedKeyframeExtractionForExtensions = options.AllowOnDemandMetadataBasedKeyframeExtractionForExtensions, + HlsAudioSeekStrategy = options.HlsAudioSeekStrategy, + }; + } + + /// <summary> + /// Maps an <see cref="EncodingOptionsDto"/> to an <see cref="EncodingOptions"/>. + /// </summary> + /// <param name="dto">The <see cref="EncodingOptionsDto"/>.</param> + /// <returns>The <see cref="EncodingOptions"/>.</returns> + public static EncodingOptions MapToInternal(EncodingOptionsDto dto) + { + return new EncodingOptions + { + EncodingThreadCount = dto.EncodingThreadCount, + TranscodingTempPath = dto.TranscodingTempPath, + FallbackFontPath = dto.FallbackFontPath, + EnableFallbackFont = dto.EnableFallbackFont, + EnableAudioVbr = dto.EnableAudioVbr, + DownMixAudioBoost = dto.DownMixAudioBoost, + DownMixStereoAlgorithm = dto.DownMixStereoAlgorithm, + MaxMuxingQueueSize = dto.MaxMuxingQueueSize, + EnableThrottling = dto.EnableThrottling, + ThrottleDelaySeconds = dto.ThrottleDelaySeconds, + EnableSegmentDeletion = dto.EnableSegmentDeletion, + SegmentKeepSeconds = dto.SegmentKeepSeconds, + HardwareAccelerationType = dto.HardwareAccelerationType, + EncoderAppPath = dto.EncoderAppPath, + EncoderAppPathDisplay = dto.EncoderAppPathDisplay, + VaapiDevice = dto.VaapiDevice, + QsvDevice = dto.QsvDevice, + EnableTonemapping = dto.EnableTonemapping, + EnableVppTonemapping = dto.EnableVppTonemapping, + EnableVideoToolboxTonemapping = dto.EnableVideoToolboxTonemapping, + TonemappingAlgorithm = dto.TonemappingAlgorithm, + TonemappingMode = dto.TonemappingMode, + TonemappingRange = dto.TonemappingRange, + TonemappingDesat = dto.TonemappingDesat, + TonemappingPeak = dto.TonemappingPeak, + TonemappingParam = dto.TonemappingParam, + VppTonemappingBrightness = dto.VppTonemappingBrightness, + VppTonemappingContrast = dto.VppTonemappingContrast, + H264Crf = dto.H264Crf, + H265Crf = dto.H265Crf, + EncoderPreset = dto.EncoderPreset, + DeinterlaceDoubleRate = dto.DeinterlaceDoubleRate, + DeinterlaceMethod = dto.DeinterlaceMethod, + EnableDecodingColorDepth10Hevc = dto.EnableDecodingColorDepth10Hevc, + EnableDecodingColorDepth10Vp9 = dto.EnableDecodingColorDepth10Vp9, + EnableDecodingColorDepth10HevcRext = dto.EnableDecodingColorDepth10HevcRext, + EnableDecodingColorDepth12HevcRext = dto.EnableDecodingColorDepth12HevcRext, + EnableEnhancedNvdecDecoder = dto.EnableEnhancedNvdecDecoder, + PreferSystemNativeHwDecoder = dto.PreferSystemNativeHwDecoder, + EnableIntelLowPowerH264HwEncoder = dto.EnableIntelLowPowerH264HwEncoder, + EnableIntelLowPowerHevcHwEncoder = dto.EnableIntelLowPowerHevcHwEncoder, + EnableHardwareEncoding = dto.EnableHardwareEncoding, + AllowHevcEncoding = dto.AllowHevcEncoding, + AllowAv1Encoding = dto.AllowAv1Encoding, + EnableSubtitleExtraction = dto.EnableSubtitleExtraction, + SubtitleExtractionTimeoutMinutes = dto.SubtitleExtractionTimeoutMinutes, + HardwareDecodingCodecs = dto.HardwareDecodingCodecs, + AllowOnDemandMetadataBasedKeyframeExtractionForExtensions = dto.AllowOnDemandMetadataBasedKeyframeExtractionForExtensions, + HlsAudioSeekStrategy = dto.HlsAudioSeekStrategy, + }; + } + +#pragma warning disable CS0618 // Type or member is obsolete + /// <summary> + /// Maps a <see cref="NetworkConfiguration"/> to a <see cref="NetworkConfigurationDto"/>. + /// </summary> + /// <param name="config">The <see cref="NetworkConfiguration"/>.</param> + /// <returns>The <see cref="NetworkConfigurationDto"/>.</returns> + public static NetworkConfigurationDto MapToDto(NetworkConfiguration config) + { + return new NetworkConfigurationDto + { + BaseUrl = config.BaseUrl, + EnableHttps = config.EnableHttps, + RequireHttps = config.RequireHttps, + CertificatePath = config.CertificatePath, + CertificatePassword = config.CertificatePassword, + InternalHttpPort = config.InternalHttpPort, + InternalHttpsPort = config.InternalHttpsPort, + PublicHttpPort = config.PublicHttpPort, + PublicHttpsPort = config.PublicHttpsPort, + AutoDiscovery = config.AutoDiscovery, + EnableUPnP = config.EnableUPnP, + EnableIPv4 = config.EnableIPv4, + EnableIPv6 = config.EnableIPv6, + EnableRemoteAccess = config.EnableRemoteAccess, + LocalNetworkSubnets = config.LocalNetworkSubnets, + LocalNetworkAddresses = config.LocalNetworkAddresses, + KnownProxies = config.KnownProxies, + IgnoreVirtualInterfaces = config.IgnoreVirtualInterfaces, + VirtualInterfaceNames = config.VirtualInterfaceNames, + EnablePublishedServerUriByRequest = config.EnablePublishedServerUriByRequest, + PublishedServerUriBySubnet = config.PublishedServerUriBySubnet, + RemoteIPFilter = config.RemoteIPFilter, + IsRemoteIPFilterBlacklist = config.IsRemoteIPFilterBlacklist, + }; + } + + /// <summary> + /// Maps a <see cref="NetworkConfigurationDto"/> to a <see cref="NetworkConfiguration"/>. + /// </summary> + /// <param name="dto">The <see cref="NetworkConfigurationDto"/>.</param> + /// <returns>The <see cref="NetworkConfiguration"/>.</returns> + public static NetworkConfiguration MapToInternal(NetworkConfigurationDto dto) + { + return new NetworkConfiguration + { + BaseUrl = dto.BaseUrl, + EnableHttps = dto.EnableHttps, + RequireHttps = dto.RequireHttps, + // The web client sends null for blank certificate fields. + CertificatePath = dto.CertificatePath!, + CertificatePassword = dto.CertificatePassword!, + InternalHttpPort = dto.InternalHttpPort, + InternalHttpsPort = dto.InternalHttpsPort, + PublicHttpPort = dto.PublicHttpPort, + PublicHttpsPort = dto.PublicHttpsPort, + AutoDiscovery = dto.AutoDiscovery, + EnableUPnP = dto.EnableUPnP, + EnableIPv4 = dto.EnableIPv4, + EnableIPv6 = dto.EnableIPv6, + EnableRemoteAccess = dto.EnableRemoteAccess, + LocalNetworkSubnets = dto.LocalNetworkSubnets, + LocalNetworkAddresses = dto.LocalNetworkAddresses, + KnownProxies = dto.KnownProxies, + IgnoreVirtualInterfaces = dto.IgnoreVirtualInterfaces, + VirtualInterfaceNames = dto.VirtualInterfaceNames, + EnablePublishedServerUriByRequest = dto.EnablePublishedServerUriByRequest, + PublishedServerUriBySubnet = dto.PublishedServerUriBySubnet, + RemoteIPFilter = dto.RemoteIPFilter, + IsRemoteIPFilterBlacklist = dto.IsRemoteIPFilterBlacklist, + }; + } +#pragma warning restore CS0618 // Type or member is obsolete + + /// <summary> + /// Maps a <see cref="MetadataConfiguration"/> to a <see cref="MetadataConfigurationDto"/>. + /// </summary> + /// <param name="config">The <see cref="MetadataConfiguration"/>.</param> + /// <returns>The <see cref="MetadataConfigurationDto"/>.</returns> + public static MetadataConfigurationDto MapToDto(MetadataConfiguration config) + { + return new MetadataConfigurationDto + { + UseFileCreationTimeForDateAdded = config.UseFileCreationTimeForDateAdded, + }; + } + + /// <summary> + /// Maps a <see cref="MetadataConfigurationDto"/> to a <see cref="MetadataConfiguration"/>. + /// </summary> + /// <param name="dto">The <see cref="MetadataConfigurationDto"/>.</param> + /// <returns>The <see cref="MetadataConfiguration"/>.</returns> + public static MetadataConfiguration MapToInternal(MetadataConfigurationDto dto) + { + return new MetadataConfiguration + { + UseFileCreationTimeForDateAdded = dto.UseFileCreationTimeForDateAdded, + }; + } + + /// <summary> + /// Maps an <see cref="XbmcMetadataOptions"/> to an <see cref="XbmcMetadataOptionsDto"/>. + /// </summary> + /// <param name="config">The <see cref="XbmcMetadataOptions"/>.</param> + /// <returns>The <see cref="XbmcMetadataOptionsDto"/>.</returns> + public static XbmcMetadataOptionsDto MapToDto(XbmcMetadataOptions config) + { + return new XbmcMetadataOptionsDto + { + UserId = config.UserId, + ReleaseDateFormat = config.ReleaseDateFormat, + SaveImagePathsInNfo = config.SaveImagePathsInNfo, + EnablePathSubstitution = config.EnablePathSubstitution, + EnableExtraThumbsDuplication = config.EnableExtraThumbsDuplication, + }; + } + + /// <summary> + /// Maps an <see cref="XbmcMetadataOptionsDto"/> to an <see cref="XbmcMetadataOptions"/>. + /// </summary> + /// <param name="dto">The <see cref="XbmcMetadataOptionsDto"/>.</param> + /// <returns>The <see cref="XbmcMetadataOptions"/>.</returns> + public static XbmcMetadataOptions MapToInternal(XbmcMetadataOptionsDto dto) + { + return new XbmcMetadataOptions + { + UserId = dto.UserId, + ReleaseDateFormat = dto.ReleaseDateFormat, + SaveImagePathsInNfo = dto.SaveImagePathsInNfo, + EnablePathSubstitution = dto.EnablePathSubstitution, + EnableExtraThumbsDuplication = dto.EnableExtraThumbsDuplication, + }; + } + + /// <summary> + /// Maps a <see cref="LiveTvOptions"/> to a <see cref="LiveTvOptionsDto"/>. + /// </summary> + /// <param name="config">The <see cref="LiveTvOptions"/>.</param> + /// <returns>The <see cref="LiveTvOptionsDto"/>.</returns> + public static LiveTvOptionsDto MapToDto(LiveTvOptions config) + { + return new LiveTvOptionsDto + { + GuideDays = config.GuideDays, + RecordingPath = config.RecordingPath, + MovieRecordingPath = config.MovieRecordingPath, + SeriesRecordingPath = config.SeriesRecordingPath, + EnableRecordingSubfolders = config.EnableRecordingSubfolders, + EnableOriginalAudioWithEncodedRecordings = config.EnableOriginalAudioWithEncodedRecordings, + TunerHosts = config.TunerHosts, + ListingProviders = config.ListingProviders, + PrePaddingSeconds = config.PrePaddingSeconds, + PostPaddingSeconds = config.PostPaddingSeconds, + MediaLocationsCreated = config.MediaLocationsCreated, + RecordingPostProcessor = config.RecordingPostProcessor, + RecordingPostProcessorArguments = config.RecordingPostProcessorArguments, + SaveRecordingNFO = config.SaveRecordingNFO, + SaveRecordingImages = config.SaveRecordingImages, + }; + } + + /// <summary> + /// Maps a <see cref="LiveTvOptionsDto"/> to a <see cref="LiveTvOptions"/>. + /// </summary> + /// <param name="dto">The <see cref="LiveTvOptionsDto"/>.</param> + /// <returns>The <see cref="LiveTvOptions"/>.</returns> + public static LiveTvOptions MapToInternal(LiveTvOptionsDto dto) + { + return new LiveTvOptions + { + GuideDays = dto.GuideDays, + RecordingPath = dto.RecordingPath, + MovieRecordingPath = dto.MovieRecordingPath, + SeriesRecordingPath = dto.SeriesRecordingPath, + EnableRecordingSubfolders = dto.EnableRecordingSubfolders, + EnableOriginalAudioWithEncodedRecordings = dto.EnableOriginalAudioWithEncodedRecordings, + TunerHosts = dto.TunerHosts, + ListingProviders = dto.ListingProviders, + PrePaddingSeconds = dto.PrePaddingSeconds, + PostPaddingSeconds = dto.PostPaddingSeconds, + MediaLocationsCreated = dto.MediaLocationsCreated, + RecordingPostProcessor = dto.RecordingPostProcessor, + RecordingPostProcessorArguments = dto.RecordingPostProcessorArguments, + SaveRecordingNFO = dto.SaveRecordingNFO, + SaveRecordingImages = dto.SaveRecordingImages, + }; + } +} diff --git a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs index f6b6c98c0c..b60ab5eef7 100644 --- a/Jellyfin.Api/Helpers/DynamicHlsHelper.cs +++ b/Jellyfin.Api/Helpers/DynamicHlsHelper.cs @@ -151,27 +151,27 @@ public class DynamicHlsHelper var isLiveStream = state.IsSegmentedLiveStream; var queryString = _httpContextAccessor.HttpContext.Request.QueryString.ToString(); + var playlistQuery = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(queryString); + + // From universal audio service: timeline is determined by segment index and runtime ticks, not StartTimeTicks + playlistQuery.Remove("StartTimeTicks"); - // from universal audio service, need to override the AudioCodec when the actual request differs from original query + // From universal audio service: override AudioCodec when the actual request differs from original query if (!string.Equals(state.OutputAudioCodec, _httpContextAccessor.HttpContext.Request.Query["AudioCodec"].ToString(), StringComparison.OrdinalIgnoreCase)) { - var newQuery = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(queryString); - newQuery["AudioCodec"] = state.OutputAudioCodec; - queryString = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(string.Empty, newQuery); + playlistQuery["AudioCodec"] = state.OutputAudioCodec; } - // from universal audio service - if (!string.IsNullOrWhiteSpace(state.Request.SegmentContainer) - && !queryString.Contains("SegmentContainer", StringComparison.OrdinalIgnoreCase)) + // From universal audio service + if (!string.IsNullOrWhiteSpace(state.Request.SegmentContainer)) { - queryString += "&SegmentContainer=" + state.Request.SegmentContainer; + playlistQuery.TryAdd("SegmentContainer", state.Request.SegmentContainer); } - // from universal audio service - if (!string.IsNullOrWhiteSpace(state.Request.TranscodeReasons) - && !queryString.Contains("TranscodeReasons=", StringComparison.OrdinalIgnoreCase)) + // From universal audio service + if (!string.IsNullOrWhiteSpace(state.Request.TranscodeReasons)) { - queryString += "&TranscodeReasons=" + state.Request.TranscodeReasons; + playlistQuery.TryAdd("TranscodeReasons", state.Request.TranscodeReasons); } // Video rotation metadata is only supported in fMP4 remuxing @@ -182,13 +182,12 @@ public class DynamicHlsHelper && !string.IsNullOrWhiteSpace(state.Request.SegmentContainer) && !string.Equals(state.Request.SegmentContainer, "mp4", StringComparison.OrdinalIgnoreCase)) { - queryString += "&AllowVideoStreamCopy=false"; + playlistQuery["AllowVideoStreamCopy"] = "false"; } // Main stream var baseUrl = isLiveStream ? "live.m3u8" : "main.m3u8"; - var playlistUrl = baseUrl + queryString; - var playlistQuery = Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(queryString); + var playlistUrl = Microsoft.AspNetCore.WebUtilities.QueryHelpers.AddQueryString(baseUrl, playlistQuery); var subtitleStreams = state.MediaSource .MediaStreams diff --git a/Jellyfin.Api/Helpers/HlsHelpers.cs b/Jellyfin.Api/Helpers/HlsHelpers.cs index 15540338b3..23f79a8226 100644 --- a/Jellyfin.Api/Helpers/HlsHelpers.cs +++ b/Jellyfin.Api/Helpers/HlsHelpers.cs @@ -32,12 +32,12 @@ public static class HlsHelpers { try { - // Need to use FileShare.ReadWrite because we're reading the file at the same time it's being written + // FFmpeg may write or replace the playlist while we're reading it. var fileStream = new FileStream( playlist, FileMode.Open, FileAccess.Read, - FileShare.ReadWrite, + FileShare.ReadWrite | FileShare.Delete, IODefaults.FileStreamBufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); await using (fileStream.ConfigureAwait(false)) @@ -111,7 +111,13 @@ public static class HlsHelpers /// <returns>The playlist text as a string.</returns> public static string GetLivePlaylistText(string path, StreamState state) { - var text = File.ReadAllText(path); + string text; + // Allow FFmpeg's playlist replacement handle to remain open while reading. + using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)) + using (var reader = new StreamReader(fileStream)) + { + text = reader.ReadToEnd(); + } var segmentFormat = EncodingHelper.GetSegmentFileExtension(state.Request.SegmentContainer).TrimStart('.'); if (string.Equals(segmentFormat, "mp4", StringComparison.OrdinalIgnoreCase)) diff --git a/Jellyfin.Api/ModelBinders/CommaDelimitedCollectionModelBinder.cs b/Jellyfin.Api/ModelBinders/CommaDelimitedCollectionModelBinder.cs index 25b84cbcc5..d94c0bf2b1 100644 --- a/Jellyfin.Api/ModelBinders/CommaDelimitedCollectionModelBinder.cs +++ b/Jellyfin.Api/ModelBinders/CommaDelimitedCollectionModelBinder.cs @@ -62,14 +62,26 @@ public class CommaDelimitedCollectionModelBinder : IModelBinder var convertedCount = 0; for (var i = 0; i < values.Count; i++) { - try + var value = values[i].Trim(); + if (elementType.IsEnum) { - parsedValues[i] = converter.ConvertFromString(values[i].Trim()); - convertedCount++; + if (Enum.TryParse(elementType, value, ignoreCase: true, out var parsedValue)) + { + parsedValues[i] = parsedValue; + convertedCount++; + } } - catch (FormatException e) + else { - _logger.LogDebug(e, "Error converting value."); + try + { + parsedValues[i] = converter.ConvertFromString(value); + convertedCount++; + } + catch (FormatException e) + { + _logger.LogDebug(e, "Error converting value."); + } } } diff --git a/Jellyfin.Server.Implementations/Item/BaseItemRepository.QueryBuilding.cs b/Jellyfin.Server.Implementations/Item/BaseItemRepository.QueryBuilding.cs index 4cd02bcd8d..0f8f8dc2dd 100644 --- a/Jellyfin.Server.Implementations/Item/BaseItemRepository.QueryBuilding.cs +++ b/Jellyfin.Server.Implementations/Item/BaseItemRepository.QueryBuilding.cs @@ -227,20 +227,23 @@ public sealed partial class BaseItemRepository { if (!string.IsNullOrWhiteSpace(filter.NameStartsWith)) { - var nameStartsWithLower = filter.NameStartsWith.ToLowerInvariant(); - dbQuery = dbQuery.Where(e => e.SortName!.ToLower().StartsWith(nameStartsWithLower)); + var paddedPrefix = BaseItem.NormalizeSortNameFilter(filter.NameStartsWith).ToLowerInvariant(); + var rawPrefix = filter.NameStartsWith.ToLowerInvariant(); + dbQuery = dbQuery.Where(e => + e.SortName!.ToLower().StartsWith(paddedPrefix) + || e.SortName!.ToLower().TrimStart('0').StartsWith(rawPrefix)); } if (!string.IsNullOrWhiteSpace(filter.NameStartsWithOrGreater)) { - var startsOrGreaterLower = filter.NameStartsWithOrGreater.ToLowerInvariant(); - dbQuery = dbQuery.Where(e => e.SortName!.ToLower().CompareTo(startsOrGreaterLower) >= 0); + var paddedValue = BaseItem.NormalizeSortNameFilter(filter.NameStartsWithOrGreater).ToLowerInvariant(); + dbQuery = dbQuery.Where(e => e.SortName!.ToLower().CompareTo(paddedValue) >= 0); } if (!string.IsNullOrWhiteSpace(filter.NameLessThan)) { - var lessThanLower = filter.NameLessThan.ToLowerInvariant(); - dbQuery = dbQuery.Where(e => e.SortName!.ToLower().CompareTo(lessThanLower) < 0); + var paddedValue = BaseItem.NormalizeSortNameFilter(filter.NameLessThan).ToLowerInvariant(); + dbQuery = dbQuery.Where(e => e.SortName!.ToLower().CompareTo(paddedValue) < 0); } return dbQuery; diff --git a/Jellyfin.Server.Implementations/Item/BaseItemRepository.Querying.cs b/Jellyfin.Server.Implementations/Item/BaseItemRepository.Querying.cs index 8d573569e9..a46cd9ab99 100644 --- a/Jellyfin.Server.Implementations/Item/BaseItemRepository.Querying.cs +++ b/Jellyfin.Server.Implementations/Item/BaseItemRepository.Querying.cs @@ -600,7 +600,7 @@ public sealed partial class BaseItemRepository } /// <inheritdoc /> - public QueryFiltersLegacy GetQueryFiltersLegacy(InternalItemsQuery filter) + public IReadOnlyList<int> GetYears(InternalItemsQuery filter) { ArgumentNullException.ThrowIfNull(filter); PrepareFilterQuery(filter); @@ -608,22 +608,34 @@ public sealed partial class BaseItemRepository using var context = _dbProvider.CreateDbContext(); var baseQuery = PrepareItemQuery(context, filter); baseQuery = TranslateQuery(baseQuery, context, filter); + return GetYears(baseQuery); + } - var matchingItemIds = baseQuery.Select(e => e.Id); + /// <inheritdoc /> + public IReadOnlyList<string> GetOfficialRatings(InternalItemsQuery filter) + { + ArgumentNullException.ThrowIfNull(filter); + PrepareFilterQuery(filter); - var years = baseQuery - .Where(e => e.ProductionYear != null && e.ProductionYear > 0) - .Select(e => e.ProductionYear!.Value) - .Distinct() - .OrderBy(y => y) - .ToArray(); + using var context = _dbProvider.CreateDbContext(); + var baseQuery = PrepareItemQuery(context, filter); + baseQuery = TranslateQuery(baseQuery, context, filter); + return GetOfficialRatings(baseQuery); + } - var officialRatings = baseQuery - .Where(e => e.OfficialRating != null && e.OfficialRating != string.Empty) - .Select(e => e.OfficialRating!) - .Distinct() - .OrderBy(r => r) - .ToArray(); + /// <inheritdoc /> + public QueryFiltersLegacy GetQueryFiltersLegacy(InternalItemsQuery filter) + { + ArgumentNullException.ThrowIfNull(filter); + PrepareFilterQuery(filter); + + using var context = _dbProvider.CreateDbContext(); + var baseQuery = PrepareItemQuery(context, filter); + baseQuery = TranslateQuery(baseQuery, context, filter); + + var matchingItemIds = baseQuery.Select(e => e.Id); + var years = GetYears(baseQuery); + var officialRatings = GetOfficialRatings(baseQuery); var tags = context.ItemValuesMap .Join( @@ -659,4 +671,24 @@ public sealed partial class BaseItemRepository Genres = genres }; } + + private static IReadOnlyList<int> GetYears(IQueryable<BaseItemEntity> query) + { + return query + .Where(e => e.ProductionYear != null && e.ProductionYear > 0) + .Select(e => e.ProductionYear!.Value) + .Distinct() + .OrderBy(y => y) + .ToArray(); + } + + private static IReadOnlyList<string> GetOfficialRatings(IQueryable<BaseItemEntity> query) + { + return query + .Where(e => e.OfficialRating != null && e.OfficialRating != string.Empty) + .Select(e => e.OfficialRating!) + .Distinct() + .OrderBy(r => r) + .ToArray(); + } } diff --git a/Jellyfin.Server.Implementations/Item/BaseItemRepository.TranslateQuery.cs b/Jellyfin.Server.Implementations/Item/BaseItemRepository.TranslateQuery.cs index e66f18bc6e..76889cb095 100644 --- a/Jellyfin.Server.Implementations/Item/BaseItemRepository.TranslateQuery.cs +++ b/Jellyfin.Server.Implementations/Item/BaseItemRepository.TranslateQuery.cs @@ -18,6 +18,7 @@ using Jellyfin.Extensions; using Jellyfin.Server.Implementations.Extensions; using MediaBrowser.Controller.Entities; using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Globalization; using Microsoft.EntityFrameworkCore; using BaseItemEntity = Jellyfin.Database.Implementations.Entities.BaseItemEntity; @@ -70,6 +71,9 @@ public sealed partial class BaseItemRepository private static string NormalizeLanguage(string language) => string.Equals(language, "und", StringComparison.OrdinalIgnoreCase) ? "und" : language; + private IReadOnlyList<string> GetStreamLanguageCodes(string language) + => _localizationManager.GetMediaStreamLanguageCodes(NormalizeLanguage(language)); + // The primary versions whose alternate version satisfies a dimension bound. Anchored on // PrimaryVersionId so the filtered index carries it rather than a scan of every item. private static IQueryable<Guid> VersionsMatchingDimension(JellyfinDbContext context, Expression<Func<BaseItemEntity, bool>> bound) @@ -825,8 +829,8 @@ public sealed partial class BaseItemRepository if (!string.IsNullOrWhiteSpace(filter.HasNoAudioTrackWithLanguage)) { - var lang = NormalizeLanguage(filter.HasNoAudioTrackWithLanguage); - var undetermined = string.Equals(lang, "und", StringComparison.Ordinal); + var lang = GetStreamLanguageCodes(filter.HasNoAudioTrackWithLanguage); + var undetermined = lang.Contains("und", StringComparer.Ordinal); var criteria = new HasMediaStreamType(MediaStreamTypeEntity.Audio, lang); // A track only an alternate version carries still belongs to the item a caller sees, so the // item's own streams alone do not decide this. Same for every stream filter below. @@ -837,15 +841,15 @@ public sealed partial class BaseItemRepository .Where(e => (!e.IsFolder && !e.MediaStreams!.Any(ms => ms.StreamType == MediaStreamTypeEntity.Audio - && (ms.Language == lang || (undetermined && string.IsNullOrEmpty(ms.Language)))) + && (lang.Contains(ms.Language) || (undetermined && string.IsNullOrEmpty(ms.Language)))) && !versionsWithAudio.Contains(e.Id)) || (e.IsFolder && !foldersWithAudio.Contains(e.Id))); } if (!string.IsNullOrWhiteSpace(filter.HasNoInternalSubtitleTrackWithLanguage)) { - var lang = NormalizeLanguage(filter.HasNoInternalSubtitleTrackWithLanguage); - var undetermined = string.Equals(lang, "und", StringComparison.Ordinal); + var lang = GetStreamLanguageCodes(filter.HasNoInternalSubtitleTrackWithLanguage); + var undetermined = lang.Contains("und", StringComparer.Ordinal); var criteria = new HasMediaStreamType(MediaStreamTypeEntity.Subtitle, lang, IsExternal: false); var versionsWithSubtitles = DescendantQueryHelper.GetPrimaryVersionIdsMatching(context, criteria); var foldersWithSubtitles = DescendantQueryHelper.GetFolderIdsMatching(context, criteria); @@ -854,15 +858,15 @@ public sealed partial class BaseItemRepository .Where(e => (!e.IsFolder && !e.MediaStreams!.Any(ms => ms.StreamType == MediaStreamTypeEntity.Subtitle && !ms.IsExternal - && (ms.Language == lang || (undetermined && string.IsNullOrEmpty(ms.Language)))) + && (lang.Contains(ms.Language) || (undetermined && string.IsNullOrEmpty(ms.Language)))) && !versionsWithSubtitles.Contains(e.Id)) || (e.IsFolder && !foldersWithSubtitles.Contains(e.Id))); } if (!string.IsNullOrWhiteSpace(filter.HasNoExternalSubtitleTrackWithLanguage)) { - var lang = NormalizeLanguage(filter.HasNoExternalSubtitleTrackWithLanguage); - var undetermined = string.Equals(lang, "und", StringComparison.Ordinal); + var lang = GetStreamLanguageCodes(filter.HasNoExternalSubtitleTrackWithLanguage); + var undetermined = lang.Contains("und", StringComparer.Ordinal); var criteria = new HasMediaStreamType(MediaStreamTypeEntity.Subtitle, lang, IsExternal: true); var versionsWithSubtitles = DescendantQueryHelper.GetPrimaryVersionIdsMatching(context, criteria); var foldersWithSubtitles = DescendantQueryHelper.GetFolderIdsMatching(context, criteria); @@ -871,15 +875,15 @@ public sealed partial class BaseItemRepository .Where(e => (!e.IsFolder && !e.MediaStreams!.Any(ms => ms.StreamType == MediaStreamTypeEntity.Subtitle && ms.IsExternal - && (ms.Language == lang || (undetermined && string.IsNullOrEmpty(ms.Language)))) + && (lang.Contains(ms.Language) || (undetermined && string.IsNullOrEmpty(ms.Language)))) && !versionsWithSubtitles.Contains(e.Id)) || (e.IsFolder && !foldersWithSubtitles.Contains(e.Id))); } if (!string.IsNullOrWhiteSpace(filter.HasNoSubtitleTrackWithLanguage)) { - var lang = NormalizeLanguage(filter.HasNoSubtitleTrackWithLanguage); - var undetermined = string.Equals(lang, "und", StringComparison.Ordinal); + var lang = GetStreamLanguageCodes(filter.HasNoSubtitleTrackWithLanguage); + var undetermined = lang.Contains("und", StringComparer.Ordinal); var criteria = new HasMediaStreamType(MediaStreamTypeEntity.Subtitle, lang); var versionsWithSubtitles = DescendantQueryHelper.GetPrimaryVersionIdsMatching(context, criteria); var foldersWithSubtitles = DescendantQueryHelper.GetFolderIdsMatching(context, criteria); @@ -888,7 +892,7 @@ public sealed partial class BaseItemRepository .Where(e => (!e.IsFolder && !e.MediaStreams!.Any(ms => ms.StreamType == MediaStreamTypeEntity.Subtitle - && (ms.Language == lang || (undetermined && string.IsNullOrEmpty(ms.Language)))) + && (lang.Contains(ms.Language) || (undetermined && string.IsNullOrEmpty(ms.Language)))) && !versionsWithSubtitles.Contains(e.Id)) || (e.IsFolder && !foldersWithSubtitles.Contains(e.Id))); } @@ -1094,8 +1098,10 @@ public sealed partial class BaseItemRepository if (filter.AncestorIds.Length > 0) { - var ancestorFilter = filter.AncestorIds.OneOrManyExpressionBuilder<AncestorId, Guid>(f => f.ParentItemId); - baseQuery = baseQuery.Where(e => e.Parents!.AsQueryable().Any(ancestorFilter)); + var descendantIds = context.AncestorIds + .WhereOneOrMany(filter.AncestorIds, a => a.ParentItemId) + .Select(a => a.ItemId); + baseQuery = baseQuery.Where(e => descendantIds.Contains(e.Id)); } if (filter.DescendantOfId.HasValue) @@ -1115,8 +1121,14 @@ public sealed partial class BaseItemRepository if (!string.IsNullOrWhiteSpace(filter.AncestorWithPresentationUniqueKey)) { - baseQuery = baseQuery - .Where(e => context.BaseItems.Where(e => e.Id != EF.Constant(PlaceholderId)).Where(f => f.PresentationUniqueKey == filter.AncestorWithPresentationUniqueKey).Any(f => f.Children!.Any(w => w.ItemId == e.Id))); + var ancestorKey = filter.AncestorWithPresentationUniqueKey; + var keyedAncestorIds = context.BaseItems + .Where(f => f.Id != EF.Constant(PlaceholderId) && f.PresentationUniqueKey == ancestorKey) + .Select(f => f.Id); + var descendantIds = context.AncestorIds + .Where(a => keyedAncestorIds.Contains(a.ParentItemId)) + .Select(a => a.ItemId); + baseQuery = baseQuery.Where(e => descendantIds.Contains(e.Id)); } if (!string.IsNullOrWhiteSpace(filter.SeriesPresentationUniqueKey)) diff --git a/Jellyfin.Server.Implementations/Item/BaseItemRepository.cs b/Jellyfin.Server.Implementations/Item/BaseItemRepository.cs index 1d2aa21853..e51957ffec 100644 --- a/Jellyfin.Server.Implementations/Item/BaseItemRepository.cs +++ b/Jellyfin.Server.Implementations/Item/BaseItemRepository.cs @@ -10,6 +10,7 @@ using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Persistence; +using MediaBrowser.Model.Globalization; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using BaseItemDto = MediaBrowser.Controller.Entities.BaseItem; @@ -38,6 +39,7 @@ public sealed partial class BaseItemRepository private readonly IServerApplicationHost _appHost; private readonly IItemTypeLookup _itemTypeLookup; private readonly IServerConfigurationManager _serverConfigurationManager; + private readonly ILocalizationManager _localizationManager; private readonly ILogger<BaseItemRepository> _logger; private static readonly IReadOnlyList<ItemValueType> _getAllArtistsValueTypes = [ItemValueType.Artist, ItemValueType.AlbumArtist]; @@ -78,18 +80,21 @@ public sealed partial class BaseItemRepository /// <param name="appHost">The Application host.</param> /// <param name="itemTypeLookup">The static type lookup.</param> /// <param name="serverConfigurationManager">The server Configuration manager.</param> + /// <param name="localizationManager">The localization manager.</param> /// <param name="logger">System logger.</param> public BaseItemRepository( IDbContextFactory<JellyfinDbContext> dbProvider, IServerApplicationHost appHost, IItemTypeLookup itemTypeLookup, IServerConfigurationManager serverConfigurationManager, + ILocalizationManager localizationManager, ILogger<BaseItemRepository> logger) { _dbProvider = dbProvider; _appHost = appHost; _itemTypeLookup = itemTypeLookup; _serverConfigurationManager = serverConfigurationManager; + _localizationManager = localizationManager; _logger = logger; } diff --git a/Jellyfin.Server.Implementations/Item/ItemCountBuilder.cs b/Jellyfin.Server.Implementations/Item/ItemCountBuilder.cs index 0f8a1b9dfe..0fb6721d74 100644 --- a/Jellyfin.Server.Implementations/Item/ItemCountBuilder.cs +++ b/Jellyfin.Server.Implementations/Item/ItemCountBuilder.cs @@ -73,6 +73,10 @@ internal static class ItemCountBuilder { result.BookCount += count; } + else if (string.Equals(type, lookup[BaseItemKind.AudioBook], StringComparison.Ordinal)) + { + result.AudioBookCount += count; + } } result.ItemCount = result.TotalItemCount(); diff --git a/Jellyfin.Server.Implementations/Item/ItemCountService.cs b/Jellyfin.Server.Implementations/Item/ItemCountService.cs index 942161a176..b0af08479d 100644 --- a/Jellyfin.Server.Implementations/Item/ItemCountService.cs +++ b/Jellyfin.Server.Implementations/Item/ItemCountService.cs @@ -7,7 +7,6 @@ using System.Linq; using Jellyfin.Data.Enums; using Jellyfin.Database.Implementations; using Jellyfin.Database.Implementations.Entities; -using Jellyfin.Database.Implementations.Enums; using Jellyfin.Extensions; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Persistence; @@ -72,6 +71,7 @@ public class ItemCountService : IItemCountService { ItemCount = counts.Sum(c => c.Count) }; + foreach (var count in counts) { if (string.Equals(count.Key, lookup[BaseItemKind.MusicAlbum], StringComparison.Ordinal)) @@ -118,6 +118,10 @@ public class ItemCountService : IItemCountService { result.BookCount = count.Count; } + else if (string.Equals(count.Key, lookup[BaseItemKind.AudioBook], StringComparison.Ordinal)) + { + result.AudioBookCount = count.Count; + } } return result; diff --git a/Jellyfin.Server.Implementations/Item/ItemPersistenceService.cs b/Jellyfin.Server.Implementations/Item/ItemPersistenceService.cs index 3bf33b969e..4e7e5a5331 100644 --- a/Jellyfin.Server.Implementations/Item/ItemPersistenceService.cs +++ b/Jellyfin.Server.Implementations/Item/ItemPersistenceService.cs @@ -374,7 +374,8 @@ public class ItemPersistenceService : IItemPersistenceService var allListedItemValuesSet = allListedItemValues.ToHashSet(); var existingValues = context.ItemValues - .Where(e => types.Contains(e.Type) && values.Contains(e.Value)) + .WhereOneOrMany(types, e => e.Type) + .WhereOneOrMany(values, e => e.Value) .AsEnumerable() .Where(e => allListedItemValuesSet.Contains((e.Type, e.Value))) .ToArray(); @@ -428,7 +429,7 @@ public class ItemPersistenceService : IItemPersistenceService var allExistingAncestorIds = itemsWithAncestors.Count > 0 ? context.AncestorIds - .Where(e => itemsWithAncestors.Contains(e.ItemId)) + .WhereOneOrMany(itemsWithAncestors, e => e.ItemId) .ToList() .GroupBy(e => e.ItemId) .ToDictionary(g => g.Key, g => g.ToList()) @@ -442,7 +443,7 @@ public class ItemPersistenceService : IItemPersistenceService var validAncestorIdsSet = allRequestedAncestorIds.Count > 0 ? context.BaseItems - .Where(e => allRequestedAncestorIds.Contains(e.Id)) + .WhereOneOrMany(allRequestedAncestorIds, e => e.Id) .Select(f => f.Id) .ToHashSet() : new HashSet<Guid>(); @@ -502,7 +503,7 @@ public class ItemPersistenceService : IItemPersistenceService { var allParentIds = folderIds.Concat(videoIds).Distinct().ToList(); var allLinkedChildren = context.LinkedChildren - .Where(e => allParentIds.Contains(e.ParentId)) + .WhereOneOrMany(allParentIds, e => e.ParentId) .ToList(); allLinkedChildrenByParent = allLinkedChildren @@ -572,7 +573,7 @@ public class ItemPersistenceService : IItemPersistenceService var pathToIdMap = pathsToResolve.Count > 0 ? context.BaseItems - .Where(e => e.Path != null && pathsToResolve.Contains(e.Path)) + .WhereOneOrMany(pathsToResolve, e => e.Path!) .Select(e => new { e.Path, e.Id }) .GroupBy(e => e.Path!) .ToDictionary(g => g.Key, g => g.First().Id) diff --git a/Jellyfin.Server.Implementations/Item/PeopleRepository.cs b/Jellyfin.Server.Implementations/Item/PeopleRepository.cs index 802138ed5e..3eb66a328f 100644 --- a/Jellyfin.Server.Implementations/Item/PeopleRepository.cs +++ b/Jellyfin.Server.Implementations/Item/PeopleRepository.cs @@ -441,7 +441,15 @@ public class PeopleRepository(IDbContextFactory<JellyfinDbContext> dbProvider, I if (filter.ParentId != null) { - query = query.Where(e => e.BaseItems!.Any(w => context.AncestorIds.Any(i => i.ParentItemId == filter.ParentId && i.ItemId == w.ItemId))); + // Seek the credits through IX_AncestorIds_ParentItemId_ItemId; a correlated EXISTS walks every person. + var parentId = filter.ParentId.Value; + var descendantIds = context.AncestorIds + .Where(a => a.ParentItemId == parentId) + .Select(a => a.ItemId); + var creditedPeopleIds = context.PeopleBaseItemMap + .Where(m => descendantIds.Contains(m.ItemId)) + .Select(m => m.PeopleId); + query = query.Where(e => creditedPeopleIds.Contains(e.Id)); } if (!filter.AppearsInItemId.IsEmpty()) diff --git a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs index a498901481..e4aed9451c 100644 --- a/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs +++ b/Jellyfin.Server/Extensions/ApiServiceCollectionExtensions.cs @@ -6,6 +6,7 @@ using System.Net.Sockets; using System.Reflection; using System.Security.Claims; using System.Text.Json.Nodes; +using System.Text.Json.Serialization.Metadata; using Emby.Server.Implementations; using Jellyfin.Api.Auth; using Jellyfin.Api.Auth.AnonymousLanAccessPolicy; @@ -17,6 +18,7 @@ using Jellyfin.Api.Auth.UserPermissionPolicy; using Jellyfin.Api.Constants; using Jellyfin.Api.Controllers; using Jellyfin.Api.Formatters; +using Jellyfin.Api.Helpers; using Jellyfin.Api.ModelBinders; using Jellyfin.Data.Enums; using Jellyfin.Database.Implementations.Enums; @@ -25,6 +27,7 @@ using Jellyfin.Server.Configuration; using Jellyfin.Server.Filters; using MediaBrowser.Common.Api; using MediaBrowser.Common.Net; +using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; @@ -107,8 +110,9 @@ namespace Jellyfin.Server.Extensions /// <param name="serviceCollection">The service collection.</param> /// <param name="pluginAssemblies">An IEnumerable containing all plugin assemblies with API controllers.</param> /// <param name="config">The <see cref="NetworkConfiguration"/>.</param> + /// <param name="serverConfiguration">The <see cref="ServerConfiguration"/>.</param> /// <returns>The MVC builder.</returns> - public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable<Assembly> pluginAssemblies, NetworkConfiguration config) + public static IMvcBuilder AddJellyfinApi(this IServiceCollection serviceCollection, IEnumerable<Assembly> pluginAssemblies, NetworkConfiguration config, ServerConfiguration serverConfiguration) { IMvcBuilder mvcBuilder = serviceCollection .AddCors() @@ -129,6 +133,11 @@ namespace Jellyfin.Server.Extensions opts.OutputFormatters.Add(new XmlOutputFormatter()); opts.ModelBinderProviders.Insert(0, new NullableEnumModelBinderProvider()); + + if (!serverConfiguration.EnableObsoleteEndpoints) + { + opts.Conventions.Add(new ObsoleteEndpointConvention()); + } }) // Clear app parts to avoid other assemblies being picked up @@ -153,6 +162,11 @@ namespace Jellyfin.Server.Extensions // From JsonDefaults.PascalCase options.JsonSerializerOptions.PropertyNamingPolicy = jsonOptions.PropertyNamingPolicy; + + options.JsonSerializerOptions.TypeInfoResolver = new DefaultJsonTypeInfoResolver + { + Modifiers = { ConfigurationJsonTypeInfoModifier.Modify } + }; }); foreach (Assembly pluginAssembly in pluginAssemblies) diff --git a/Jellyfin.Server/Filters/AdditionalModelFilter.cs b/Jellyfin.Server/Filters/AdditionalModelFilter.cs index efa2f4cca5..a32cb62d98 100644 --- a/Jellyfin.Server/Filters/AdditionalModelFilter.cs +++ b/Jellyfin.Server/Filters/AdditionalModelFilter.cs @@ -4,10 +4,7 @@ using System.ComponentModel; using System.Linq; using System.Reflection; using System.Text.Json.Nodes; -using Jellyfin.Extensions; -using Jellyfin.Server.Migrations; using MediaBrowser.Common.Plugins; -using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Net; using MediaBrowser.Controller.Net.WebSocketMessages; using MediaBrowser.Model.ApiClient; @@ -23,19 +20,6 @@ namespace Jellyfin.Server.Filters /// </summary> public class AdditionalModelFilter : IDocumentFilter { - // Array of options that should not be visible in the api spec. - private static readonly Type[] _ignoredConfigurations = [typeof(MigrationOptions), typeof(MediaBrowser.Model.Branding.BrandingOptions)]; - private readonly IServerConfigurationManager _serverConfigurationManager; - - /// <summary> - /// Initializes a new instance of the <see cref="AdditionalModelFilter"/> class. - /// </summary> - /// <param name="serverConfigurationManager">Instance of the <see cref="IServerConfigurationManager"/> interface.</param> - public AdditionalModelFilter(IServerConfigurationManager serverConfigurationManager) - { - _serverConfigurationManager = serverConfigurationManager; - } - /// <inheritdoc /> public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { @@ -202,16 +186,6 @@ namespace Jellyfin.Server.Filters context.SchemaRepository.Schemas[nameof(GroupUpdate<object>)] = groupUpdateSchema; context.SchemaGenerator.GenerateSchema(typeof(ServerDiscoveryInfo), context.SchemaRepository); - - foreach (var configuration in _serverConfigurationManager.GetConfigurationStores()) - { - if (_ignoredConfigurations.IndexOf(configuration.ConfigurationType) != -1) - { - continue; - } - - context.SchemaGenerator.GenerateSchema(configuration.ConfigurationType, context.SchemaRepository); - } } } } diff --git a/Jellyfin.Server/Filters/ObsoleteEndpointConvention.cs b/Jellyfin.Server/Filters/ObsoleteEndpointConvention.cs new file mode 100644 index 0000000000..c53b61a4d3 --- /dev/null +++ b/Jellyfin.Server/Filters/ObsoleteEndpointConvention.cs @@ -0,0 +1,29 @@ +using System; +using System.Linq; +using Microsoft.AspNetCore.Mvc.ApplicationModels; + +namespace Jellyfin.Server.Filters +{ + /// <summary> + /// Searches for actions and controllers marked with <see cref="ObsoleteAttribute"/> and applies a custom filter. + /// </summary> + public class ObsoleteEndpointConvention : IApplicationModelConvention + { + /// <inheritdoc /> + public void Apply(ApplicationModel application) + { + foreach (var controller in application.Controllers) + { + var isControllerObsolete = controller.Attributes.OfType<ObsoleteAttribute>().Any(); + + foreach (var action in controller.Actions) + { + if (isControllerObsolete || action.Attributes.OfType<ObsoleteAttribute>().Any()) + { + action.Filters.Add(new ObsoleteEndpointFilter()); + } + } + } + } + } +} diff --git a/Jellyfin.Server/Filters/ObsoleteEndpointFilter.cs b/Jellyfin.Server/Filters/ObsoleteEndpointFilter.cs new file mode 100644 index 0000000000..b2c02fd516 --- /dev/null +++ b/Jellyfin.Server/Filters/ObsoleteEndpointFilter.cs @@ -0,0 +1,26 @@ +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Filters; + +namespace Jellyfin.Server.Filters; + +/// <summary> +/// Short circuits an obsolete endpoint to return an error code. +/// </summary> +public class ObsoleteEndpointFilter : IAsyncActionFilter +{ + /// <inheritdoc/> + public Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) + { + var obsoleteResponse = new + { + error = "Endpoint Obsolete", + message = "This endpoint has been manually disabled. You can revert this with the EnableObsoleteEndpoints setting." + }; + + context.Result = new ObjectResult(obsoleteResponse) { StatusCode = StatusCodes.Status410Gone }; + + return Task.CompletedTask; + } +} diff --git a/Jellyfin.Server/Migrations/IAsyncMigrationRoutine.cs b/Jellyfin.Server/Migrations/IAsyncMigrationRoutine.cs index 5b6a5fe942..a40b831cf2 100644 --- a/Jellyfin.Server/Migrations/IAsyncMigrationRoutine.cs +++ b/Jellyfin.Server/Migrations/IAsyncMigrationRoutine.cs @@ -1,4 +1,3 @@ -using System; using System.Threading; using System.Threading.Tasks; @@ -16,16 +15,3 @@ internal interface IAsyncMigrationRoutine /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> public Task PerformAsync(CancellationToken cancellationToken); } - -/// <summary> -/// Interface that describes a migration routine. -/// </summary> -[Obsolete("Use IAsyncMigrationRoutine instead")] -internal interface IMigrationRoutine -{ - /// <summary> - /// Execute the migration routine. - /// </summary> - [Obsolete("Use IAsyncMigrationRoutine.PerformAsync instead")] - public void Perform(); -} diff --git a/Jellyfin.Server/Migrations/IDatabaseMigrationRoutine.cs b/Jellyfin.Server/Migrations/IDatabaseMigrationRoutine.cs index d2d80a81eb..a794708764 100644 --- a/Jellyfin.Server/Migrations/IDatabaseMigrationRoutine.cs +++ b/Jellyfin.Server/Migrations/IDatabaseMigrationRoutine.cs @@ -7,8 +7,6 @@ namespace Jellyfin.Server.Migrations; /// <summary> /// Defines a migration that operates on the Database. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete -internal interface IDatabaseMigrationRoutine : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +internal interface IDatabaseMigrationRoutine : IAsyncMigrationRoutine { } diff --git a/Jellyfin.Server/Migrations/JellyfinMigrationAttribute.cs b/Jellyfin.Server/Migrations/JellyfinMigrationAttribute.cs index 70e54125b8..f07693c8e0 100644 --- a/Jellyfin.Server/Migrations/JellyfinMigrationAttribute.cs +++ b/Jellyfin.Server/Migrations/JellyfinMigrationAttribute.cs @@ -17,9 +17,7 @@ public sealed class JellyfinMigrationAttribute : Attribute /// </summary> /// <param name="order">The ordering this migration should be applied to. Must be a valid DateTime ISO8601 formatted string.</param> /// <param name="name">The name of this Migration.</param> -#pragma warning disable CS0618 // Type or member is obsolete public JellyfinMigrationAttribute(string order, string name) : this(order, name, null) -#pragma warning restore CS0618 // Type or member is obsolete { } @@ -29,7 +27,6 @@ public sealed class JellyfinMigrationAttribute : Attribute /// <param name="order">The ordering this migration should be applied to. Must be a valid DateTime ISO8601 formatted string.</param> /// <param name="name">The name of this Migration.</param> /// <param name="key">[ONLY FOR LEGACY MIGRATIONS]The unique key of this migration. Must be a valid Guid formatted string.</param> - [Obsolete("This Constructor should only be used for Legacy migrations. Use the (Order,Name) one for all new ones instead.")] public JellyfinMigrationAttribute(string order, string name, string? key) { Order = DateTime.Parse(order, CultureInfo.InvariantCulture); diff --git a/Jellyfin.Server/Migrations/JellyfinMigrationService.cs b/Jellyfin.Server/Migrations/JellyfinMigrationService.cs index 21ffab8dd6..0722409c53 100644 --- a/Jellyfin.Server/Migrations/JellyfinMigrationService.cs +++ b/Jellyfin.Server/Migrations/JellyfinMigrationService.cs @@ -59,8 +59,7 @@ internal class JellyfinMigrationService _backupService = backupService; _jellyfinDatabaseProvider = jellyfinDatabaseProvider; _applicationPaths = applicationPaths; -#pragma warning disable CS0618 // Type or member is obsolete - Migrations = [.. typeof(IMigrationRoutine).Assembly.GetTypes().Where(e => typeof(IMigrationRoutine).IsAssignableFrom(e) || typeof(IAsyncMigrationRoutine).IsAssignableFrom(e)) + Migrations = [.. typeof(IAsyncMigrationRoutine).Assembly.GetTypes().Where(e => typeof(IAsyncMigrationRoutine).IsAssignableFrom(e)) .Select(e => (Type: e, Metadata: e.GetCustomAttribute<JellyfinMigrationAttribute>(), Backup: e.GetCustomAttributes<JellyfinMigrationBackupAttribute>())) .Where(e => e.Metadata is not null) .GroupBy(e => e.Metadata!.Stage) @@ -80,7 +79,6 @@ internal class JellyfinMigrationService return stage; })]; -#pragma warning restore CS0618 // Type or member is obsolete } private interface IInternalMigration diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs index fd472cff7c..87cbe0477c 100644 --- a/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs +++ b/Jellyfin.Server/Migrations/PreStartupRoutines/CreateNetworkConfiguration.cs @@ -1,5 +1,7 @@ using System; using System.IO; +using System.Threading; +using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using Emby.Server.Implementations; @@ -8,10 +10,8 @@ using Microsoft.Extensions.Logging; namespace Jellyfin.Server.Migrations.PreStartupRoutines; /// <inheritdoc /> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T00:00:00", nameof(CreateNetworkConfiguration), "9B354818-94D5-4B68-AC49-E35CB85F9D84", Stage = Stages.JellyfinMigrationStageTypes.PreInitialisation)] -public class CreateNetworkConfiguration : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +public class CreateNetworkConfiguration : IAsyncMigrationRoutine { private readonly ServerApplicationPaths _applicationPaths; private readonly ILogger<CreateNetworkConfiguration> _logger; @@ -28,13 +28,13 @@ public class CreateNetworkConfiguration : IMigrationRoutine } /// <inheritdoc /> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { string path = Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "network.xml"); if (File.Exists(path)) { _logger.LogDebug("Network configuration file already exists, skipping"); - return; + return Task.CompletedTask; } var serverConfigSerializer = new XmlSerializer(typeof(OldNetworkConfiguration), new XmlRootAttribute("ServerConfiguration")); @@ -45,6 +45,8 @@ public class CreateNetworkConfiguration : IMigrationRoutine var xmlWriterSettings = new XmlWriterSettings { Indent = true }; using var xmlWriter = XmlWriter.Create(path, xmlWriterSettings); networkConfigSerializer.Serialize(xmlWriter, networkSettings); + + return Task.CompletedTask; } #pragma warning disable diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateEncodingOptions.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateEncodingOptions.cs index a5006c9bfa..78b8697baf 100644 --- a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateEncodingOptions.cs +++ b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateEncodingOptions.cs @@ -1,5 +1,7 @@ using System; using System.IO; +using System.Threading; +using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using Emby.Server.Implementations; @@ -10,10 +12,8 @@ using Microsoft.Extensions.Logging; namespace Jellyfin.Server.Migrations.PreStartupRoutines; /// <inheritdoc /> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T03:00:00", nameof(MigrateEncodingOptions), "A8E61960-7726-4450-8F3D-82C12DAABBCB", Stage = Stages.JellyfinMigrationStageTypes.PreInitialisation)] -public class MigrateEncodingOptions : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +public class MigrateEncodingOptions : IAsyncMigrationRoutine { private readonly ServerApplicationPaths _applicationPaths; private readonly ILogger<MigrateEncodingOptions> _logger; @@ -30,7 +30,7 @@ public class MigrateEncodingOptions : IMigrationRoutine } /// <inheritdoc /> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { string path = Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "encoding.xml"); var oldSerializer = new XmlSerializer(typeof(OldEncodingOptions), new XmlRootAttribute("EncodingOptions")); @@ -52,7 +52,7 @@ public class MigrateEncodingOptions : IMigrationRoutine if (oldConfig is null) { - return; + return Task.CompletedTask; } var hardwareAccelerationType = HardwareAccelerationType.none; @@ -143,6 +143,8 @@ public class MigrateEncodingOptions : IMigrationRoutine var xmlWriterSettings = new XmlWriterSettings { Indent = true }; using var xmlWriter = XmlWriter.Create(path, xmlWriterSettings); newSerializer.Serialize(xmlWriter, encodingOptions); + + return Task.CompletedTask; } #pragma warning disable diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateMusicBrainzTimeout.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateMusicBrainzTimeout.cs index e8da9f515d..3eb26b8689 100644 --- a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateMusicBrainzTimeout.cs +++ b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateMusicBrainzTimeout.cs @@ -1,5 +1,7 @@ using System; using System.IO; +using System.Threading; +using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using Emby.Server.Implementations; @@ -9,10 +11,8 @@ using Microsoft.Extensions.Logging; namespace Jellyfin.Server.Migrations.PreStartupRoutines; /// <inheritdoc /> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T02:00:00", nameof(MigrateMusicBrainzTimeout), "A6DCACF4-C057-4Ef9-80D3-61CEF9DDB4F0", Stage = Stages.JellyfinMigrationStageTypes.PreInitialisation)] -public class MigrateMusicBrainzTimeout : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +public class MigrateMusicBrainzTimeout : IAsyncMigrationRoutine { private readonly ServerApplicationPaths _applicationPaths; private readonly ILogger<MigrateMusicBrainzTimeout> _logger; @@ -29,13 +29,13 @@ public class MigrateMusicBrainzTimeout : IMigrationRoutine } /// <inheritdoc /> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { string path = Path.Combine(_applicationPaths.PluginConfigurationsPath, "Jellyfin.Plugin.MusicBrainz.xml"); if (!File.Exists(path)) { _logger.LogDebug("No MusicBrainz plugin configuration file found, skipping"); - return; + return Task.CompletedTask; } var oldPluginConfiguration = ReadOld(path); @@ -51,6 +51,8 @@ public class MigrateMusicBrainzTimeout : IMigrationRoutine newPluginConfiguration.RateLimit = newRateLimit < 1.0 ? 1.0 : newRateLimit; WriteNew(path, newPluginConfiguration); } + + return Task.CompletedTask; } private OldMusicBrainzConfiguration? ReadOld(string path) diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateNetworkConfiguration.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateNetworkConfiguration.cs index f2790c1a1f..e409b78130 100644 --- a/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateNetworkConfiguration.cs +++ b/Jellyfin.Server/Migrations/PreStartupRoutines/MigrateNetworkConfiguration.cs @@ -2,6 +2,8 @@ using System; using System.IO; +using System.Threading; +using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using Emby.Server.Implementations; @@ -12,7 +14,7 @@ namespace Jellyfin.Server.Migrations.PreStartupRoutines; /// <inheritdoc /> [JellyfinMigration("2025-04-20T01:00:00", nameof(MigrateNetworkConfiguration), "4FB5C950-1991-11EE-9B4B-0800200C9A66", Stage = Stages.JellyfinMigrationStageTypes.PreInitialisation)] -public class MigrateNetworkConfiguration : IMigrationRoutine +public class MigrateNetworkConfiguration : IAsyncMigrationRoutine { private readonly ServerApplicationPaths _applicationPaths; private readonly ILogger<MigrateNetworkConfiguration> _logger; @@ -29,7 +31,7 @@ public class MigrateNetworkConfiguration : IMigrationRoutine } /// <inheritdoc /> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { string path = Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "network.xml"); var oldNetworkConfigSerializer = new XmlSerializer(typeof(OldNetworkConfiguration), new XmlRootAttribute("NetworkConfiguration")); @@ -51,7 +53,7 @@ public class MigrateNetworkConfiguration : IMigrationRoutine if (oldNetworkConfiguration is null) { - return; + return Task.CompletedTask; } // Migrate network config values to new config schema @@ -96,6 +98,8 @@ public class MigrateNetworkConfiguration : IMigrationRoutine var xmlWriterSettings = new XmlWriterSettings { Indent = true }; using var xmlWriter = XmlWriter.Create(path, xmlWriterSettings); networkConfigSerializer.Serialize(xmlWriter, networkConfiguration); + + return Task.CompletedTask; } #pragma warning disable diff --git a/Jellyfin.Server/Migrations/PreStartupRoutines/RenameEnableGroupingIntoCollections.cs b/Jellyfin.Server/Migrations/PreStartupRoutines/RenameEnableGroupingIntoCollections.cs index 995b2bbf9b..a33bd4004b 100644 --- a/Jellyfin.Server/Migrations/PreStartupRoutines/RenameEnableGroupingIntoCollections.cs +++ b/Jellyfin.Server/Migrations/PreStartupRoutines/RenameEnableGroupingIntoCollections.cs @@ -2,6 +2,8 @@ using System; using System.IO; using System.Linq; using System.Text; +using System.Threading; +using System.Threading.Tasks; using System.Xml.Linq; using Emby.Server.Implementations; using Microsoft.Extensions.Logging; @@ -9,10 +11,8 @@ using Microsoft.Extensions.Logging; namespace Jellyfin.Server.Migrations.PreStartupRoutines; /// <inheritdoc /> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T04:00:00", nameof(RenameEnableGroupingIntoCollections), "E73B777D-CD5C-4E71-957A-B86B3660B7CF", Stage = Stages.JellyfinMigrationStageTypes.PreInitialisation)] -public class RenameEnableGroupingIntoCollections : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +public class RenameEnableGroupingIntoCollections : IAsyncMigrationRoutine { private readonly ServerApplicationPaths _applicationPaths; private readonly ILogger<RenameEnableGroupingIntoCollections> _logger; @@ -29,13 +29,13 @@ public class RenameEnableGroupingIntoCollections : IMigrationRoutine } /// <inheritdoc /> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { string path = Path.Combine(_applicationPaths.ConfigurationDirectoryPath, "system.xml"); if (!File.Exists(path)) { _logger.LogWarning("Configuration file not found: {Path}", path); - return; + return Task.CompletedTask; } try @@ -53,5 +53,7 @@ public class RenameEnableGroupingIntoCollections : IMigrationRoutine { _logger.LogError(ex, "An error occurred while updating the XML file: {Message}", ex.Message); } + + return Task.CompletedTask; } } diff --git a/Jellyfin.Server/Migrations/Routines/20250420050000_DisableTranscodingThrottling.cs b/Jellyfin.Server/Migrations/Routines/20250420050000_DisableTranscodingThrottling.cs index acf2835fe0..4e0046f254 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420050000_DisableTranscodingThrottling.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420050000_DisableTranscodingThrottling.cs @@ -1,4 +1,6 @@ using System; +using System.Threading; +using System.Threading.Tasks; using MediaBrowser.Common.Configuration; using Microsoft.Extensions.Logging; @@ -7,10 +9,8 @@ namespace Jellyfin.Server.Migrations.Routines /// <summary> /// Disable transcode throttling for all installations since it is currently broken for certain video formats. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T05:00:00", nameof(DisableTranscodingThrottling), "4124C2CD-E939-4FFB-9BE9-9B311C413638")] - internal class DisableTranscodingThrottling : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete + internal class DisableTranscodingThrottling : IAsyncMigrationRoutine { private readonly ILogger<DisableTranscodingThrottling> _logger; private readonly IConfigurationManager _configManager; @@ -22,7 +22,7 @@ namespace Jellyfin.Server.Migrations.Routines } /// <inheritdoc/> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { // Set EnableThrottling to false since it wasn't used before and may introduce issues var encoding = _configManager.GetEncodingOptions(); @@ -33,6 +33,8 @@ namespace Jellyfin.Server.Migrations.Routines _configManager.SaveConfiguration("encoding", encoding); } + + return Task.CompletedTask; } } } diff --git a/Jellyfin.Server/Migrations/Routines/20250420060000_CreateUserLoggingConfigFile.cs b/Jellyfin.Server/Migrations/Routines/20250420060000_CreateUserLoggingConfigFile.cs index 1326a6dc8d..bfbc5a9dad 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420060000_CreateUserLoggingConfigFile.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420060000_CreateUserLoggingConfigFile.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading; +using System.Threading.Tasks; using MediaBrowser.Common.Configuration; using Newtonsoft.Json.Linq; @@ -12,10 +14,8 @@ namespace Jellyfin.Server.Migrations.Routines /// If the deprecated logging.json file exists and has a custom config, it will be used as logging.user.json, /// otherwise a blank file will be created. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T06:00:00", nameof(CreateUserLoggingConfigFile), "EF103419-8451-40D8-9F34-D1A8E93A1679")] - internal class CreateUserLoggingConfigFile : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete + internal class CreateUserLoggingConfigFile : IAsyncMigrationRoutine { /// <summary> /// File history for logging.json as existed during this migration creation. The contents for each has been minified. @@ -46,7 +46,7 @@ namespace Jellyfin.Server.Migrations.Routines } /// <inheritdoc/> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { var logDirectory = _appPaths.ConfigurationDirectoryPath; var existingConfigPath = Path.Combine(logDirectory, "logging.json"); @@ -57,6 +57,8 @@ namespace Jellyfin.Server.Migrations.Routines { File.Move(existingConfigPath, Path.Combine(logDirectory, "logging.old.json")); } + + return Task.CompletedTask; } /// <summary> diff --git a/Jellyfin.Server/Migrations/Routines/20250420070000_MigrateActivityLogDb.cs b/Jellyfin.Server/Migrations/Routines/20250420070000_MigrateActivityLogDb.cs index 8c8563190d..c4d4495201 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420070000_MigrateActivityLogDb.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420070000_MigrateActivityLogDb.cs @@ -1,6 +1,8 @@ using System; using System.Collections.Generic; using System.IO; +using System.Threading; +using System.Threading.Tasks; using Emby.Server.Implementations.Data; using Jellyfin.Database.Implementations; using Jellyfin.Database.Implementations.Entities; @@ -14,10 +16,8 @@ namespace Jellyfin.Server.Migrations.Routines /// <summary> /// The migration routine for migrating the activity log database to EF Core. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T07:00:00", nameof(MigrateActivityLogDb), "3793eb59-bc8c-456c-8b9f-bd5a62a42978")] - public class MigrateActivityLogDb : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete + public class MigrateActivityLogDb : IAsyncMigrationRoutine { private const string DbFilename = "activitylog.db"; @@ -38,8 +38,15 @@ namespace Jellyfin.Server.Migrations.Routines _paths = paths; } - /// <inheritdoc/> - public void Perform() + /// <inheritdoc /> + public Task PerformAsync(CancellationToken cancellationToken) + { + // This routine predates the async interface and has not been ported to async database access yet. + PerformCore(); + return Task.CompletedTask; + } + + private void PerformCore() { var logLevelDictionary = new Dictionary<string, LogLevel>(StringComparer.OrdinalIgnoreCase) { diff --git a/Jellyfin.Server/Migrations/Routines/20250420080000_RemoveDuplicateExtras.cs b/Jellyfin.Server/Migrations/Routines/20250420080000_RemoveDuplicateExtras.cs index c9e66d0cfe..3cc4c4f9ed 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420080000_RemoveDuplicateExtras.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420080000_RemoveDuplicateExtras.cs @@ -2,6 +2,8 @@ using System; using System.Globalization; using System.IO; using System.Linq; +using System.Threading; +using System.Threading.Tasks; using Emby.Server.Implementations.Data; using MediaBrowser.Controller; using Microsoft.Data.Sqlite; @@ -12,10 +14,8 @@ namespace Jellyfin.Server.Migrations.Routines; /// <summary> /// Remove duplicate entries which were caused by a bug where a file was considered to be an "Extra" to itself. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T08:00:00", nameof(RemoveDuplicateExtras), "ACBE17B7-8435-4A83-8B64-6FCF162CB9BD")] -internal class RemoveDuplicateExtras : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +internal class RemoveDuplicateExtras : IAsyncMigrationRoutine { private const string DbFilename = "library.db"; private readonly ILogger<RemoveDuplicateExtras> _logger; @@ -27,8 +27,15 @@ internal class RemoveDuplicateExtras : IMigrationRoutine _paths = paths; } - /// <inheritdoc/> - public void Perform() + /// <inheritdoc /> + public Task PerformAsync(CancellationToken cancellationToken) + { + // This routine predates the async interface and has not been ported to async database access yet. + PerformCore(); + return Task.CompletedTask; + } + + private void PerformCore() { var dataPath = _paths.DataPath; var dbPath = Path.Combine(dataPath, DbFilename); diff --git a/Jellyfin.Server/Migrations/Routines/20250420090000_AddDefaultPluginRepository.cs b/Jellyfin.Server/Migrations/Routines/20250420090000_AddDefaultPluginRepository.cs index 8c8398a161..c705f8513f 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420090000_AddDefaultPluginRepository.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420090000_AddDefaultPluginRepository.cs @@ -1,4 +1,6 @@ using System; +using System.Threading; +using System.Threading.Tasks; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Updates; @@ -7,10 +9,8 @@ namespace Jellyfin.Server.Migrations.Routines /// <summary> /// Migration to initialize system configuration with the default plugin repository. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T09:00:00", nameof(AddDefaultPluginRepository), "EB58EBEE-9514-4B9B-8225-12E1A40020DF", RunMigrationOnSetup = true)] - public class AddDefaultPluginRepository : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete + public class AddDefaultPluginRepository : IAsyncMigrationRoutine { private readonly IServerConfigurationManager _serverConfigurationManager; @@ -30,10 +30,12 @@ namespace Jellyfin.Server.Migrations.Routines } /// <inheritdoc/> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { _serverConfigurationManager.Configuration.PluginRepositories = new[] { _defaultRepositoryInfo }; _serverConfigurationManager.SaveConfiguration(); + + return Task.CompletedTask; } } } diff --git a/Jellyfin.Server/Migrations/Routines/20250420100000_MigrateUserDb.cs b/Jellyfin.Server/Migrations/Routines/20250420100000_MigrateUserDb.cs index 8c3361ee16..f577a9d9fa 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420100000_MigrateUserDb.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420100000_MigrateUserDb.cs @@ -1,5 +1,7 @@ using System; using System.IO; +using System.Threading; +using System.Threading.Tasks; using Emby.Server.Implementations.Data; using Jellyfin.Data; using Jellyfin.Database.Implementations; @@ -22,10 +24,8 @@ namespace Jellyfin.Server.Migrations.Routines; /// <summary> /// The migration routine for migrating the user database to EF Core. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T10:00:00", nameof(MigrateUserDb), "5C4B82A2-F053-4009-BD05-B6FCAD82F14C")] -public class MigrateUserDb : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +public class MigrateUserDb : IAsyncMigrationRoutine { private const string DbFilename = "users.db"; @@ -53,8 +53,15 @@ public class MigrateUserDb : IMigrationRoutine _xmlSerializer = xmlSerializer; } - /// <inheritdoc/> - public void Perform() + /// <inheritdoc /> + public Task PerformAsync(CancellationToken cancellationToken) + { + // This routine predates the async interface and has not been ported to async database access yet. + PerformCore(); + return Task.CompletedTask; + } + + private void PerformCore() { var dataPath = _paths.DataPath; var userDbPath = Path.Combine(dataPath, DbFilename); diff --git a/Jellyfin.Server/Migrations/Routines/20250420110000_ReaddDefaultPluginRepository.cs b/Jellyfin.Server/Migrations/Routines/20250420110000_ReaddDefaultPluginRepository.cs index ebf4a2780e..df2a8cef98 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420110000_ReaddDefaultPluginRepository.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420110000_ReaddDefaultPluginRepository.cs @@ -1,4 +1,6 @@ using System; +using System.Threading; +using System.Threading.Tasks; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Updates; @@ -7,10 +9,8 @@ namespace Jellyfin.Server.Migrations.Routines; /// <summary> /// Migration to initialize system configuration with the default plugin repository. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T11:00:00", nameof(ReaddDefaultPluginRepository), "5F86E7F6-D966-4C77-849D-7A7B40B68C4E", RunMigrationOnSetup = true)] -public class ReaddDefaultPluginRepository : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +public class ReaddDefaultPluginRepository : IAsyncMigrationRoutine { private readonly IServerConfigurationManager _serverConfigurationManager; @@ -30,7 +30,7 @@ public class ReaddDefaultPluginRepository : IMigrationRoutine } /// <inheritdoc/> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { // Only add if repository list is empty if (_serverConfigurationManager.Configuration.PluginRepositories.Length == 0) @@ -38,5 +38,7 @@ public class ReaddDefaultPluginRepository : IMigrationRoutine _serverConfigurationManager.Configuration.PluginRepositories = new[] { _defaultRepositoryInfo }; _serverConfigurationManager.SaveConfiguration(); } + + return Task.CompletedTask; } } diff --git a/Jellyfin.Server/Migrations/Routines/20250420120000_MigrateDisplayPreferencesDb.cs b/Jellyfin.Server/Migrations/Routines/20250420120000_MigrateDisplayPreferencesDb.cs index ffd06fea0d..b3d08790dc 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420120000_MigrateDisplayPreferencesDb.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420120000_MigrateDisplayPreferencesDb.cs @@ -4,6 +4,8 @@ using System.IO; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; +using System.Threading; +using System.Threading.Tasks; using Emby.Server.Implementations.Data; using Jellyfin.Database.Implementations; using Jellyfin.Database.Implementations.Entities; @@ -20,10 +22,8 @@ namespace Jellyfin.Server.Migrations.Routines /// <summary> /// The migration routine for migrating the display preferences database to EF Core. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T12:00:00", nameof(MigrateDisplayPreferencesDb), "06387815-C3CC-421F-A888-FB5F9992BEA8")] - public class MigrateDisplayPreferencesDb : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete + public class MigrateDisplayPreferencesDb : IAsyncMigrationRoutine { private const string DbFilename = "displaypreferences.db"; @@ -55,7 +55,14 @@ namespace Jellyfin.Server.Migrations.Routines } /// <inheritdoc /> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) + { + // This routine predates the async interface and has not been ported to async database access yet. + PerformCore(); + return Task.CompletedTask; + } + + private void PerformCore() { HomeSectionType[] defaults = { diff --git a/Jellyfin.Server/Migrations/Routines/20250420130000_RemoveDownloadImagesInAdvance.cs b/Jellyfin.Server/Migrations/Routines/20250420130000_RemoveDownloadImagesInAdvance.cs index b626c473e3..805a25decd 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420130000_RemoveDownloadImagesInAdvance.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420130000_RemoveDownloadImagesInAdvance.cs @@ -1,4 +1,6 @@ using System; +using System.Threading; +using System.Threading.Tasks; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using Microsoft.Extensions.Logging; @@ -8,10 +10,8 @@ namespace Jellyfin.Server.Migrations.Routines; /// <summary> /// Removes the old 'RemoveDownloadImagesInAdvance' from library options. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T13:00:00", nameof(RemoveDownloadImagesInAdvance), "A81F75E0-8F43-416F-A5E8-516CCAB4D8CC")] -internal class RemoveDownloadImagesInAdvance : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +internal class RemoveDownloadImagesInAdvance : IAsyncMigrationRoutine { private readonly ILogger<RemoveDownloadImagesInAdvance> _logger; private readonly ILibraryManager _libraryManager; @@ -23,7 +23,7 @@ internal class RemoveDownloadImagesInAdvance : IMigrationRoutine } /// <inheritdoc/> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { var virtualFolders = _libraryManager.GetVirtualFolders(false); _logger.LogInformation("Removing 'RemoveDownloadImagesInAdvance' settings in all the libraries"); @@ -41,5 +41,7 @@ internal class RemoveDownloadImagesInAdvance : IMigrationRoutine collectionFolder.UpdateLibraryOptions(libraryOptions); _logger.LogInformation("Removed from '{VirtualFolder}'", virtualFolder.Name); } + + return Task.CompletedTask; } } diff --git a/Jellyfin.Server/Migrations/Routines/20250420140000_MigrateAuthenticationDb.cs b/Jellyfin.Server/Migrations/Routines/20250420140000_MigrateAuthenticationDb.cs index cbdc6efb44..e71f802985 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420140000_MigrateAuthenticationDb.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420140000_MigrateAuthenticationDb.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Threading; +using System.Threading.Tasks; using Emby.Server.Implementations.Data; using Jellyfin.Database.Implementations; using Jellyfin.Database.Implementations.Entities.Security; @@ -16,10 +18,8 @@ namespace Jellyfin.Server.Migrations.Routines /// <summary> /// A migration that moves data from the authentication database into the new schema. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T14:00:00", nameof(MigrateAuthenticationDb), "5BD72F41-E6F3-4F60-90AA-09869ABE0E22")] - public class MigrateAuthenticationDb : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete + public class MigrateAuthenticationDb : IAsyncMigrationRoutine { private const string DbFilename = "authentication.db"; @@ -48,7 +48,14 @@ namespace Jellyfin.Server.Migrations.Routines } /// <inheritdoc /> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) + { + // This routine predates the async interface and has not been ported to async database access yet. + PerformCore(); + return Task.CompletedTask; + } + + private void PerformCore() { var dataPath = _appPaths.DataPath; var dbFilePath = Path.Combine(dataPath, DbFilename); diff --git a/Jellyfin.Server/Migrations/Routines/20250420150000_FixPlaylistOwner.cs b/Jellyfin.Server/Migrations/Routines/20250420150000_FixPlaylistOwner.cs index 56614ece3c..eda91958eb 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420150000_FixPlaylistOwner.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420150000_FixPlaylistOwner.cs @@ -1,6 +1,7 @@ using System; using System.Linq; using System.Threading; +using System.Threading.Tasks; using Jellyfin.Data.Enums; using MediaBrowser.Controller.Entities; @@ -13,10 +14,8 @@ namespace Jellyfin.Server.Migrations.Routines; /// <summary> /// Properly set playlist owner. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T15:00:00", nameof(FixPlaylistOwner), "615DFA9E-2497-4DBB-A472-61938B752C5B")] -internal class FixPlaylistOwner : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +internal class FixPlaylistOwner : IAsyncMigrationRoutine { private readonly ILogger<FixPlaylistOwner> _logger; private readonly ILibraryManager _libraryManager; @@ -32,8 +31,15 @@ internal class FixPlaylistOwner : IMigrationRoutine _playlistManager = playlistManager; } - /// <inheritdoc/> - public void Perform() + /// <inheritdoc /> + public Task PerformAsync(CancellationToken cancellationToken) + { + // This routine predates the async interface and has not been ported to async database access yet. + PerformCore(); + return Task.CompletedTask; + } + + private void PerformCore() { var playlists = _libraryManager.GetItemList(new InternalItemsQuery { diff --git a/Jellyfin.Server/Migrations/Routines/20250420160000_AddDefaultCastReceivers.cs b/Jellyfin.Server/Migrations/Routines/20250420160000_AddDefaultCastReceivers.cs index 00d152b4b8..e52b03f757 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420160000_AddDefaultCastReceivers.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420160000_AddDefaultCastReceivers.cs @@ -1,4 +1,6 @@ using System; +using System.Threading; +using System.Threading.Tasks; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.System; @@ -7,10 +9,8 @@ namespace Jellyfin.Server.Migrations.Routines; /// <summary> /// Migration to add the default cast receivers to the system config. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T16:00:00", nameof(AddDefaultCastReceivers), "34A1A1C4-5572-418E-A2F8-32CDFE2668E8", RunMigrationOnSetup = true)] -public class AddDefaultCastReceivers : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +public class AddDefaultCastReceivers : IAsyncMigrationRoutine { private readonly IServerConfigurationManager _serverConfigurationManager; @@ -24,7 +24,7 @@ public class AddDefaultCastReceivers : IMigrationRoutine } /// <inheritdoc /> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { _serverConfigurationManager.Configuration.CastReceiverApplications = [ @@ -41,5 +41,7 @@ public class AddDefaultCastReceivers : IMigrationRoutine ]; _serverConfigurationManager.SaveConfiguration(); + + return Task.CompletedTask; } } diff --git a/Jellyfin.Server/Migrations/Routines/20250420170000_UpdateDefaultPluginRepository.cs b/Jellyfin.Server/Migrations/Routines/20250420170000_UpdateDefaultPluginRepository.cs index f58cf27413..a97dbef707 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420170000_UpdateDefaultPluginRepository.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420170000_UpdateDefaultPluginRepository.cs @@ -1,4 +1,6 @@ using System; +using System.Threading; +using System.Threading.Tasks; using MediaBrowser.Controller.Configuration; namespace Jellyfin.Server.Migrations.Routines; @@ -6,10 +8,8 @@ namespace Jellyfin.Server.Migrations.Routines; /// <summary> /// Migration to update the default Jellyfin plugin repository. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T17:00:00", nameof(UpdateDefaultPluginRepository), "852816E0-2712-49A9-9240-C6FC5FCAD1A8", RunMigrationOnSetup = true)] -public class UpdateDefaultPluginRepository : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +public class UpdateDefaultPluginRepository : IAsyncMigrationRoutine { private const string NewRepositoryUrl = "https://repo.jellyfin.org/files/plugin/manifest.json"; private const string OldRepositoryUrl = "https://repo.jellyfin.org/releases/plugin/manifest-stable.json"; @@ -26,7 +26,7 @@ public class UpdateDefaultPluginRepository : IMigrationRoutine } /// <inheritdoc /> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { var updated = false; foreach (var repo in _serverConfigurationManager.Configuration.PluginRepositories) @@ -42,5 +42,7 @@ public class UpdateDefaultPluginRepository : IMigrationRoutine { _serverConfigurationManager.SaveConfiguration(); } + + return Task.CompletedTask; } } diff --git a/Jellyfin.Server/Migrations/Routines/20250420180000_FixAudioData.cs b/Jellyfin.Server/Migrations/Routines/20250420180000_FixAudioData.cs index d102e24b91..a736ccb4ec 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420180000_FixAudioData.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420180000_FixAudioData.cs @@ -1,5 +1,6 @@ using System.Linq; using System.Threading; +using System.Threading.Tasks; using Jellyfin.Data.Enums; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; @@ -12,11 +13,9 @@ namespace Jellyfin.Server.Migrations.Routines /// <summary> /// Fixes the data column of audio types to be deserializable. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T18:00:00", nameof(FixAudioData), "CF6FABC2-9FBE-4933-84A5-FFE52EF22A58")] [JellyfinMigrationBackup(LegacyLibraryDb = true)] - internal class FixAudioData : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete + internal class FixAudioData : IAsyncMigrationRoutine { private readonly ILogger<FixAudioData> _logger; private readonly IItemRepository _itemRepository; @@ -36,7 +35,7 @@ namespace Jellyfin.Server.Migrations.Routines } /// <inheritdoc/> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { _logger.LogInformation("Backfilling audio lyrics data to database."); var startIndex = 0; @@ -71,6 +70,8 @@ namespace Jellyfin.Server.Migrations.Routines startIndex += results.Count; _logger.LogInformation("Backfilled data for {UpdatedRecords} of {TotalRecords} audio records", startIndex, records); } + + return Task.CompletedTask; } } } diff --git a/Jellyfin.Server/Migrations/Routines/20250420200000_MigrateLibraryDb.cs b/Jellyfin.Server/Migrations/Routines/20250420200000_MigrateLibraryDb.cs index 3e4205547a..06eba8cd94 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420200000_MigrateLibraryDb.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420200000_MigrateLibraryDb.cs @@ -9,6 +9,8 @@ using System.Globalization; using System.IO; using System.Linq; using System.Text; +using System.Threading; +using System.Threading.Tasks; using Emby.Server.Implementations.Data; using Jellyfin.Database.Implementations; using Jellyfin.Database.Implementations.Entities; @@ -59,8 +61,15 @@ internal class MigrateLibraryDb : IDatabaseMigrationRoutine _jellyfinDatabaseProvider = jellyfinDatabaseProvider; } - /// <inheritdoc/> - public void Perform() + /// <inheritdoc /> + public Task PerformAsync(CancellationToken cancellationToken) + { + // This routine predates the async interface and has not been ported to async database access yet. + PerformCore(); + return Task.CompletedTask; + } + + private void PerformCore() { _logger.LogInformation("Migrating the userdata from library.db may take a while, do not stop Jellyfin."); diff --git a/Jellyfin.Server/Migrations/Routines/20250420230000_MoveTrickplayFiles.cs b/Jellyfin.Server/Migrations/Routines/20250420230000_MoveTrickplayFiles.cs index 79a8f9577c..46f4ce13c0 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420230000_MoveTrickplayFiles.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420230000_MoveTrickplayFiles.cs @@ -3,6 +3,8 @@ using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; +using System.Threading; +using System.Threading.Tasks; using Jellyfin.Data.Enums; using Jellyfin.Server.ServerSetupApp; using MediaBrowser.Controller.Entities; @@ -16,10 +18,8 @@ namespace Jellyfin.Server.Migrations.Routines; /// <summary> /// Migration to move trickplay files to the new directory. /// </summary> -#pragma warning disable CS0618 // Type or member is obsolete [JellyfinMigration("2025-04-20T23:00:00", nameof(MoveTrickplayFiles), RunMigrationOnSetup = true)] -public class MoveTrickplayFiles : IMigrationRoutine -#pragma warning restore CS0618 // Type or member is obsolete +public class MoveTrickplayFiles : IAsyncMigrationRoutine { private readonly ITrickplayManager _trickplayManager; private readonly IFileSystem _fileSystem; @@ -46,7 +46,7 @@ public class MoveTrickplayFiles : IMigrationRoutine } /// <inheritdoc /> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) { const int Limit = 5000; int itemCount = 0, offset = 0, previousCount; @@ -103,6 +103,8 @@ public class MoveTrickplayFiles : IMigrationRoutine } while (previousCount == Limit); _logger.LogInformation("Moved {Count} items in {Time}", itemCount, sw.Elapsed); + + return Task.CompletedTask; } private string GetOldTrickplayDirectory(BaseItem item, int? width = null) diff --git a/Jellyfin.Server/Migrations/Routines/20250420230000_RefreshInternalDateModified.cs b/Jellyfin.Server/Migrations/Routines/20250420230000_RefreshInternalDateModified.cs index b23a7dbc42..420105b856 100644 --- a/Jellyfin.Server/Migrations/Routines/20250420230000_RefreshInternalDateModified.cs +++ b/Jellyfin.Server/Migrations/Routines/20250420230000_RefreshInternalDateModified.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; +using System.Threading; +using System.Threading.Tasks; using Jellyfin.Database.Implementations; using Jellyfin.Database.Implementations.Entities; using Jellyfin.Extensions; @@ -70,7 +72,14 @@ public class RefreshInternalDateModified : IDatabaseMigrationRoutine } /// <inheritdoc /> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) + { + // This routine predates the async interface and has not been ported to async database access yet. + PerformCore(); + return Task.CompletedTask; + } + + private void PerformCore() { const int Limit = 5000; int itemCount = 0, offset = 0; diff --git a/Jellyfin.Server/Migrations/Routines/20250421000000_MigrateKeyframeData.cs b/Jellyfin.Server/Migrations/Routines/20250421000000_MigrateKeyframeData.cs index aa55309264..fd42ce5224 100644 --- a/Jellyfin.Server/Migrations/Routines/20250421000000_MigrateKeyframeData.cs +++ b/Jellyfin.Server/Migrations/Routines/20250421000000_MigrateKeyframeData.cs @@ -5,6 +5,8 @@ using System.Globalization; using System.IO; using System.Linq; using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; using Jellyfin.Data.Enums; using Jellyfin.Database.Implementations; using Jellyfin.Database.Implementations.Entities; @@ -47,7 +49,14 @@ public class MigrateKeyframeData : IDatabaseMigrationRoutine private string KeyframeCachePath => Path.Combine(_appPaths.DataPath, "keyframes"); /// <inheritdoc /> - public void Perform() + public Task PerformAsync(CancellationToken cancellationToken) + { + // This routine predates the async interface and has not been ported to async database access yet. + PerformCore(); + return Task.CompletedTask; + } + + private void PerformCore() { const int Limit = 5000; int itemCount = 0, offset = 0; diff --git a/Jellyfin.Server/Migrations/Routines/20260113120000_MigrateLinkedChildren.cs b/Jellyfin.Server/Migrations/Routines/20260113120000_MigrateLinkedChildren.cs index 7fa555f005..ea2c0ddc22 100644 --- a/Jellyfin.Server/Migrations/Routines/20260113120000_MigrateLinkedChildren.cs +++ b/Jellyfin.Server/Migrations/Routines/20260113120000_MigrateLinkedChildren.cs @@ -3,6 +3,8 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; using Jellyfin.Database.Implementations; using Jellyfin.Database.Implementations.Entities; using Jellyfin.Extensions; @@ -49,8 +51,15 @@ internal class MigrateLinkedChildren : IDatabaseMigrationRoutine _appPaths = appPaths; } - /// <inheritdoc/> - public void Perform() + /// <inheritdoc /> + public Task PerformAsync(CancellationToken cancellationToken) + { + // This routine predates the async interface and has not been ported to async database access yet. + PerformCore(); + return Task.CompletedTask; + } + + private void PerformCore() { using var context = _dbProvider.CreateDbContext(); diff --git a/Jellyfin.Server/Migrations/Routines/20260206200000_FixLibrarySubtitleDownloadLanguages.cs b/Jellyfin.Server/Migrations/Routines/20260206200000_FixLibrarySubtitleDownloadLanguages.cs deleted file mode 100644 index 2b1f549940..0000000000 --- a/Jellyfin.Server/Migrations/Routines/20260206200000_FixLibrarySubtitleDownloadLanguages.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Jellyfin.Server.ServerSetupApp; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Globalization; -using Microsoft.Extensions.Logging; - -namespace Jellyfin.Server.Migrations.Routines; - -/// <summary> -/// Migration to fix broken library subtitle download languages. -/// </summary> -[JellyfinMigration("2026-02-06T20:00:00", nameof(FixLibrarySubtitleDownloadLanguages))] -internal class FixLibrarySubtitleDownloadLanguages : IAsyncMigrationRoutine -{ - private readonly ILocalizationManager _localizationManager; - private readonly ILibraryManager _libraryManager; - private readonly ILogger _logger; - - /// <summary> - /// Initializes a new instance of the <see cref="FixLibrarySubtitleDownloadLanguages"/> class. - /// </summary> - /// <param name="localizationManager">The Localization manager.</param> - /// <param name="startupLogger">The startup logger for Startup UI integration.</param> - /// <param name="libraryManager">The Library manager.</param> - /// <param name="logger">The logger.</param> - public FixLibrarySubtitleDownloadLanguages( - ILocalizationManager localizationManager, - IStartupLogger<FixLibrarySubtitleDownloadLanguages> startupLogger, - ILibraryManager libraryManager, - ILogger<FixLibrarySubtitleDownloadLanguages> logger) - { - _localizationManager = localizationManager; - _libraryManager = libraryManager; - _logger = startupLogger.With(logger); - } - - /// <inheritdoc /> - public Task PerformAsync(CancellationToken cancellationToken) - { - _logger.LogInformation("Starting to fix library subtitle download languages."); - - var virtualFolders = _libraryManager.GetVirtualFolders(false); - - foreach (var virtualFolder in virtualFolders) - { - var options = virtualFolder.LibraryOptions; - if (options?.SubtitleDownloadLanguages is null || options.SubtitleDownloadLanguages.Length == 0) - { - continue; - } - - // Some virtual folders don't have a proper item id. - if (!Guid.TryParse(virtualFolder.ItemId, out var folderId)) - { - continue; - } - - var collectionFolder = _libraryManager.GetItemById<CollectionFolder>(folderId); - if (collectionFolder is null) - { - _logger.LogWarning("Could not find collection folder for virtual folder '{LibraryName}' with id '{FolderId}'. Skipping.", virtualFolder.Name, folderId); - continue; - } - - var fixedLanguages = new List<string>(); - - foreach (var language in options.SubtitleDownloadLanguages) - { - var foundLanguage = _localizationManager.FindLanguageInfo(language)?.ThreeLetterISOLanguageName; - if (foundLanguage is not null) - { - // Converted ISO 639-2/B to T (ger to deu) - if (!string.Equals(foundLanguage, language, StringComparison.OrdinalIgnoreCase)) - { - _logger.LogInformation("Converted '{Language}' to '{ResolvedLanguage}' in library '{LibraryName}'.", language, foundLanguage, virtualFolder.Name); - } - - if (fixedLanguages.Contains(foundLanguage, StringComparer.OrdinalIgnoreCase)) - { - _logger.LogInformation("Language '{Language}' already exists for library '{LibraryName}'. Skipping duplicate.", foundLanguage, virtualFolder.Name); - continue; - } - - fixedLanguages.Add(foundLanguage); - } - else - { - _logger.LogInformation("Could not resolve language '{Language}' in library '{LibraryName}'. Skipping.", language, virtualFolder.Name); - } - } - - options.SubtitleDownloadLanguages = [.. fixedLanguages]; - collectionFolder.UpdateLibraryOptions(options); - } - - _logger.LogInformation("Library subtitle download languages fixed."); - - return Task.CompletedTask; - } -} diff --git a/Jellyfin.Server/Migrations/Routines/20260729120000_RestorePlaylistChildrenFromMetadata.cs b/Jellyfin.Server/Migrations/Routines/20260729120000_RestorePlaylistChildrenFromMetadata.cs index 16ac6cb5e5..82c8601e9e 100644 --- a/Jellyfin.Server/Migrations/Routines/20260729120000_RestorePlaylistChildrenFromMetadata.cs +++ b/Jellyfin.Server/Migrations/Routines/20260729120000_RestorePlaylistChildrenFromMetadata.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; +using System.Threading; +using System.Threading.Tasks; using System.Xml; using Jellyfin.Database.Implementations; using Jellyfin.Database.Implementations.Entities; @@ -34,8 +36,15 @@ internal class RestorePlaylistChildrenFromMetadata : IDatabaseMigrationRoutine _appHost = appHost; } - /// <inheritdoc/> - public void Perform() + /// <inheritdoc /> + public Task PerformAsync(CancellationToken cancellationToken) + { + // This routine predates the async interface and has not been ported to async database access yet. + PerformCore(); + return Task.CompletedTask; + } + + private void PerformCore() { using var context = _dbProvider.CreateDbContext(); diff --git a/Jellyfin.Server/Migrations/Routines/20260911120000_StripEmbeddedLinkedChildren.cs b/Jellyfin.Server/Migrations/Routines/20260911120000_StripEmbeddedLinkedChildren.cs index f61e42337a..4f7b464ac4 100644 --- a/Jellyfin.Server/Migrations/Routines/20260911120000_StripEmbeddedLinkedChildren.cs +++ b/Jellyfin.Server/Migrations/Routines/20260911120000_StripEmbeddedLinkedChildren.cs @@ -1,3 +1,5 @@ +using System.Threading; +using System.Threading.Tasks; using Jellyfin.Database.Implementations; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; @@ -22,23 +24,26 @@ internal class StripEmbeddedLinkedChildren : IDatabaseMigrationRoutine } /// <inheritdoc/> - public void Perform() + public async Task PerformAsync(CancellationToken cancellationToken) { - using var context = _dbProvider.CreateDbContext(); + var context = await _dbProvider.CreateDbContextAsync(cancellationToken).ConfigureAwait(false); + await using (context.ConfigureAwait(false)) + { + // json_valid guards the rare malformed blob: json_remove would abort the statement on it, + // and one bad row must not cost every other row the fix. + var updated = await context.Database.ExecuteSqlRawAsync( + """ + UPDATE "BaseItems" + SET "Data" = json_remove("Data", '$.LinkedChildren', '$.ExtraIds', '$.SupportsExternalTransfer') + WHERE "Data" IS NOT NULL + AND json_valid("Data") = 1 + AND ("Data" LIKE '%"LinkedChildren"%' + OR "Data" LIKE '%"ExtraIds"%' + OR "Data" LIKE '%"SupportsExternalTransfer"%') + """, + cancellationToken).ConfigureAwait(false); - // json_valid guards the rare malformed blob: json_remove would abort the statement on it, - // and one bad row must not cost every other row the fix. - var updated = context.Database.ExecuteSqlRaw( - """ - UPDATE "BaseItems" - SET "Data" = json_remove("Data", '$.LinkedChildren', '$.ExtraIds', '$.SupportsExternalTransfer') - WHERE "Data" IS NOT NULL - AND json_valid("Data") = 1 - AND ("Data" LIKE '%"LinkedChildren"%' - OR "Data" LIKE '%"ExtraIds"%' - OR "Data" LIKE '%"SupportsExternalTransfer"%') - """); - - _logger.LogInformation("Dropped dead keys from the serialized data of {Count} items", updated); + _logger.LogInformation("Dropped dead keys from the serialized data of {Count} items", updated); + } } } diff --git a/Jellyfin.Server/Migrations/Routines/20260915120000_MigrateRatingLevels.cs b/Jellyfin.Server/Migrations/Routines/20260915120000_MigrateRatingLevels.cs deleted file mode 100644 index 903d91e046..0000000000 --- a/Jellyfin.Server/Migrations/Routines/20260915120000_MigrateRatingLevels.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System.Linq; -using Jellyfin.Database.Implementations; -using Jellyfin.Server.ServerSetupApp; -using MediaBrowser.Model.Globalization; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Logging; - -namespace Jellyfin.Server.Migrations.Routines; - -/// <summary> -/// Migrate rating levels. -/// </summary> -#pragma warning disable CS0618 // Type or member is obsolete -[JellyfinMigration("2026-09-15T12:00:00", nameof(MigrateRatingLevels))] -[JellyfinMigrationBackup(JellyfinDb = true)] -#pragma warning restore CS0618 // Type or member is obsolete -internal class MigrateRatingLevels : IDatabaseMigrationRoutine -{ - private readonly IStartupLogger _logger; - private readonly IDbContextFactory<JellyfinDbContext> _provider; - private readonly ILocalizationManager _localizationManager; - - public MigrateRatingLevels( - IDbContextFactory<JellyfinDbContext> provider, - IStartupLogger<MigrateRatingLevels> logger, - ILocalizationManager localizationManager) - { - _provider = provider; - _localizationManager = localizationManager; - _logger = logger; - } - - /// <inheritdoc/> - public void Perform() - { - _logger.LogInformation("Recalculating parental rating levels based on rating string."); - using var context = _provider.CreateDbContext(); - using var transaction = context.Database.BeginTransaction(); - var ratings = context.BaseItems.AsNoTracking().Select(e => e.OfficialRating).Distinct(); - foreach (var rating in ratings) - { - if (string.IsNullOrEmpty(rating)) - { - int? value = null; - context.BaseItems - .Where(e => e.OfficialRating == null || e.OfficialRating == string.Empty) - .ExecuteUpdate(f => f.SetProperty(e => e.InheritedParentalRatingValue, value)); - context.BaseItems - .Where(e => e.OfficialRating == null || e.OfficialRating == string.Empty) - .ExecuteUpdate(f => f.SetProperty(e => e.InheritedParentalRatingSubValue, value)); - } - else - { - var ratingValue = _localizationManager.GetRatingScore(rating); - var score = ratingValue?.Score; - var subScore = ratingValue?.SubScore; - context.BaseItems - .Where(e => e.OfficialRating == rating) - .ExecuteUpdate(f => f.SetProperty(e => e.InheritedParentalRatingValue, score)); - context.BaseItems - .Where(e => e.OfficialRating == rating) - .ExecuteUpdate(f => f.SetProperty(e => e.InheritedParentalRatingSubValue, subScore)); - } - } - - transaction.Commit(); - } -} diff --git a/Jellyfin.Server/Migrations/Routines/20260927120000_FixLibrarySubtitleDownloadLanguages.cs b/Jellyfin.Server/Migrations/Routines/20260927120000_FixLibrarySubtitleDownloadLanguages.cs new file mode 100644 index 0000000000..f6af977a8a --- /dev/null +++ b/Jellyfin.Server/Migrations/Routines/20260927120000_FixLibrarySubtitleDownloadLanguages.cs @@ -0,0 +1,136 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Jellyfin.Server.ServerSetupApp; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Globalization; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server.Migrations.Routines; + +/// <summary> +/// Migration to fix broken library subtitle download languages. +/// </summary> +[JellyfinMigration("2026-09-27T12:00:00", nameof(FixLibrarySubtitleDownloadLanguages))] +internal class FixLibrarySubtitleDownloadLanguages : IAsyncMigrationRoutine +{ + private readonly ILocalizationManager _localizationManager; + private readonly IServerConfigurationManager _serverConfigurationManager; + private readonly ILibraryManager _libraryManager; + private readonly ILogger _logger; + + /// <summary> + /// Initializes a new instance of the <see cref="FixLibrarySubtitleDownloadLanguages"/> class. + /// </summary> + /// <param name="localizationManager">The Localization manager.</param> + /// <param name="serverConfigurationManager">The server configuration manager.</param> + /// <param name="startupLogger">The startup logger for Startup UI integration.</param> + /// <param name="libraryManager">The Library manager.</param> + /// <param name="logger">The logger.</param> + public FixLibrarySubtitleDownloadLanguages( + ILocalizationManager localizationManager, + IServerConfigurationManager serverConfigurationManager, + IStartupLogger<FixLibrarySubtitleDownloadLanguages> startupLogger, + ILibraryManager libraryManager, + ILogger<FixLibrarySubtitleDownloadLanguages> logger) + { + _localizationManager = localizationManager; + _serverConfigurationManager = serverConfigurationManager; + _libraryManager = libraryManager; + _logger = startupLogger.With(logger); + } + + /// <inheritdoc /> + public Task PerformAsync(CancellationToken cancellationToken) + { + _logger.LogInformation("Starting to fix library subtitle download languages."); + + var virtualFolders = _libraryManager.GetVirtualFolders(false); + + foreach (var virtualFolder in virtualFolders) + { + var options = virtualFolder.LibraryOptions; + if (options?.SubtitleDownloadLanguages is null || options.SubtitleDownloadLanguages.Length == 0) + { + continue; + } + + // Some virtual folders don't have a proper item id. + if (!Guid.TryParse(virtualFolder.ItemId, out var folderId)) + { + continue; + } + + var collectionFolder = _libraryManager.GetItemById<CollectionFolder>(folderId); + if (collectionFolder is null) + { + _logger.LogWarning("Could not find collection folder for virtual folder '{LibraryName}' with id '{FolderId}'. Skipping.", virtualFolder.Name, folderId); + continue; + } + + var fixedLanguages = new List<string>(); + + // 12.0 stored every regional variant as its base code (Portuguese (Brazil) as por), so the + // metadata language is the only remaining hint of which variant the user actually picked. + var preferredLanguage = _localizationManager.FindLanguageInfo( + string.IsNullOrEmpty(options.PreferredMetadataLanguage) + ? _serverConfigurationManager.Configuration.PreferredMetadataLanguage + : options.PreferredMetadataLanguage); + + var cultures = options.SubtitleDownloadLanguages + .Select(language => _localizationManager.FindLanguageInfo(language)) + .ToArray(); + + for (var i = 0; i < options.SubtitleDownloadLanguages.Length; i++) + { + var language = options.SubtitleDownloadLanguages[i]; + + // Keep unresolvable values as they are, dropping them would silently discard a user setting. + var culture = cultures[i]; + if (culture is null) + { + _logger.LogWarning("Could not resolve language '{Language}' in library '{LibraryName}'. Keeping it unchanged.", language, virtualFolder.Name); + } + + var foundLanguage = culture?.ThreeLetterISOLanguageName ?? language; + + // A variant picked alongside the base code (10.10 stored por and pob separately) means the base code was meant generically. + var hasExplicitVariant = cultures.Any(other => other is not null + && !string.Equals(other.ThreeLetterISOLanguageName, foundLanguage, StringComparison.OrdinalIgnoreCase) + && other.ThreeLetterISOLanguageNames.Contains(language, StringComparer.OrdinalIgnoreCase)); + if (!hasExplicitVariant + && preferredLanguage?.ThreeLetterISOLanguageName is { } preferredCode + && !string.Equals(preferredCode, foundLanguage, StringComparison.OrdinalIgnoreCase) + && preferredLanguage.ThreeLetterISOLanguageNames.Contains(language, StringComparer.OrdinalIgnoreCase)) + { + foundLanguage = preferredCode; + } + + // Converted ISO 639-2/B to T (ger to deu) or a legacy code to its BCP-47 tag (pob to pt-br) + if (!string.Equals(foundLanguage, language, StringComparison.OrdinalIgnoreCase)) + { + _logger.LogInformation("Converted '{Language}' to '{ResolvedLanguage}' in library '{LibraryName}'.", language, foundLanguage, virtualFolder.Name); + } + + if (fixedLanguages.Contains(foundLanguage, StringComparer.OrdinalIgnoreCase)) + { + _logger.LogInformation("Language '{Language}' already exists for library '{LibraryName}'. Skipping duplicate.", foundLanguage, virtualFolder.Name); + continue; + } + + fixedLanguages.Add(foundLanguage); + } + + options.SubtitleDownloadLanguages = [.. fixedLanguages]; + collectionFolder.UpdateLibraryOptions(options); + } + + _logger.LogInformation("Library subtitle download languages fixed."); + + return Task.CompletedTask; + } +} diff --git a/Jellyfin.Server/Migrations/Routines/20260928120000_MigrateRatingLevels.cs b/Jellyfin.Server/Migrations/Routines/20260928120000_MigrateRatingLevels.cs new file mode 100644 index 0000000000..a2bf5bed9a --- /dev/null +++ b/Jellyfin.Server/Migrations/Routines/20260928120000_MigrateRatingLevels.cs @@ -0,0 +1,250 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Jellyfin.Database.Implementations; +using Jellyfin.Server.ServerSetupApp; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Globalization; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.Server.Migrations.Routines; + +/// <summary> +/// Migrate rating levels. +/// </summary> +[JellyfinMigration("2026-09-28T12:00:00", nameof(MigrateRatingLevels))] +[JellyfinMigrationBackup(JellyfinDb = true)] +internal class MigrateRatingLevels : IDatabaseMigrationRoutine +{ + private const string EpisodeType = "MediaBrowser.Controller.Entities.TV.Episode"; + private const string SeasonType = "MediaBrowser.Controller.Entities.TV.Season"; + private const string AggregateFolderType = "MediaBrowser.Controller.Entities.AggregateFolder"; + private const string UserRootFolderType = "MediaBrowser.Controller.Entities.UserRootFolder"; + private const int UpdateBatchSize = 1000; + + private readonly IStartupLogger _logger; + private readonly IDbContextFactory<JellyfinDbContext> _provider; + private readonly ILocalizationManager _localizationManager; + private readonly ILibraryManager _libraryManager; + private readonly IServerApplicationHost _appHost; + + public MigrateRatingLevels( + IDbContextFactory<JellyfinDbContext> provider, + IStartupLogger<MigrateRatingLevels> logger, + ILocalizationManager localizationManager, + ILibraryManager libraryManager, + IServerApplicationHost appHost) + { + _provider = provider; + _localizationManager = localizationManager; + _libraryManager = libraryManager; + _appHost = appHost; + _logger = logger; + } + + /// <inheritdoc /> + public Task PerformAsync(CancellationToken cancellationToken) + { + // This routine predates the async interface and has not been ported to async database access yet. + PerformCore(); + return Task.CompletedTask; + } + + private void PerformCore() + { + _logger.LogInformation("Recalculating parental rating levels based on rating string."); + using var context = _provider.CreateDbContext(); + using var transaction = context.Database.BeginTransaction(); + + var items = context.BaseItems + .AsNoTracking() + .Select(e => new RatingNode( + e.Id, + e.Type, + e.ParentId, + e.OwnerId, + e.SeasonId, + e.SeriesId, + e.OfficialRating, + e.CustomRating, + e.Path, + e.PreferredMetadataCountryCode, + e.InheritedParentalRatingValue, + e.InheritedParentalRatingSubValue)) + .ToDictionary(e => e.Id); + + var libraries = GetLibraries(items); + var libraryCountryCodes = new Dictionary<Guid, string?>(); + var scores = new Dictionary<(string Rating, string? CountryCode), ParentalRatingScore?>(); + var changes = new Dictionary<(int? Score, int? SubScore), List<Guid>>(); + foreach (var item in items.Values) + { + // Mirrors BaseItem.OnMetadataChanged: a custom rating anywhere up the display parent chain + // wins over the official one, and items without a rating of their own inherit their parent's. + var rating = ResolveRating(items, item, static e => e.CustomRating) + ?? ResolveRating(items, item, static e => e.OfficialRating); + + ParentalRatingScore? ratingScore = null; + if (rating is not null) + { + var scoreKey = (Rating: rating, CountryCode: ResolveCountryCode(items, libraries, libraryCountryCodes, item)); + if (!scores.TryGetValue(scoreKey, out ratingScore)) + { + ratingScore = _localizationManager.GetRatingScore(scoreKey.Rating, scoreKey.CountryCode); + scores[scoreKey] = ratingScore; + } + } + + var key = (ratingScore?.Score, ratingScore?.SubScore); + if (key.Score == item.InheritedParentalRatingValue && key.SubScore == item.InheritedParentalRatingSubValue) + { + continue; + } + + if (!changes.TryGetValue(key, out var ids)) + { + ids = []; + changes[key] = ids; + } + + ids.Add(item.Id); + } + + foreach (var ((score, subScore), ids) in changes) + { + foreach (var batch in ids.Chunk(UpdateBatchSize)) + { + context.BaseItems + .Where(e => batch.Contains(e.Id)) + .ExecuteUpdate(f => f + .SetProperty(e => e.InheritedParentalRatingValue, score) + .SetProperty(e => e.InheritedParentalRatingSubValue, subScore)); + } + } + + transaction.Commit(); + _logger.LogInformation("Updated the parental rating level of {Count} items.", changes.Values.Sum(e => e.Count)); + } + + private List<Library> GetLibraries(Dictionary<Guid, RatingNode> items) + { + var libraries = new List<Library>(); + foreach (var virtualFolder in _libraryManager.GetVirtualFolders(false)) + { + RatingNode? folder = null; + if (Guid.TryParse(virtualFolder.ItemId, out var folderId)) + { + items.TryGetValue(folderId, out folder); + } + + // The database stores paths under the data directory as %AppDataPath%, Locations holds them expanded. + libraries.Add(new Library( + folder?.Path, + [.. (virtualFolder.Locations ?? []).Select(_appHost.ReverseVirtualPath)], + folder?.PreferredMetadataCountryCode, + virtualFolder.LibraryOptions?.MetadataCountryCode)); + } + + return libraries; + } + + // Mirrors BaseItem.GetPreferredMetadataCountryCode; a null result falls back to the server's country. + private static string? ResolveCountryCode(Dictionary<Guid, RatingNode> items, List<Library> libraries, Dictionary<Guid, string?> libraryCountryCodes, RatingNode item) + { + var visited = new HashSet<Guid>(); + for (RatingNode? current = item; current is not null && visited.Add(current.Id); current = GetItem(items, current.ParentId)) + { + if (!string.IsNullOrEmpty(current.PreferredMetadataCountryCode)) + { + return current.PreferredMetadataCountryCode; + } + } + + // Like LibraryManager.GetCollectionFolders: the item below the root decides which libraries it is in. + // A CollectionFolder sits below the UserRootFolder instead and is matched by its own path. + visited.Clear(); + var top = item; + while (visited.Add(top.Id)) + { + var parent = GetItem(items, top.ParentId); + if (parent?.Type is AggregateFolderType or UserRootFolderType) + { + break; + } + + var next = parent ?? GetItem(items, top.OwnerId); + if (next is null) + { + break; + } + + top = next; + } + + if (libraryCountryCodes.TryGetValue(top.Id, out var cached)) + { + return cached; + } + + var matches = top.Path is null + ? [] + : libraries.Where(l => string.Equals(l.Path, top.Path, StringComparison.OrdinalIgnoreCase) + || l.Locations.Contains(top.Path, StringComparer.OrdinalIgnoreCase)).ToList(); + + var countryCode = matches.Select(l => l.PreferredMetadataCountryCode).FirstOrDefault(c => !string.IsNullOrEmpty(c)) + ?? matches.FirstOrDefault()?.MetadataCountryCode; + + countryCode = string.IsNullOrEmpty(countryCode) ? null : countryCode; + libraryCountryCodes[top.Id] = countryCode; + return countryCode; + } + + private static RatingNode? GetItem(Dictionary<Guid, RatingNode> items, Guid? id) + => id is { } value && items.TryGetValue(value, out var item) ? item : null; + + private static string? ResolveRating(Dictionary<Guid, RatingNode> items, RatingNode item, Func<RatingNode, string?> selector) + { + var visited = new HashSet<Guid>(); + RatingNode? current = item; + while (current is not null && visited.Add(current.Id)) + { + var rating = selector(current); + if (!string.IsNullOrEmpty(rating)) + { + return rating; + } + + var parentId = current.Type switch + { + EpisodeType => current.SeasonId, + SeasonType => current.SeriesId, + _ => current.ParentId + }; + + current = GetItem(items, parentId); + } + + return null; + } + + private sealed record RatingNode( + Guid Id, + string Type, + Guid? ParentId, + Guid? OwnerId, + Guid? SeasonId, + Guid? SeriesId, + string? OfficialRating, + string? CustomRating, + string? Path, + string? PreferredMetadataCountryCode, + int? InheritedParentalRatingValue, + int? InheritedParentalRatingSubValue); + + private sealed record Library(string? Path, string[] Locations, string? PreferredMetadataCountryCode, string? MetadataCountryCode); +} diff --git a/Jellyfin.Server/Migrations/Stages/CodeMigration.cs b/Jellyfin.Server/Migrations/Stages/CodeMigration.cs index 71706811b8..fa2210ea40 100644 --- a/Jellyfin.Server/Migrations/Stages/CodeMigration.cs +++ b/Jellyfin.Server/Migrations/Stages/CodeMigration.cs @@ -22,9 +22,9 @@ internal class CodeMigration(Type migrationType, JellyfinMigrationAttribute meta public async Task Perform(IServiceProvider serviceProvider, IStartupLogger logger, CancellationToken cancellationToken) { - if (!IsMigrationRoutine(MigrationType)) + if (!typeof(IAsyncMigrationRoutine).IsAssignableFrom(MigrationType)) { - throw new InvalidOperationException($"The type {MigrationType} does not implement either IMigrationRoutine or IAsyncMigrationRoutine and is not a valid migration type"); + throw new InvalidOperationException($"The type {MigrationType} does not implement IAsyncMigrationRoutine and is not a valid migration type"); } // The routine runs against a scope of the applications own container. Copying the application service @@ -37,28 +37,8 @@ internal class CodeMigration(Type migrationType, JellyfinMigrationAttribute meta // Nests everything the routine logs through an injected IStartupLogger under the migrations own topic. using (StartupLogger.BeginAmbientTopic(logger.Topic)) { - await RunAsync(ActivatorUtilities.CreateInstance(scope.ServiceProvider, MigrationType), cancellationToken).ConfigureAwait(false); + await ((IAsyncMigrationRoutine)ActivatorUtilities.CreateInstance(scope.ServiceProvider, MigrationType)).PerformAsync(cancellationToken).ConfigureAwait(false); } } } - - // The obsolete IMigrationRoutine is still implemented by every routine that predates the async interface, so - // the members that have to touch it are grouped here behind a single suppression. -#pragma warning disable CS0618 // Type or member is obsolete - private static bool IsMigrationRoutine(Type migrationType) - { - return typeof(IMigrationRoutine).IsAssignableFrom(migrationType) || typeof(IAsyncMigrationRoutine).IsAssignableFrom(migrationType); - } - - private static async Task RunAsync(object routine, CancellationToken cancellationToken) - { - if (routine is IMigrationRoutine migrationRoutine) - { - migrationRoutine.Perform(); - return; - } - - await ((IAsyncMigrationRoutine)routine).PerformAsync(cancellationToken).ConfigureAwait(false); - } -#pragma warning restore CS0618 // Type or member is obsolete } diff --git a/Jellyfin.Server/Program.cs b/Jellyfin.Server/Program.cs index 29c7d512d0..7b3920f76d 100644 --- a/Jellyfin.Server/Program.cs +++ b/Jellyfin.Server/Program.cs @@ -271,6 +271,12 @@ namespace Jellyfin.Server { _restartOnShutdown = false; _logger.LogCritical(ex, "Error while starting server"); + if (options.StartupMode is not (null or Configuration.StartupMode.MediaServer)) + { + // A MigrateSystem or SeedSystem run is started from a script, which can only tell that it failed by the exit code. + Environment.ExitCode = 1; + } + if (_setupServer!.IsAlive && !configurationCompleted) { _setupServer!.SoftStop(); diff --git a/Jellyfin.Server/Startup.cs b/Jellyfin.Server/Startup.cs index 560a419945..7aef47d438 100644 --- a/Jellyfin.Server/Startup.cs +++ b/Jellyfin.Server/Startup.cs @@ -70,7 +70,7 @@ namespace Jellyfin.Server options.HttpsPort = _serverApplicationHost.HttpsPort; }); - services.AddJellyfinApi(_serverApplicationHost.GetApiPluginAssemblies(), _serverConfigurationManager.GetNetworkConfiguration()); + services.AddJellyfinApi(_serverApplicationHost.GetApiPluginAssemblies(), _serverConfigurationManager.GetNetworkConfiguration(), _serverConfigurationManager.Configuration); services.AddJellyfinDbContext(_serverApplicationHost.ConfigurationManager, _configuration); services.AddJellyfinApiSwagger(); diff --git a/MediaBrowser.Common/Net/HttpResponseBodyException.cs b/MediaBrowser.Common/Net/HttpResponseBodyException.cs new file mode 100644 index 0000000000..2194640b61 --- /dev/null +++ b/MediaBrowser.Common/Net/HttpResponseBodyException.cs @@ -0,0 +1,31 @@ +using System.Net; +using System.Net.Http; + +namespace MediaBrowser.Common.Net; + +/// <summary> +/// An <see cref="HttpRequestException"/> that retains the body of the failed response. +/// </summary> +/// <remarks> +/// Providers report why they refused a request in the response body, which +/// <see cref="HttpResponseMessage.EnsureSuccessStatusCode"/> discards. +/// </remarks> +public class HttpResponseBodyException : HttpRequestException +{ + /// <summary> + /// Initializes a new instance of the <see cref="HttpResponseBodyException"/> class. + /// </summary> + /// <param name="message">The exception message.</param> + /// <param name="statusCode">The status code of the failed response.</param> + /// <param name="responseBody">The body of the failed response.</param> + public HttpResponseBodyException(string message, HttpStatusCode? statusCode, string? responseBody) + : base(message, null, statusCode) + { + ResponseBody = responseBody; + } + + /// <summary> + /// Gets the body of the failed response. + /// </summary> + public string? ResponseBody { get; } +} diff --git a/MediaBrowser.Common/Net/NetworkConfigurationDto.cs b/MediaBrowser.Common/Net/NetworkConfigurationDto.cs new file mode 100644 index 0000000000..12be0d9fb8 --- /dev/null +++ b/MediaBrowser.Common/Net/NetworkConfigurationDto.cs @@ -0,0 +1,124 @@ +#pragma warning disable CA1819 + +namespace MediaBrowser.Common.Net; + +/// <summary> +/// The network configuration DTO for API use. +/// </summary> +public class NetworkConfigurationDto +{ + /// <summary> + /// Gets or sets a value used to specify the URL prefix that your Jellyfin instance can be accessed at. + /// </summary> + public string BaseUrl { get; set; } = null!; + + /// <summary> + /// Gets or sets a value indicating whether to use HTTPS. + /// </summary> + public bool EnableHttps { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the server should force connections over HTTPS. + /// </summary> + public bool RequireHttps { get; set; } + + /// <summary> + /// Gets or sets the filesystem path of an X.509 certificate to use for SSL. + /// </summary> + public string? CertificatePath { get; set; } + + /// <summary> + /// Gets or sets the password required to access the X.509 certificate data in the file specified by <see cref="CertificatePath"/>. + /// </summary> + public string? CertificatePassword { get; set; } + + /// <summary> + /// Gets or sets the internal HTTP server port. + /// </summary> + public int InternalHttpPort { get; set; } + + /// <summary> + /// Gets or sets the internal HTTPS server port. + /// </summary> + public int InternalHttpsPort { get; set; } + + /// <summary> + /// Gets or sets the public HTTP port. + /// </summary> + public int PublicHttpPort { get; set; } + + /// <summary> + /// Gets or sets the public HTTPS port. + /// </summary> + public int PublicHttpsPort { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether Autodiscovery is enabled. + /// </summary> + public bool AutoDiscovery { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to enable automatic port forwarding. + /// </summary> + public bool EnableUPnP { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether IPv4 is enabled. + /// </summary> + public bool EnableIPv4 { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether IPv6 is enabled. + /// </summary> + public bool EnableIPv6 { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether access from outside of the LAN is permitted. + /// </summary> + public bool EnableRemoteAccess { get; set; } + + /// <summary> + /// Gets or sets the subnets that are deemed to make up the LAN. + /// </summary> + public string[] LocalNetworkSubnets { get; set; } = null!; + + /// <summary> + /// Gets or sets the interface addresses which Jellyfin will bind to. If empty, all interfaces will be used. + /// </summary> + public string[] LocalNetworkAddresses { get; set; } = null!; + + /// <summary> + /// Gets or sets the known proxies. + /// </summary> + public string[] KnownProxies { get; set; } = null!; + + /// <summary> + /// Gets or sets a value indicating whether address names that match <see cref="VirtualInterfaceNames"/> should be ignored for the purposes of binding. + /// </summary> + public bool IgnoreVirtualInterfaces { get; set; } + + /// <summary> + /// Gets or sets a value indicating the interface name prefixes that should be ignored. + /// </summary> + public string[] VirtualInterfaceNames { get; set; } = null!; + + /// <summary> + /// Gets or sets a value indicating whether the published server uri is based on information in HTTP requests. + /// </summary> + public bool EnablePublishedServerUriByRequest { get; set; } + + /// <summary> + /// Gets or sets PublishedServerUri to advertise for specific subnets. + /// </summary> + public string[] PublishedServerUriBySubnet { get; set; } = null!; + + /// <summary> + /// Gets or sets the filter for remote IP connectivity. Used in conjunction with <seealso cref="IsRemoteIPFilterBlacklist"/>. + /// </summary> + public string[] RemoteIPFilter { get; set; } = null!; + + /// <summary> + /// Gets or sets a value indicating whether <seealso cref="RemoteIPFilter"/> contains a blacklist or a whitelist. Default is a whitelist. + /// </summary> + public bool IsRemoteIPFilterBlacklist { get; set; } +} diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index a1e955f33f..2e3665f528 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1045,20 +1045,41 @@ namespace MediaBrowser.Controller.Entities } } + return ModifySortChunks(ApplySortCharacterRules(sortable, configuration)); + } + + private static string ApplySortCharacterRules(string name, ServerConfiguration configuration) + { foreach (var removeChar in configuration.SortRemoveCharacters) { - sortable = sortable.Replace(removeChar, string.Empty, StringComparison.Ordinal); + name = name.Replace(removeChar, string.Empty, StringComparison.Ordinal); } foreach (var replaceChar in configuration.SortReplaceCharacters) { - sortable = sortable.Replace(replaceChar, " ", StringComparison.Ordinal); + name = name.Replace(replaceChar, " ", StringComparison.Ordinal); } - return ModifySortChunks(sortable); + return name; } - internal static string ModifySortChunks(ReadOnlySpan<char> name) + /// <summary> + /// Normalizes a user-provided name filter value to match against <see cref="SortName"/>. + /// Applies the same character removal/replacement, zero-padding, diacritics removal, and transliteration + /// as sort name generation, but not <c>SortRemoveWords</c> since stripping articles from a prefix is unsafe. + /// </summary> + /// <param name="input">The raw filter value from the API.</param> + /// <returns>The normalized value suitable for comparison against SortName. Casing is preserved; callers requiring case-sensitive matching must handle it themselves.</returns> + public static string NormalizeSortNameFilter(string input) + => ModifySortChunks(ApplySortCharacterRules(input, ConfigurationManager.Configuration)); + + /// <summary> + /// Processes a name by zero-padding numeric chunks to 10 digits for natural sort order, + /// removing diacritics, and transliterating non-ASCII characters. + /// </summary> + /// <param name="name">The input name to process.</param> + /// <returns>The processed string with padded numeric chunks.</returns> + public static string ModifySortChunks(ReadOnlySpan<char> name) { static void AppendChunk(StringBuilder builder, bool isDigitChunk, ReadOnlySpan<char> chunk) { diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 626bc0d5a1..f325778f8b 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -1182,17 +1182,22 @@ namespace MediaBrowser.Controller.Entities { if (!string.IsNullOrWhiteSpace(query.NameStartsWith)) { - items = items.Where(i => i.SortName.StartsWith(query.NameStartsWith, StringComparison.OrdinalIgnoreCase)); + var paddedPrefix = BaseItem.NormalizeSortNameFilter(query.NameStartsWith); + items = items.Where(i => + i.SortName.StartsWith(paddedPrefix, StringComparison.OrdinalIgnoreCase) + || i.SortName.TrimStart('0').StartsWith(query.NameStartsWith, StringComparison.OrdinalIgnoreCase)); } if (!string.IsNullOrWhiteSpace(query.NameStartsWithOrGreater)) { - items = items.Where(i => string.Compare(i.SortName, query.NameStartsWithOrGreater, StringComparison.OrdinalIgnoreCase) >= 0); + var paddedValue = BaseItem.NormalizeSortNameFilter(query.NameStartsWithOrGreater); + items = items.Where(i => string.Compare(i.SortName, paddedValue, StringComparison.OrdinalIgnoreCase) >= 0); } if (!string.IsNullOrWhiteSpace(query.NameLessThan)) { - items = items.Where(i => string.Compare(i.SortName, query.NameLessThan, StringComparison.OrdinalIgnoreCase) < 0); + var paddedValue = BaseItem.NormalizeSortNameFilter(query.NameLessThan); + items = items.Where(i => string.Compare(i.SortName, paddedValue, StringComparison.OrdinalIgnoreCase) < 0); } return items; diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs index 82256cd964..f88759a5d8 100644 --- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs +++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs @@ -531,18 +531,22 @@ namespace MediaBrowser.Controller.Entities IUserDataManager userDataManager, ILibraryManager libraryManager) { - if (!string.IsNullOrEmpty(query.NameStartsWith) && !item.SortName.StartsWith(query.NameStartsWith, StringComparison.InvariantCultureIgnoreCase)) + if (!string.IsNullOrEmpty(query.NameStartsWith) + && !item.SortName.StartsWith(BaseItem.NormalizeSortNameFilter(query.NameStartsWith), StringComparison.InvariantCultureIgnoreCase) + && !item.SortName.TrimStart('0').StartsWith(query.NameStartsWith, StringComparison.InvariantCultureIgnoreCase)) { return false; } #pragma warning disable CA1309 // Use ordinal string comparison - if (!string.IsNullOrEmpty(query.NameStartsWithOrGreater) && string.Compare(query.NameStartsWithOrGreater, item.SortName, StringComparison.InvariantCultureIgnoreCase) == 1) + if (!string.IsNullOrEmpty(query.NameStartsWithOrGreater) + && string.Compare(BaseItem.NormalizeSortNameFilter(query.NameStartsWithOrGreater), item.SortName, StringComparison.InvariantCultureIgnoreCase) == 1) { return false; } - if (!string.IsNullOrEmpty(query.NameLessThan) && string.Compare(query.NameLessThan, item.SortName, StringComparison.InvariantCultureIgnoreCase) != 1) + if (!string.IsNullOrEmpty(query.NameLessThan) + && string.Compare(BaseItem.NormalizeSortNameFilter(query.NameLessThan), item.SortName, StringComparison.InvariantCultureIgnoreCase) != 1) #pragma warning restore CA1309 // Use ordinal string comparison { return false; diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index ae15c75350..8d00858b37 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -851,6 +851,20 @@ namespace MediaBrowser.Controller.Library QueryFiltersLegacy GetQueryFiltersLegacy(InternalItemsQuery query); /// <summary> + /// Gets the distinct, sorted production years of the matching items. + /// </summary> + /// <param name="query">The query filter.</param> + /// <returns>The production years.</returns> + IReadOnlyList<int> GetYears(InternalItemsQuery query); + + /// <summary> + /// Gets the distinct, sorted official ratings of the matching items. + /// </summary> + /// <param name="query">The query filter.</param> + /// <returns>The official ratings.</returns> + IReadOnlyList<string> GetOfficialRatings(InternalItemsQuery query); + + /// <summary> /// Gets a list of all distinct tags of the matching items. /// </summary> /// <param name="query">The query filter.</param> diff --git a/MediaBrowser.Controller/LiveTv/ISchedulesDirectService.cs b/MediaBrowser.Controller/LiveTv/ISchedulesDirectService.cs index 6953650952..a0df011811 100644 --- a/MediaBrowser.Controller/LiveTv/ISchedulesDirectService.cs +++ b/MediaBrowser.Controller/LiveTv/ISchedulesDirectService.cs @@ -1,6 +1,8 @@ using System.IO; +using System.Net; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Entities; namespace MediaBrowser.Controller.LiveTv; @@ -17,15 +19,36 @@ public interface ISchedulesDirectService Task<Stream> GetAvailableCountries(CancellationToken cancellationToken); /// <summary> - /// Gets a value indicating whether the Schedules Direct daily image download limit is currently active. + /// Gets a value indicating whether an image may be downloaded from the given url. /// </summary> - /// <returns><c>true</c> if the image limit has been hit and has not yet reset; otherwise <c>false</c>.</returns> - bool IsImageDailyLimitActive(); + /// <param name="imageUrl">The image url.</param> + /// <returns><c>false</c> for a Schedules Direct url while the daily image limit is active; otherwise <c>true</c>.</returns> + bool CanDownloadImage(string imageUrl); /// <summary> - /// Gets a value indicating whether the Schedules Direct service is available. - /// Returns <c>false</c> if a permanent account error has occurred or a transient backoff is active. + /// Reports a successful image download, so that an unexplained failure streak is reset. /// </summary> - /// <returns><c>true</c> if the service can accept requests; otherwise <c>false</c>.</returns> - bool IsServiceAvailable(); + /// <param name="imageUrl">The image url that was downloaded.</param> + void ReportImageDownloadSuccess(string imageUrl); + + /// <summary> + /// Reports a failed image download. Schedules Direct answers an exhausted image quota with + /// an HTTP 200 JSON error body rather than a failure status, so the body is what decides + /// whether image acquisition has to stop. + /// </summary> + /// <param name="imageUrl">The image url that failed.</param> + /// <param name="statusCode">The HTTP status code of the failure, if any.</param> + /// <param name="responseBody">The body of the failed response, if it was readable.</param> + /// <returns>What the caller must do with the image.</returns> + ImageDownloadFailureAction ReportImageDownloadFailure(string imageUrl, HttpStatusCode? statusCode, string? responseBody); + + /// <summary> + /// Downloads a remote image unless Schedules Direct has blocked it, and reports the outcome. + /// Schedules Direct counts every image request, so downloads outside the guide refresh go through here. + /// </summary> + /// <param name="item">The item the image belongs to.</param> + /// <param name="image">The remote image.</param> + /// <param name="imageIndex">The image index.</param> + /// <returns>The local image, or <c>null</c> when the download is blocked.</returns> + Task<ItemImageInfo?> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex); } diff --git a/MediaBrowser.Controller/LiveTv/ImageDownloadFailureAction.cs b/MediaBrowser.Controller/LiveTv/ImageDownloadFailureAction.cs new file mode 100644 index 0000000000..78a1e554b6 --- /dev/null +++ b/MediaBrowser.Controller/LiveTv/ImageDownloadFailureAction.cs @@ -0,0 +1,17 @@ +namespace MediaBrowser.Controller.LiveTv; + +/// <summary> +/// What the caller must do with an image after a failed download. +/// </summary> +public enum ImageDownloadFailureAction +{ + /// <summary> + /// Keep the image; the download may succeed on a later attempt. + /// </summary> + None = 0, + + /// <summary> + /// Drop the image. The url is permanently invalid and re-requesting it gets the account blocked. + /// </summary> + RemoveImage = 1 +} diff --git a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs index ebfa78176a..f3382b2d51 100644 --- a/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs +++ b/MediaBrowser.Controller/MediaEncoding/EncodingHelper.cs @@ -3116,6 +3116,16 @@ namespace MediaBrowser.Controller.MediaEncoding } seekParam += string.Format(CultureInfo.InvariantCulture, "-ss {0}", _mediaEncoder.GetTimeParameter(seekTick)); + + // Retain audio from the preceding keyframe to match copied video's start time. + if (isHlsRemuxing + && state.AudioStream is not null + && !string.IsNullOrEmpty(state.OutputAudioCodec) + && !IsCopyCodec(state.OutputAudioCodec) + && !string.Equals(state.InputContainer, "wtv", StringComparison.OrdinalIgnoreCase)) + { + seekParam += " -noaccurate_seek"; + } } return seekParam; diff --git a/MediaBrowser.Controller/Persistence/IItemRepository.cs b/MediaBrowser.Controller/Persistence/IItemRepository.cs index 3cf06b897c..69c74d3757 100644 --- a/MediaBrowser.Controller/Persistence/IItemRepository.cs +++ b/MediaBrowser.Controller/Persistence/IItemRepository.cs @@ -149,6 +149,20 @@ public interface IItemRepository QueryFiltersLegacy GetQueryFiltersLegacy(InternalItemsQuery filter); /// <summary> + /// Gets the distinct, sorted production years of the matching items. + /// </summary> + /// <param name="filter">The query filter.</param> + /// <returns>The production years.</returns> + IReadOnlyList<int> GetYears(InternalItemsQuery filter); + + /// <summary> + /// Gets the distinct, sorted official ratings of the matching items. + /// </summary> + /// <param name="filter">The query filter.</param> + /// <returns>The official ratings.</returns> + IReadOnlyList<string> GetOfficialRatings(InternalItemsQuery filter); + + /// <summary> /// Gets whether all children of the requested item have been played. /// </summary> /// <param name="user">The user to check against.</param> diff --git a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs index fbe8afc66e..756b67e063 100644 --- a/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs +++ b/MediaBrowser.MediaEncoding/Attachments/AttachmentExtractor.cs @@ -100,22 +100,10 @@ namespace MediaBrowser.MediaEncoding.Attachments MediaSourceInfo mediaSource, CancellationToken cancellationToken) { - var shouldExtractOneByOne = mediaSource.MediaAttachments.Any(a => !string.IsNullOrEmpty(a.FileName) - && !string.Equals(PathHelper.GetSafeLeafFileName(a.FileName), a.FileName, StringComparison.Ordinal)); - if (shouldExtractOneByOne && !inputFile.EndsWith(".mks", StringComparison.OrdinalIgnoreCase)) - { - await ExtractAllAttachmentsIndividuallyInternal( - inputFile, - mediaSource, - cancellationToken).ConfigureAwait(false); - } - else - { - await ExtractAllAttachmentsInternal( - inputFile, - mediaSource, - cancellationToken).ConfigureAwait(false); - } + await ExtractAllAttachmentsIndividuallyInternal( + inputFile, + mediaSource, + cancellationToken).ConfigureAwait(false); } private async Task ExtractAllAttachmentsIndividuallyInternal( @@ -252,117 +240,6 @@ namespace MediaBrowser.MediaEncoding.Attachments } } - private async Task ExtractAllAttachmentsInternal( - string inputFile, - MediaSourceInfo mediaSource, - CancellationToken cancellationToken) - { - var inputPath = _mediaEncoder.GetInputArgument(inputFile, mediaSource); - - ArgumentException.ThrowIfNullOrEmpty(inputPath); - - var outputFolder = _pathManager.GetAttachmentFolderPath(mediaSource.Id); - if (outputFolder is null) - { - _logger.LogDebug("Skipping attachment extraction for input {InputFile}: MediaSource Id is not a GUID.", inputFile); - return; - } - - using (await _semaphoreLocks.LockAsync(outputFolder, cancellationToken).ConfigureAwait(false)) - { - var directory = Directory.CreateDirectory(outputFolder); - var fileNames = directory.GetFiles("*", SearchOption.TopDirectoryOnly).Select(f => f.Name).ToHashSet(); - var missingFiles = mediaSource.MediaAttachments.Where(a => a.FileName is not null && !fileNames.Contains(a.FileName) && !string.Equals(a.Codec, "mjpeg", StringComparison.OrdinalIgnoreCase)); - if (!missingFiles.Any()) - { - // Skip extraction if all files already exist - return; - } - - // Files without video/audio streams (e.g. MKS subtitle files) don't need a dummy - // output since there are no streams to process. Omit "-t 0 -f null null" so ffmpeg - // doesn't fail trying to open an output with no streams. It will exit with code 1 - // ("at least one output file must be specified") which is expected and harmless - // since we only need the -dump_attachment side effect. - var hasVideoOrAudioStream = mediaSource.MediaStreams - .Any(s => s.Type == MediaStreamType.Video || s.Type == MediaStreamType.Audio); - var processArgs = string.Format( - CultureInfo.InvariantCulture, - "-dump_attachment:t \"\" -y {0} -i {1} {2}", - inputPath.EndsWith(".concat\"", StringComparison.OrdinalIgnoreCase) ? "-f concat -safe 0" : string.Empty, - inputPath, - hasVideoOrAudioStream ? "-t 0 -f null null" : string.Empty); - - int exitCode; - - using (var process = new Process - { - StartInfo = new ProcessStartInfo - { - Arguments = processArgs, - FileName = _mediaEncoder.EncoderPath, - UseShellExecute = false, - CreateNoWindow = true, - WindowStyle = ProcessWindowStyle.Hidden, - WorkingDirectory = outputFolder, - ErrorDialog = false - }, - EnableRaisingEvents = true - }) - { - _logger.LogInformation("{File} {Arguments}", process.StartInfo.FileName, process.StartInfo.Arguments); - - process.Start(); - - try - { - await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); - exitCode = process.ExitCode; - } - catch (OperationCanceledException) - { - process.Kill(true); - exitCode = -1; - } - } - - var failed = false; - - if (exitCode != 0) - { - if (hasVideoOrAudioStream || exitCode != 1) - { - failed = true; - - _logger.LogWarning("Deleting extracted attachments {Path} due to failure: {ExitCode}", outputFolder, exitCode); - try - { - Directory.Delete(outputFolder); - } - catch (IOException ex) - { - _logger.LogError(ex, "Error deleting extracted attachments {Path}", outputFolder); - } - } - } - - if (!failed && !Directory.Exists(outputFolder)) - { - failed = true; - } - - if (failed) - { - _logger.LogError("ffmpeg attachment extraction failed for {InputPath} to {OutputPath}", inputPath, outputFolder); - - throw new InvalidOperationException( - string.Format(CultureInfo.InvariantCulture, "ffmpeg attachment extraction failed for {0} to {1}", inputPath, outputFolder)); - } - - _logger.LogInformation("ffmpeg attachment extraction completed for {InputPath} to {OutputPath}", inputPath, outputFolder); - } - } - private async Task<Stream> GetAttachmentStream( MediaSourceInfo mediaSource, MediaAttachment mediaAttachment, diff --git a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs index c9d618c84a..6cf4d22581 100644 --- a/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs +++ b/MediaBrowser.MediaEncoding/Probing/ProbeResultNormalizer.cs @@ -170,8 +170,10 @@ namespace MediaBrowser.MediaEncoding.Probing FFProbeHelpers.GetDictionaryDateTime(tags, "retail date") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "retail_date") ?? FFProbeHelpers.GetDictionaryDateTime(tags, "date_released") ?? - FFProbeHelpers.GetDictionaryDateTime(tags, "date") ?? - FFProbeHelpers.GetDictionaryDateTime(tags, "creation_time"); + FFProbeHelpers.GetDictionaryDateTime(tags, "date"); + + // creation_time is when the file was written, not a release date + info.ContainerCreationDate = FFProbeHelpers.GetDictionaryDateTime(tags, "creation_time"); // Set common metadata for music (audio) and music videos (video) info.Album = tags.GetValueOrDefault("album"); diff --git a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs index 27a987fefe..58129da0ca 100644 --- a/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs +++ b/MediaBrowser.MediaEncoding/Subtitles/SubtitleEncoder.cs @@ -8,6 +8,7 @@ using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; +using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -222,6 +223,12 @@ namespace MediaBrowser.MediaEncoding.Subtitles var outputPath = GetSubtitleCachePath(mediaSource, subtitleStream.Index, "." + outputFileExtension) ?? throw new ResourceNotFoundException($"MediaSource {mediaSource.Id} has no subtitle cache (non-GUID Id, e.g. Live TV stream)."); + // Failed batch extraction can leave stale cache files behind. + if (!IsCachedSubtitleFresh(outputPath, mediaSource, subtitleStream)) + { + throw new ResourceNotFoundException($"Subtitle extraction did not produce a current cache for stream {subtitleStream.Index} of MediaSource {mediaSource.Id}."); + } + return new SubtitleInfo() { Path = outputPath, @@ -342,7 +349,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false)) { - if (!IsCachedSubtitleFresh(outputPath, subtitleStream.Path)) + if (!IsCachedSubtitleFresh(outputPath, mediaSource, subtitleStream)) { await ConvertTextSubtitleToSrtInternal(subtitleStream, mediaSource, outputPath, cancellationToken).ConfigureAwait(false); } @@ -360,13 +367,25 @@ namespace MediaBrowser.MediaEncoding.Subtitles }; } - // Records "this cache was built from this exact source revision" in a sidecar file next to the cache: "<sizeBytes>:<mtimeTicks>" private static string GetCacheMetaPath(string cachePath) => cachePath + ".meta"; - private static string FormatCacheMeta(long length, DateTime lastWriteUtc) - => string.Create(CultureInfo.InvariantCulture, $"{length}:{lastWriteUtc.Ticks}"); + private string FormatCacheMeta(MediaSourceInfo mediaSource, MediaStream subtitleStream) + { + var sourcePath = string.IsNullOrEmpty(subtitleStream.Path) ? mediaSource.Path : subtitleStream.Path; + // Identify the source track independently of its public stream index. + var streamIndex = EncodingHelper.GetSubtitleStreamIndexForFfmpeg(mediaSource, subtitleStream); + var sourceId = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(sourcePath ?? string.Empty))); + var revision = string.Empty; + if (File.Exists(sourcePath)) + { + var sourceInfo = _fileSystem.GetFileInfo(sourcePath); + revision = string.Create(CultureInfo.InvariantCulture, $"{sourceInfo.Length}:{sourceInfo.LastWriteTimeUtc.Ticks}"); + } - private bool IsCachedSubtitleFresh(string cachePath, string? sourcePath) + return string.Create(CultureInfo.InvariantCulture, $"v2:{streamIndex}:{revision}:{sourceId}"); + } + + internal bool IsCachedSubtitleFresh(string cachePath, MediaSourceInfo mediaSource, MediaStream subtitleStream) { if (!File.Exists(cachePath)) { @@ -379,11 +398,6 @@ namespace MediaBrowser.MediaEncoding.Subtitles return false; } - if (string.IsNullOrEmpty(sourcePath) || !File.Exists(sourcePath)) - { - return true; - } - var metaPath = GetCacheMetaPath(cachePath); if (!File.Exists(metaPath)) { @@ -393,8 +407,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles try { - var sourceInfo = _fileSystem.GetFileInfo(sourcePath); - var expected = FormatCacheMeta(sourceInfo.Length, sourceInfo.LastWriteTimeUtc); + var expected = FormatCacheMeta(mediaSource, subtitleStream); var actual = File.ReadAllText(metaPath); return string.Equals(expected, actual, StringComparison.Ordinal); } @@ -404,22 +417,11 @@ namespace MediaBrowser.MediaEncoding.Subtitles } } - private void WriteCacheMeta(string cachePath, string? sourcePath) + internal void WriteCacheMeta(string cachePath, MediaSourceInfo mediaSource, MediaStream subtitleStream) { - if (string.IsNullOrEmpty(sourcePath)) - { - return; - } - try { - var sourceInfo = _fileSystem.GetFileInfo(sourcePath); - if (!sourceInfo.Exists) - { - return; - } - - File.WriteAllText(GetCacheMetaPath(cachePath), FormatCacheMeta(sourceInfo.Length, sourceInfo.LastWriteTimeUtc)); + File.WriteAllText(GetCacheMetaPath(cachePath), FormatCacheMeta(mediaSource, subtitleStream)); } catch (IOException ex) { @@ -470,7 +472,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles [outputPath], cancellationToken).ConfigureAwait(false); - WriteCacheMeta(outputPath, inputPath); + WriteCacheMeta(outputPath, mediaSource, subtitleStream); } private string GetExtractableSubtitleFormat(MediaStream subtitleStream) @@ -546,8 +548,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var releaser = await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false); - var sourcePath = string.IsNullOrEmpty(subtitleStream.Path) ? mediaSource.Path : subtitleStream.Path; - if (IsCachedSubtitleFresh(outputPath, sourcePath)) + if (IsCachedSubtitleFresh(outputPath, mediaSource, subtitleStream)) { releaser.Dispose(); continue; @@ -601,7 +602,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles foreach (string mksFile in mksFiles) { var inputPath = _mediaEncoder.GetInputArgument(mksFile, mediaSource); - var outputPaths = new List<string>(); + var outputStreams = new Dictionary<string, MediaStream>(); var args = string.Format( CultureInfo.InvariantCulture, "-y -i {0}", @@ -633,7 +634,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid.")); - outputPaths.Add(outputPath); + outputStreams.Add(outputPath, subtitleStream); args += string.Format( CultureInfo.InvariantCulture, " -map 0:{0} -an -vn -c:s {1}{2} -flush_packets 1 \"{3}\"", @@ -643,11 +644,11 @@ namespace MediaBrowser.MediaEncoding.Subtitles outputPath.EscapeProcessArgument()); } - await ExtractSubtitlesForFile(inputPath, args, outputPaths, cancellationToken).ConfigureAwait(false); + await ExtractSubtitlesForFile(inputPath, args, outputStreams.Keys.ToArray(), cancellationToken).ConfigureAwait(false); - foreach (var outputPath in outputPaths) + foreach (var (outputPath, subtitleStream) in outputStreams) { - WriteCacheMeta(outputPath, mksFile); + WriteCacheMeta(outputPath, mediaSource, subtitleStream); } } } @@ -658,7 +659,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles CancellationToken cancellationToken) { var inputPath = _mediaEncoder.GetInputPathArgument(mediaSource.Path, mediaSource); - var outputPaths = new List<string>(); + var outputStreams = new Dictionary<string, MediaStream>(); var args = string.Format( CultureInfo.InvariantCulture, "-y -i {0}", @@ -691,7 +692,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles Directory.CreateDirectory(Path.GetDirectoryName(outputPath) ?? throw new FileNotFoundException($"Calculated path ({outputPath}) is not valid.")); - outputPaths.Add(outputPath); + outputStreams.Add(outputPath, subtitleStream); args += string.Format( CultureInfo.InvariantCulture, " -map 0:{0} -an -vn -c:s {1}{2} -flush_packets 1 \"{3}\"", @@ -701,13 +702,13 @@ namespace MediaBrowser.MediaEncoding.Subtitles outputPath.EscapeProcessArgument()); } - if (outputPaths.Count > 0) + if (outputStreams.Count > 0) { - await ExtractSubtitlesForFile(inputPath, args, outputPaths, cancellationToken).ConfigureAwait(false); + await ExtractSubtitlesForFile(inputPath, args, outputStreams.Keys.ToArray(), cancellationToken).ConfigureAwait(false); - foreach (var outputPath in outputPaths) + foreach (var (outputPath, subtitleStream) in outputStreams) { - WriteCacheMeta(outputPath, mediaSource.Path); + WriteCacheMeta(outputPath, mediaSource, subtitleStream); } } } @@ -722,7 +723,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles var failed = false; - if (exitCode == -1) + if (exitCode != 0) { failed = true; @@ -809,7 +810,7 @@ namespace MediaBrowser.MediaEncoding.Subtitles { using (await _semaphoreLocks.LockAsync(outputPath, cancellationToken).ConfigureAwait(false)) { - if (!File.Exists(outputPath) || _fileSystem.GetFileInfo(outputPath).Length == 0) + if (!IsCachedSubtitleFresh(outputPath, mediaSource, subtitleStream)) { var subtitleStreamIndex = EncodingHelper.FindIndex(mediaSource.MediaStreams, subtitleStream); @@ -826,6 +827,8 @@ namespace MediaBrowser.MediaEncoding.Subtitles outputCodec, outputPath, cancellationToken).ConfigureAwait(false); + + WriteCacheMeta(outputPath, mediaSource, subtitleStream); } } } diff --git a/MediaBrowser.Model/Configuration/EncodingOptionsDto.cs b/MediaBrowser.Model/Configuration/EncodingOptionsDto.cs new file mode 100644 index 0000000000..0bc009f402 --- /dev/null +++ b/MediaBrowser.Model/Configuration/EncodingOptionsDto.cs @@ -0,0 +1,257 @@ +#pragma warning disable CA1819 + +#nullable disable +using MediaBrowser.Model.Entities; + +namespace MediaBrowser.Model.Configuration; + +/// <summary> +/// The encoding options DTO for API use. +/// </summary> +public class EncodingOptionsDto +{ + /// <summary> + /// Gets or sets the thread count used for encoding. + /// </summary> + public int EncodingThreadCount { get; set; } + + /// <summary> + /// Gets or sets the temporary transcoding path. + /// </summary> + public string TranscodingTempPath { get; set; } + + /// <summary> + /// Gets or sets the path to the fallback font. + /// </summary> + public string FallbackFontPath { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to use the fallback font. + /// </summary> + public bool EnableFallbackFont { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether audio VBR is enabled. + /// </summary> + public bool EnableAudioVbr { get; set; } + + /// <summary> + /// Gets or sets the audio boost applied when downmixing audio. + /// </summary> + public double DownMixAudioBoost { get; set; } + + /// <summary> + /// Gets or sets the algorithm used for downmixing audio to stereo. + /// </summary> + public DownMixStereoAlgorithms DownMixStereoAlgorithm { get; set; } + + /// <summary> + /// Gets or sets the maximum size of the muxing queue. + /// </summary> + public int MaxMuxingQueueSize { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether throttling is enabled. + /// </summary> + public bool EnableThrottling { get; set; } + + /// <summary> + /// Gets or sets the delay after which throttling happens. + /// </summary> + public int ThrottleDelaySeconds { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether segment deletion is enabled. + /// </summary> + public bool EnableSegmentDeletion { get; set; } + + /// <summary> + /// Gets or sets seconds for which segments should be kept before being deleted. + /// </summary> + public int SegmentKeepSeconds { get; set; } + + /// <summary> + /// Gets or sets the hardware acceleration type. + /// </summary> + public HardwareAccelerationType HardwareAccelerationType { get; set; } + + /// <summary> + /// Gets or sets the FFmpeg path as set by the user via the UI. + /// </summary> + public string EncoderAppPath { get; set; } + + /// <summary> + /// Gets or sets the current FFmpeg path being used by the system and displayed on the transcode page. + /// </summary> + public string EncoderAppPathDisplay { get; set; } + + /// <summary> + /// Gets or sets the VA-API device. + /// </summary> + public string VaapiDevice { get; set; } + + /// <summary> + /// Gets or sets the QSV device. + /// </summary> + public string QsvDevice { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether tonemapping is enabled. + /// </summary> + public bool EnableTonemapping { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether VPP tonemapping is enabled. + /// </summary> + public bool EnableVppTonemapping { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether videotoolbox tonemapping is enabled. + /// </summary> + public bool EnableVideoToolboxTonemapping { get; set; } + + /// <summary> + /// Gets or sets the tone-mapping algorithm. + /// </summary> + public TonemappingAlgorithm TonemappingAlgorithm { get; set; } + + /// <summary> + /// Gets or sets the tone-mapping mode. + /// </summary> + public TonemappingMode TonemappingMode { get; set; } + + /// <summary> + /// Gets or sets the tone-mapping range. + /// </summary> + public TonemappingRange TonemappingRange { get; set; } + + /// <summary> + /// Gets or sets the tone-mapping desaturation. + /// </summary> + public double TonemappingDesat { get; set; } + + /// <summary> + /// Gets or sets the tone-mapping peak. + /// </summary> + public double TonemappingPeak { get; set; } + + /// <summary> + /// Gets or sets the tone-mapping parameters. + /// </summary> + public double TonemappingParam { get; set; } + + /// <summary> + /// Gets or sets the VPP tone-mapping brightness. + /// </summary> + public double VppTonemappingBrightness { get; set; } + + /// <summary> + /// Gets or sets the VPP tone-mapping contrast. + /// </summary> + public double VppTonemappingContrast { get; set; } + + /// <summary> + /// Gets or sets the H264 CRF. + /// </summary> + public int H264Crf { get; set; } + + /// <summary> + /// Gets or sets the H265 CRF. + /// </summary> + public int H265Crf { get; set; } + + /// <summary> + /// Gets or sets the encoder preset. + /// </summary> + public EncoderPreset EncoderPreset { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the framerate is doubled when deinterlacing. + /// </summary> + public bool DeinterlaceDoubleRate { get; set; } + + /// <summary> + /// Gets or sets the deinterlace method. + /// </summary> + public DeinterlaceMethod DeinterlaceMethod { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether 10bit HEVC decoding is enabled. + /// </summary> + public bool EnableDecodingColorDepth10Hevc { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether 10bit VP9 decoding is enabled. + /// </summary> + public bool EnableDecodingColorDepth10Vp9 { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether 8/10bit HEVC RExt decoding is enabled. + /// </summary> + public bool EnableDecodingColorDepth10HevcRext { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether 12bit HEVC RExt decoding is enabled. + /// </summary> + public bool EnableDecodingColorDepth12HevcRext { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the enhanced NVDEC is enabled. + /// </summary> + public bool EnableEnhancedNvdecDecoder { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the system native hardware decoder should be used. + /// </summary> + public bool PreferSystemNativeHwDecoder { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the Intel H264 low-power hardware encoder should be used. + /// </summary> + public bool EnableIntelLowPowerH264HwEncoder { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the Intel HEVC low-power hardware encoder should be used. + /// </summary> + public bool EnableIntelLowPowerHevcHwEncoder { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether hardware encoding is enabled. + /// </summary> + public bool EnableHardwareEncoding { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether HEVC encoding is enabled. + /// </summary> + public bool AllowHevcEncoding { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether AV1 encoding is enabled. + /// </summary> + public bool AllowAv1Encoding { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether subtitle extraction is enabled. + /// </summary> + public bool EnableSubtitleExtraction { get; set; } + + /// <summary> + /// Gets or sets the timeout for subtitle extraction in minutes. + /// </summary> + public int SubtitleExtractionTimeoutMinutes { get; set; } + + /// <summary> + /// Gets or sets the codecs hardware encoding is used for. + /// </summary> + public string[] HardwareDecodingCodecs { get; set; } + + /// <summary> + /// Gets or sets the file extensions on-demand metadata based keyframe extraction is enabled for. + /// </summary> + public string[] AllowOnDemandMetadataBasedKeyframeExtractionForExtensions { get; set; } + + /// <summary> + /// Gets or sets the method used for audio seeking in HLS. + /// </summary> + public HlsAudioSeekStrategy HlsAudioSeekStrategy { get; set; } +} diff --git a/MediaBrowser.Model/Configuration/MetadataConfigurationDto.cs b/MediaBrowser.Model/Configuration/MetadataConfigurationDto.cs new file mode 100644 index 0000000000..e07f9e34de --- /dev/null +++ b/MediaBrowser.Model/Configuration/MetadataConfigurationDto.cs @@ -0,0 +1,12 @@ +namespace MediaBrowser.Model.Configuration; + +/// <summary> +/// The metadata configuration DTO for API use. +/// </summary> +public class MetadataConfigurationDto +{ + /// <summary> + /// Gets or sets a value indicating whether to use file creation time for date added. + /// </summary> + public bool UseFileCreationTimeForDateAdded { get; set; } +} diff --git a/MediaBrowser.Model/Configuration/ServerConfiguration.cs b/MediaBrowser.Model/Configuration/ServerConfiguration.cs index ac5c12304e..97a996c479 100644 --- a/MediaBrowser.Model/Configuration/ServerConfiguration.cs +++ b/MediaBrowser.Model/Configuration/ServerConfiguration.cs @@ -288,4 +288,9 @@ public class ServerConfiguration : BaseApplicationConfiguration /// Gets or sets a value indicating whether old authorization methods are allowed. /// </summary> public bool EnableLegacyAuthorization { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether obsolete endpoints are allowed. + /// </summary> + public bool EnableObsoleteEndpoints { get; set; } = true; } diff --git a/MediaBrowser.Model/Configuration/ServerConfigurationDto.cs b/MediaBrowser.Model/Configuration/ServerConfigurationDto.cs new file mode 100644 index 0000000000..3f2bfe04f0 --- /dev/null +++ b/MediaBrowser.Model/Configuration/ServerConfigurationDto.cs @@ -0,0 +1,125 @@ +#pragma warning disable CS1591 +#pragma warning disable CA1819 + +using MediaBrowser.Model.Drawing; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.System; +using MediaBrowser.Model.Updates; + +namespace MediaBrowser.Model.Configuration; + +/// <summary> +/// The server configuration DTO for API use. +/// </summary> +public class ServerConfigurationDto +{ + public int LogFileRetentionDays { get; set; } + + public bool IsStartupWizardCompleted { get; set; } + + public string? CachePath { get; set; } + + public string? PreviousVersionStr { get; set; } + + public bool EnableMetrics { get; set; } + + public bool EnableNormalizedItemByNameIds { get; set; } + + public bool IsPortAuthorized { get; set; } + + public bool QuickConnectAvailable { get; set; } + + public bool EnableCaseSensitiveItemIds { get; set; } + + public bool DisableLiveTvChannelUserDataName { get; set; } + + public string MetadataPath { get; set; } = null!; + + public string PreferredMetadataLanguage { get; set; } = null!; + + public string MetadataCountryCode { get; set; } = null!; + + public string[] SortReplaceCharacters { get; set; } = null!; + + public string[] SortRemoveCharacters { get; set; } = null!; + + public string[] SortRemoveWords { get; set; } = null!; + + public int MinResumePct { get; set; } + + public int MaxResumePct { get; set; } + + public int MinResumeDurationSeconds { get; set; } + + public int MinAudiobookResume { get; set; } + + public int MaxAudiobookResume { get; set; } + + public int InactiveSessionThreshold { get; set; } + + public int LibraryMonitorDelay { get; set; } + + public int LibraryUpdateDuration { get; set; } + + public int CacheSize { get; set; } + + public ImageSavingConvention ImageSavingConvention { get; set; } + + public MetadataOptions[] MetadataOptions { get; set; } = null!; + + public bool SkipDeserializationForBasicTypes { get; set; } + + public string ServerName { get; set; } = null!; + + public string UICulture { get; set; } = null!; + + public bool SaveMetadataHidden { get; set; } + + public NameValuePair[] ContentTypes { get; set; } = null!; + + public int RemoteClientBitrateLimit { get; set; } + + public bool EnableFolderView { get; set; } + + public bool EnableGroupingMoviesIntoCollections { get; set; } + + public bool EnableGroupingShowsIntoCollections { get; set; } + + public bool DisplaySpecialsWithinSeasons { get; set; } + + public string[] CodecsUsed { get; set; } = null!; + + public RepositoryInfo[] PluginRepositories { get; set; } = null!; + + public bool EnableExternalContentInSuggestions { get; set; } + + public int ImageExtractionTimeoutMs { get; set; } + + public PathSubstitution[] PathSubstitutions { get; set; } = null!; + + public bool EnableSlowResponseWarning { get; set; } + + public long SlowResponseThresholdMs { get; set; } + + public string[] CorsHosts { get; set; } = null!; + + public int? ActivityLogRetentionDays { get; set; } + + public int LibraryScanFanoutConcurrency { get; set; } + + public int LibraryMetadataRefreshConcurrency { get; set; } + + public bool AllowClientLogUpload { get; set; } + + public int DummyChapterDuration { get; set; } + + public ImageResolution ChapterImageResolution { get; set; } + + public int ParallelImageEncodingLimit { get; set; } + + public CastReceiverApplication[] CastReceiverApplications { get; set; } = null!; + + public TrickplayOptions TrickplayOptions { get; set; } = null!; + + public bool EnableLegacyAuthorization { get; set; } +} diff --git a/MediaBrowser.Model/Configuration/XbmcMetadataOptionsDto.cs b/MediaBrowser.Model/Configuration/XbmcMetadataOptionsDto.cs new file mode 100644 index 0000000000..e2c118ddbe --- /dev/null +++ b/MediaBrowser.Model/Configuration/XbmcMetadataOptionsDto.cs @@ -0,0 +1,32 @@ +namespace MediaBrowser.Model.Configuration; + +/// <summary> +/// The XBMC metadata options DTO for API use. +/// </summary> +public class XbmcMetadataOptionsDto +{ + /// <summary> + /// Gets or sets the user id. + /// </summary> + public string? UserId { get; set; } + + /// <summary> + /// Gets or sets the release date format. + /// </summary> + public string ReleaseDateFormat { get; set; } = null!; + + /// <summary> + /// Gets or sets a value indicating whether to save image paths in NFO. + /// </summary> + public bool SaveImagePathsInNfo { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to enable path substitution. + /// </summary> + public bool EnablePathSubstitution { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to enable extra thumbs duplication. + /// </summary> + public bool EnableExtraThumbsDuplication { get; set; } +} diff --git a/MediaBrowser.Model/Dlna/StreamBuilder.cs b/MediaBrowser.Model/Dlna/StreamBuilder.cs index 4799ed5410..7e2c3d4773 100644 --- a/MediaBrowser.Model/Dlna/StreamBuilder.cs +++ b/MediaBrowser.Model/Dlna/StreamBuilder.cs @@ -25,6 +25,7 @@ namespace MediaBrowser.Model.Dlna internal const TranscodeReason VideoCodecReasons = TranscodeReason.VideoResolutionNotSupported | TranscodeReason.AnamorphicVideoNotSupported | TranscodeReason.InterlacedVideoNotSupported | TranscodeReason.VideoBitDepthNotSupported | TranscodeReason.VideoBitrateNotSupported | TranscodeReason.VideoFramerateNotSupported | TranscodeReason.VideoLevelNotSupported | TranscodeReason.RefFramesNotSupported | TranscodeReason.VideoRangeTypeNotSupported | TranscodeReason.VideoProfileNotSupported | TranscodeReason.VideoRotationNotSupported; internal const TranscodeReason VideoReasons = TranscodeReason.VideoCodecNotSupported | VideoCodecReasons; internal const TranscodeReason DirectStreamReasons = AudioReasons | TranscodeReason.ContainerNotSupported | TranscodeReason.VideoCodecTagNotSupported; + internal const TranscodeReason GenericReasons = TranscodeReason.VideoCodecNotSupported | TranscodeReason.AudioCodecNotSupported | TranscodeReason.ContainerNotSupported; private const string ManifestContainers = "hls,applehttp,dash"; @@ -77,6 +78,8 @@ namespace MediaBrowser.Model.Dlna private StreamInfo? GetOptimalAudioStream(MediaSourceInfo item, MediaOptions options) { + CheckCompatibility(MediaType.Audio, item, options); + var playlistItem = new StreamInfo { ItemId = options.ItemId, @@ -649,6 +652,8 @@ namespace MediaBrowser.Model.Dlna { ArgumentNullException.ThrowIfNull(item); + CheckCompatibility(MediaType.Video, item, options); + StreamInfo playlistItem = new StreamInfo { ItemId = options.ItemId, @@ -1311,24 +1316,18 @@ namespace MediaBrowser.Model.Dlna // Check container conditions var containerProfileReasons = GetCompatibilityContainer(options, mediaSource, container, videoStream); - // Check video conditions - var videoCodecProfileReasons = videoStream is null ? default : GetCompatibilityVideoCodec(options, mediaSource, container, videoStream); + // FIXME: Throw if DirectPlayErrors has no value? + var videoCodecProfileReasons = (videoStream?.DirectPlayErrors ?? 0) & ~GenericReasons; - // Check audio candidates profile conditions - var audioStreamMatches = candidateAudioStreams.ToDictionary(s => s, audioStream => GetCompatibilityAudioCodecDirect(options, mediaSource, container, audioStream, true, mediaSource.IsSecondaryAudio(audioStream) ?? false)); + // FIXME: Throw if DirectPlayErrors has no value? + var audioStreamMatches = candidateAudioStreams.ToDictionary(s => s, audioStream => (audioStream.DirectPlayErrors ?? 0) & ~GenericReasons); - TranscodeReason subtitleProfileReasons = 0; - if (subtitleStream is not null) - { - var subtitleProfile = GetSubtitleProfile(mediaSource, subtitleStream, options.Profile.SubtitleProfiles, PlayMethod.DirectPlay, _transcoderSupport, container, null); + // FIXME: Throw if DirectPlayErrors has no value? + var subtitleProfileReasons = (subtitleStream?.DirectPlayErrors ?? 0) & ~GenericReasons; - if (subtitleProfile.Method != SubtitleDeliveryMethod.Drop - && subtitleProfile.Method != SubtitleDeliveryMethod.External - && subtitleProfile.Method != SubtitleDeliveryMethod.Embed) - { - _logger.LogDebug("Not eligible for {0} due to unsupported subtitles", PlayMethod.DirectPlay); - subtitleProfileReasons |= TranscodeReason.SubtitleCodecNotSupported; - } + if ((subtitleProfileReasons & TranscodeReason.SubtitleCodecNotSupported) != 0) + { + _logger.LogDebug("Not eligible for {0} due to unsupported subtitles", PlayMethod.DirectPlay); } var containerSupported = false; @@ -2489,5 +2488,188 @@ namespace MediaBrowser.Model.Dlna return failures; } + + /// <summary> + /// Sets compatibility errors (if any) for streams. + /// </summary> + /// <param name="mediaType">The <see cref="MediaType"/> of object for which to check compatibility.</param> + /// <param name="options">The <see cref="MediaOptions"/> object for which to check compatibility.</param> + public void CheckCompatibility(MediaType mediaType, MediaOptions options) + { + foreach (var mediaSource in options.MediaSources) + { + CheckCompatibility(mediaType, mediaSource, options); + } + } + + /// <summary> + /// Sets compatibility errors (if any) for streams. + /// </summary> + /// <param name="mediaType">The <see cref="MediaType"/> of object for which to check compatibility.</param> + /// <param name="mediaSource">The <see cref="MediaSourceInfo"/>.</param> + /// <param name="options">The <see cref="MediaOptions"/> object for which to check compatibility.</param> + public void CheckCompatibility(MediaType mediaType, MediaSourceInfo mediaSource, MediaOptions options) + { + foreach (var stream in mediaSource.MediaStreams) + { + stream.DirectPlayErrors ??= GetCompatibility(mediaType, mediaSource, stream, options); + } + } + + /// <summary> + /// Gets stream compatibility errors, if any. + /// </summary> + /// <param name="mediaType">The <see cref="MediaType"/> of object for which to check compatibility.</param> + /// <param name="mediaSource">The <see cref="MediaSourceInfo"/>.</param> + /// <param name="stream">The <see cref="MediaStream"/> for which to check compatibility.</param> + /// <param name="options">The <see cref="MediaOptions"/> object for which to check compatibility.</param> + /// <returns>Stream compatibility errors, if any.</returns> + private TranscodeReason GetCompatibility(MediaType mediaType, MediaSourceInfo mediaSource, MediaStream stream, MediaOptions options) + { + switch (stream.Type) + { + case MediaStreamType.Audio: + return GetCompatibilityAudio(options, mediaSource, stream, mediaType == MediaType.Video); + + case MediaStreamType.Video: + return GetCompatibilityVideo(options, mediaSource, stream); + + case MediaStreamType.Subtitle: + var subtitleProfile = GetSubtitleProfile(mediaSource, stream, options.Profile.SubtitleProfiles, PlayMethod.DirectPlay, _transcoderSupport, mediaSource.Container, null); + + if (subtitleProfile.Method != SubtitleDeliveryMethod.Drop + && subtitleProfile.Method != SubtitleDeliveryMethod.External + && subtitleProfile.Method != SubtitleDeliveryMethod.Embed) + { + return TranscodeReason.SubtitleCodecNotSupported; + } + + break; + } + + return 0; + } + + /// <summary> + /// Gets video stream compatibility errors, if any. + /// </summary> + /// <param name="options">Media options.</param> + /// <param name="mediaSource">Media source.</param> + /// <param name="videoStream">Video stream.</param> + /// <returns>Video stream compatibility errors, if any.</returns> + private TranscodeReason GetCompatibilityVideo(MediaOptions options, MediaSourceInfo mediaSource, MediaStream videoStream) + { + var profile = options.Profile; + string container = mediaSource.Container; + string videoCodec = videoStream.Codec; + + bool containerSupported = false; + bool videoSupported = false; + + foreach (var directPlayProfile in profile.DirectPlayProfiles) + { + if (directPlayProfile.Type == DlnaProfileType.Video) + { + bool profileSupportsContainer = directPlayProfile.SupportsContainer(container); + + if (!videoSupported && profileSupportsContainer) + { + containerSupported = true; + } + + if (directPlayProfile.SupportsVideoCodec(videoCodec)) + { + videoSupported = true; + containerSupported = profileSupportsContainer; + + if (containerSupported) + { + break; + } + } + } + } + + TranscodeReason failures = default; + + if (!containerSupported) + { + failures |= TranscodeReason.ContainerNotSupported; + } + + if (videoSupported) + { + failures |= GetCompatibilityVideoCodec(options, mediaSource, container, videoStream); + } + else + { + failures |= TranscodeReason.VideoCodecNotSupported; + } + + return failures; + } + + /// <summary> + /// Gets audio stream compatibility errors, if any. + /// </summary> + /// <param name="options">Media options.</param> + /// <param name="mediaSource">The <see cref="MediaSourceInfo"/>.</param> + /// <param name="audioStream">The <see cref="MediaStream"/> of the audio stream.</param> + /// <param name="isVideo">True if source is video.</param> + /// <returns>Audio stream compatibility errors, if any.</returns> + private TranscodeReason GetCompatibilityAudio(MediaOptions options, MediaSourceInfo mediaSource, MediaStream audioStream, bool isVideo) + { + var profile = options.Profile; + string container = mediaSource.Container; + string audioCodec = audioStream.Codec; + DlnaProfileType profileType = isVideo ? DlnaProfileType.Video : DlnaProfileType.Audio; + + bool containerSupported = false; + bool audioSupported = false; + + foreach (var directPlayProfile in profile.DirectPlayProfiles) + { + if (directPlayProfile.Type == profileType) + { + bool profileSupportsContainer = directPlayProfile.SupportsContainer(container); + + if (!audioSupported && profileSupportsContainer) + { + containerSupported = true; + } + + if (directPlayProfile.SupportsAudioCodec(audioCodec)) + { + audioSupported = true; + containerSupported = profileSupportsContainer; + + if (containerSupported) + { + break; + } + } + } + } + + TranscodeReason failures = default; + + if (!containerSupported) + { + failures |= TranscodeReason.ContainerNotSupported; + } + + if (audioSupported) + { + bool isSecondaryAudio = isVideo ? mediaSource.IsSecondaryAudio(audioStream) ?? false : false; + + failures |= GetCompatibilityAudioCodecDirect(options, mediaSource, container, audioStream, isVideo, isSecondaryAudio); + } + else + { + failures |= TranscodeReason.AudioCodecNotSupported; + } + + return failures; + } } } diff --git a/MediaBrowser.Model/Dto/ItemCounts.cs b/MediaBrowser.Model/Dto/ItemCounts.cs index a15a0c82a8..6204645f64 100644 --- a/MediaBrowser.Model/Dto/ItemCounts.cs +++ b/MediaBrowser.Model/Dto/ItemCounts.cs @@ -72,6 +72,12 @@ namespace MediaBrowser.Model.Dto public int BookCount { get; set; } /// <summary> + /// Gets or sets the audio book count. + /// </summary> + /// <value>The audio book count.</value> + public int AudioBookCount { get; set; } + + /// <summary> /// Gets or sets the item count. /// </summary> /// <value>The item count.</value> @@ -83,7 +89,7 @@ namespace MediaBrowser.Model.Dto /// <returns>The total of the counts.</returns> public int TotalItemCount() { - return MovieCount + SeriesCount + EpisodeCount + ArtistCount + ProgramCount + TrailerCount + SongCount + AlbumCount + MusicVideoCount + BoxSetCount + BookCount; + return MovieCount + SeriesCount + EpisodeCount + ArtistCount + ProgramCount + TrailerCount + SongCount + AlbumCount + MusicVideoCount + BoxSetCount + BookCount + AudioBookCount; } } } diff --git a/MediaBrowser.Model/Entities/MediaStream.cs b/MediaBrowser.Model/Entities/MediaStream.cs index 67af843626..2d1bed4b85 100644 --- a/MediaBrowser.Model/Entities/MediaStream.cs +++ b/MediaBrowser.Model/Entities/MediaStream.cs @@ -12,6 +12,7 @@ using Jellyfin.Extensions; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.MediaInfo; +using MediaBrowser.Model.Session; namespace MediaBrowser.Model.Entities { @@ -701,6 +702,29 @@ namespace MediaBrowser.Model.Entities /// <value><c>true</c> if this instance is anamorphic; otherwise, <c>false</c>.</value> public bool? IsAnamorphic { get; set; } + /// <summary> + /// Gets or sets DirectPlay errors. + /// </summary> + /// <value>DirectPlay errors.</value> + public TranscodeReason? DirectPlayErrors { get; set; } + + /// <summary> + /// Gets a value indicating whether this instance is compatible with the device. + /// </summary> + /// <value><c>true</c> if this instance is compatible with the device; otherwise, <c>false</c>.</value> + public bool? SupportsDirectPlay + { + get + { + if (!DirectPlayErrors.HasValue) + { + return null; + } + + return DirectPlayErrors.Value == 0; + } + } + internal string GetResolutionText() { if (!Width.HasValue || !Height.HasValue) diff --git a/MediaBrowser.Model/Globalization/LocalizationManagerExtensions.cs b/MediaBrowser.Model/Globalization/LocalizationManagerExtensions.cs new file mode 100644 index 0000000000..67cf88e5b8 --- /dev/null +++ b/MediaBrowser.Model/Globalization/LocalizationManagerExtensions.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace MediaBrowser.Model.Globalization +{ + /// <summary> + /// Extension methods for <see cref="ILocalizationManager"/>. + /// </summary> + public static class LocalizationManagerExtensions + { + /// <summary> + /// Gets every code a media stream in the given language can be tagged with, the most specific first. + /// </summary> + /// <param name="localizationManager">The localization manager.</param> + /// <param name="language">The language, as stored in a setting or a preference.</param> + /// <returns>The language codes.</returns> + public static IReadOnlyList<string> GetMediaStreamLanguageCodes(this ILocalizationManager localizationManager, string language) + { + var culture = localizationManager.FindLanguageInfo(language); + if (culture is null) + { + return [language]; + } + + List<string> codes = []; + var tag = culture.TwoLetterISOLanguageName; + var separator = tag.IndexOf('-', StringComparison.Ordinal); + if (separator > 0) + { + codes.Add(tag); + } + + codes.AddRange(culture.ThreeLetterISOLanguageNames); + + // ffprobe tags a regional track with the code of its base language, a fr-CA track as "fre". + if (separator > 0 && localizationManager.FindLanguageInfo(tag[..separator]) is { } baseCulture) + { + codes.AddRange(baseCulture.ThreeLetterISOLanguageNames); + } + + // A stream scanned with a legacy code (pob) keeps it until the item is refreshed. + codes.Add(language); + + return codes.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); + } + } +} diff --git a/MediaBrowser.Model/LiveTv/LiveTvOptionsDto.cs b/MediaBrowser.Model/LiveTv/LiveTvOptionsDto.cs new file mode 100644 index 0000000000..3ed7d5b2e5 --- /dev/null +++ b/MediaBrowser.Model/LiveTv/LiveTvOptionsDto.cs @@ -0,0 +1,84 @@ +#pragma warning disable CA1819 + +namespace MediaBrowser.Model.LiveTv; + +/// <summary> +/// The LiveTV options DTO for API use. +/// </summary> +public class LiveTvOptionsDto +{ + /// <summary> + /// Gets or sets the guide days. + /// </summary> + public int? GuideDays { get; set; } + + /// <summary> + /// Gets or sets the recording path. + /// </summary> + public string? RecordingPath { get; set; } + + /// <summary> + /// Gets or sets the movie recording path. + /// </summary> + public string? MovieRecordingPath { get; set; } + + /// <summary> + /// Gets or sets the series recording path. + /// </summary> + public string? SeriesRecordingPath { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to enable recording subfolders. + /// </summary> + public bool EnableRecordingSubfolders { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to enable original audio with encoded recordings. + /// </summary> + public bool EnableOriginalAudioWithEncodedRecordings { get; set; } + + /// <summary> + /// Gets or sets the tuner hosts. + /// </summary> + public TunerHostInfo[] TunerHosts { get; set; } = null!; + + /// <summary> + /// Gets or sets the listing providers. + /// </summary> + public ListingsProviderInfo[] ListingProviders { get; set; } = null!; + + /// <summary> + /// Gets or sets the pre-padding seconds. + /// </summary> + public int PrePaddingSeconds { get; set; } + + /// <summary> + /// Gets or sets the post-padding seconds. + /// </summary> + public int PostPaddingSeconds { get; set; } + + /// <summary> + /// Gets or sets the media locations created. + /// </summary> + public string[] MediaLocationsCreated { get; set; } = null!; + + /// <summary> + /// Gets or sets the recording post processor. + /// </summary> + public string? RecordingPostProcessor { get; set; } + + /// <summary> + /// Gets or sets the recording post processor arguments. + /// </summary> + public string RecordingPostProcessorArguments { get; set; } = null!; + + /// <summary> + /// Gets or sets a value indicating whether to save recording NFO. + /// </summary> + public bool SaveRecordingNFO { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether to save recording images. + /// </summary> + public bool SaveRecordingImages { get; set; } +} diff --git a/MediaBrowser.Model/MediaInfo/MediaInfo.cs b/MediaBrowser.Model/MediaInfo/MediaInfo.cs index 453aeb028a..2e67daba63 100644 --- a/MediaBrowser.Model/MediaInfo/MediaInfo.cs +++ b/MediaBrowser.Model/MediaInfo/MediaInfo.cs @@ -61,6 +61,8 @@ namespace MediaBrowser.Model.MediaInfo public DateTime? PremiereDate { get; set; } + public DateTime? ContainerCreationDate { get; set; } + public BaseItemPerson[] People { get; set; } public Dictionary<string, string> ProviderIds { get; set; } diff --git a/MediaBrowser.Model/Querying/QueryFilters.cs b/MediaBrowser.Model/Querying/QueryFilters.cs index 095f460923..d4a3d92934 100644 --- a/MediaBrowser.Model/Querying/QueryFilters.cs +++ b/MediaBrowser.Model/Querying/QueryFilters.cs @@ -15,6 +15,8 @@ namespace MediaBrowser.Model.Querying Genres = Array.Empty<NameGuidPair>(); AudioLanguages = Array.Empty<NameValuePair>(); SubtitleLanguages = Array.Empty<NameValuePair>(); + Years = Array.Empty<int>(); + OfficialRatings = Array.Empty<string>(); } public IReadOnlyList<NameGuidPair> Genres { get; set; } @@ -24,5 +26,9 @@ namespace MediaBrowser.Model.Querying public IReadOnlyList<NameValuePair> AudioLanguages { get; set; } public IReadOnlyList<NameValuePair> SubtitleLanguages { get; set; } + + public IReadOnlyList<int> Years { get; set; } + + public IReadOnlyList<string> OfficialRatings { get; set; } } } diff --git a/MediaBrowser.Providers/Manager/ProviderManager.cs b/MediaBrowser.Providers/Manager/ProviderManager.cs index 855765441b..3179c7a4a8 100644 --- a/MediaBrowser.Providers/Manager/ProviderManager.cs +++ b/MediaBrowser.Providers/Manager/ProviderManager.cs @@ -212,7 +212,16 @@ namespace MediaBrowser.Providers.Manager var httpClient = _httpClientFactory.CreateClient(NamedClient.Default); using var response = await httpClient.GetAsync(url, cancellationToken).ConfigureAwait(false); - response.EnsureSuccessStatusCode(); + if (!response.IsSuccessStatusCode) + { + // Keep the body: providers report why they refused in it, and a caller that + // only sees the status code cannot tell a missing image from an exhausted quota. + var errorBody = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + throw new HttpResponseBodyException( + $"Response status code does not indicate success: {(int)response.StatusCode} ({response.ReasonPhrase}).", + response.StatusCode, + errorBody); + } var contentType = response.Content.Headers.ContentType?.MediaType; @@ -236,7 +245,17 @@ namespace MediaBrowser.Providers.Manager if (!contentType.StartsWith("image/", StringComparison.OrdinalIgnoreCase)) { - throw new HttpRequestException($"Request returned '{contentType}' instead of an image type", null, HttpStatusCode.NotFound); + // A provider can answer 200 with a JSON error instead of the image; Schedules + // Direct reports an exhausted image quota that way, so keep the body. + var errorBody = contentType.Contains("json", StringComparison.OrdinalIgnoreCase) + || contentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) + ? await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false) + : null; + + throw new HttpResponseBodyException( + $"Request returned '{contentType}' instead of an image type", + HttpStatusCode.NotFound, + errorBody); } var responseBytes = await response.Content.ReadAsByteArrayAsync(cancellationToken).ConfigureAwait(false); diff --git a/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs b/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs index 81d4b640a3..2b265d8b76 100644 --- a/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs +++ b/MediaBrowser.Providers/MediaInfo/AudioFileProber.cs @@ -188,7 +188,7 @@ namespace MediaBrowser.Providers.MediaInfo // To properly handle fallback values, we make a clone of those fields when valid. var trackTitle = (string.IsNullOrEmpty(track.Title) ? mediaInfo.Name : track.Title)?.Trim(); var trackAlbum = (string.IsNullOrEmpty(track.Album) ? mediaInfo.Album : track.Album)?.Trim(); - var trackYear = track.Year is null or 0 ? mediaInfo.ProductionYear : track.Year; + var trackYear = track.Year is null or 0 ? mediaInfo.ProductionYear ?? mediaInfo.ContainerCreationDate?.Year : track.Year; var trackTrackNumber = track.TrackNumber is null or 0 ? mediaInfo.IndexNumber : track.TrackNumber; var trackDiscNumber = track.DiscNumber is null or 0 ? mediaInfo.ParentIndexNumber : track.DiscNumber; diff --git a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs index 1cb8e09414..513b6f8590 100644 --- a/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs +++ b/MediaBrowser.Providers/MediaInfo/FFProbeVideoInfo.cs @@ -442,11 +442,20 @@ namespace MediaBrowser.Providers.MediaInfo } } - if (useContainerDates && data.PremiereDate is not null) + if (useContainerDates) { - if (video.PremiereDate is null || replaceData) + // creation_time is the mux time, so it only stands in where the tags gave no date + // and it cannot contradict a year we already know, which in practice is home video. + var containerDate = data.PremiereDate; + if (containerDate is null + && (video.ProductionYear is null || data.ContainerCreationDate?.ToLocalTime().Year == video.ProductionYear)) { - video.PremiereDate = data.PremiereDate; + containerDate = data.ContainerCreationDate; + } + + if (containerDate is not null && (video.PremiereDate is null || replaceData)) + { + video.PremiereDate = containerDate; } } @@ -553,7 +562,8 @@ namespace MediaBrowser.Providers.MediaInfo { var downloadedLanguages = await new SubtitleDownloader( _logger, - _subtitleManager).DownloadSubtitles( + _subtitleManager, + _localization).DownloadSubtitles( video, currentStreams.Concat(externalSubtitleStreams).ToList(), libraryOptions.SkipSubtitlesIfEmbeddedSubtitlesPresent, diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs index 227f310255..9f5690f627 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleDownloader.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using Jellyfin.Extensions; using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; @@ -14,6 +15,7 @@ using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Globalization; using Microsoft.Extensions.Logging; namespace MediaBrowser.Providers.MediaInfo @@ -22,11 +24,13 @@ namespace MediaBrowser.Providers.MediaInfo { private readonly ILogger _logger; private readonly ISubtitleManager _subtitleManager; + private readonly ILocalizationManager _localizationManager; - public SubtitleDownloader(ILogger logger, ISubtitleManager subtitleManager) + public SubtitleDownloader(ILogger logger, ISubtitleManager subtitleManager, ILocalizationManager localizationManager) { _logger = logger; _subtitleManager = subtitleManager; + _localizationManager = localizationManager; } public async Task<List<string>> DownloadSubtitles( @@ -131,8 +135,10 @@ namespace MediaBrowser.Providers.MediaInfo bool isAutomated, CancellationToken cancellationToken) { + var languageCodes = _localizationManager.GetMediaStreamLanguageCodes(language); + // There's already subtitles for this language - if (mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle && i.IsTextSubtitleStream && string.Equals(i.Language, language, StringComparison.OrdinalIgnoreCase))) + if (mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle && i.IsTextSubtitleStream && languageCodes.Contains(i.Language, StringComparison.OrdinalIgnoreCase))) { return false; } @@ -148,14 +154,14 @@ namespace MediaBrowser.Providers.MediaInfo // There's already a default audio stream for this language if (skipIfAudioTrackMatches && - defaultAudioStreams.Any(i => string.Equals(i.Language, language, StringComparison.OrdinalIgnoreCase))) + defaultAudioStreams.Any(i => languageCodes.Contains(i.Language, StringComparison.OrdinalIgnoreCase))) { return false; } // There's an internal subtitle stream for this language if (skipIfEmbeddedSubtitlesPresent && - mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal && string.Equals(i.Language, language, StringComparison.OrdinalIgnoreCase))) + mediaStreams.Any(i => i.Type == MediaStreamType.Subtitle && !i.IsExternal && languageCodes.Contains(i.Language, StringComparison.OrdinalIgnoreCase))) { return false; } diff --git a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs index 1d3a273354..3065ef23e8 100644 --- a/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs +++ b/MediaBrowser.Providers/MediaInfo/SubtitleScheduledTask.cs @@ -185,7 +185,8 @@ namespace MediaBrowser.Providers.MediaInfo var downloadedLanguages = await new SubtitleDownloader( _logger, - _subtitleManager).DownloadSubtitles( + _subtitleManager, + _localization).DownloadSubtitles( video, mediaStreams, skipIfEmbeddedSubtitlesPresent, diff --git a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs index 4ef8c53b30..bd967b4041 100644 --- a/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs +++ b/MediaBrowser.Providers/Plugins/Tmdb/TmdbUtils.cs @@ -402,6 +402,12 @@ namespace MediaBrowser.Providers.Plugins.Tmdb { preferredLanguage = NormalizeLanguage(preferredLanguage, countryCode); + // TMDb matches no images for es-419, only for the bare language or a country variant + if (preferredLanguage.EndsWith("-419", StringComparison.Ordinal)) + { + preferredLanguage = preferredLanguage[..^4]; + } + languages.Add(preferredLanguage); } @@ -490,11 +496,24 @@ namespace MediaBrowser.Providers.Plugins.Tmdb return imageLanguage; } - return string.IsNullOrEmpty(imageRegion) || string.Equals(imageRegion, requestParts[1], StringComparison.OrdinalIgnoreCase) + return string.IsNullOrEmpty(imageRegion) || IsRequestedRegion(imageRegion, requestParts[1]) ? requestLanguage : imageLanguage + "-" + imageRegion.ToUpperInvariant(); } + private static bool IsRequestedRegion(string imageRegion, string requestRegion) + { + // TMDb has no Latin American (419) region, it files those images under the individual countries. + if (string.Equals(requestRegion, "419", StringComparison.Ordinal)) + { + return !string.Equals(imageRegion, "ES", StringComparison.OrdinalIgnoreCase); + } + + // TMDb has no Swiss variants either, NormalizeLanguage requests the bare language instead. + return string.Equals(requestRegion, "CH", StringComparison.OrdinalIgnoreCase) + || string.Equals(imageRegion, requestRegion, StringComparison.OrdinalIgnoreCase); + } + /// <summary> /// Determines whether the configured image size fetches the image at its original resolution. /// An unset size falls back to <see cref="OriginalImageSize"/>, see TmdbClientManager.GetUrl. @@ -166,7 +166,7 @@ The following sections describe some more advanced scenarios for running the ser It is not necessary to host the frontend web client as part of the backend server. Hosting these two components separately may be useful for frontend developers who would prefer to host the client in a separate webpack development server for a tighter development loop. See the [jellyfin-web](https://github.com/jellyfin/jellyfin-web#getting-started) repo for instructions on how to do this. To instruct the server not to host the web content, there is a `nowebclient` configuration flag that must be set. This can be specified using the command line -switch `--nowebclient` or the environment variable `JELLYFIN_NOWEBCONTENT=true`. +switch `--nowebclient` or the environment variable `JELLYFIN_HOSTWEBCLIENT=false`. Since this is a common scenario, there is also a separate launch profile defined for Visual Studio called `Jellyfin.Server (nowebcontent)` that can be selected from the 'Start Debugging' dropdown in the main toolbar. diff --git a/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/AncestorIdConfiguration.cs b/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/AncestorIdConfiguration.cs index 67269153d3..38a9c9a548 100644 --- a/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/AncestorIdConfiguration.cs +++ b/src/Jellyfin.Database/Jellyfin.Database.Implementations/ModelConfiguration/AncestorIdConfiguration.cs @@ -13,7 +13,8 @@ public class AncestorIdConfiguration : IEntityTypeConfiguration<AncestorId> public void Configure(EntityTypeBuilder<AncestorId> builder) { builder.HasKey(e => new { e.ItemId, e.ParentItemId }); - builder.HasIndex(e => e.ParentItemId); + // Covers ItemId so descendant lookups by parent never touch the table. + builder.HasIndex(e => new { e.ParentItemId, e.ItemId }); builder.HasOne(e => e.ParentItem).WithMany(e => e.Children).HasForeignKey(f => f.ParentItemId); builder.HasOne(e => e.Item).WithMany(e => e.Parents).HasForeignKey(f => f.ItemId); } diff --git a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20261024092111_CoverAncestorIdsParentIndex.Designer.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20261024092111_CoverAncestorIdsParentIndex.Designer.cs new file mode 100644 index 0000000000..452e70293c --- /dev/null +++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20261024092111_CoverAncestorIdsParentIndex.Designer.cs @@ -0,0 +1,1809 @@ +// <auto-generated /> +using System; +using Jellyfin.Database.Implementations; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; + +#nullable disable + +namespace Jellyfin.Database.Providers.Sqlite.Migrations +{ + [DbContext(typeof(JellyfinDbContext))] + [Migration("20261024092111_CoverAncestorIdsParentIndex")] + partial class CoverAncestorIdsParentIndex + { + /// <inheritdoc /> + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "10.0.12"); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AccessSchedule", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<int>("DayOfWeek") + .HasColumnType("INTEGER"); + + b.Property<double>("EndHour") + .HasColumnType("REAL"); + + b.Property<double>("StartHour") + .HasColumnType("REAL"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("AccessSchedules"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ActivityLog", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<DateTime>("DateCreated") + .HasColumnType("TEXT"); + + b.Property<string>("ItemId") + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property<int>("LogSeverity") + .HasColumnType("INTEGER"); + + b.Property<string>("Name") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property<string>("Overview") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property<uint>("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property<string>("ShortOverview") + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property<string>("Type") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("DateCreated"); + + b.ToTable("ActivityLogs"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AncestorId", b => + { + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<Guid>("ParentItemId") + .HasColumnType("TEXT"); + + b.HasKey("ItemId", "ParentItemId"); + + b.HasIndex("ParentItemId", "ItemId"); + + b.ToTable("AncestorIds"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AttachmentStreamInfo", b => + { + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<int>("Index") + .HasColumnType("INTEGER"); + + b.Property<string>("Codec") + .HasColumnType("TEXT"); + + b.Property<string>("CodecTag") + .HasColumnType("TEXT"); + + b.Property<string>("Comment") + .HasColumnType("TEXT"); + + b.Property<string>("Filename") + .HasColumnType("TEXT"); + + b.Property<string>("MimeType") + .HasColumnType("TEXT"); + + b.HasKey("ItemId", "Index"); + + b.ToTable("AttachmentStreamInfos"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemEntity", b => + { + b.Property<Guid>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property<string>("Album") + .HasColumnType("TEXT"); + + b.Property<string>("AlbumArtists") + .HasColumnType("TEXT"); + + b.Property<string>("Artists") + .HasColumnType("TEXT"); + + b.Property<int?>("Audio") + .HasColumnType("INTEGER"); + + b.Property<Guid?>("ChannelId") + .HasColumnType("TEXT"); + + b.Property<string>("CleanName") + .HasColumnType("TEXT"); + + b.Property<float?>("CommunityRating") + .HasColumnType("REAL"); + + b.Property<float?>("CriticRating") + .HasColumnType("REAL"); + + b.Property<string>("CustomRating") + .HasColumnType("TEXT"); + + b.Property<string>("Data") + .HasColumnType("TEXT"); + + b.Property<DateTime?>("DateCreated") + .HasColumnType("TEXT"); + + b.Property<DateTime?>("DateLastMediaAdded") + .HasColumnType("TEXT"); + + b.Property<DateTime?>("DateLastRefreshed") + .HasColumnType("TEXT"); + + b.Property<DateTime?>("DateLastSaved") + .HasColumnType("TEXT"); + + b.Property<DateTime?>("DateModified") + .HasColumnType("TEXT"); + + b.Property<DateTime?>("EndDate") + .HasColumnType("TEXT"); + + b.Property<string>("EpisodeTitle") + .HasColumnType("TEXT"); + + b.Property<string>("ExternalId") + .HasColumnType("TEXT"); + + b.Property<string>("ExternalSeriesId") + .HasColumnType("TEXT"); + + b.Property<string>("ExternalServiceId") + .HasColumnType("TEXT"); + + b.Property<int?>("ExtraType") + .HasColumnType("INTEGER"); + + b.Property<string>("ForcedSortName") + .HasColumnType("TEXT"); + + b.Property<string>("Genres") + .HasColumnType("TEXT"); + + b.Property<int?>("Height") + .HasColumnType("INTEGER"); + + b.Property<int?>("IndexNumber") + .HasColumnType("INTEGER"); + + b.Property<int?>("InheritedParentalRatingSubValue") + .HasColumnType("INTEGER"); + + b.Property<int?>("InheritedParentalRatingValue") + .HasColumnType("INTEGER"); + + b.Property<bool>("IsFolder") + .HasColumnType("INTEGER"); + + b.Property<bool>("IsInMixedFolder") + .HasColumnType("INTEGER"); + + b.Property<bool>("IsLocked") + .HasColumnType("INTEGER"); + + b.Property<bool>("IsMovie") + .HasColumnType("INTEGER"); + + b.Property<bool>("IsRepeat") + .HasColumnType("INTEGER"); + + b.Property<bool>("IsSeries") + .HasColumnType("INTEGER"); + + b.Property<bool>("IsVirtualItem") + .HasColumnType("INTEGER"); + + b.Property<float?>("LUFS") + .HasColumnType("REAL"); + + b.Property<string>("MediaType") + .HasColumnType("TEXT"); + + b.Property<string>("Name") + .HasColumnType("TEXT"); + + b.Property<float?>("NormalizationGain") + .HasColumnType("REAL"); + + b.Property<string>("OfficialRating") + .HasColumnType("TEXT"); + + b.Property<string>("OriginalLanguage") + .HasColumnType("TEXT"); + + b.Property<string>("OriginalTitle") + .HasColumnType("TEXT"); + + b.Property<string>("Overview") + .HasColumnType("TEXT"); + + b.Property<Guid?>("OwnerId") + .HasColumnType("TEXT"); + + b.Property<Guid?>("ParentId") + .HasColumnType("TEXT"); + + b.Property<int?>("ParentIndexNumber") + .HasColumnType("INTEGER"); + + b.Property<string>("Path") + .HasColumnType("TEXT"); + + b.Property<string>("PreferredMetadataCountryCode") + .HasColumnType("TEXT"); + + b.Property<string>("PreferredMetadataLanguage") + .HasColumnType("TEXT"); + + b.Property<DateTime?>("PremiereDate") + .HasColumnType("TEXT"); + + b.Property<string>("PresentationUniqueKey") + .HasColumnType("TEXT"); + + b.Property<Guid?>("PrimaryVersionId") + .HasColumnType("TEXT"); + + b.Property<string>("ProductionLocations") + .HasColumnType("TEXT"); + + b.Property<int?>("ProductionYear") + .HasColumnType("INTEGER"); + + b.Property<long?>("RunTimeTicks") + .HasColumnType("INTEGER"); + + b.Property<Guid?>("SeasonId") + .HasColumnType("TEXT"); + + b.Property<string>("SeasonName") + .HasColumnType("TEXT"); + + b.Property<Guid?>("SeriesId") + .HasColumnType("TEXT"); + + b.Property<string>("SeriesName") + .HasColumnType("TEXT"); + + b.Property<string>("SeriesPresentationUniqueKey") + .HasColumnType("TEXT"); + + b.Property<string>("ShowId") + .HasColumnType("TEXT"); + + b.Property<long?>("Size") + .HasColumnType("INTEGER"); + + b.Property<string>("SortName") + .HasColumnType("TEXT"); + + b.Property<DateTime?>("StartDate") + .HasColumnType("TEXT"); + + b.Property<string>("Studios") + .HasColumnType("TEXT"); + + b.Property<string>("Tagline") + .HasColumnType("TEXT"); + + b.Property<string>("Tags") + .HasColumnType("TEXT"); + + b.Property<Guid?>("TopParentId") + .HasColumnType("TEXT"); + + b.Property<int?>("TotalBitrate") + .HasColumnType("INTEGER"); + + b.Property<string>("Type") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("UnratedType") + .HasColumnType("TEXT"); + + b.Property<int?>("Width") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.HasIndex("OwnerId") + .HasFilter("\"OwnerId\" IS NOT NULL"); + + b.HasIndex("ParentId"); + + b.HasIndex("Path"); + + b.HasIndex("PresentationUniqueKey"); + + b.HasIndex("PrimaryVersionId") + .HasFilter("\"PrimaryVersionId\" IS NOT NULL"); + + b.HasIndex("SeasonId"); + + b.HasIndex("SeriesId"); + + b.HasIndex("SeriesName"); + + b.HasIndex("ExtraType", "OwnerId") + .HasFilter("\"ExtraType\" IS NOT NULL"); + + b.HasIndex("TopParentId", "Id"); + + b.HasIndex("Type", "CleanName"); + + b.HasIndex("TopParentId", "Type", "IsVirtualItem") + .HasFilter("\"PrimaryVersionId\" IS NULL AND (\"OwnerId\" IS NULL OR \"ExtraType\" IS NOT NULL)"); + + b.HasIndex("Type", "TopParentId", "Id"); + + b.HasIndex("Type", "TopParentId", "PresentationUniqueKey"); + + b.HasIndex("Type", "TopParentId", "SortName"); + + b.HasIndex("Type", "TopParentId", "StartDate"); + + b.HasIndex("MediaType", "TopParentId", "IsVirtualItem", "PresentationUniqueKey"); + + b.HasIndex("TopParentId", "IsFolder", "IsVirtualItem", "DateCreated"); + + b.HasIndex("TopParentId", "MediaType", "IsVirtualItem", "DateCreated"); + + b.HasIndex("TopParentId", "Type", "IsVirtualItem", "DateCreated"); + + b.HasIndex("Type", "SeriesPresentationUniqueKey", "IsFolder", "IsVirtualItem"); + + b.HasIndex("Type", "SeriesPresentationUniqueKey", "ParentIndexNumber", "IndexNumber"); + + b.HasIndex("Type", "SeriesPresentationUniqueKey", "PresentationUniqueKey", "SortName"); + + b.HasIndex("IsFolder", "TopParentId", "IsVirtualItem", "PresentationUniqueKey", "DateCreated"); + + b.HasIndex("Type", "TopParentId", "IsVirtualItem", "PresentationUniqueKey", "DateCreated"); + + b.ToTable("BaseItems"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + + b.HasData( + new + { + Id = new Guid("00000000-0000-0000-0000-000000000001"), + IsFolder = false, + IsInMixedFolder = false, + IsLocked = false, + IsMovie = false, + IsRepeat = false, + IsSeries = false, + IsVirtualItem = false, + Name = "This is a placeholder item for UserData that has been detached from its original item", + Type = "PLACEHOLDER" + }); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemImageInfo", b => + { + b.Property<Guid>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property<byte[]>("Blurhash") + .HasColumnType("BLOB"); + + b.Property<DateTime?>("DateModified") + .HasColumnType("TEXT"); + + b.Property<int>("Height") + .HasColumnType("INTEGER"); + + b.Property<int>("ImageType") + .HasColumnType("INTEGER"); + + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<string>("Path") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<int>("Width") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("ItemId", "ImageType"); + + b.ToTable("BaseItemImageInfos"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemMetadataField", b => + { + b.Property<int>("Id") + .HasColumnType("INTEGER"); + + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.HasKey("Id", "ItemId"); + + b.HasIndex("ItemId"); + + b.ToTable("BaseItemMetadataFields"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemProvider", b => + { + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<string>("ProviderId") + .HasColumnType("TEXT"); + + b.Property<string>("ProviderValue") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("ItemId", "ProviderId"); + + b.HasIndex("ProviderId", "ItemId", "ProviderValue"); + + b.ToTable("BaseItemProviders"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemTrailerType", b => + { + b.Property<int>("Id") + .HasColumnType("INTEGER"); + + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.HasKey("Id", "ItemId"); + + b.HasIndex("ItemId"); + + b.ToTable("BaseItemTrailerTypes"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Chapter", b => + { + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<int>("ChapterIndex") + .HasColumnType("INTEGER"); + + b.Property<DateTime?>("ImageDateModified") + .HasColumnType("TEXT"); + + b.Property<string>("ImagePath") + .HasColumnType("TEXT"); + + b.Property<string>("Name") + .HasColumnType("TEXT"); + + b.Property<long>("StartPositionTicks") + .HasColumnType("INTEGER"); + + b.HasKey("ItemId", "ChapterIndex"); + + b.ToTable("Chapters"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.CustomItemDisplayPreferences", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<string>("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<string>("Key") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.Property<string>("Value") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "ItemId", "Client", "Key") + .IsUnique(); + + b.ToTable("CustomItemDisplayPreferences"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.DisplayPreferences", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<int>("ChromecastVersion") + .HasColumnType("INTEGER"); + + b.Property<string>("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<string>("DashboardTheme") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<bool>("EnableNextVideoInfoOverlay") + .HasColumnType("INTEGER"); + + b.Property<int?>("IndexBy") + .HasColumnType("INTEGER"); + + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<int>("ScrollDirection") + .HasColumnType("INTEGER"); + + b.Property<bool>("ShowBackdrop") + .HasColumnType("INTEGER"); + + b.Property<bool>("ShowSidebar") + .HasColumnType("INTEGER"); + + b.Property<int>("SkipBackwardLength") + .HasColumnType("INTEGER"); + + b.Property<int>("SkipForwardLength") + .HasColumnType("INTEGER"); + + b.Property<string>("TvHome") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "ItemId", "Client") + .IsUnique(); + + b.ToTable("DisplayPreferences"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.HomeSection", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<int>("DisplayPreferencesId") + .HasColumnType("INTEGER"); + + b.Property<int>("Order") + .HasColumnType("INTEGER"); + + b.Property<int>("Type") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("DisplayPreferencesId"); + + b.ToTable("HomeSection"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ImageInfo", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<DateTime>("LastModified") + .HasColumnType("TEXT"); + + b.Property<string>("Path") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("TEXT"); + + b.Property<Guid?>("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId") + .IsUnique(); + + b.ToTable("ImageInfos"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ItemDisplayPreferences", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<string>("Client") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<int?>("IndexBy") + .HasColumnType("INTEGER"); + + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<bool>("RememberIndexing") + .HasColumnType("INTEGER"); + + b.Property<bool>("RememberSorting") + .HasColumnType("INTEGER"); + + b.Property<string>("SortBy") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property<int>("SortOrder") + .HasColumnType("INTEGER"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.Property<int>("ViewType") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId"); + + b.ToTable("ItemDisplayPreferences"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ItemValue", b => + { + b.Property<Guid>("ItemValueId") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property<string>("CleanValue") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<int>("Type") + .HasColumnType("INTEGER"); + + b.Property<string>("Value") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("ItemValueId"); + + b.HasIndex("Type", "CleanValue"); + + b.HasIndex("Type", "Value") + .IsUnique(); + + b.ToTable("ItemValues"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ItemValueMap", b => + { + b.Property<Guid>("ItemValueId") + .HasColumnType("TEXT"); + + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.HasKey("ItemValueId", "ItemId"); + + b.HasIndex("ItemId"); + + b.ToTable("ItemValuesMap"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.KeyframeData", b => + { + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.PrimitiveCollection<string>("KeyframeTicks") + .HasColumnType("TEXT"); + + b.Property<long>("TotalDuration") + .HasColumnType("INTEGER"); + + b.HasKey("ItemId"); + + b.ToTable("KeyframeData"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.LinkedChildEntity", b => + { + b.Property<Guid>("ParentId") + .HasColumnType("TEXT"); + + b.Property<int>("SortOrder") + .HasColumnType("INTEGER"); + + b.Property<Guid>("ChildId") + .HasColumnType("TEXT"); + + b.Property<int>("ChildType") + .HasColumnType("INTEGER"); + + b.HasKey("ParentId", "SortOrder"); + + b.HasIndex("ChildId", "ChildType"); + + b.HasIndex("ParentId", "ChildType"); + + b.ToTable("LinkedChildren", (string)null); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.MediaSegment", b => + { + b.Property<Guid>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property<long>("EndTicks") + .HasColumnType("INTEGER"); + + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<string>("SegmentProviderId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<long>("StartTicks") + .HasColumnType("INTEGER"); + + b.Property<int>("Type") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.ToTable("MediaSegments"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.MediaStreamInfo", b => + { + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<int>("StreamIndex") + .HasColumnType("INTEGER"); + + b.Property<string>("AspectRatio") + .HasColumnType("TEXT"); + + b.Property<float?>("AverageFrameRate") + .HasColumnType("REAL"); + + b.Property<int?>("BitDepth") + .HasColumnType("INTEGER"); + + b.Property<int?>("BitRate") + .HasColumnType("INTEGER"); + + b.Property<int?>("BlPresentFlag") + .HasColumnType("INTEGER"); + + b.Property<string>("ChannelLayout") + .HasColumnType("TEXT"); + + b.Property<int?>("Channels") + .HasColumnType("INTEGER"); + + b.Property<string>("Codec") + .HasColumnType("TEXT"); + + b.Property<string>("CodecTag") + .HasColumnType("TEXT"); + + b.Property<string>("CodecTimeBase") + .HasColumnType("TEXT"); + + b.Property<string>("ColorPrimaries") + .HasColumnType("TEXT"); + + b.Property<string>("ColorSpace") + .HasColumnType("TEXT"); + + b.Property<string>("ColorTransfer") + .HasColumnType("TEXT"); + + b.Property<string>("Comment") + .HasColumnType("TEXT"); + + b.Property<int?>("DvBlSignalCompatibilityId") + .HasColumnType("INTEGER"); + + b.Property<int?>("DvLevel") + .HasColumnType("INTEGER"); + + b.Property<int?>("DvProfile") + .HasColumnType("INTEGER"); + + b.Property<int?>("DvVersionMajor") + .HasColumnType("INTEGER"); + + b.Property<int?>("DvVersionMinor") + .HasColumnType("INTEGER"); + + b.Property<int?>("ElPresentFlag") + .HasColumnType("INTEGER"); + + b.Property<bool?>("Hdr10PlusPresentFlag") + .HasColumnType("INTEGER"); + + b.Property<int?>("Height") + .HasColumnType("INTEGER"); + + b.Property<bool?>("IsAnamorphic") + .HasColumnType("INTEGER"); + + b.Property<bool?>("IsAvc") + .HasColumnType("INTEGER"); + + b.Property<bool>("IsDefault") + .HasColumnType("INTEGER"); + + b.Property<bool>("IsExternal") + .HasColumnType("INTEGER"); + + b.Property<bool>("IsForced") + .HasColumnType("INTEGER"); + + b.Property<bool?>("IsHearingImpaired") + .HasColumnType("INTEGER"); + + b.Property<bool?>("IsInterlaced") + .HasColumnType("INTEGER"); + + b.Property<bool>("IsOriginal") + .HasColumnType("INTEGER"); + + b.Property<string>("KeyFrames") + .HasColumnType("TEXT"); + + b.Property<string>("Language") + .HasColumnType("TEXT"); + + b.Property<float?>("Level") + .HasColumnType("REAL"); + + b.Property<string>("NalLengthSize") + .HasColumnType("TEXT"); + + b.Property<string>("Path") + .HasColumnType("TEXT"); + + b.Property<string>("PixelFormat") + .HasColumnType("TEXT"); + + b.Property<string>("Profile") + .HasColumnType("TEXT"); + + b.Property<float?>("RealFrameRate") + .HasColumnType("REAL"); + + b.Property<int?>("RefFrames") + .HasColumnType("INTEGER"); + + b.Property<int?>("Rotation") + .HasColumnType("INTEGER"); + + b.Property<int?>("RpuPresentFlag") + .HasColumnType("INTEGER"); + + b.Property<int?>("SampleRate") + .HasColumnType("INTEGER"); + + b.Property<int>("StreamType") + .HasColumnType("INTEGER"); + + b.Property<string>("TimeBase") + .HasColumnType("TEXT"); + + b.Property<string>("Title") + .HasColumnType("TEXT"); + + b.Property<int?>("Width") + .HasColumnType("INTEGER"); + + b.HasKey("ItemId", "StreamIndex"); + + b.HasIndex("StreamType", "ItemId", "Language", "IsExternal"); + + b.ToTable("MediaStreamInfos"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.People", b => + { + b.Property<Guid>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property<string>("Name") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("PersonType") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("Name"); + + b.ToTable("Peoples"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.PeopleBaseItemMap", b => + { + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<Guid>("PeopleId") + .HasColumnType("TEXT"); + + b.Property<string>("Role") + .HasColumnType("TEXT"); + + b.Property<int?>("ListOrder") + .HasColumnType("INTEGER"); + + b.Property<int?>("SortOrder") + .HasColumnType("INTEGER"); + + b.HasKey("ItemId", "PeopleId", "Role"); + + b.HasIndex("ItemId", "ListOrder"); + + b.HasIndex("ItemId", "SortOrder"); + + b.HasIndex("PeopleId", "ItemId"); + + b.ToTable("PeopleBaseItemMap"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Permission", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<int>("Kind") + .HasColumnType("INTEGER"); + + b.Property<uint>("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.Property<bool>("Value") + .HasColumnType("INTEGER"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "Kind") + .IsUnique(); + + b.ToTable("Permissions"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Preference", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<int>("Kind") + .HasColumnType("INTEGER"); + + b.Property<uint>("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.Property<string>("Value") + .IsRequired() + .HasMaxLength(65535) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("UserId", "Kind") + .IsUnique(); + + b.ToTable("Preferences"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Security.ApiKey", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<string>("AccessToken") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<DateTime>("DateCreated") + .HasColumnType("TEXT"); + + b.Property<DateTime>("DateLastActivity") + .HasColumnType("TEXT"); + + b.Property<string>("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("AccessToken") + .IsUnique(); + + b.ToTable("ApiKeys"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Security.Device", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<string>("AccessToken") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property<string>("AppName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property<string>("AppVersion") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<DateTime>("DateCreated") + .HasColumnType("TEXT"); + + b.Property<DateTime>("DateLastActivity") + .HasColumnType("TEXT"); + + b.Property<DateTime>("DateModified") + .HasColumnType("TEXT"); + + b.Property<string>("DeviceId") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("TEXT"); + + b.Property<string>("DeviceName") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("TEXT"); + + b.Property<bool>("IsActive") + .HasColumnType("INTEGER"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("AccessToken", "DateLastActivity"); + + b.HasIndex("DeviceId", "DateLastActivity"); + + b.HasIndex("UserId", "DeviceId"); + + b.ToTable("Devices"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Security.DeviceOptions", b => + { + b.Property<int>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property<string>("CustomName") + .HasColumnType("TEXT"); + + b.Property<string>("DeviceId") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("DeviceId") + .IsUnique(); + + b.ToTable("DeviceOptions"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.TrickplayInfo", b => + { + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<int>("Width") + .HasColumnType("INTEGER"); + + b.Property<int>("Bandwidth") + .HasColumnType("INTEGER"); + + b.Property<int>("Height") + .HasColumnType("INTEGER"); + + b.Property<int>("Interval") + .HasColumnType("INTEGER"); + + b.Property<int>("ThumbnailCount") + .HasColumnType("INTEGER"); + + b.Property<int>("TileHeight") + .HasColumnType("INTEGER"); + + b.Property<int>("TileWidth") + .HasColumnType("INTEGER"); + + b.HasKey("ItemId", "Width"); + + b.ToTable("TrickplayInfos"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.User", b => + { + b.Property<Guid>("Id") + .ValueGeneratedOnAdd() + .HasColumnType("TEXT"); + + b.Property<string>("AudioLanguagePreference") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property<string>("AuthenticationProviderId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property<string>("CastReceiverId") + .HasMaxLength(32) + .HasColumnType("TEXT"); + + b.Property<bool>("DisplayCollectionsView") + .HasColumnType("INTEGER"); + + b.Property<bool>("DisplayMissingEpisodes") + .HasColumnType("INTEGER"); + + b.Property<bool>("EnableAutoLogin") + .HasColumnType("INTEGER"); + + b.Property<bool>("EnableLocalPassword") + .HasColumnType("INTEGER"); + + b.Property<bool>("EnableNextEpisodeAutoPlay") + .HasColumnType("INTEGER"); + + b.Property<bool>("EnableUserPreferenceAccess") + .HasColumnType("INTEGER"); + + b.Property<bool>("HidePlayedInLatest") + .HasColumnType("INTEGER"); + + b.Property<long>("InternalId") + .HasColumnType("INTEGER"); + + b.Property<int>("InvalidLoginAttemptCount") + .HasColumnType("INTEGER"); + + b.Property<DateTime?>("LastActivityDate") + .HasColumnType("TEXT"); + + b.Property<DateTime?>("LastLoginDate") + .HasColumnType("TEXT"); + + b.Property<int?>("LoginAttemptsBeforeLockout") + .HasColumnType("INTEGER"); + + b.Property<int>("MaxActiveSessions") + .HasColumnType("INTEGER"); + + b.Property<int?>("MaxParentalRatingScore") + .HasColumnType("INTEGER"); + + b.Property<int?>("MaxParentalRatingSubScore") + .HasColumnType("INTEGER"); + + b.Property<bool>("MustUpdatePassword") + .HasColumnType("INTEGER"); + + b.Property<string>("NormalizedUsername") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property<string>("Password") + .HasMaxLength(65535) + .HasColumnType("TEXT"); + + b.Property<string>("PasswordResetProviderId") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property<bool>("PlayDefaultAudioTrack") + .HasColumnType("INTEGER"); + + b.Property<bool>("RememberAudioSelections") + .HasColumnType("INTEGER"); + + b.Property<bool>("RememberSubtitleSelections") + .HasColumnType("INTEGER"); + + b.Property<int?>("RemoteClientBitrateLimit") + .HasColumnType("INTEGER"); + + b.Property<uint>("RowVersion") + .IsConcurrencyToken() + .HasColumnType("INTEGER"); + + b.Property<string>("SubtitleLanguagePreference") + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.Property<int>("SubtitleMode") + .HasColumnType("INTEGER"); + + b.Property<int>("SyncPlayAccess") + .HasColumnType("INTEGER"); + + b.Property<string>("Username") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.HasIndex("NormalizedUsername") + .IsUnique(); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("Users"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.UserData", b => + { + b.Property<Guid>("ItemId") + .HasColumnType("TEXT"); + + b.Property<Guid>("UserId") + .HasColumnType("TEXT"); + + b.Property<string>("CustomDataKey") + .HasColumnType("TEXT"); + + b.Property<int?>("AudioStreamIndex") + .HasColumnType("INTEGER"); + + b.Property<bool>("IsFavorite") + .HasColumnType("INTEGER"); + + b.Property<DateTime?>("LastPlayedDate") + .HasColumnType("TEXT"); + + b.Property<bool?>("Likes") + .HasColumnType("INTEGER"); + + b.Property<int>("PlayCount") + .HasColumnType("INTEGER"); + + b.Property<long>("PlaybackPositionTicks") + .HasColumnType("INTEGER"); + + b.Property<bool>("Played") + .HasColumnType("INTEGER"); + + b.Property<double?>("Rating") + .HasColumnType("REAL"); + + b.Property<DateTime?>("RetentionDate") + .HasColumnType("TEXT"); + + b.Property<int?>("SubtitleStreamIndex") + .HasColumnType("INTEGER"); + + b.HasKey("ItemId", "UserId", "CustomDataKey"); + + b.HasIndex("ItemId", "UserId", "IsFavorite"); + + b.HasIndex("ItemId", "UserId", "LastPlayedDate"); + + b.HasIndex("ItemId", "UserId", "PlaybackPositionTicks"); + + b.HasIndex("ItemId", "UserId", "Played"); + + b.HasIndex("UserId", "IsFavorite", "ItemId"); + + b.HasIndex("UserId", "ItemId", "LastPlayedDate"); + + b.HasIndex("UserId", "Played", "ItemId"); + + b.ToTable("UserData"); + + b.HasAnnotation("Sqlite:UseSqlReturningClause", false); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AccessSchedule", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.User", null) + .WithMany("AccessSchedules") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AncestorId", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item") + .WithMany("Parents") + .HasForeignKey("ItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "ParentItem") + .WithMany("Children") + .HasForeignKey("ParentItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Item"); + + b.Navigation("ParentItem"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AttachmentStreamInfo", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item") + .WithMany() + .HasForeignKey("ItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Item"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemEntity", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Owner") + .WithMany("Extras") + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.NoAction); + + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "DirectParent") + .WithMany("DirectChildren") + .HasForeignKey("ParentId") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("DirectParent"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemImageInfo", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item") + .WithMany("Images") + .HasForeignKey("ItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Item"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemMetadataField", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item") + .WithMany("LockedFields") + .HasForeignKey("ItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Item"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemProvider", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item") + .WithMany("Provider") + .HasForeignKey("ItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Item"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemTrailerType", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item") + .WithMany("TrailerTypes") + .HasForeignKey("ItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Item"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Chapter", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item") + .WithMany("Chapters") + .HasForeignKey("ItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Item"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.DisplayPreferences", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.User", null) + .WithMany("DisplayPreferences") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.HomeSection", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.DisplayPreferences", null) + .WithMany("HomeSections") + .HasForeignKey("DisplayPreferencesId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ImageInfo", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.User", null) + .WithOne("ProfileImage") + .HasForeignKey("Jellyfin.Database.Implementations.Entities.ImageInfo", "UserId") + .OnDelete(DeleteBehavior.Cascade); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ItemDisplayPreferences", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.User", null) + .WithMany("ItemDisplayPreferences") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ItemValueMap", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item") + .WithMany("ItemValues") + .HasForeignKey("ItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Jellyfin.Database.Implementations.Entities.ItemValue", "ItemValue") + .WithMany("BaseItemsMap") + .HasForeignKey("ItemValueId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Item"); + + b.Navigation("ItemValue"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.KeyframeData", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item") + .WithMany() + .HasForeignKey("ItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Item"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.LinkedChildEntity", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Child") + .WithMany("LinkedChildOfEntities") + .HasForeignKey("ChildId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Parent") + .WithMany("LinkedChildEntities") + .HasForeignKey("ParentId") + .OnDelete(DeleteBehavior.NoAction) + .IsRequired(); + + b.Navigation("Child"); + + b.Navigation("Parent"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.MediaStreamInfo", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item") + .WithMany("MediaStreams") + .HasForeignKey("ItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Item"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.PeopleBaseItemMap", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item") + .WithMany("Peoples") + .HasForeignKey("ItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Jellyfin.Database.Implementations.Entities.People", "People") + .WithMany("BaseItems") + .HasForeignKey("PeopleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Item"); + + b.Navigation("People"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Permission", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.User", null) + .WithMany("Permissions") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Preference", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.User", null) + .WithMany("Preferences") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.Security.Device", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.UserData", b => + { + b.HasOne("Jellyfin.Database.Implementations.Entities.BaseItemEntity", "Item") + .WithMany("UserData") + .HasForeignKey("ItemId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Jellyfin.Database.Implementations.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Item"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.BaseItemEntity", b => + { + b.Navigation("Chapters"); + + b.Navigation("Children"); + + b.Navigation("DirectChildren"); + + b.Navigation("Extras"); + + b.Navigation("Images"); + + b.Navigation("ItemValues"); + + b.Navigation("LinkedChildEntities"); + + b.Navigation("LinkedChildOfEntities"); + + b.Navigation("LockedFields"); + + b.Navigation("MediaStreams"); + + b.Navigation("Parents"); + + b.Navigation("Peoples"); + + b.Navigation("Provider"); + + b.Navigation("TrailerTypes"); + + b.Navigation("UserData"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.DisplayPreferences", b => + { + b.Navigation("HomeSections"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.ItemValue", b => + { + b.Navigation("BaseItemsMap"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.People", b => + { + b.Navigation("BaseItems"); + }); + + modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.User", b => + { + b.Navigation("AccessSchedules"); + + b.Navigation("DisplayPreferences"); + + b.Navigation("ItemDisplayPreferences"); + + b.Navigation("Permissions"); + + b.Navigation("Preferences"); + + b.Navigation("ProfileImage"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20261024092111_CoverAncestorIdsParentIndex.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20261024092111_CoverAncestorIdsParentIndex.cs new file mode 100644 index 0000000000..a0a4d06fcd --- /dev/null +++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20261024092111_CoverAncestorIdsParentIndex.cs @@ -0,0 +1,36 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace Jellyfin.Database.Providers.Sqlite.Migrations +{ + /// <inheritdoc /> + public partial class CoverAncestorIdsParentIndex : Migration + { + /// <inheritdoc /> + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_AncestorIds_ParentItemId", + table: "AncestorIds"); + + migrationBuilder.CreateIndex( + name: "IX_AncestorIds_ParentItemId_ItemId", + table: "AncestorIds", + columns: new[] { "ParentItemId", "ItemId" }); + } + + /// <inheritdoc /> + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropIndex( + name: "IX_AncestorIds_ParentItemId_ItemId", + table: "AncestorIds"); + + migrationBuilder.CreateIndex( + name: "IX_AncestorIds_ParentItemId", + table: "AncestorIds", + column: "ParentItemId"); + } + } +} diff --git a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/JellyfinDbModelSnapshot.cs b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/JellyfinDbModelSnapshot.cs index d3df73d2f6..006fb4bec3 100644 --- a/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/JellyfinDbModelSnapshot.cs +++ b/src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/JellyfinDbModelSnapshot.cs @@ -15,7 +15,7 @@ namespace Jellyfin.Server.Implementations.Migrations protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 - modelBuilder.HasAnnotation("ProductVersion", "10.0.11"); + modelBuilder.HasAnnotation("ProductVersion", "10.0.12"); modelBuilder.Entity("Jellyfin.Database.Implementations.Entities.AccessSchedule", b => { @@ -104,7 +104,7 @@ namespace Jellyfin.Server.Implementations.Migrations b.HasKey("ItemId", "ParentItemId"); - b.HasIndex("ParentItemId"); + b.HasIndex("ParentItemId", "ItemId"); b.ToTable("AncestorIds"); diff --git a/src/Jellyfin.LiveTv/Guide/GuideManager.cs b/src/Jellyfin.LiveTv/Guide/GuideManager.cs index a11f83f2f8..15486081b0 100644 --- a/src/Jellyfin.LiveTv/Guide/GuideManager.cs +++ b/src/Jellyfin.LiveTv/Guide/GuideManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Jellyfin.Data.Enums; @@ -8,6 +9,7 @@ using Jellyfin.Extensions; using Jellyfin.LiveTv.Configuration; using Jellyfin.LiveTv.Listings; using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; @@ -747,26 +749,17 @@ public class GuideManager : IGuideManager return false; } - private async Task PreCacheImages(IReadOnlyList<BaseItem> programs, DateTime maxCacheDate) + internal async Task PreCacheImages(IReadOnlyList<BaseItem> programs, DateTime maxCacheDate) { - var sdLimitActive = _schedulesDirectService.IsImageDailyLimitActive(); - await Parallel.ForEachAsync( programs .Where(p => p.EndDate.HasValue && p.EndDate.Value < maxCacheDate) - .Where(p => !sdLimitActive || !p.ImageInfos.All( - img => img.IsLocalFile || img.Path.Contains("schedulesdirect", StringComparison.OrdinalIgnoreCase))) + .Where(p => p.ImageInfos.Any(img => !img.IsLocalFile)) .DistinctBy(p => p.Id), _cacheParallelOptions, async (program, cancellationToken) => { - // Re-check: limit may have been set by a parallel task since the LINQ filter ran. - if (_schedulesDirectService.IsImageDailyLimitActive() - && program.ImageInfos.All( - img => img.IsLocalFile || img.Path.Contains("schedulesdirect", StringComparison.OrdinalIgnoreCase))) - { - return; - } + List<ItemImageInfo>? deadImages = null; for (var i = 0; i < program.ImageInfos.Length; i++) { @@ -781,10 +774,12 @@ public class GuideManager : IGuideManager continue; } - // Skip SD downloads once the daily limit has been hit. - if (imageInfo.Path.Contains("schedulesdirect", StringComparison.OrdinalIgnoreCase) - && _schedulesDirectService.IsImageDailyLimitActive()) + // Re-checked per image: the limit may have been hit by a parallel task. A blocked + // url left on the program would still be fetched when a client asks for it. + if (!_schedulesDirectService.CanDownloadImage(imageInfo.Path)) { + deadImages ??= []; + deadImages.Add(imageInfo); continue; } @@ -797,12 +792,35 @@ public class GuideManager : IGuideManager imageIndex: 0, removeOnFailure: false) .ConfigureAwait(false); + _schedulesDirectService.ReportImageDownloadSuccess(imageInfo.Path); } catch (Exception ex) { + // A rejected download never surfaces as an error on its own, so feed the + // response back to the provider to stop us hammering an exhausted account. + var httpException = (ex as HttpRequestException) ?? ex.InnerException as HttpRequestException; + var action = _schedulesDirectService.ReportImageDownloadFailure( + imageInfo.Path, + httpException?.StatusCode, + (httpException as HttpResponseBodyException)?.ResponseBody); + + if (action == ImageDownloadFailureAction.RemoveImage) + { + deadImages ??= []; + deadImages.Add(imageInfo); + } + _logger.LogWarning(ex, "Unable to pre-cache {Url}", imageInfo.Path); } } + + if (deadImages is not null) + { + // Requesting a url Schedules Direct has already rejected is what gets an + // account blocked, so it must not survive to the next refresh. + program.RemoveImages(deadImages); + await program.UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, cancellationToken).ConfigureAwait(false); + } }).ConfigureAwait(false); } } diff --git a/src/Jellyfin.LiveTv/Listings/ListingsManager.cs b/src/Jellyfin.LiveTv/Listings/ListingsManager.cs index 7274a3030c..2f4afc2b27 100644 --- a/src/Jellyfin.LiveTv/Listings/ListingsManager.cs +++ b/src/Jellyfin.LiveTv/Listings/ListingsManager.cs @@ -124,6 +124,8 @@ public class ListingsManager : IListingsManager { ArgumentNullException.ThrowIfNull(channel); + Exception? failure = null; + foreach (var (provider, providerInfo) in GetListingProviders()) { if (!IsListingProviderEnabledForTuner(providerInfo, channel.TunerHostId)) @@ -144,19 +146,42 @@ public class ListingsManager : IListingsManager provider.Name, providerInfo.ListingsId ?? string.Empty); - var epgChannels = await GetEpgChannels(provider, providerInfo, true, cancellationToken).ConfigureAwait(false); + List<ProgramInfo> programs; + try + { + // Listing the provider's channels can fail as well, and that must not stop the + // fallback to the next provider either. + var epgChannels = await GetEpgChannels(provider, providerInfo, true, cancellationToken).ConfigureAwait(false); - var epgChannel = GetEpgChannelFromTunerChannel(providerInfo.ChannelMappings, channel, epgChannels); - if (epgChannel is null) + var epgChannel = GetEpgChannelFromTunerChannel(providerInfo.ChannelMappings, channel, epgChannels); + if (epgChannel is null) + { + _logger.LogDebug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Name, providerInfo.ListingsId ?? string.Empty); + continue; + } + + programs = (await provider + .GetProgramsAsync(providerInfo, epgChannel.Id, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false)) + .ToList(); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception ex) { - _logger.LogDebug("EPG channel not found for tuner channel {0}-{1} from {2}-{3}", channel.Number, channel.Name, provider.Name, providerInfo.ListingsId ?? string.Empty); + // Another provider may still be able to serve this channel, so the failure is + // held back rather than thrown, and only surfaces if nothing else answers. + _logger.LogError( + ex, + "Error getting programs for channel {Number}-{Name} from {Provider}", + channel.Number, + channel.Name, + provider.Name); + failure ??= ex; continue; } - var programs = (await provider - .GetProgramsAsync(providerInfo, epgChannel.Id, startDateUtc, endDateUtc, cancellationToken).ConfigureAwait(false)) - .ToList(); - // Replace the value that came from the provider with a normalized value foreach (var program in programs) { @@ -170,7 +195,16 @@ public class ListingsManager : IListingsManager } } - return Enumerable.Empty<ProgramInfo>(); + // Reporting no programs would have the guide refresh delete the ones this channel already + // has, so a channel nothing could be fetched for has to fail instead. + if (failure is not null) + { + throw new InvalidOperationException( + $"No listings provider could supply programs for channel {channel.Number}-{channel.Name}", + failure); + } + + return []; } /// <inheritdoc /> diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirect.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirect.cs index 40ec99e9a5..801c4f163b 100644 --- a/src/Jellyfin.LiveTv/Listings/SchedulesDirect.cs +++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirect.cs @@ -25,6 +25,8 @@ using Jellyfin.LiveTv.Listings.SchedulesDirectDtos; using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Authentication; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Entities; @@ -38,31 +40,76 @@ namespace Jellyfin.LiveTv.Listings private const string ApiUrl = "https://json.schedulesdirect.org/20141201"; private const int CountryCacheDays = 7; + // Schedules Direct disables an account that keeps requesting images after the daily + // download limit, so stop after a short streak of rejections instead of retrying forever. + private const int MaxConsecutiveImageFailures = 10; + + // Hard server-side cap on elements in a single programs request. + private const int MaxProgramsPerRequest = 5000; + + // Memory ceiling on the rejected image uris (~2MB of 64-char keys). The daily invalid-uri + // limit stops the account long before this many can accumulate. + private const int MaxRejectedImageUris = 10000; + + // Stations that stopped being queried keep their cached schedules for this long. + private const int ScheduleCacheMaxAgeDays = 30; + + // Long enough to outlive any restart, short enough that the list cannot fill up for good. + private const int RejectedImageUriMaxAgeDays = 30; + + // The spec requires a client to stay away for an hour once the service reports Offline. + private const int OfflineBackoffMinutes = 60; + + private const int LoginBackoffMinutes = 30; + private const int MaxLoginsBackoffHours = 24; + + private const int StatusCacheMinutes = 10; + private readonly ILogger<SchedulesDirect> _logger; private readonly IHttpClientFactory _httpClientFactory; private readonly IApplicationPaths _appPaths; + private readonly ILibraryManager _libraryManager; private readonly AsyncNonKeyedLocker _tokenLock = new(1); + private readonly AsyncNonKeyedLocker _statusLock = new(1); + private readonly SchedulesDirectScheduleCache _scheduleCache; + private readonly SchedulesDirectLineupCache _lineupCache; + + // Image uris Schedules Direct answered with IMAGE_NOT_FOUND. Requesting one of these + // again is what trips MAX_IMAGE_INVALID_URI_ERRORS and gets the account blocked. + private readonly ConcurrentDictionary<string, byte> _rejectedImageUris = new(StringComparer.Ordinal); + private readonly Lock _rejectedImageUrisFileLock = new(); + + // Station/date pairs the server has queued for generation, with the retryTime it gave. + private readonly ConcurrentDictionary<string, DateTime> _scheduleRetryTimes = new(StringComparer.Ordinal); private readonly ConcurrentDictionary<string, NameValuePair> _tokens = new(); private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; - private long _lastErrorResponseTicks; + private long _loginBackoffUntilTicks; private volatile bool _accountError; - private bool _disposed = false; + private bool _disposed; private byte[] _countriesCache; private DateOnly? _imageLimitHitDate; private DateOnly? _metadataLimitHitDate; + private int _consecutiveImageFailures; + private long _offlineUntilTicks; + private StatusCacheEntry _status; public SchedulesDirect( ILogger<SchedulesDirect> logger, IHttpClientFactory httpClientFactory, - IApplicationPaths appPaths) + IApplicationPaths appPaths, + ILibraryManager libraryManager) { _logger = logger; _httpClientFactory = httpClientFactory; _appPaths = appPaths; + _libraryManager = libraryManager; + _scheduleCache = new SchedulesDirectScheduleCache(logger, appPaths); + _lineupCache = new SchedulesDirectLineupCache(logger, appPaths); _imageLimitHitDate = LoadDailyLimitDate(ImageLimitFilePath); _metadataLimitHitDate = LoadDailyLimitDate(MetadataLimitFilePath); + LoadRejectedImageUris(); } /// <inheritdoc /> @@ -72,6 +119,8 @@ namespace Jellyfin.LiveTv.Listings private string MetadataLimitFilePath => Path.Combine(_appPaths.CachePath, "sd-metadata-limit.txt"); + private string RejectedImageUrisFilePath => Path.Combine(_appPaths.CachePath, "sd-rejected-images.txt"); + /// <inheritdoc /> public string Type => nameof(SchedulesDirect); @@ -93,9 +142,11 @@ namespace Jellyfin.LiveTv.Listings public async Task<IEnumerable<ProgramInfo>> GetProgramsAsync(ListingsProviderInfo info, string channelId, DateTime startDateUtc, DateTime endDateUtc, CancellationToken cancellationToken) { + // A failure must not come back as "this channel has no programs": GuideManager only + // skips CleanDatabase when a channel throws, so an empty list deletes the guide. if (IsMetadataLimitActive()) { - return []; + throw new InvalidOperationException("The Schedules Direct daily request limit has been reached."); } ArgumentException.ThrowIfNullOrEmpty(channelId); @@ -107,108 +158,461 @@ namespace Jellyfin.LiveTv.Listings if (string.IsNullOrEmpty(token)) { - _logger.LogWarning("SchedulesDirect token is empty, returning empty program list"); + throw new AuthenticationException("Could not authenticate with Schedules Direct"); + } - return []; + if (!await IsSystemOnline(info, cancellationToken).ConfigureAwait(false)) + { + throw new InvalidOperationException("Schedules Direct reports that the service is offline."); } var dates = GetScheduleRequestDates(startDateUtc, endDateUtc); - _logger.LogInformation("Channel Station ID is: {ChannelID}", channelId); - var requestList = new List<RequestScheduleForChannelDto>() + + // Ask what changed before downloading anything; a day whose md5 still matches is + // served from the cache and costs no schedule or program request. + var (md5s, unavailableDates) = await GetScheduleMd5s(info, channelId, dates, cancellationToken).ConfigureAwait(false); + + var cachedDays = new List<SchedulesDirectCachedDay>(); + var datesToFetch = new List<string>(); + foreach (var date in dates) + { + if (unavailableDates.Contains(date)) { - new() - { - StationId = channelId, - Date = dates - } - }; + // The hash check already said the server has no schedule for this day, so + // requesting it would only earn the same error again. + continue; + } - _logger.LogDebug("Request string for schedules is: {@RequestString}", requestList); + md5s.TryGetValue(date, out var md5); + var cached = await _scheduleCache.GetAsync(channelId, date, md5, cancellationToken).ConfigureAwait(false); + if (cached?.Schedule is not null) + { + cachedDays.Add(cached); + } + else if (!IsScheduleRetryPending(channelId, date)) + { + datesToFetch.Add(date); + } + } - using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules"); - options.Content = JsonContent.Create(requestList, options: _jsonOptions); - options.Headers.TryAddWithoutValidation("token", token); - var dailySchedules = await Request<IReadOnlyList<DayDto>>(options, true, info, cancellationToken).ConfigureAwait(false); - if (dailySchedules is null) + _logger.LogDebug( + "Channel {ChannelID}: {CachedCount} of {TotalCount} days served from cache", + channelId, + cachedDays.Count, + dates.Count); + + if (datesToFetch.Count > 0) { - return []; + // The hash check may have stopped us (offline, a login limit) or replaced the token, + // and its failure is swallowed, so the schedule request must not go out regardless. + token = await GetToken(info, cancellationToken).ConfigureAwait(false); + if (string.IsNullOrEmpty(token) || IsMetadataLimitActive()) + { + throw new InvalidOperationException("Schedules Direct stopped accepting requests while checking for schedule changes."); + } } - _logger.LogDebug("Found {ScheduleCount} programs on {ChannelID} ScheduleDirect", dailySchedules.Count, channelId); + var freshDays = await DownloadSchedules(info, channelId, datesToFetch, token, cancellationToken).ConfigureAwait(false); - using var programRequestOptions = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/programs"); - programRequestOptions.Headers.TryAddWithoutValidation("token", token); + // A day that is neither cached nor downloaded (queued, a per-day error, a pending retry) + // must not go missing: the guide refresh would delete its programs. The previous copy + // stands in for it, and without one the whole channel fails. + var coveredDates = cachedDays.Concat(freshDays) + .Select(d => d.Schedule?.Metadata?.StartDate?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)) + .ToHashSet(StringComparer.Ordinal); + foreach (var date in dates) + { + if (unavailableDates.Contains(date) || coveredDates.Contains(date)) + { + continue; + } + + var stale = await _scheduleCache.GetLatestAsync(channelId, date, cancellationToken).ConfigureAwait(false); + if (stale?.Schedule is null) + { + throw new InvalidOperationException( + string.Format( + CultureInfo.InvariantCulture, + "Could not get the schedule for station {0} on {1}", + channelId, + date)); + } + + _logger.LogDebug("Serving the previous schedule for {StationId} {Date} until a new one is available", channelId, date); + cachedDays.Add(stale); + } - var programIds = dailySchedules.SelectMany(d => d.Programs.Select(s => s.ProgramId)).Distinct(); - programRequestOptions.Content = JsonContent.Create(programIds, options: _jsonOptions); + _scheduleCache.Prune(channelId, dates); - var programDetails = await Request<IReadOnlyList<ProgramDetailsDto>>(programRequestOptions, true, info, cancellationToken).ConfigureAwait(false); - if (programDetails is null) + // Only reachable when the server reported every day as unavailable. + var allDays = cachedDays.Select(c => c.Schedule!).Concat(freshDays.Select(f => f.Schedule!)).ToList(); + if (allDays.Count == 0) { return []; } - var programDict = programDetails.ToDictionary(p => p.ProgramId, y => y); - - var programIdsWithImages = programDetails - .Where(p => p.HasImageArtwork) - .Select(p => p.ProgramId) + var programDict = cachedDays.Concat(freshDays) + .SelectMany(d => d.Programs) + .Where(p => !string.IsNullOrEmpty(p.ProgramId)) + .DistinctBy(p => p.ProgramId) + .ToDictionary(p => p.ProgramId, y => y); + + // Artwork uris are ephemeral and must not be cached, and artwork changes are not + // reflected in the schedule md5 either, so the index is requested fresh - but only for + // the programs whose images are actually going to be pre-cached. + var imageProgramIds = allDays.SelectMany(d => d.Programs) + .Where(s => WillBeImageCached(s) + && !string.IsNullOrEmpty(s.ProgramId) + && programDict.TryGetValue(s.ProgramId, out var detail) + && detail.HasImageArtwork) + .Select(s => s.ProgramId) + .Distinct() .ToList(); - var images = await GetImageForPrograms(info, programIdsWithImages, cancellationToken).ConfigureAwait(false); + var images = await GetImageForPrograms(info, imageProgramIds, cancellationToken).ConfigureAwait(false); var programsInfo = new List<ProgramInfo>(); - foreach (ProgramDto schedule in dailySchedules.SelectMany(d => d.Programs)) + foreach (ProgramDto schedule in allDays.SelectMany(d => d.Programs)) { - if (string.IsNullOrEmpty(schedule.ProgramId)) + if (string.IsNullOrEmpty(schedule.ProgramId) + || !programDict.TryGetValue(schedule.ProgramId, out var programDetail)) { continue; } // Only add images which will be pre-cached until we can implement dynamic token fetching - var endDate = schedule.AirDateTime?.AddSeconds(schedule.Duration); - var willBeCached = endDate.HasValue && endDate.Value < DateTime.UtcNow.AddDays(GuideManager.MaxCacheDays); - if (willBeCached && images is not null) + if (WillBeImageCached(schedule)) { - var imageIndex = images.FindIndex(i => - i.ProgramId is not null && schedule.ProgramId.StartsWith(i.ProgramId, StringComparison.Ordinal)); - if (imageIndex > -1) - { - var programEntry = programDict[schedule.ProgramId]; + SetProgramImages(schedule.ProgramId, programDetail, images, token); + } - var allImages = images[imageIndex].Data; - var imagesWithText = allImages.Where(i => string.Equals(i.Text, "yes", StringComparison.OrdinalIgnoreCase)).ToList(); - var imagesWithoutText = allImages.Where(i => string.Equals(i.Text, "no", StringComparison.OrdinalIgnoreCase)).ToList(); + programsInfo.Add(GetProgram(channelId, schedule, programDetail)); + } - const double DesiredAspect = 2.0 / 3; + return programsInfo; + } - programEntry.PrimaryImage = GetProgramImage(ApiUrl, imagesWithText, DesiredAspect, token) ?? - GetProgramImage(ApiUrl, allImages, DesiredAspect, token); + private async Task<(Dictionary<string, string> Md5s, HashSet<string> UnavailableDates)> GetScheduleMd5s( + ListingsProviderInfo info, + string stationId, + IReadOnlyList<string> dates, + CancellationToken cancellationToken) + { + var result = new Dictionary<string, string>(StringComparer.Ordinal); + var unavailable = new HashSet<string>(StringComparer.Ordinal); + + var token = await GetToken(info, cancellationToken).ConfigureAwait(false); + if (string.IsNullOrEmpty(token)) + { + return (result, unavailable); + } - const double WideAspect = 16.0 / 9; + var requestList = new List<RequestScheduleForChannelDto> + { + new() { StationId = stationId, Date = dates } + }; - programEntry.ThumbImage = GetProgramImage(ApiUrl, imagesWithText, WideAspect, token); + using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules/md5"); + message.Content = JsonContent.Create(requestList, options: _jsonOptions); + message.Headers.TryAddWithoutValidation("token", token); - // Don't supply the same image twice - if (string.Equals(programEntry.PrimaryImage, programEntry.ThumbImage, StringComparison.Ordinal)) + try + { + var response = await Request<Dictionary<string, Dictionary<string, ScheduleMd5Dto>>>(message, true, info, cancellationToken) + .ConfigureAwait(false); + if (response is null || !response.TryGetValue(stationId, out var days)) + { + return (result, unavailable); + } + + foreach (var (date, entry) in days) + { + if (entry.Code != 0) + { + // Only a definitive "there is no such day" is worth skipping; a transient + // error still gets the normal request, which may well succeed. + if (IsDefinitiveScheduleError(entry.Code)) { - programEntry.ThumbImage = null; + unavailable.Add(date); } - programEntry.BackdropImage = GetProgramImage(ApiUrl, imagesWithoutText, WideAspect, token); + LogEntryErrors([(entry.Code, date, entry.Message)], "schedule"); + } + else if (!string.IsNullOrEmpty(entry.Md5)) + { + result[date] = entry.Md5; + } + } + } + catch (Exception ex) when (ex is HttpRequestException or JsonException) + { + // Without md5s every requested day is treated as changed, which is the old + // behaviour. Nothing is marked unavailable, so no day is skipped on a failure. + _logger.LogWarning(ex, "Unable to get schedule hashes for station {StationId}", stationId); + } + + return (result, unavailable); + } + + // Whether the code means the day will never be available, as opposed to a transient + // failure that is worth another request. + private static bool IsDefinitiveScheduleError(int code) + => code is (int)SdErrorCode.ScheduleRangeExceeded + or (int)SdErrorCode.ScheduleNotInLineup + or (int)SdErrorCode.StationIdNotFound + or (int)SdErrorCode.StationIdDeleted; + + private bool IsScheduleRetryPending(string stationId, string date) + { + var key = stationId + "|" + date; + if (!_scheduleRetryTimes.TryGetValue(key, out var retryTime)) + { + return false; + } + + if (DateTime.UtcNow < retryTime) + { + _logger.LogDebug( + "Schedules Direct has queued {StationId} {Date}; not requesting it before {RetryTime}", + stationId, + date, + retryTime); + return true; + } + + _scheduleRetryTimes.TryRemove(key, out _); + return false; + } + + private static bool WillBeImageCached(ProgramDto schedule) + { + var endDate = schedule.AirDateTime?.AddSeconds(schedule.Duration); + return endDate.HasValue && endDate.Value < DateTime.UtcNow.AddDays(GuideManager.MaxCacheDays); + } + + private async Task<IReadOnlyList<SchedulesDirectCachedDay>> DownloadSchedules( + ListingsProviderInfo info, + string stationId, + IReadOnlyList<string> dates, + string token, + CancellationToken cancellationToken) + { + if (dates.Count == 0) + { + return []; + } + + var requestList = new List<RequestScheduleForChannelDto> + { + new() { StationId = stationId, Date = dates } + }; + + _logger.LogDebug("Request string for schedules is: {@RequestString}", requestList); + + using var options = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/schedules"); + options.Content = JsonContent.Create(requestList, options: _jsonOptions); + options.Headers.TryAddWithoutValidation("token", token); + + // A station-wide failure such as SCHEDULE_QUEUED arrives as a bare object rather than + // the usual array, so the shape has to be inspected before it is deserialized. + var payload = await Request<JsonElement>(options, true, info, cancellationToken, bodyCodeIsError: false).ConfigureAwait(false); + var dailySchedules = payload.ValueKind switch + { + JsonValueKind.Array => payload.Deserialize<IReadOnlyList<DayDto>>(_jsonOptions), + JsonValueKind.Object => [payload.Deserialize<DayDto>(_jsonOptions)], + _ => null + }; + + if (dailySchedules is null) + { + return []; + } + + var errorDays = dailySchedules.Where(d => d.Code.HasValue).ToList(); + RecordQueuedSchedules(stationId, dates, errorDays); + LogEntryErrors(errorDays.Select(d => (d.Code!.Value, d.StationId ?? stationId, d.Message ?? d.Response)), "schedule"); + var days = dailySchedules.Where(d => !d.Code.HasValue).ToList(); + + _logger.LogDebug("Found {ScheduleCount} days on {ChannelID} ScheduleDirect", days.Count, stationId); - // programEntry.bannerImage = GetProgramImage(ApiUrl, data, "Banner", false) ?? - // GetProgramImage(ApiUrl, data, "Banner-L1", false) ?? - // GetProgramImage(ApiUrl, data, "Banner-LO", false) ?? - // GetProgramImage(ApiUrl, data, "Banner-LOT", false); + var programIds = days.SelectMany(d => d.Programs.Select(s => s.ProgramId)) + .Where(id => !string.IsNullOrEmpty(id)) + .Distinct() + .ToList(); + + var programDetails = await GetProgramDetails(info, programIds, token, cancellationToken).ConfigureAwait(false); + var detailsById = programDetails.ToDictionary(p => p.ProgramId, StringComparer.Ordinal); + + var result = new List<SchedulesDirectCachedDay>(days.Count); + foreach (var day in days) + { + var dayPrograms = day.Programs + .Select(p => p.ProgramId) + .Where(id => !string.IsNullOrEmpty(id) && detailsById.ContainsKey(id)) + .Distinct() + .Select(id => detailsById[id]) + .ToList(); + + var cachedDay = new SchedulesDirectCachedDay + { + Md5 = day.Metadata?.Md5, + Schedule = day, + Programs = dayPrograms + }; + + var date = day.Metadata?.StartDate?.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture); + var missingIds = day.Programs + .Select(p => p.ProgramId) + .Where(id => !string.IsNullOrEmpty(id) && !detailsById.ContainsKey(id)) + .Distinct(StringComparer.Ordinal) + .ToList(); + + if (missingIds.Count == 0) + { + if (date is not null) + { + // Must stay ahead of SetProgramImages: it stamps ephemeral uris and a token + // that expires daily onto these programs, and neither may reach the cache. + await _scheduleCache.SetAsync(stationId, date, cachedDay, cancellationToken).ConfigureAwait(false); } + + result.Add(cachedDay); + continue; } - programsInfo.Add(GetProgram(channelId, schedule, programDict[schedule.ProgramId])); + // A queued program (6001) is not cached: finishing it need not change the day's md5. + // Dropping its airings would delete them, so the previous copy's details stand in; + // without those the day stays uncovered and GetProgramsAsync falls back or fails. + var stale = date is null + ? null + : await _scheduleCache.GetLatestAsync(stationId, date, cancellationToken).ConfigureAwait(false); + var staleById = stale?.Programs + .Where(p => !string.IsNullOrEmpty(p.ProgramId)) + .DistinctBy(p => p.ProgramId, StringComparer.Ordinal) + .ToDictionary(p => p.ProgramId, StringComparer.Ordinal); + if (staleById is not null && missingIds.TrueForAll(staleById.ContainsKey)) + { + cachedDay.Programs = [.. dayPrograms, .. missingIds.Select(id => staleById[id])]; + result.Add(cachedDay); + } } - return programsInfo; + return result; + } + + private void RecordQueuedSchedules(string stationId, IReadOnlyList<string> dates, IReadOnlyList<DayDto> errorDays) + { + // Dates roll out of the guide window without being asked for again, so entries that + // are no longer holding anything back have to be swept here. + var now = DateTime.UtcNow; + foreach (var (key, value) in _scheduleRetryTimes) + { + if (value <= now) + { + _scheduleRetryTimes.TryRemove(key, out _); + } + } + + foreach (var day in errorDays) + { + if (day.Code != (int)SdErrorCode.ScheduleQueued || day.RetryTime is not { } retryTime) + { + continue; + } + + // The response is station-wide and names no date, so it covers everything asked for. + _logger.LogInformation( + "Schedules Direct has queued the schedule for station {StationId}; retrying after {RetryTime}", + day.StationId ?? stationId, + retryTime); + + foreach (var date in dates) + { + _scheduleRetryTimes[(day.StationId ?? stationId) + "|" + date] = retryTime.ToUniversalTime(); + } + } + } + + private async Task<List<ProgramDetailsDto>> GetProgramDetails( + ListingsProviderInfo info, + IReadOnlyList<string> programIds, + string token, + CancellationToken cancellationToken) + { + var results = new List<ProgramDetailsDto>(programIds.Count); + + for (var i = 0; i < programIds.Count; i += MaxProgramsPerRequest) + { + var batch = programIds.Skip(i).Take(MaxProgramsPerRequest); + + using var message = new HttpRequestMessage(HttpMethod.Post, ApiUrl + "/programs"); + message.Headers.TryAddWithoutValidation("token", token); + message.Content = JsonContent.Create(batch, options: _jsonOptions); + + var batchResult = await Request<IReadOnlyList<ProgramDetailsDto>>(message, true, info, cancellationToken).ConfigureAwait(false); + if (batchResult is null) + { + continue; + } + + LogEntryErrors(batchResult.Where(p => p.Code.HasValue).Select(p => (p.Code!.Value, p.ProgramId, p.Message)), "program"); + + // Error entries carry no program data. A queued program (6001) is a soft failure, + // so it is left out, and its day is not cached so the next refresh asks again. + results.AddRange(batchResult.Where(p => !p.Code.HasValue && !string.IsNullOrEmpty(p.ProgramId))); + } + + return results.DistinctBy(p => p.ProgramId, StringComparer.Ordinal).ToList(); + } + + private void SetProgramImages(string programId, ProgramDetailsDto programEntry, IReadOnlyList<ShowImagesDto> images, string token) + { + var match = images.FirstOrDefault(i => + i.ProgramId is not null && programId.StartsWith(i.ProgramId, StringComparison.Ordinal)); + if (match is null) + { + return; + } + + var allImages = match.Data; + var imagesWithText = allImages.Where(i => string.Equals(i.Text, "yes", StringComparison.OrdinalIgnoreCase)).ToList(); + var imagesWithoutText = allImages.Where(i => string.Equals(i.Text, "no", StringComparison.OrdinalIgnoreCase)).ToList(); + + const double DesiredAspect = 2.0 / 3; + const double WideAspect = 16.0 / 9; + + programEntry.PrimaryImage = GetProgramImage(ApiUrl, imagesWithText, DesiredAspect, token) ?? + GetProgramImage(ApiUrl, allImages, DesiredAspect, token); + + programEntry.ThumbImage = GetProgramImage(ApiUrl, imagesWithText, WideAspect, token); + + // Don't supply the same image twice + if (string.Equals(programEntry.PrimaryImage, programEntry.ThumbImage, StringComparison.Ordinal)) + { + programEntry.ThumbImage = null; + } + + programEntry.BackdropImage = GetProgramImage(ApiUrl, imagesWithoutText, WideAspect, token); + } + + private void LogEntryErrors(IEnumerable<(int Code, string Id, string Message)> errors, string kind) + { + foreach (var (code, id, message) in errors) + { + _logger.LogWarning( + "Schedules Direct returned an error for {Kind} {Id}: code={Code}, message={Message}", + kind, + id, + code, + message); + + var sdCode = ToKnownErrorCode(code); + if (sdCode.HasValue) + { + ApplyErrorCode(sdCode.Value); + } + } } private static int GetSizeOrder(ImageDataDto image) @@ -299,7 +703,6 @@ namespace Jellyfin.LiveTv.Listings CommunityRating = null, EpisodeTitle = episodeTitle, Audio = audioType, - // IsNew = programInfo.@new ?? false, IsRepeat = programInfo.New is null, IsSeries = string.Equals(details.EntityType, "episode", StringComparison.OrdinalIgnoreCase), ImageUrl = details.PrimaryImage, @@ -417,9 +820,12 @@ namespace Jellyfin.LiveTv.Listings return info; } - private static string GetProgramImage(string apiUrl, IEnumerable<ImageDataDto> images, double desiredAspect, string token) + private string GetProgramImage(string apiUrl, IEnumerable<ImageDataDto> images, double desiredAspect, string token) { + // A uri Schedules Direct has already rejected must never be offered again; repeating + // the request is what trips MAX_IMAGE_INVALID_URI_ERRORS and blocks the account. var match = images + .Where(i => !string.IsNullOrWhiteSpace(i.Uri) && !_rejectedImageUris.ContainsKey(GetImageKey(i.Uri))) .OrderBy(i => Math.Abs(desiredAspect - GetAspectRatio(i))) .ThenByDescending(i => GetSizeOrder(i)) .FirstOrDefault(); @@ -431,11 +837,6 @@ namespace Jellyfin.LiveTv.Listings var uri = match.Uri; - if (string.IsNullOrWhiteSpace(uri)) - { - return null; - } - if (uri.Contains("http", StringComparison.OrdinalIgnoreCase)) { return uri; @@ -444,6 +845,20 @@ namespace Jellyfin.LiveTv.Listings return apiUrl + "/image/" + uri + "?token=" + token; } + private static string GetImageKey(string uriOrUrl) + { + var value = uriOrUrl; + + var imageSegment = value.IndexOf("/image/", StringComparison.OrdinalIgnoreCase); + if (imageSegment >= 0) + { + value = value[(imageSegment + 7)..]; + } + + var query = value.IndexOf('?', StringComparison.Ordinal); + return query < 0 ? value : value[..query]; + } + private static double GetAspectRatio(ImageDataDto i) { int width = 0; @@ -554,6 +969,13 @@ namespace Jellyfin.LiveTv.Listings throw new AuthenticationException("Could not authenticate with Schedules Direct"); } + // The spec puts the status check ahead of all processing, and an empty lineup list is + // indistinguishable from "nothing for this postal code", so this has to surface. + if (!await IsSystemOnline(info, cancellationToken).ConfigureAwait(false)) + { + throw new InvalidOperationException("Schedules Direct reports that the service is offline. Try again later."); + } + var lineups = new List<NameIdPair>(); using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/headends?country=" + country + "&postalcode=" + location); @@ -586,7 +1008,9 @@ namespace Jellyfin.LiveTv.Listings private void ResetErrorState(ListingsProviderInfo info) { _accountError = false; - Interlocked.Exchange(ref _lastErrorResponseTicks, 0); + Interlocked.Exchange(ref _loginBackoffUntilTicks, 0); + Interlocked.Exchange(ref _offlineUntilTicks, 0); + _status = null; // Only the account being saved is retried, the tokens of the other accounts stay valid. if (!string.IsNullOrWhiteSpace(info.Username)) @@ -619,10 +1043,21 @@ namespace Jellyfin.LiveTv.Listings return null; } - // Avoid hammering SD after transient login failures (e.g. max attempts / temporary lockout) - if ((DateTime.UtcNow - new DateTime(Interlocked.Read(ref _lastErrorResponseTicks), DateTimeKind.Utc)).TotalMinutes < 30) + // Avoid hammering SD after login failures (temporary lockout, too many logins). + var backoffUntil = Interlocked.Read(ref _loginBackoffUntilTicks); + if (DateTime.UtcNow.Ticks < backoffUntil) + { + _logger.LogWarning( + "Skipping Schedules Direct request because of a recent login failure. Retrying no earlier than {RetryAt}.", + new DateTime(backoffUntil, DateTimeKind.Utc)); + + return null; + } + + // A login during the offline hour counts towards MAX_LOGIN_ATTEMPTS and cannot succeed. + if (IsOfflineBackoffActive()) { - _logger.LogWarning("Skipping Schedules Direct request because of a recent login failure. Retrying no earlier than 30 minutes after it."); + _logger.LogWarning("Skipping Schedules Direct request, the service reported itself offline"); return null; } @@ -663,7 +1098,7 @@ namespace Jellyfin.LiveTv.Listings && (int)ex.StatusCode.Value < 500) { _tokens.Clear(); - Interlocked.Exchange(ref _lastErrorResponseTicks, DateTime.UtcNow.Ticks); + BackOffLogins(TimeSpan.FromMinutes(LoginBackoffMinutes)); } throw; @@ -671,86 +1106,202 @@ namespace Jellyfin.LiveTv.Listings } } + private async Task<bool> IsSystemOnline(ListingsProviderInfo info, CancellationToken cancellationToken) + { + if (IsOfflineBackoffActive()) + { + _logger.LogWarning("Skipping Schedules Direct request, the service reported itself offline"); + return false; + } + + var status = await GetStatus(info, cancellationToken).ConfigureAwait(false); + if (status is null) + { + // A failed status check is not a reason to skip the refresh on its own, unless it + // failed with SERVICE_OFFLINE. + return !IsOfflineBackoffActive(); + } + + // The spec does not define the order of the entries, so any of them can be the one + // that takes the service down. + var offline = status.SystemStatus.FirstOrDefault( + i => string.Equals(i.Status, "Offline", StringComparison.OrdinalIgnoreCase)); + if (offline is not null) + { + _logger.LogWarning( + "Schedules Direct reports the service is offline ({Message}). Not retrying for {Minutes} minutes.", + offline.Message, + OfflineBackoffMinutes); + Interlocked.Exchange(ref _offlineUntilTicks, DateTime.UtcNow.AddMinutes(OfflineBackoffMinutes).Ticks); + return false; + } + + if (status.Account?.Expires is { } expires && expires < DateTime.UtcNow.AddDays(7)) + { + _logger.LogWarning("The Schedules Direct subscription expires on {Expires}", expires); + } + + return true; + } + + private async Task<StatusDto> GetStatus(ListingsProviderInfo info, CancellationToken cancellationToken) + { + if (TryGetCachedStatus(out var cached)) + { + return cached; + } + + using (await _statusLock.LockAsync(cancellationToken).ConfigureAwait(false)) + { + // Whoever held the lock may have just refreshed it, and a guide refresh asking + // once per channel must not turn into one request per channel. + if (TryGetCachedStatus(out cached)) + { + return cached; + } + + StatusDto status = null; + try + { + var token = await GetToken(info, cancellationToken).ConfigureAwait(false); + + using var message = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/status"); + message.Headers.TryAddWithoutValidation("token", token); + + status = await Request<StatusDto>(message, true, info, cancellationToken).ConfigureAwait(false); + } + catch (Exception ex) when (ex is HttpRequestException or JsonException or AuthenticationException) + { + _logger.LogWarning(ex, "Unable to get the Schedules Direct service status"); + } + + // A failed check still counts as checked, or every channel retries it. + _status = new StatusCacheEntry(DateTime.UtcNow, status); + return status; + } + } + + private bool TryGetCachedStatus(out StatusDto status) + { + // One reference, so the time of the check and what it found can never disagree. + var entry = _status; + status = entry?.Status; + return entry is not null && (DateTime.UtcNow - entry.CheckedAt).TotalMinutes < StatusCacheMinutes; + } + + private bool ApplyErrorCode(SdErrorCode sdCode) + { + switch (sdCode) + { + case SdErrorCode.AccountExpired: + case SdErrorCode.InvalidHash: + case SdErrorCode.InvalidUser: + case SdErrorCode.AccountLocked: + case SdErrorCode.AppLocked: + case SdErrorCode.AccountInactive: + // Permanent account errors — disable SD for this server lifetime. + _logger.LogError("Schedules Direct account error (code {SdCode}). Disabling SD until server restart.", sdCode); + _tokens.Clear(); + _accountError = true; + return true; + + case SdErrorCode.ServiceOffline: + // The spec requires staying away for an hour once the service reports offline. + _logger.LogError("Schedules Direct is offline (code {SdCode}). Not retrying for {Minutes} minutes.", sdCode, OfflineBackoffMinutes); + _tokens.Clear(); + Interlocked.Exchange(ref _offlineUntilTicks, DateTime.UtcNow.AddMinutes(OfflineBackoffMinutes).Ticks); + return true; + + case SdErrorCode.ServiceBusy: + case SdErrorCode.AccountTempLock: + // Transient login errors — back off for 30 minutes, then allow retry. + _logger.LogError("Schedules Direct transient error (code {SdCode}). Backing off for {Minutes} minutes.", sdCode, LoginBackoffMinutes); + _tokens.Clear(); + BackOffLogins(TimeSpan.FromMinutes(LoginBackoffMinutes)); + return true; + + case SdErrorCode.MaxLoginAttempts: + // Counts logins, so asking for a token again is what earned it. SD support confirmed it + // clears 24 hours after the first login; waiting 24 hours from now is always past that. + _logger.LogError( + "Schedules Direct login limit reached (code {SdCode}). Not logging in again for {Hours} hours.", + sdCode, + MaxLoginsBackoffHours); + _tokens.Clear(); + BackOffLogins(TimeSpan.FromHours(MaxLoginsBackoffHours)); + SetImageLimitHit(); + SetMetadataLimitHit(); + return true; + + case SdErrorCode.MaxIPAttempts: + // Unconfirmed whether this one self-heals, so it stays disabled like an account error. + _logger.LogError( + "Schedules Direct unique IP limit reached (code {SdCode}). Disabling SD until server restart; the user has to contact Schedules Direct support.", + sdCode); + _tokens.Clear(); + _accountError = true; + SetImageLimitHit(); + SetMetadataLimitHit(); + return true; + + case SdErrorCode.MaxImageDownloads: + case SdErrorCode.MaxImageDownloadsTrial: + case SdErrorCode.MaxInvalidImages: + // Stop image requests until SD resets at 00:00 UTC. + _logger.LogError("Schedules Direct image download limit hit (code {SdCode}). Disabling image acquisition until SD reset.", sdCode); + SetImageLimitHit(); + return true; + + case SdErrorCode.MaxLineupChanges: + // Only blocks further lineup edits; guide data is unaffected. + _logger.LogError("Schedules Direct lineup change limit reached (code {SdCode}). Lineup edits are rejected until SD reset.", sdCode); + return true; + + default: + return false; + } + } + private async Task<T> Request<T>( HttpRequestMessage message, bool enableRetry, ListingsProviderInfo providerInfo, CancellationToken cancellationToken, - HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) + bool bodyCodeIsError = true) { using var response = await _httpClientFactory.CreateClient(NamedClient.Default) - .SendAsync(message, completionOption, cancellationToken) + .SendAsync(message, HttpCompletionOption.ResponseContentRead, cancellationToken) .ConfigureAwait(false); - if (response.IsSuccessStatusCode) - { - return await response.Content.ReadFromJsonAsync<T>(_jsonOptions, cancellationToken).ConfigureAwait(false); - } - var responseBody = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - // Try to extract the Schedules Direct error code from the response body. - SdErrorCode? sdCode = null; - try + // SD can report a failure as HTTP 200 with a non-zero code, which would otherwise + // deserialize into an empty object and read as success. + var errorCode = TryGetErrorCode(responseBody); + if (response.IsSuccessStatusCode && (!bodyCodeIsError || errorCode is null or 0)) { - using var doc = JsonDocument.Parse(responseBody); - if (doc.RootElement.TryGetProperty("code", out var codeProp) - && codeProp.TryGetInt32(out var parsedCode) - && Enum.IsDefined((SdErrorCode)parsedCode)) - { - sdCode = (SdErrorCode)parsedCode; - } - } - catch (JsonException) - { - // Response body is not valid JSON; sdCode stays null. + return JsonSerializer.Deserialize<T>(responseBody, _jsonOptions); } + var sdCode = ToKnownErrorCode(errorCode); + _logger.LogError( "Request to {Url} failed with HTTP {StatusCode}, SD code {SdCode}: {Response}", message.RequestUri, (int)response.StatusCode, - sdCode?.ToString() ?? "N/A", + sdCode?.ToString() ?? errorCode?.ToString(CultureInfo.InvariantCulture) ?? "N/A", responseBody); - if (sdCode is SdErrorCode.AccountExpired or SdErrorCode.InvalidHash or SdErrorCode.InvalidUser or SdErrorCode.AccountLocked or SdErrorCode.AppLocked or SdErrorCode.AccountInactive) - { - // Permanent account errors — disable SD for this server lifetime. - _logger.LogError("Schedules Direct account error (code {SdCode}). Disabling SD until server restart.", sdCode); - _tokens.Clear(); - _accountError = true; - } - else if (sdCode is SdErrorCode.ServiceOffline or SdErrorCode.ServiceBusy or SdErrorCode.AccountTempLock) - { - // Transient login errors — back off for 30 minutes, then allow retry. - _logger.LogError("Schedules Direct transient error (code {SdCode}). Backing off for 30 minutes.", sdCode); - _tokens.Clear(); - Interlocked.Exchange(ref _lastErrorResponseTicks, DateTime.UtcNow.Ticks); - } - else if (sdCode is SdErrorCode.MaxLoginAttempts or SdErrorCode.MaxIPAttempts) - { - // 24 hour bans - stop image and metadata requests until SD reset at 00:00 UTC. - _logger.LogError("Schedules Direct service limit error (code {SdCode}). Disabling until SD reset.", sdCode); - SetImageLimitHit(); - SetMetadataLimitHit(); - } - else if (sdCode is SdErrorCode.MaxImageDownloads or SdErrorCode.MaxImageDownloadsTrial) + if (sdCode.HasValue && ApplyErrorCode(sdCode.Value)) { - // Max image downloads — stop image requests until SD resets at 00:00 UTC. - _logger.LogError("Schedules Direct image download limit hit (code {SdCode}). Disabling image acquisition until SD reset.", sdCode); - SetImageLimitHit(); - } - else if (sdCode is SdErrorCode.MaxScheduleRequests) - { - // Max schedule/metadata requests — stop metadata requests until SD resets at 00:00 UTC. - _logger.LogError("Schedules Direct metadata download limit hit (code {SdCode}). Disabling metadata acquisition until SD reset.", sdCode); - SetMetadataLimitHit(); + // Handled by the error code. } else if (enableRetry && (int)response.StatusCode < 500 - && (sdCode == SdErrorCode.TokenExpired || (response.StatusCode == HttpStatusCode.Forbidden && sdCode is null))) + && (sdCode is SdErrorCode.TokenExpired or SdErrorCode.TokenInvalid or SdErrorCode.TokenMissing + || (response.StatusCode == HttpStatusCode.Forbidden && errorCode is null))) { - // Token expired — clear tokens and retry with a fresh token. - // Also retry on 403 with no parseable SD code (legacy/unexpected auth failure). + // Token rejected — clear tokens and retry with a fresh token. Also retry on 403 + // carrying no code at all; a code we simply do not know is not an auth failure. _tokens.Clear(); using var retryMessage = new HttpRequestMessage(message.Method, message.RequestUri); retryMessage.Content = message.Content; @@ -782,7 +1333,7 @@ namespace Jellyfin.LiveTv.Listings var root = await Request<TokenDto>(options, false, null, cancellationToken).ConfigureAwait(false); if (string.Equals(root?.Message, "OK", StringComparison.Ordinal)) { - _logger.LogInformation("Authenticated with Schedules Direct token: {Token}", root.Token); + _logger.LogInformation("Authenticated with Schedules Direct. Token expires at {TokenTimestamp}", root.TokenTimestamp); return root.Token; } @@ -807,9 +1358,26 @@ namespace Jellyfin.LiveTv.Listings if (!response.IsSuccessStatusCode) { + var responseBody = await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + var errorCode = TryGetErrorCode(responseBody); + var sdCode = ToKnownErrorCode(errorCode); + if (sdCode.HasValue) + { + ApplyErrorCode(sdCode.Value); + } + _logger.LogError( - "Error adding lineup to account: {Response}", - await response.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false)); + "Error adding lineup {Id} to account, SD code {SdCode}: {Response}", + info.ListingsId, + sdCode?.ToString() ?? errorCode?.ToString(CultureInfo.InvariantCulture) ?? "N/A", + responseBody); + + // Reporting success here leaves the user with a listings provider that silently + // has no lineup, so the failure has to surface. + throw new HttpRequestException( + string.Format(CultureInfo.InvariantCulture, "Could not add lineup {0} to the Schedules Direct account", info.ListingsId), + null, + response.StatusCode); } } @@ -913,23 +1481,225 @@ namespace Jellyfin.LiveTv.Listings } /// <inheritdoc /> - public bool IsServiceAvailable() + public bool CanDownloadImage(string imageUrl) + => !IsSchedulesDirectUrl(imageUrl) + || (!IsImageDailyLimitActive() && !_rejectedImageUris.ContainsKey(GetImageKey(imageUrl))); + + /// <inheritdoc /> + public void ReportImageDownloadSuccess(string imageUrl) { - if (_accountError) + if (IsSchedulesDirectUrl(imageUrl)) { - return false; + Interlocked.Exchange(ref _consecutiveImageFailures, 0); } + } - if ((DateTime.UtcNow - new DateTime(Interlocked.Read(ref _lastErrorResponseTicks), DateTimeKind.Utc)).TotalMinutes < 30) + /// <inheritdoc /> + public ImageDownloadFailureAction ReportImageDownloadFailure(string imageUrl, HttpStatusCode? statusCode, string responseBody) + { + if (!IsSchedulesDirectUrl(imageUrl)) { - return false; + return ImageDownloadFailureAction.None; } - return true; + var errorCode = TryGetErrorCode(responseBody); + if (errorCode is null) + { + // No readable code, so stop after a short streak of unexplained rejections rather + // than keep retrying an account that may already be refusing us. + if (Interlocked.Increment(ref _consecutiveImageFailures) == MaxConsecutiveImageFailures) + { + _logger.LogError( + "Schedules Direct image downloads keep failing without a readable error code (last status {StatusCode}). Disabling image acquisition until SD reset.", + statusCode); + SetImageLimitHit(); + } + + return ImageDownloadFailureAction.None; + } + + Interlocked.Exchange(ref _consecutiveImageFailures, 0); + + var sdCode = ToKnownErrorCode(errorCode); + if (sdCode is null) + { + return ImageDownloadFailureAction.None; + } + + // SD reports an exhausted image quota with an HTTP 200 body, so the code decides. + ApplyErrorCode(sdCode.Value); + + switch (sdCode.Value) + { + // The uri is gone. Remembering it is what keeps the next refresh from asking for + // it again and walking the account into MAX_IMAGE_INVALID_URI_ERRORS. + case SdErrorCode.ImageNotFound: + RejectImageUri(imageUrl); + return ImageDownloadFailureAction.RemoveImage; + + // The account is already being warned about invalid uris; this url is not + // necessarily one of them, so drop it for now but do not blacklist it. + case SdErrorCode.MaxInvalidImages: + return ImageDownloadFailureAction.RemoveImage; + + // The token baked into the url is stale; the next refresh mints a fresh one. + case SdErrorCode.TokenMissing: + case SdErrorCode.TokenInvalid: + case SdErrorCode.TokenExpired: + _tokens.Clear(); + return ImageDownloadFailureAction.RemoveImage; + + default: + return ImageDownloadFailureAction.None; + } } /// <inheritdoc /> - public bool IsImageDailyLimitActive() + public async Task<ItemImageInfo> ConvertImageToLocal(BaseItem item, ItemImageInfo image, int imageIndex) + { + ArgumentNullException.ThrowIfNull(image); + + var remotePath = image.Path; + if (!CanDownloadImage(remotePath)) + { + return null; + } + + try + { + var localImage = await _libraryManager.ConvertImageToLocal(item, image, imageIndex).ConfigureAwait(false); + ReportImageDownloadSuccess(remotePath); + return localImage; + } + catch (Exception ex) when ((ex as HttpRequestException ?? ex.InnerException as HttpRequestException) is { } httpException) + { + ReportImageDownloadFailure(remotePath, httpException.StatusCode, (httpException as HttpResponseBodyException)?.ResponseBody); + throw; + } + } + + private void RejectImageUri(string imageUrl) + { + var key = GetImageKey(imageUrl); + if (string.IsNullOrEmpty(key)) + { + return; + } + + // Stop learning rather than forgetting: clearing here would re-offer every known-bad + // uri at once, which is the burst that trips MAX_IMAGE_INVALID_URI_ERRORS. + if (_rejectedImageUris.Count < MaxRejectedImageUris && _rejectedImageUris.TryAdd(key, 0)) + { + // Persisted, or a restart would offer every rejected uri again in one refresh. + var line = DateTime.UtcNow.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + "\t" + key + Environment.NewLine; + try + { + lock (_rejectedImageUrisFileLock) + { + Directory.CreateDirectory(Path.GetDirectoryName(RejectedImageUrisFilePath)!); + File.AppendAllText(RejectedImageUrisFilePath, line); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + _logger.LogWarning(ex, "Failed to persist rejected SD image uri to {Path}", RejectedImageUrisFilePath); + } + } + } + + private void LoadRejectedImageUris() + { + var path = RejectedImageUrisFilePath; + if (!File.Exists(path)) + { + return; + } + + try + { + var cutoff = DateOnly.FromDateTime(DateTime.UtcNow.AddDays(-RejectedImageUriMaxAgeDays)); + var kept = new List<string>(); + var lines = File.ReadAllLines(path); + foreach (var line in lines) + { + var separator = line.IndexOf('\t', StringComparison.Ordinal); + if (separator <= 0 + || !DateOnly.TryParseExact(line.AsSpan(0, separator), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date) + || date < cutoff + || _rejectedImageUris.Count >= MaxRejectedImageUris) + { + continue; + } + + if (_rejectedImageUris.TryAdd(line[(separator + 1)..], 0)) + { + kept.Add(line); + } + } + + if (kept.Count != lines.Length) + { + File.WriteAllLines(path, kept); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + _logger.LogWarning(ex, "Failed to load rejected SD image uris from {Path}", path); + } + } + + private static bool IsSchedulesDirectUrl(string url) + => url is not null && url.Contains("schedulesdirect", StringComparison.OrdinalIgnoreCase); + + private static int? TryGetErrorCode(string responseBody) + { + // Only an object can carry a code; this also spares parsing large program arrays twice. + if (string.IsNullOrWhiteSpace(responseBody) || !responseBody.AsSpan().TrimStart().StartsWith('{')) + { + return null; + } + + try + { + using var doc = JsonDocument.Parse(responseBody); + if (doc.RootElement.ValueKind == JsonValueKind.Object + && doc.RootElement.TryGetProperty("code", out var codeProp) + && codeProp.TryGetInt32(out var parsedCode)) + { + return parsedCode; + } + } + catch (JsonException) + { + // Not an SD error payload. + } + + return null; + } + + private bool IsOfflineBackoffActive() + => DateTime.UtcNow.Ticks < Interlocked.Read(ref _offlineUntilTicks); + + private void BackOffLogins(TimeSpan duration) + { + // Keep the later deadline, so a generic 30 minute back-off cannot shorten the 24 hours of MAX_LOGIN_ATTEMPTS. + var until = DateTime.UtcNow.Add(duration).Ticks; + long current; + do + { + current = Interlocked.Read(ref _loginBackoffUntilTicks); + if (current >= until) + { + return; + } + } + while (Interlocked.CompareExchange(ref _loginBackoffUntilTicks, until, current) != current); + } + + private static SdErrorCode? ToKnownErrorCode(int? code) + => code.HasValue && Enum.IsDefined((SdErrorCode)code.Value) ? (SdErrorCode)code.Value : null; + + private bool IsImageDailyLimitActive() { if (!_imageLimitHitDate.HasValue) { @@ -939,6 +1709,7 @@ namespace Jellyfin.LiveTv.Listings if (_imageLimitHitDate.Value < DateOnly.FromDateTime(DateTime.UtcNow)) { _imageLimitHitDate = null; + Interlocked.Exchange(ref _consecutiveImageFailures, 0); TryDeleteFile(ImageLimitFilePath); return false; } @@ -1016,6 +1787,11 @@ namespace Jellyfin.LiveTv.Listings } } + if (!await IsSystemOnline(info, CancellationToken.None).ConfigureAwait(false)) + { + throw new InvalidOperationException("Schedules Direct reports that the service is offline. Try again later."); + } + if (validateListings) { ArgumentException.ThrowIfNullOrEmpty(info.ListingsId); @@ -1042,20 +1818,27 @@ namespace Jellyfin.LiveTv.Listings return []; } + // An empty channel list maps no channel, which the guide refresh reads as "no programs" + // and deletes the stored ones, so a failure has to surface here as well. var token = await GetToken(info, cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(token)) { - return []; + throw new AuthenticationException("Could not authenticate with Schedules Direct"); } - using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId); - options.Headers.TryAddWithoutValidation("token", token); + if (!await IsSystemOnline(info, cancellationToken).ConfigureAwait(false)) + { + throw new InvalidOperationException("Schedules Direct reports that the service is offline."); + } - var root = await Request<ChannelDto>(options, true, info, cancellationToken).ConfigureAwait(false); + // Stations that have left every lineup would otherwise keep their schedules forever. + _scheduleCache.PruneStale(TimeSpan.FromDays(ScheduleCacheMaxAgeDays)); + + var root = await GetLineup(info, listingsId, cancellationToken).ConfigureAwait(false); if (root is null) { - return new List<ChannelInfo>(); + return []; } _logger.LogInformation("Found {ChannelCount} channels on the lineup on ScheduleDirect", root.Map.Count); @@ -1093,6 +1876,44 @@ namespace Jellyfin.LiveTv.Listings return list; } + private async Task<ChannelDto> GetLineup(ListingsProviderInfo info, string listingsId, CancellationToken cancellationToken) + { + var status = await GetStatus(info, cancellationToken).ConfigureAwait(false); + var lineup = status?.Lineups.FirstOrDefault( + i => string.Equals(i.Lineup ?? i.Id, listingsId, StringComparison.OrdinalIgnoreCase)); + + if (lineup?.IsDeleted == true) + { + _logger.LogWarning( + "The Schedules Direct lineup {ListingsId} has been deleted at the headend. Pick a new lineup for this listings provider.", + listingsId); + } + + var modified = lineup?.Modified; + if (modified.HasValue) + { + var cached = await _lineupCache.GetAsync(listingsId, modified.Value, cancellationToken).ConfigureAwait(false); + if (cached is not null) + { + _logger.LogDebug("Serving the Schedules Direct lineup {ListingsId} from cache", listingsId); + return cached; + } + } + + var token = await GetToken(info, cancellationToken).ConfigureAwait(false); + + using var options = new HttpRequestMessage(HttpMethod.Get, ApiUrl + "/lineups/" + listingsId); + options.Headers.TryAddWithoutValidation("token", token); + + var root = await Request<ChannelDto>(options, true, info, cancellationToken).ConfigureAwait(false); + if (root is not null && modified.HasValue) + { + await _lineupCache.SetAsync(listingsId, modified.Value, root, cancellationToken).ConfigureAwait(false); + } + + return root; + } + /// <inheritdoc /> public void Dispose() { @@ -1114,9 +1935,12 @@ namespace Jellyfin.LiveTv.Listings if (disposing) { _tokenLock?.Dispose(); + _statusLock?.Dispose(); } _disposed = true; } + + private sealed record StatusCacheEntry(DateTime CheckedAt, StatusDto Status); } } diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirectCachedDay.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirectCachedDay.cs new file mode 100644 index 0000000000..c5dae1682e --- /dev/null +++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirectCachedDay.cs @@ -0,0 +1,29 @@ +using System.Collections.Generic; +using Jellyfin.LiveTv.Listings.SchedulesDirectDtos; + +namespace Jellyfin.LiveTv.Listings; + +/// <summary> +/// One station's schedule for one day, together with the details of its programs. +/// </summary> +/// <remarks> +/// Artwork is deliberately not cached: the spec states the image uri is ephemeral and must not be +/// stored, and artwork changes are not reflected in the schedule md5 this entry is keyed by. +/// </remarks> +public class SchedulesDirectCachedDay +{ + /// <summary> + /// Gets or sets the md5 Schedules Direct reported for this day's schedule. + /// </summary> + public string? Md5 { get; set; } + + /// <summary> + /// Gets or sets the schedule. + /// </summary> + public DayDto? Schedule { get; set; } + + /// <summary> + /// Gets or sets the details of the programs in the schedule. + /// </summary> + public IReadOnlyList<ProgramDetailsDto> Programs { get; set; } = []; +} diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/DayDto.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/DayDto.cs index 094f9a3194..4959e12675 100644 --- a/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/DayDto.cs +++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/DayDto.cs @@ -22,6 +22,35 @@ namespace Jellyfin.LiveTv.Listings.SchedulesDirectDtos public IReadOnlyList<ProgramDto> Programs { get; set; } = Array.Empty<ProgramDto>(); /// <summary> + /// Gets or sets the error code. Set when this entry is a per-station error + /// (for example SCHEDULE_RANGE_EXCEEDED) instead of a schedule. + /// </summary> + [JsonPropertyName("code")] + public int? Code { get; set; } + + /// <summary> + /// Gets or sets the error message that goes with <see cref="Code"/>. + /// </summary> + /// <remarks> + /// Not every error entry carries one; STATIONID_DELETED only sets <see cref="Response"/>. + /// </remarks> + [JsonPropertyName("message")] + public string? Message { get; set; } + + /// <summary> + /// Gets or sets the symbolic name of <see cref="Code"/>, for example STATIONID_DELETED. + /// </summary> + [JsonPropertyName("response")] + public string? Response { get; set; } + + /// <summary> + /// Gets or sets the earliest time a queued schedule (SCHEDULE_QUEUED) may be requested + /// again. The spec requires the client to wait at least this long. + /// </summary> + [JsonPropertyName("retryTime")] + public DateTime? RetryTime { get; set; } + + /// <summary> /// Gets or sets the metadata schedule. /// </summary> [JsonPropertyName("metadata")] diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/ProgramDetailsDto.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/ProgramDetailsDto.cs index 7bfc4bc8be..0b883e44aa 100644 --- a/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/ProgramDetailsDto.cs +++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/ProgramDetailsDto.cs @@ -22,6 +22,19 @@ namespace Jellyfin.LiveTv.Listings.SchedulesDirectDtos public string? ProgramId { get; set; } /// <summary> + /// Gets or sets the error code. Set when this entry is a per-program error + /// (for example INVALID_PROGRAMID) instead of a program. + /// </summary> + [JsonPropertyName("code")] + public int? Code { get; set; } + + /// <summary> + /// Gets or sets the error message that goes with <see cref="Code"/>. + /// </summary> + [JsonPropertyName("message")] + public string? Message { get; set; } + + /// <summary> /// Gets or sets the list of titles. /// </summary> [JsonPropertyName("titles")] diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/ScheduleMd5Dto.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/ScheduleMd5Dto.cs new file mode 100644 index 0000000000..6acd2172a9 --- /dev/null +++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/ScheduleMd5Dto.cs @@ -0,0 +1,34 @@ +using System; +using System.Text.Json.Serialization; + +namespace Jellyfin.LiveTv.Listings.SchedulesDirectDtos; + +/// <summary> +/// The md5 and last modified date of one station's schedule for one day. +/// </summary> +public class ScheduleMd5Dto +{ + /// <summary> + /// Gets or sets the error code. Non-zero when the day is unavailable. + /// </summary> + [JsonPropertyName("code")] + public int Code { get; set; } + + /// <summary> + /// Gets or sets the message that goes with <see cref="Code"/>. + /// </summary> + [JsonPropertyName("message")] + public string? Message { get; set; } + + /// <summary> + /// Gets or sets the time the schedule was last modified. + /// </summary> + [JsonPropertyName("lastModified")] + public DateTime? LastModified { get; set; } + + /// <summary> + /// Gets or sets the md5 of the schedule. A change means the schedule must be downloaded again. + /// </summary> + [JsonPropertyName("md5")] + public string? Md5 { get; set; } +} diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/SdErrorCode.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/SdErrorCode.cs index fffbfb9a58..b44ddc2bb4 100644 --- a/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/SdErrorCode.cs +++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/SdErrorCode.cs @@ -1,19 +1,161 @@ -#pragma warning disable CA1008 // Enums should have zero value - namespace Jellyfin.LiveTv.Listings.SchedulesDirectDtos; /// <summary> -/// Schedules Direct API error codes. See https://github.com/SchedulesDirect/JSON-Service/wiki/API-20141201#error-response for details. +/// Schedules Direct API error codes. See https://github.com/SchedulesDirect/JSON-Service/wiki/API-20141201#error-codes for details. /// </summary> +/// <remarks> +/// A complete mirror of the documented table. Codes the client does not act on are still listed, +/// because membership is what lets a response be logged by name instead of by number. +/// </remarks> public enum SdErrorCode { /// <summary> - /// Schedules Direct unavailable/out of service. + /// No error. + /// </summary> + Ok = 0, + + /// <summary> + /// Unable to decode JSON. + /// </summary> + InvalidJson = 1001, + + /// <summary> + /// Did not receive a User-Agent in the request header. + /// </summary> + UserAgentRequired = 1003, + + /// <summary> + /// Token required but not provided in the request header. + /// </summary> + TokenMissing = 1004, + + /// <summary> + /// Did not recognize the submitted client. + /// </summary> + UnknownClient = 1005, + + /// <summary> + /// The maximum number of elements in a single request is 5000. + /// </summary> + MaxChunkExceeded = 1006, + + /// <summary> + /// The request sent to the server was empty. + /// </summary> + EmptyRequest = 1007, + + /// <summary> + /// The request is improperly formatted. + /// </summary> + IncorrectRequest = 1008, + + /// <summary> + /// The maximum number of elements in a single request is 500. + /// </summary> + MaxChunkExceededMetadata = 1009, + + /// <summary> + /// Token is not 32 characters. + /// </summary> + TokenInvalid = 1010, + + /// <summary> + /// The Content-Type header must be application/json. + /// </summary> + IncorrectContentType = 1011, + + /// <summary> + /// Did not receive request. + /// </summary> + RequiredRequestMissing = 2002, + + /// <summary> + /// Searching for lineups requires a 3-letter country parameter. + /// </summary> + CountryRequired = 2004, + + /// <summary> + /// Searching for lineups requires a postal code parameter. + /// </summary> + PostalCodeRequired = 2005, + + /// <summary> + /// The request is missing the personID / nameID in the path. + /// </summary> + PersonIdRequired = 2020, + + /// <summary> + /// The country parameter must be ISO-3166-1 alpha 3. + /// </summary> + InvalidCountryParameter = 2050, + + /// <summary> + /// Unknown request; available data may be requested for COUNTRIES. + /// </summary> + UnknownRequest = 2054, + + /// <summary> + /// Unexpected debug connection from client. + /// </summary> + InvalidDebugParameter = 2055, + + /// <summary> + /// Lineup already in account. + /// </summary> + DuplicateLineup = 2100, + + /// <summary> + /// Lineup not in account; add it before requesting its mapping. + /// </summary> + LineupNotFound = 2101, + + /// <summary> + /// Invalid lineup requested; check the country/postal code combination. + /// </summary> + UnknownLineup = 2102, + + /// <summary> + /// Delete of a lineup that is not in the account. + /// </summary> + InvalidLineupDelete = 2103, + + /// <summary> + /// Lineup must be formatted COUNTRY-LINEUP-DEVICE or COUNTRY-OTA-POSTALCODE. + /// </summary> + LineupWrongFormat = 2104, + + /// <summary> + /// The requested lineup has been deleted from the server. + /// </summary> + LineupDeleted = 2106, + + /// <summary> + /// The requested country is mis-typed or has no valid data. + /// </summary> + InvalidCountry = 2108, + + /// <summary> + /// The requested personID does not exist. + /// </summary> + InvalidPersonId = 2109, + + /// <summary> + /// The requested stationID is not in any of the configured lineups. + /// </summary> + StationIdNotFound = 2200, + + /// <summary> + /// The requested stationID has been marked as deleted and will be purged. + /// </summary> + StationIdDeleted = 2201, + + /// <summary> + /// Server offline for maintenance. /// </summary> ServiceOffline = 3000, /// <summary> - /// Schedules Direct busy. + /// Server is busy processing other requests. Retry. /// </summary> ServiceBusy = 3001, @@ -23,72 +165,125 @@ public enum SdErrorCode AccountExpired = 4001, /// <summary> - /// Invalid password hash. + /// Password hash must be a lowercase 40 character sha1_hex of the password. /// </summary> InvalidHash = 4002, /// <summary> - /// Invalid user or password. + /// Invalid username or password. /// </summary> InvalidUser = 4003, /// <summary> - /// Account temporarily locked due to login failures. + /// Too many login failures. Locked for 15 minutes. /// </summary> AccountTempLock = 4004, /// <summary> - /// Account permanently locked due to abuse. + /// Access to the account via JSON has been disabled; the user must contact SD support. /// </summary> AccountLocked = 4005, /// <summary> - /// Token has expired. Request a new one. + /// Token has expired. Request a new token. /// </summary> TokenExpired = 4006, /// <summary> - /// Application locked out. + /// Application not authorized to use the data service. /// </summary> AppLocked = 4007, /// <summary> - /// Account not active. + /// Account inactive. /// </summary> AccountInactive = 4008, /// <summary> - /// Maximum login attempts exceeded. + /// Exceeded the maximum number of logins in 24 hours; clears 24 hours after the first login. /// </summary> MaxLoginAttempts = 4009, /// <summary> - /// Maximum unique IP attempts reached. + /// Exceeded the maximum number of unique IP addresses in 24 hours; the user must contact SD support. /// </summary> MaxIPAttempts = 4010, /// <summary> - /// Lineup change maximum reached. + /// Exceeded the maximum number of lineup changes for today. /// </summary> - MaxScheduleRequests = 4100, + MaxLineupChanges = 4100, /// <summary> - /// Requested image not found. + /// Exceeded the number of lineups this account may hold. + /// </summary> + MaxLineups = 4101, + + /// <summary> + /// No lineups have been added to this account. + /// </summary> + NoLineups = 4102, + + /// <summary> + /// Could not find the requested image. /// </summary> ImageNotFound = 5000, /// <summary> - /// Maximum image downloads reached for the day. + /// Maximum image downloads reached. The counter resets at 00:00Z. /// </summary> MaxImageDownloads = 5002, /// <summary> - /// Trial specific maximum image downloads reached for the day. + /// Maximum image downloads for a trial user reached. The counter resets at 00:00Z. /// </summary> MaxImageDownloadsTrial = 5003, /// <summary> - /// Maximum schedule/metadata requests reached for the day. + /// Exceeded the maximum number of invalid image URIs in 24 hours. The application is + /// requesting URIs which do not exist and the account is about to be blocked. + /// </summary> + MaxInvalidImages = 5004, + + /// <summary> + /// The requested programID does not exist. Permanent failure, do not ask again. + /// </summary> + InvalidProgramId = 6000, + + /// <summary> + /// The requested programID is queued for generation at the server. Soft failure, retry later. + /// </summary> + ProgramQueued = 6001, + + /// <summary> + /// The requested schedule should be available but was not found. + /// </summary> + ScheduleNotFound = 7000, + + /// <summary> + /// The server cannot determine whether the requested schedule is valid; the user has to open + /// a support ticket. + /// </summary> + InvalidScheduleRequest = 7010, + + /// <summary> + /// The requested date is outside the range the server holds for that station. + /// </summary> + ScheduleRangeExceeded = 7020, + + /// <summary> + /// The requested schedule is not in any of the configured lineups. + /// </summary> + ScheduleNotInLineup = 7030, + + /// <summary> + /// The schedule is queued for generation and is not ready yet. The client must wait until the + /// retryTime carried by the response before asking for it again. + /// </summary> + ScheduleQueued = 7100, + + /// <summary> + /// Unknown error; the user has to open a support ticket. /// </summary> - MaxInvalidImages = 5004 + UnknownError = 9999 } diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/StatusAccountDto.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/StatusAccountDto.cs new file mode 100644 index 0000000000..fca28e0511 --- /dev/null +++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/StatusAccountDto.cs @@ -0,0 +1,22 @@ +using System; +using System.Text.Json.Serialization; + +namespace Jellyfin.LiveTv.Listings.SchedulesDirectDtos; + +/// <summary> +/// The account block of the /status response. +/// </summary> +public class StatusAccountDto +{ + /// <summary> + /// Gets or sets the time the subscription expires. + /// </summary> + [JsonPropertyName("expires")] + public DateTime? Expires { get; set; } + + /// <summary> + /// Gets or sets the maximum number of lineups the account may hold. + /// </summary> + [JsonPropertyName("maxLineups")] + public int? MaxLineups { get; set; } +} diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/StatusDto.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/StatusDto.cs new file mode 100644 index 0000000000..ce6b2ccc22 --- /dev/null +++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/StatusDto.cs @@ -0,0 +1,35 @@ +using System.Collections.Generic; +using System.Text.Json.Serialization; + +namespace Jellyfin.LiveTv.Listings.SchedulesDirectDtos; + +/// <summary> +/// The /status response. +/// </summary> +public class StatusDto +{ + /// <summary> + /// Gets or sets the account details. + /// </summary> + [JsonPropertyName("account")] + public StatusAccountDto? Account { get; set; } + + /// <summary> + /// Gets or sets the lineups on the account, with the time each was last modified. + /// </summary> + [JsonPropertyName("lineups")] + public IReadOnlyList<StatusLineupDto> Lineups { get; set; } = []; + + /// <summary> + /// Gets or sets the system status entries. The spec does not define their order, so every + /// entry has to be inspected. + /// </summary> + [JsonPropertyName("systemStatus")] + public IReadOnlyList<SystemStatusDto> SystemStatus { get; set; } = []; + + /// <summary> + /// Gets or sets the response code. + /// </summary> + [JsonPropertyName("code")] + public int Code { get; set; } +} diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/StatusLineupDto.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/StatusLineupDto.cs new file mode 100644 index 0000000000..9a3559e406 --- /dev/null +++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/StatusLineupDto.cs @@ -0,0 +1,35 @@ +using System; +using System.Text.Json.Serialization; + +namespace Jellyfin.LiveTv.Listings.SchedulesDirectDtos; + +/// <summary> +/// One lineup entry of the /status response. +/// </summary> +public class StatusLineupDto +{ + /// <summary> + /// Gets or sets the lineup id. + /// </summary> + [JsonPropertyName("lineup")] + public string? Lineup { get; set; } + + /// <summary> + /// Gets or sets the lineup id as reported for deleted lineups, which use a different name. + /// </summary> + [JsonPropertyName("ID")] + public string? Id { get; set; } + + /// <summary> + /// Gets or sets the time the lineup was last modified. A client only has to download the + /// lineup again when this is newer than the copy it holds. + /// </summary> + [JsonPropertyName("modified")] + public DateTime? Modified { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether the lineup has been deleted at the headend. + /// </summary> + [JsonPropertyName("isDeleted")] + public bool IsDeleted { get; set; } +} diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/SystemStatusDto.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/SystemStatusDto.cs new file mode 100644 index 0000000000..00909218f3 --- /dev/null +++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirectDtos/SystemStatusDto.cs @@ -0,0 +1,28 @@ +using System; +using System.Text.Json.Serialization; + +namespace Jellyfin.LiveTv.Listings.SchedulesDirectDtos; + +/// <summary> +/// One entry of the system status. +/// </summary> +public class SystemStatusDto +{ + /// <summary> + /// Gets or sets the time the status was posted. + /// </summary> + [JsonPropertyName("date")] + public DateTime? Date { get; set; } + + /// <summary> + /// Gets or sets the status. "Offline" means the client must disconnect for an hour. + /// </summary> + [JsonPropertyName("status")] + public string? Status { get; set; } + + /// <summary> + /// Gets or sets the message describing the status. + /// </summary> + [JsonPropertyName("message")] + public string? Message { get; set; } +} diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirectLineupCache.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirectLineupCache.cs new file mode 100644 index 0000000000..a24961f0aa --- /dev/null +++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirectLineupCache.cs @@ -0,0 +1,117 @@ +using System; +using System.Globalization; +using System.IO; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Jellyfin.Extensions.Json; +using Jellyfin.LiveTv.Listings.SchedulesDirectDtos; +using MediaBrowser.Common.Configuration; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.LiveTv.Listings; + +/// <summary> +/// Caches a lineup's channel map, keyed by the "modified" date Schedules Direct reports for it. +/// </summary> +/// <remarks> +/// The spec's steady-state flow is to compare the lineup's modified date in /status against the +/// copy the client holds and only download the lineup again when the server's is newer. +/// </remarks> +public class SchedulesDirectLineupCache +{ + private readonly ILogger _logger; + private readonly string _cacheRoot; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; + + /// <summary> + /// Initializes a new instance of the <see cref="SchedulesDirectLineupCache"/> class. + /// </summary> + /// <param name="logger">The logger.</param> + /// <param name="appPaths">The application paths.</param> + public SchedulesDirectLineupCache(ILogger logger, IApplicationPaths appPaths) + { + _logger = logger; + _cacheRoot = Path.Combine(appPaths.CachePath, "schedulesdirect", "lineups"); + } + + /// <summary> + /// Reads the cached lineup if it was stored under the same modified date. + /// </summary> + /// <param name="lineupId">The lineup id.</param> + /// <param name="modified">The modified date Schedules Direct currently reports.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The cached lineup, or <c>null</c> when it is missing or stale.</returns> + public async Task<ChannelDto?> GetAsync(string lineupId, DateTime modified, CancellationToken cancellationToken) + { + var path = GetPath(lineupId, modified); + if (!File.Exists(path)) + { + return null; + } + + try + { + var stream = File.OpenRead(path); + await using (stream.ConfigureAwait(false)) + { + return await JsonSerializer.DeserializeAsync<ChannelDto>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false); + } + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + _logger.LogDebug(ex, "Discarding unreadable Schedules Direct lineup cache entry {Path}", path); + return null; + } + } + + /// <summary> + /// Stores a freshly downloaded lineup and drops the copies it supersedes. + /// </summary> + /// <param name="lineupId">The lineup id.</param> + /// <param name="modified">The modified date Schedules Direct reports for it.</param> + /// <param name="lineup">The lineup to store.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>A task representing the write.</returns> + public async Task SetAsync(string lineupId, DateTime modified, ChannelDto lineup, CancellationToken cancellationToken) + { + var path = GetPath(lineupId, modified); + + try + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var stream = File.Create(path); + await using (stream.ConfigureAwait(false)) + { + await JsonSerializer.SerializeAsync(stream, lineup, _jsonOptions, cancellationToken).ConfigureAwait(false); + } + + foreach (var stale in Directory.EnumerateFiles(Path.GetDirectoryName(path)!, "*.json")) + { + if (!string.Equals(stale, path, StringComparison.Ordinal)) + { + File.Delete(stale); + } + } + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + _logger.LogWarning(ex, "Failed to cache Schedules Direct lineup {Path}", path); + } + } + + private static string GetSafeName(string value) + => string.Create(value.Length, value, (span, source) => + { + for (var i = 0; i < source.Length; i++) + { + span[i] = char.IsAsciiLetterOrDigit(source[i]) ? source[i] : '_'; + } + }); + + private string GetPath(string lineupId, DateTime modified) + => Path.Combine( + _cacheRoot, + GetSafeName(lineupId), + modified.ToUniversalTime().ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture) + ".json"); +} diff --git a/src/Jellyfin.LiveTv/Listings/SchedulesDirectScheduleCache.cs b/src/Jellyfin.LiveTv/Listings/SchedulesDirectScheduleCache.cs new file mode 100644 index 0000000000..e1a9e56cc4 --- /dev/null +++ b/src/Jellyfin.LiveTv/Listings/SchedulesDirectScheduleCache.cs @@ -0,0 +1,205 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Jellyfin.Extensions.Json; +using MediaBrowser.Common.Configuration; +using Microsoft.Extensions.Logging; + +namespace Jellyfin.LiveTv.Listings; + +/// <summary> +/// Caches one station's schedule for one day, keyed by the md5 Schedules Direct reports for it. +/// </summary> +/// <remarks> +/// The API requires clients to ask /schedules/md5 what changed and re-download only that. A day +/// whose md5 still matches needs no /schedules, /programs or /metadata/programs request at all, +/// which is what keeps a guide refresh inside the account's daily quotas. +/// </remarks> +public class SchedulesDirectScheduleCache +{ + private readonly ILogger _logger; + private readonly string _cacheRoot; + private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options; + + /// <summary> + /// Initializes a new instance of the <see cref="SchedulesDirectScheduleCache"/> class. + /// </summary> + /// <param name="logger">The logger.</param> + /// <param name="appPaths">The application paths.</param> + public SchedulesDirectScheduleCache(ILogger logger, IApplicationPaths appPaths) + { + _logger = logger; + _cacheRoot = Path.Combine(appPaths.CachePath, "schedulesdirect", "schedules"); + } + + /// <summary> + /// Reads the cached day if it was stored under the same md5. + /// </summary> + /// <param name="stationId">The station id.</param> + /// <param name="date">The date, formatted yyyy-MM-dd.</param> + /// <param name="md5">The md5 Schedules Direct currently reports, or null if unknown.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The cached entry, or <c>null</c> when it is missing or stale.</returns> + public async Task<SchedulesDirectCachedDay?> GetAsync(string stationId, string date, string? md5, CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(md5)) + { + return null; + } + + var cached = await ReadAsync(stationId, date, cancellationToken).ConfigureAwait(false); + return string.Equals(cached?.Md5, md5, StringComparison.Ordinal) ? cached : null; + } + + /// <summary> + /// Reads the cached day whatever md5 it was stored under, to stand in for a day that could not + /// be downloaded. + /// </summary> + /// <param name="stationId">The station id.</param> + /// <param name="date">The date, formatted yyyy-MM-dd.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>The cached entry, or <c>null</c> when there is none.</returns> + public Task<SchedulesDirectCachedDay?> GetLatestAsync(string stationId, string date, CancellationToken cancellationToken) + => ReadAsync(stationId, date, cancellationToken); + + /// <summary> + /// Stores a freshly downloaded day. + /// </summary> + /// <param name="stationId">The station id.</param> + /// <param name="date">The date, formatted yyyy-MM-dd.</param> + /// <param name="day">The day to store.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <returns>A task representing the write.</returns> + public async Task SetAsync(string stationId, string date, SchedulesDirectCachedDay day, CancellationToken cancellationToken) + { + if (string.IsNullOrEmpty(day.Md5)) + { + // Without an md5 there is nothing to validate the entry against later. + return; + } + + var path = GetPath(stationId, date); + + try + { + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var stream = File.Create(path); + await using (stream.ConfigureAwait(false)) + { + await JsonSerializer.SerializeAsync(stream, day, _jsonOptions, cancellationToken).ConfigureAwait(false); + } + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + _logger.LogWarning(ex, "Failed to cache Schedules Direct schedule {Path}", path); + } + } + + /// <summary> + /// Deletes cached days that are no longer requested, so the cache cannot grow without bound. + /// </summary> + /// <param name="stationId">The station id.</param> + /// <param name="keepDates">The dates to keep.</param> + public void Prune(string stationId, IEnumerable<string> keepDates) + { + var directory = Path.Combine(_cacheRoot, GetSafeName(stationId)); + if (!Directory.Exists(directory)) + { + return; + } + + var keep = new HashSet<string>(keepDates.Select(GetSafeName), StringComparer.Ordinal); + + try + { + foreach (var file in Directory.EnumerateFiles(directory, "*.json")) + { + if (!keep.Contains(Path.GetFileNameWithoutExtension(file))) + { + File.Delete(file); + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + _logger.LogDebug(ex, "Failed to prune Schedules Direct cache in {Directory}", directory); + } + } + + /// <summary> + /// Deletes entries that have not been touched for a while, so that stations which have left + /// the lineup do not keep their cache forever. + /// </summary> + /// <param name="maxAge">The age past which an untouched entry is deleted.</param> + public void PruneStale(TimeSpan maxAge) + { + if (!Directory.Exists(_cacheRoot)) + { + return; + } + + var cutoff = DateTime.UtcNow - maxAge; + + try + { + foreach (var directory in Directory.EnumerateDirectories(_cacheRoot)) + { + foreach (var file in Directory.EnumerateFiles(directory, "*.json")) + { + if (File.GetLastWriteTimeUtc(file) < cutoff) + { + File.Delete(file); + } + } + + if (!Directory.EnumerateFileSystemEntries(directory).Any()) + { + Directory.Delete(directory); + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + _logger.LogDebug(ex, "Failed to prune stale Schedules Direct cache entries in {Directory}", _cacheRoot); + } + } + + private async Task<SchedulesDirectCachedDay?> ReadAsync(string stationId, string date, CancellationToken cancellationToken) + { + var path = GetPath(stationId, date); + if (!File.Exists(path)) + { + return null; + } + + try + { + var stream = File.OpenRead(path); + await using (stream.ConfigureAwait(false)) + { + return await JsonSerializer.DeserializeAsync<SchedulesDirectCachedDay>(stream, _jsonOptions, cancellationToken).ConfigureAwait(false); + } + } + catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException) + { + _logger.LogDebug(ex, "Discarding unreadable Schedules Direct cache entry {Path}", path); + return null; + } + } + + private static string GetSafeName(string value) + => string.Create(value.Length, value, (span, source) => + { + for (var i = 0; i < source.Length; i++) + { + span[i] = char.IsAsciiLetterOrDigit(source[i]) ? source[i] : '_'; + } + }); + + private string GetPath(string stationId, string date) + => Path.Combine(_cacheRoot, GetSafeName(stationId), GetSafeName(date) + ".json"); +} diff --git a/src/Jellyfin.LiveTv/Recordings/RecordingsMetadataManager.cs b/src/Jellyfin.LiveTv/Recordings/RecordingsMetadataManager.cs index e0e5a00fb9..d9e9112fbe 100644 --- a/src/Jellyfin.LiveTv/Recordings/RecordingsMetadataManager.cs +++ b/src/Jellyfin.LiveTv/Recordings/RecordingsMetadataManager.cs @@ -30,6 +30,7 @@ public class RecordingsMetadataManager private readonly ILogger<RecordingsMetadataManager> _logger; private readonly IConfigurationManager _config; private readonly ILibraryManager _libraryManager; + private readonly ISchedulesDirectService _schedulesDirectService; /// <summary> /// Initializes a new instance of the <see cref="RecordingsMetadataManager"/> class. @@ -37,14 +38,17 @@ public class RecordingsMetadataManager /// <param name="logger">The <see cref="ILogger"/>.</param> /// <param name="config">The <see cref="IConfigurationManager"/>.</param> /// <param name="libraryManager">The <see cref="ILibraryManager"/>.</param> + /// <param name="schedulesDirectService">The <see cref="ISchedulesDirectService"/>.</param> public RecordingsMetadataManager( ILogger<RecordingsMetadataManager> logger, IConfigurationManager config, - ILibraryManager libraryManager) + ILibraryManager libraryManager, + ISchedulesDirectService schedulesDirectService) { _logger = logger; _config = config; _libraryManager = libraryManager; + _schedulesDirectService = schedulesDirectService; } /// <summary> @@ -469,7 +473,14 @@ public class RecordingsMetadataManager { if (!image.IsLocalFile) { - image = await _libraryManager.ConvertImageToLocal(program, image, 0).ConfigureAwait(false); + var localImage = await _schedulesDirectService.ConvertImageToLocal(program, image, 0).ConfigureAwait(false); + if (localImage is null) + { + _logger.LogDebug("Not saving recording image {Url}: Schedules Direct has blocked it", image.Path); + return; + } + + image = localImage; } var imageSaveFilenameWithoutExtension = image.Type switch diff --git a/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsSegmentTests.cs b/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsSegmentTests.cs new file mode 100644 index 0000000000..f6ed059260 --- /dev/null +++ b/tests/Jellyfin.Api.Tests/Controllers/DynamicHlsSegmentTests.cs @@ -0,0 +1,385 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Threading; +using System.Threading.Tasks; +using AutoFixture; +using AutoFixture.AutoMoq; +using Jellyfin.Api.Controllers; +using Jellyfin.Api.Helpers; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Controller.Streaming; +using MediaBrowser.MediaEncoding.Transcoding; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.IO; +using MediaBrowser.Model.MediaInfo; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Api.Tests.Controllers; + +public sealed class DynamicHlsSegmentTests : IAsyncLifetime +{ + private readonly DirectoryInfo _directory = Directory.CreateTempSubdirectory("jellyfin-hls-segments-"); + private readonly IFixture _fixture = new Fixture().Customize(new AutoMoqCustomization()); + private readonly List<Task<ActionResult>> _requests = []; + private readonly Audio _item = new() { Id = Guid.NewGuid() }; + private readonly TranscodeManager _manager; + private readonly TranscodingJob _job; + private string _prefix = string.Empty; + + public DynamicHlsSegmentTests() + { + var configuration = new Mock<IServerConfigurationManager>(); + configuration.Setup(x => x.GetConfiguration("encoding")) + .Returns(new EncodingOptions { TranscodingTempPath = _directory.FullName }); + configuration.SetupGet(x => x.CommonApplicationPaths).Returns(Mock.Of<IApplicationPaths>()); + _fixture.Inject(configuration.Object); + _fixture.Inject<ILoggerFactory>(NullLoggerFactory.Instance); + _fixture.Inject<ILogger<DynamicHlsController>>(NullLogger<DynamicHlsController>.Instance); + + // The API test project has no production filesystem adapter; enumeration still reads real files. + var fileSystem = new Mock<IFileSystem>(MockBehavior.Strict); + fileSystem.Setup(x => x.GetFilePaths(_directory.FullName, true)).Returns(Array.Empty<string>()); + fileSystem.Setup(x => x.GetFiles(_directory.FullName, It.IsAny<IReadOnlyList<string>>(), true, false)) + .Returns((string path, IReadOnlyList<string> extensions, bool caseSensitive, bool recursive) => + new DirectoryInfo(path).GetFiles() + .Where(file => extensions.Contains(file.Extension)) + .Select(file => new FileSystemMetadata + { + Name = file.Name, + FullName = file.FullName, + LastWriteTimeUtc = file.LastWriteTimeUtc + })); + fileSystem.Setup(x => x.GetLastWriteTimeUtc(It.IsAny<FileSystemMetadata>())) + .Returns((FileSystemMetadata file) => file.LastWriteTimeUtc); + _fixture.Inject(fileSystem.Object); + + var source = new MediaSourceInfo + { + Id = _item.Id.ToString("N"), + Path = Path.Combine(_directory.FullName, "input.aac"), + Container = "aac", + Protocol = MediaProtocol.File, + RunTimeTicks = TimeSpan.FromMinutes(2).Ticks, + MediaStreams = + [ + new MediaStream { Type = MediaStreamType.Audio, Codec = "aac", Index = 0, Channels = 2, SampleRate = 48000, BitRate = 128000 } + ] + }; + var library = new Mock<ILibraryManager>(); + library.Setup(x => x.GetItemById<BaseItem>(_item.Id)).Returns(_item); + _fixture.Inject(library.Object); + var sources = new Mock<IMediaSourceManager>(); + sources.Setup(x => x.GetPlaybackMediaSources(_item, null, false, false, It.IsAny<CancellationToken>())) + .ReturnsAsync(new[] { source }); + _fixture.Inject(sources.Object); + _fixture.Inject(_fixture.Create<EncodingHelper>()); + _manager = _fixture.Create<TranscodeManager>(); + _fixture.Inject<ITranscodeManager>(_manager); + _job = new TranscodingJob(NullLogger<TranscodingJob>.Instance) + { + Type = TranscodingJobType.Hls, + PlaySessionId = "session", + MediaSource = source, + CancellationTokenSource = new CancellationTokenSource() + }; + } + + public async ValueTask InitializeAsync() + { + using var state = await StreamingHelpers.GetStreamingState( + new StreamingRequestDto + { + Id = _item.Id, + Container = "mp4", + SegmentContainer = "mp4", + AudioCodec = "aac", + SegmentLength = 6, + DeviceId = "device", + PlaySessionId = "session" + }, + Context(9, TestContext.Current.CancellationToken), + _fixture.Create<IMediaSourceManager>(), + _fixture.Create<IUserManager>(), + _fixture.Create<ILibraryManager>(), + _fixture.Create<IServerConfigurationManager>(), + _fixture.Create<IMediaEncoder>(), + _fixture.Create<EncodingHelper>(), + _manager, + TranscodingJobType.Hls, + TestContext.Current.CancellationToken); + _job.Path = Path.ChangeExtension(state.OutputFilePath, ".m3u8"); + _prefix = Path.Combine(_directory.FullName, Path.GetFileNameWithoutExtension(_job.Path)); + await WriteSegment(9); + await WriteSegment(10); + File.SetLastWriteTimeUtc(SegmentPath(9), DateTime.UtcNow.AddSeconds(-2)); + + // Registration is private and otherwise starts FFmpeg; only controlled job seeding uses reflection. + var activeJobs = (List<TranscodingJob>)typeof(TranscodeManager) + .GetField("_activeTranscodingJobs", BindingFlags.Instance | BindingFlags.NonPublic)! + .GetValue(_manager)!; + activeJobs.Add(_job); + } + + [Fact] + public async Task ReadySegment_DoesNotWaitForLaterSegmentReadiness() + { + var later = Request(10, TestContext.Current.CancellationToken); + Assert.Equal(1, _job.ActiveRequestCount); + + var ready = Request(9, TestContext.Current.CancellationToken); + AssertSegment(9, await AwaitResult(ready.Result)); + Assert.False(later.Result.IsCompleted); + Assert.Equal(2, _job.ActiveRequestCount); + await ready.Complete(); + Assert.Equal(1, _job.ActiveRequestCount); + + await WriteSegment(11); + AssertSegment(10, await AwaitResult(later.Result)); + await later.Complete(); + Assert.Equal(0, _job.ActiveRequestCount); + } + + [Fact] + public async Task CancelReadinessWait_ReleasesRequestWithoutCancelingSharedJob() + { + using var abort = new CancellationTokenSource(); + var request = Request(10, abort.Token); + Assert.Equal(1, _job.ActiveRequestCount); + + await abort.CancelAsync(); + + await Assert.ThrowsAnyAsync<OperationCanceledException>(() => AwaitResult(request.Result)); + Assert.Equal(0, _job.ActiveRequestCount); + Assert.False(_job.HasExited); + Assert.False(_job.CancellationTokenSource!.IsCancellationRequested); + var ready = Request(9, TestContext.Current.CancellationToken); + AssertSegment(9, await AwaitResult(ready.Result)); + await ready.Complete(); + Assert.Equal(0, _job.ActiveRequestCount); + } + + [Fact] + public async Task CancelPlaylistLockWait_DoesNotRegisterRequest() + { + using var abort = new CancellationTokenSource(); + using (await _manager.LockAsync(_job.Path!, TestContext.Current.CancellationToken)) + { + var request = Request(9, abort.Token); + Assert.Equal(0, _job.ActiveRequestCount); + await abort.CancelAsync(); + await Assert.ThrowsAnyAsync<OperationCanceledException>(() => AwaitResult(request.Result)); + } + + Assert.Equal(0, _job.ActiveRequestCount); + Assert.False(_job.CancellationTokenSource!.IsCancellationRequested); + } + + [Fact] + public async Task ResponseRegistrationFailure_ReleasesRequest() + { + var request = Request(9, TestContext.Current.CancellationToken, failResponseRegistration: true); + + await Assert.ThrowsAsync<InvalidOperationException>(() => AwaitResult(request.Result)); + + Assert.Equal(0, _job.ActiveRequestCount); + Assert.False(_job.CancellationTokenSource!.IsCancellationRequested); + } + + [Fact] + public async Task CancelReplacementWait_PreservesActiveReader() + { + var reader = Request(9, TestContext.Current.CancellationToken); + AssertSegment(9, await AwaitResult(reader.Result)); + using var abort = new CancellationTokenSource(); + var replacement = Request(8, abort.Token); + Assert.False(replacement.Result.IsCompleted); + + await abort.CancelAsync(); + + await Assert.ThrowsAnyAsync<OperationCanceledException>(() => AwaitResult(replacement.Result)); + Assert.Equal(1, _job.ActiveRequestCount); + Assert.Same(_job, _manager.GetTranscodingJob(_job.Path!, TranscodingJobType.Hls)); + Assert.False(_job.CancellationTokenSource!.IsCancellationRequested); + await reader.Complete(); + Assert.Equal(0, _job.ActiveRequestCount); + } + + [Theory] + [InlineData(8)] + [InlineData(-1)] + public async Task ReplacementWait_AllowsReadersAndRechecksSegmentAfterTheyFinish(int segment) + { + var first = Request(9, TestContext.Current.CancellationToken); + AssertSegment(9, await AwaitResult(first.Result)); + var replacement = Request(segment, TestContext.Current.CancellationToken); + Assert.False(replacement.Result.IsCompleted); + Assert.Equal(1, _job.ActiveRequestCount); + Assert.Same(_job, _manager.GetTranscodingJob(_job.Path!, TranscodingJobType.Hls)); + + var second = Request(9, TestContext.Current.CancellationToken); + AssertSegment(9, await AwaitResult(second.Result)); + Assert.Equal(2, _job.ActiveRequestCount); + await first.Complete(); + Assert.False(replacement.Result.IsCompleted); + Assert.Equal(1, _job.ActiveRequestCount); + + await WriteSegment(segment); + File.SetLastWriteTimeUtc(SegmentPath(segment), DateTime.UtcNow.AddSeconds(-2)); + await second.Complete(); + AssertSegment(segment, await AwaitResult(replacement.Result)); + Assert.False(_job.CancellationTokenSource!.IsCancellationRequested); + Assert.Equal(1, _job.ActiveRequestCount); + await replacement.Complete(); + Assert.Equal(0, _job.ActiveRequestCount); + } + + [Fact] + public async Task CompletedJob_ServesLastSegmentWithoutNextFile() + { + _job.HasExited = true; + var request = Request(10, TestContext.Current.CancellationToken); + + AssertSegment(10, await AwaitResult(request.Result)); + + Assert.Equal(1, _job.ActiveRequestCount); + await request.Complete(); + Assert.Equal(0, _job.ActiveRequestCount); + } + + public async ValueTask DisposeAsync() + { + _job.HasExited = true; + _job.ActiveRequestCount = 0; + try + { + await Task.WhenAll(_requests.Where(task => !task.IsCompleted)).WaitAsync(TimeSpan.FromSeconds(10), CancellationToken.None); + } + finally + { + _job.Dispose(); + _manager.Dispose(); + _directory.Delete(true); + } + } + + // Deadlock guard only: tests assert ordering and ownership, not elapsed time. + private static Task<ActionResult> AwaitResult(Task<ActionResult> task) + => task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + + private static async Task CompleteAll(List<Func<Task>> completions) + { + foreach (var callback in completions) + { + await callback(); + } + } + + private string SegmentPath(int segment) => _prefix + segment.ToString(CultureInfo.InvariantCulture) + ".mp4"; + + private Task WriteSegment(int segment) + => File.WriteAllTextAsync(SegmentPath(segment), "controlled segment", TestContext.Current.CancellationToken); + + private void AssertSegment(int segment, ActionResult result) + => Assert.Equal(SegmentPath(segment), Assert.IsType<PhysicalFileResult>(result).FileName); + + private DefaultHttpContext Context(int segment, CancellationToken token) + { + var context = new DefaultHttpContext { RequestAborted = token }; + context.Request.Path = $"/Audio/{_item.Id}/hls1/main/{segment}.mp4"; + context.Request.Headers.UserAgent = "hls-segment-test"; + return context; + } + + private (Task<ActionResult> Result, Func<Task> Complete) Request(int segment, CancellationToken token, bool failResponseRegistration = false) + { + var completions = new List<Func<Task>>(); + var response = new Mock<IHttpResponseFeature>(); + response.Setup(x => x.OnCompleted(It.IsAny<Func<object, Task>>(), It.IsAny<object>())) + .Callback((Func<object, Task> callback, object state) => + { + if (failResponseRegistration) + { + throw new InvalidOperationException("Response registration failed"); + } + + completions.Add(() => callback(state)); + }); + var context = Context(segment, token); + context.Features.Set(response.Object); + var controller = _fixture.Build<DynamicHlsController>().OmitAutoProperties().Create(); + controller.ControllerContext = new ControllerContext { HttpContext = context }; + var task = controller.GetHlsAudioSegment( + itemId: _item.Id, + playlistId: "main", + segmentId: segment, + container: "mp4", + runtimeTicks: TimeSpan.FromSeconds(segment * 6).Ticks, + actualSegmentLengthTicks: TimeSpan.FromSeconds(6).Ticks, + @static: null, + @params: null, + tag: null, + deviceProfileId: null, + playSessionId: "session", + segmentContainer: "mp4", + segmentLength: 6, + minSegments: null, + mediaSourceId: null, + deviceId: "device", + audioCodec: "aac", + enableAutoStreamCopy: null, + allowVideoStreamCopy: null, + allowAudioStreamCopy: null, + audioSampleRate: null, + maxAudioBitDepth: null, + maxStreamingBitrate: null, + audioBitRate: null, + audioChannels: null, + maxAudioChannels: null, + profile: null, + level: null, + framerate: null, + maxFramerate: null, + copyTimestamps: null, + startTimeTicks: null, + width: null, + height: null, + videoBitRate: null, + subtitleStreamIndex: null, + subtitleMethod: null, + maxRefFrames: null, + maxVideoBitDepth: null, + requireAvc: null, + deInterlace: null, + requireNonAnamorphic: null, + transcodingMaxAudioChannels: null, + cpuCoreLimit: null, + liveStreamId: null, + enableMpegtsM2TsMode: null, + videoCodec: null, + subtitleCodec: null, + transcodeReasons: null, + audioStreamIndex: null, + videoStreamIndex: null, + context: null, + streamOptions: new Dictionary<string, string>()); + _requests.Add(task); + return (task, () => CompleteAll(completions)); + } +} diff --git a/tests/Jellyfin.Api.Tests/Helpers/HlsHelpersTests.cs b/tests/Jellyfin.Api.Tests/Helpers/HlsHelpersTests.cs new file mode 100644 index 0000000000..e25a1a853a --- /dev/null +++ b/tests/Jellyfin.Api.Tests/Helpers/HlsHelpersTests.cs @@ -0,0 +1,111 @@ +using System; +using System.ComponentModel; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Jellyfin.Api.Helpers; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Controller.Streaming; +using MediaBrowser.Model.Dto; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Win32.SafeHandles; +using Moq; +using Xunit; + +namespace Jellyfin.Api.Tests.Helpers; + +public sealed class HlsHelpersTests : IDisposable +{ + private const string PlaylistText = "#EXTM3U\n#EXTINF:3.0,Café\nplaylist0.ts\n#EXTINF:3.0,\nplaylist1.ts\n"; + private readonly DirectoryInfo _directory = Directory.CreateTempSubdirectory(); + + private string PlaylistPath => Path.Combine(_directory.FullName, "playlist.m3u8"); + + [Fact] + public void GetLivePlaylistText_PreservesText() + { + File.WriteAllText(PlaylistPath, PlaylistText); + using var state = CreateState("ts"); + + Assert.Equal(PlaylistText, HlsHelpers.GetLivePlaylistText(PlaylistPath, state)); + } + + [Fact] + public void GetLivePlaylistText_ReadsWhileReplacementHandleIsOpen_Windows() + { + Assert.SkipUnless(OperatingSystem.IsWindows(), "Requires Windows file sharing semantics and CreateFileW."); + File.WriteAllText(PlaylistPath, "#EXTM3U\n"); + var temporaryPath = PlaylistPath + ".tmp"; + File.WriteAllText(temporaryPath, PlaylistText); + using var replacementHandle = OpenDeleteHandle(temporaryPath); + File.Move(temporaryPath, PlaylistPath, true); + using var state = CreateState("ts"); + + Assert.Equal(PlaylistText, HlsHelpers.GetLivePlaylistText(PlaylistPath, state)); + } + + [Fact] + public void GetLivePlaylistText_DoesNotShareWithInPlaceWriter_Windows() + { + Assert.SkipUnless(OperatingSystem.IsWindows(), "Requires Windows file sharing semantics."); + File.WriteAllText(PlaylistPath, PlaylistText); + using var writer = new FileStream(PlaylistPath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete); + using var state = CreateState("ts"); + + Assert.Throws<IOException>(() => HlsHelpers.GetLivePlaylistText(PlaylistPath, state)); + } + + [Fact] + public async Task WaitForMinimumSegmentCount_ReadsWhileReplacementHandleIsOpen_Windows() + { + Assert.SkipUnless(OperatingSystem.IsWindows(), "Requires Windows file sharing semantics and CreateFileW."); + await File.WriteAllTextAsync(PlaylistPath, "#EXTM3U\n", TestContext.Current.CancellationToken); + var temporaryPath = PlaylistPath + ".tmp"; + await File.WriteAllTextAsync(temporaryPath, PlaylistText, TestContext.Current.CancellationToken); + using var replacementHandle = OpenDeleteHandle(temporaryPath); + File.Move(temporaryPath, PlaylistPath, true); + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + cancellation.CancelAfter(TimeSpan.FromSeconds(10)); + + // The DELETE-access handle stays open for the entire wait; no overlap timing is required. + await HlsHelpers.WaitForMinimumSegmentCount(PlaylistPath, 2, NullLogger.Instance, cancellation.Token); + Assert.False(cancellation.IsCancellationRequested); + } + + public void Dispose() + { + _directory.Delete(true); + } + + private static StreamState CreateState(string container) + { + return new StreamState(Mock.Of<IMediaSourceManager>(), TranscodingJobType.Hls, Mock.Of<ITranscodeManager>()) + { + Request = new StreamingRequestDto { SegmentContainer = container }, + MediaSource = new MediaSourceInfo() + }; + } + + private static SafeFileHandle OpenDeleteHandle(string path) + { + // DELETE access without FILE_FLAG_DELETE_ON_CLOSE models FFmpeg's retained rename handle. + const uint DeleteAccess = 0x00010000; + const uint OpenExisting = 3; + var handle = CreateFile(path, DeleteAccess, FileShare.ReadWrite | FileShare.Delete, IntPtr.Zero, OpenExisting, 0, IntPtr.Zero); + Assert.False(handle.IsInvalid, new Win32Exception(Marshal.GetLastPInvokeError()).Message); + return handle; + } + + [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + private static extern SafeFileHandle CreateFile( + string fileName, + uint desiredAccess, + FileShare shareMode, + IntPtr securityAttributes, + uint creationDisposition, + uint flagsAndAttributes, + IntPtr templateFile); +} diff --git a/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedCollectionModelBinderTests.cs b/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedCollectionModelBinderTests.cs index e6b9acfe19..6514523cf4 100644 --- a/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedCollectionModelBinderTests.cs +++ b/tests/Jellyfin.Api.Tests/ModelBinders/CommaDelimitedCollectionModelBinderTests.cs @@ -3,8 +3,10 @@ using System.Collections.Generic; using System.Globalization; using System.Threading.Tasks; using Jellyfin.Api.ModelBinders; +using MediaBrowser.Model.Querying; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Primitives; using Moq; @@ -226,5 +228,111 @@ namespace Jellyfin.Api.Tests.ModelBinders Assert.NotNull(listResult); Assert.Single(listResult); } + + [Fact] + public async Task BindModelAsync_ItemFieldsQuery_SkipsLegacyValues() + { + var bindingContextMock = CreateBindingContext( + "fields", + typeof(ItemFields[]), + new StringValues("PremiereDate,Overview,UserData,Genres,RunTimeTicks")); + var modelBinder = new CommaDelimitedCollectionModelBinder(new NullLogger<CommaDelimitedCollectionModelBinder>()); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + + Assert.Equal( + new[] { ItemFields.Overview, ItemFields.Genres }, + (ItemFields[]?)bindingContextMock.Object.Result.Model); + } + + [Fact] + public async Task BindModelAsync_ItemFieldsQuery_ReturnsEmptyForOnlyLegacyValues() + { + var bindingContextMock = CreateBindingContext( + "fields", + typeof(ItemFields[]), + new StringValues("PremiereDate,UserData,RunTimeTicks")); + var modelBinder = new CommaDelimitedCollectionModelBinder(new NullLogger<CommaDelimitedCollectionModelBinder>()); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + + Assert.Empty((ItemFields[]?)bindingContextMock.Object.Result.Model ?? Array.Empty<ItemFields>()); + } + + [Fact] + public async Task BindModelAsync_ItemFieldsQuery_BindsCaseInsensitiveValues() + { + var bindingContextMock = CreateBindingContext("fields", typeof(ItemFields[]), new StringValues("overview,GENRES")); + var modelBinder = new CommaDelimitedCollectionModelBinder(new NullLogger<CommaDelimitedCollectionModelBinder>()); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + + Assert.Equal( + new[] { ItemFields.Overview, ItemFields.Genres }, + (ItemFields[]?)bindingContextMock.Object.Result.Model); + } + + [Fact] + public async Task BindModelAsync_ItemFieldsQuery_BindsRepeatedQueryParameters() + { + var bindingContextMock = CreateBindingContext( + "fields", + typeof(ItemFields[]), + new StringValues(new[] { "Overview", "Genres" })); + var modelBinder = new CommaDelimitedCollectionModelBinder(new NullLogger<CommaDelimitedCollectionModelBinder>()); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + + Assert.Equal( + new[] { ItemFields.Overview, ItemFields.Genres }, + (ItemFields[]?)bindingContextMock.Object.Result.Model); + } + + [Fact] + public async Task BindModelAsync_EnumArrayQuery_PreservesNumericValues() + { + var bindingContextMock = CreateBindingContext("test", typeof(TestType[]), new StringValues("0,1")); + var modelBinder = new CommaDelimitedCollectionModelBinder(new NullLogger<CommaDelimitedCollectionModelBinder>()); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + + Assert.Equal(new[] { TestType.How, TestType.Much }, (TestType[]?)bindingContextMock.Object.Result.Model); + } + + [Fact] + public async Task BindModelAsync_InvalidEnumValues_DoesNotLogExceptions() + { + var bindingContextMock = CreateBindingContext( + "fields", + typeof(ItemFields[]), + new StringValues("PremiereDate,UserData,RunTimeTicks")); + var loggerMock = new Mock<ILogger<CommaDelimitedCollectionModelBinder>>(); + var modelBinder = new CommaDelimitedCollectionModelBinder(loggerMock.Object); + + await modelBinder.BindModelAsync(bindingContextMock.Object); + + loggerMock.Verify( + logger => logger.Log( + It.IsAny<LogLevel>(), + It.IsAny<EventId>(), + It.IsAny<It.IsAnyType>(), + It.IsAny<Exception?>(), + It.IsAny<Func<It.IsAnyType, Exception?, string>>()), + Times.Never); + } + + private static Mock<ModelBindingContext> CreateBindingContext(string modelName, Type modelType, StringValues values) + { + var valueProvider = new QueryStringValueProvider( + new BindingSource(string.Empty, string.Empty, false, false), + new QueryCollection(new Dictionary<string, StringValues> { { modelName, values } }), + CultureInfo.InvariantCulture); + var bindingContextMock = new Mock<ModelBindingContext>(); + bindingContextMock.Setup(b => b.ValueProvider).Returns(valueProvider); + bindingContextMock.Setup(b => b.ModelName).Returns(modelName); + bindingContextMock.Setup(b => b.ModelType).Returns(modelType); + bindingContextMock.SetupProperty(b => b.Result); + return bindingContextMock; + } } } diff --git a/tests/Jellyfin.Controller.Tests/Entities/UserViewBuilderFilterTests.cs b/tests/Jellyfin.Controller.Tests/Entities/UserViewBuilderFilterTests.cs new file mode 100644 index 0000000000..e37aa76b22 --- /dev/null +++ b/tests/Jellyfin.Controller.Tests/Entities/UserViewBuilderFilterTests.cs @@ -0,0 +1,113 @@ +using System.Linq; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Model.Configuration; +using Moq; +using Xunit; + +namespace Jellyfin.Controller.Tests.Entities; + +public class UserViewBuilderFilterTests +{ + public UserViewBuilderFilterTests() + { + var configManager = new Mock<IServerConfigurationManager>(); + configManager.Setup(m => m.Configuration).Returns(new ServerConfiguration()); + BaseItem.ConfigurationManager = configManager.Object; + } + + private static Video CreateVideo(string name) => new Video { Name = name }; + + [Theory] + // Numeric names: NameStartsWith should match after stripping zero-padding + [InlineData("12 Years a Slave", "1", true)] + [InlineData("12 Years a Slave", "12", true)] + [InlineData("12 Years a Slave", "2", false)] + [InlineData("300", "3", true)] + [InlineData("300", "30", true)] + [InlineData("300", "0", false)] + // Alphabetic names: standard prefix match on SortName + [InlineData("Avatar", "A", true)] + [InlineData("Avatar", "a", true)] + [InlineData("Avatar", "B", false)] + [InlineData("The Matrix", "m", true)] + [InlineData("The Matrix", "t", false)] + // Mixed alpha-numeric input: handled via ModifySortChunks padding + [InlineData("Apollo 13", "apollo 13", true)] + [InlineData("Apollo 13", "apollo 2", false)] + // Edge case: "0" should only match items whose name genuinely starts with "0" + [InlineData("0", "0", true)] + [InlineData("1", "0", false)] + [InlineData("0.0MHz", "0", true)] + [InlineData("0.0MHz", "0.0", true)] + [InlineData("0.0MHz", "1", false)] + // Punctuation in the filter goes through the same replace/remove rules as sort names + [InlineData("Mr. Bean", "Mr. B", true)] + [InlineData("Spider-Man", "Spider-M", true)] + public void Filter_NameStartsWith_MatchesNumericAndAlphabeticPrefixes(string name, string nameStartsWith, bool expected) + { + var item = CreateVideo(name); + + var query = new InternalItemsQuery + { + NameStartsWith = nameStartsWith + }; + + var result = UserViewBuilder.Filter(new[] { (BaseItem)item }, null!, query, null!, null!).Any(); + + Assert.Equal(expected, result); + } + + [Fact] + public void Filter_NameStartsWith_NullOrEmpty_PassesThrough() + { + var items = new[] { (BaseItem)CreateVideo("Avatar") }; + + var queryNull = new InternalItemsQuery { NameStartsWith = null }; + var queryEmpty = new InternalItemsQuery { NameStartsWith = string.Empty }; + + Assert.True(UserViewBuilder.Filter(items, null!, queryNull, null!, null!).Any()); + Assert.True(UserViewBuilder.Filter(items, null!, queryEmpty, null!, null!).Any()); + } + + [Theory] + // Input is plain user value — padding is applied internally + [InlineData("12 Years a Slave", "12", true)] + [InlineData("12 Years a Slave", "13", false)] + [InlineData("Avatar", "a", true)] + [InlineData("Avatar", "avatar", true)] + [InlineData("Avatar", "b", false)] + public void Filter_NameStartsWithOrGreater_PadsInputBeforeComparing(string name, string nameStartsWithOrGreater, bool expected) + { + var item = CreateVideo(name); + + var query = new InternalItemsQuery + { + NameStartsWithOrGreater = nameStartsWithOrGreater + }; + + var result = UserViewBuilder.Filter(new[] { (BaseItem)item }, null!, query, null!, null!).Any(); + + Assert.Equal(expected, result); + } + + [Theory] + // Input is plain user value — padding is applied internally + [InlineData("12 Years a Slave", "13", true)] + [InlineData("12 Years a Slave", "12", false)] + [InlineData("Avatar", "b", true)] + [InlineData("Avatar", "a", false)] + public void Filter_NameLessThan_PadsInputBeforeComparing(string name, string nameLessThan, bool expected) + { + var item = CreateVideo(name); + + var query = new InternalItemsQuery + { + NameLessThan = nameLessThan + }; + + var result = UserViewBuilder.Filter(new[] { (BaseItem)item }, null!, query, null!, null!).Any(); + + Assert.Equal(expected, result); + } +} diff --git a/tests/Jellyfin.Controller.Tests/MediaEncoding/HlsPrerollTests.cs b/tests/Jellyfin.Controller.Tests/MediaEncoding/HlsPrerollTests.cs new file mode 100644 index 0000000000..10453a29ff --- /dev/null +++ b/tests/Jellyfin.Controller.Tests/MediaEncoding/HlsPrerollTests.cs @@ -0,0 +1,89 @@ +using System; +using System.Globalization; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.IO; +using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; +using Microsoft.Extensions.Configuration; +using Moq; +using Xunit; +using IConfigurationManager = MediaBrowser.Common.Configuration.IConfigurationManager; + +namespace Jellyfin.Controller.Tests.MediaEncoding; + +public class HlsPrerollTests +{ + [Theory] + [InlineData(TranscodingJobType.Hls, "copy", "aac", "mp4", "mkv", true)] + [InlineData(TranscodingJobType.Hls, "copy", "aac", "ts", "mkv", true)] + [InlineData(TranscodingJobType.Hls, "copy", "opus", "mp4", "mkv", true)] + [InlineData(TranscodingJobType.Hls, "copy", "mp3", "ts", "mkv", true)] + [InlineData(TranscodingJobType.Hls, "copy", "copy", "mp4", "mkv", false)] + [InlineData(TranscodingJobType.Hls, "libx264", "copy", "mp4", "mkv", false)] + [InlineData(TranscodingJobType.Hls, "libx264", "aac", "mp4", "mkv", false)] + [InlineData(TranscodingJobType.Progressive, "copy", "aac", "mp4", "mkv", false)] + [InlineData(TranscodingJobType.Hls, "copy", "aac", "mp4", "wtv", false)] + public void GetFastSeekCommandLineParameter_RetainsAudioPreroll( + TranscodingJobType type, + string video, + string audio, + string container, + string input, + bool retainsPreroll) + { + var state = CreateState(type); + state.OutputVideoCodec = video; + state.OutputAudioCodec = audio; + state.InputContainer = input; + state.BaseRequest.StartTimeTicks = 312_810_000L; + var args = CreateHelper().GetFastSeekCommandLineParameter(state, new EncodingOptions(), container); + Assert.Equal(retainsPreroll, args.Contains("-noaccurate_seek", StringComparison.Ordinal)); + Assert.StartsWith(type == TranscodingJobType.Hls && video == "copy" ? "-ss 00:00:31.781" : "-ss 00:00:31.281", args, StringComparison.Ordinal); + } + + [Theory] + [InlineData(false, "aac", 312_810_000L)] + [InlineData(true, "", 312_810_000L)] + [InlineData(true, "aac", 0L)] + public void GetFastSeekCommandLineParameter_WithoutAudioOrSeek_OmitsNoAccurateSeek(bool hasAudio, string audioCodec, long seekTicks) + { + var state = CreateState(); + if (!hasAudio) + { + state.AudioStream = null; + } + + state.OutputAudioCodec = audioCodec; + state.BaseRequest.StartTimeTicks = seekTicks; + var args = CreateHelper().GetFastSeekCommandLineParameter(state, new EncodingOptions(), "mp4"); + Assert.DoesNotContain("noaccurate_seek", args, StringComparison.Ordinal); + } + + private static EncodingHelper CreateHelper() + { + var encoder = new Mock<IMediaEncoder>(); + encoder.Setup(e => e.GetTimeParameter(It.IsAny<long>())) + .Returns((long ticks) => TimeSpan.FromTicks(ticks).ToString(@"hh\:mm\:ss\.fff", CultureInfo.InvariantCulture)); + encoder.SetupGet(e => e.EncoderVersion).Returns(new Version(8, 1, 3)); + return new EncodingHelper( + Mock.Of<IApplicationPaths>(), + encoder.Object, + Mock.Of<ISubtitleEncoder>(), + Mock.Of<IConfiguration>(), + Mock.Of<IConfigurationManager>(), + Mock.Of<IPathManager>()); + } + + private static EncodingJobInfo CreateState(TranscodingJobType type = TranscodingJobType.Hls) => new(type) + { + IsVideoRequest = true, + OutputVideoCodec = "copy", + OutputAudioCodec = "aac", + InputContainer = "mkv", + RunTimeTicks = TimeSpan.FromSeconds(45).Ticks, + VideoStream = new MediaStream { Codec = "h264", Type = MediaStreamType.Video, NalLengthSize = "4" }, + AudioStream = new MediaStream { Codec = "flac", Type = MediaStreamType.Audio, Channels = 1 }, + BaseRequest = new BaseEncodingJobOptions() + }; +} diff --git a/tests/Jellyfin.LiveTv.Tests/Guide/GuideManagerTests.cs b/tests/Jellyfin.LiveTv.Tests/Guide/GuideManagerTests.cs new file mode 100644 index 0000000000..a09768df86 --- /dev/null +++ b/tests/Jellyfin.LiveTv.Tests/Guide/GuideManagerTests.cs @@ -0,0 +1,95 @@ +using System; +using System.Net; +using System.Threading.Tasks; +using Jellyfin.LiveTv.Guide; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Controller.Persistence; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.LiveTv.Tests.Guide; + +public sealed class GuideManagerTests : IDisposable +{ + private const string ImageUrl = "https://json.schedulesdirect.org/20141201/image/assets/p1_b.jpg?token=abc"; + private const string ImageNotFoundBody = "{\"response\":\"IMAGE_NOT_FOUND\",\"code\":5000,\"message\":\"test\"}"; + + private readonly ILibraryManager? _previousLibraryManager = BaseItem.LibraryManager; + private readonly Mock<ILibraryManager> _libraryManager = new(); + private readonly Mock<ISchedulesDirectService> _schedulesDirect = new(); + + public GuideManagerTests() + { + // UpdateToRepositoryAsync goes through the static. + BaseItem.LibraryManager = _libraryManager.Object; + } + + public void Dispose() + { + BaseItem.LibraryManager = _previousLibraryManager!; + } + + [Fact] + public async Task PreCacheImages_ImageNotFound_ReportsTheBodyAndRemovesTheImage() + { + var program = CreateProgram(); + _schedulesDirect.Setup(s => s.CanDownloadImage(ImageUrl)).Returns(true); + _schedulesDirect.Setup(s => s.ReportImageDownloadFailure(ImageUrl, HttpStatusCode.NotFound, ImageNotFoundBody)) + .Returns(ImageDownloadFailureAction.RemoveImage); + + // ConvertImageToLocal wraps the rejection, which is the only place the SD error body survives. + _libraryManager.Setup(l => l.ConvertImageToLocal(program, It.IsAny<ItemImageInfo>(), 0, false)) + .ThrowsAsync(new InvalidOperationException( + "test", + new HttpResponseBodyException("test", HttpStatusCode.NotFound, ImageNotFoundBody))); + + await CreateGuideManager().PreCacheImages([program], DateTime.UtcNow.AddDays(GuideManager.MaxCacheDays)); + + _schedulesDirect.Verify(s => s.ReportImageDownloadFailure(ImageUrl, HttpStatusCode.NotFound, ImageNotFoundBody), Times.Once); + Assert.Empty(program.ImageInfos); + } + + [Fact] + public async Task PreCacheImages_ImageBlocked_RemovesItWithoutDownloading() + { + // A blocked url left on the program would be fetched from SD when a client displays it. + var program = CreateProgram(); + _schedulesDirect.Setup(s => s.CanDownloadImage(ImageUrl)).Returns(false); + + await CreateGuideManager().PreCacheImages([program], DateTime.UtcNow.AddDays(GuideManager.MaxCacheDays)); + + _libraryManager.Verify( + l => l.ConvertImageToLocal(It.IsAny<BaseItem>(), It.IsAny<ItemImageInfo>(), It.IsAny<int>(), It.IsAny<bool>()), + Times.Never); + Assert.Empty(program.ImageInfos); + } + + private static LiveTvProgram CreateProgram() + => new() + { + Id = Guid.NewGuid(), + Name = "Test", + EndDate = DateTime.UtcNow.AddHours(1), + ImageInfos = [new ItemImageInfo { Path = ImageUrl, Type = ImageType.Primary }] + }; + + private GuideManager CreateGuideManager() + => new( + NullLogger<GuideManager>.Instance, + Mock.Of<IConfigurationManager>(), + Mock.Of<IFileSystem>(), + Mock.Of<IItemRepository>(), + _libraryManager.Object, + Mock.Of<ILiveTvManager>(), + Mock.Of<ITunerHostManager>(), + Mock.Of<IRecordingsManager>(), + _schedulesDirect.Object, + null!); +} diff --git a/tests/Jellyfin.LiveTv.Tests/Listings/ListingsManagerTests.cs b/tests/Jellyfin.LiveTv.Tests/Listings/ListingsManagerTests.cs index 40934d9c6b..ebeacf9115 100644 --- a/tests/Jellyfin.LiveTv.Tests/Listings/ListingsManagerTests.cs +++ b/tests/Jellyfin.LiveTv.Tests/Listings/ListingsManagerTests.cs @@ -1,4 +1,8 @@ using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; using Jellyfin.LiveTv.Configuration; using Jellyfin.LiveTv.Listings; using MediaBrowser.Common.Configuration; @@ -47,4 +51,44 @@ public class ListingsManagerTests _config.GetLiveTvConfiguration().ListingProviders, p => p.Id.Equals(id, StringComparison.Ordinal)); } + + [Fact] + public async Task GetProgramsAsync_FirstProviderCannotListChannels_FallsBackToTheNext() + { + // Arrange + var failing = new Mock<IListingsProvider>(); + failing.SetupGet(x => x.Type).Returns("failing"); + failing.Setup(x => x.GetChannels(It.IsAny<ListingsProviderInfo>(), It.IsAny<CancellationToken>())) + .ThrowsAsync(new InvalidOperationException("offline")); + + var working = new Mock<IListingsProvider>(); + working.SetupGet(x => x.Type).Returns("working"); + working.Setup(x => x.GetChannels(It.IsAny<ListingsProviderInfo>(), It.IsAny<CancellationToken>())) + .ReturnsAsync(new List<ChannelInfo> { new() { Id = "5", Number = "5" } }); + working.Setup(x => x.GetProgramsAsync(It.IsAny<ListingsProviderInfo>(), "5", It.IsAny<DateTime>(), It.IsAny<DateTime>(), It.IsAny<CancellationToken>())) + .ReturnsAsync(new[] { new ProgramInfo { Id = "p1" } }); + + Mock.Get(_config) + .Setup(x => x.GetConfiguration(It.IsAny<string>())) + .Returns(new LiveTvOptions + { + ListingProviders = + [ + new ListingsProviderInfo { Id = "a", Type = "failing" }, + new ListingsProviderInfo { Id = "b", Type = "working" } + ] + }); + + var manager = new ListingsManager(_logger, _config, _taskManager, _tunerHostManager, [failing.Object, working.Object]); + + // Act + var programs = await manager.GetProgramsAsync( + new ChannelInfo { Id = "5", Number = "5", TunerHostId = "tuner" }, + DateTime.UtcNow, + DateTime.UtcNow.AddDays(1), + CancellationToken.None); + + // Assert + Assert.Single(programs); + } } diff --git a/tests/Jellyfin.LiveTv.Tests/Listings/SchedulesDirectLineupTests.cs b/tests/Jellyfin.LiveTv.Tests/Listings/SchedulesDirectLineupTests.cs deleted file mode 100644 index 04c7b05c3d..0000000000 --- a/tests/Jellyfin.LiveTv.Tests/Listings/SchedulesDirectLineupTests.cs +++ /dev/null @@ -1,130 +0,0 @@ -using System; -using System.IO; -using System.Net; -using System.Net.Http; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Model.LiveTv; -using Microsoft.Extensions.Logging.Abstractions; -using Moq; -using Moq.Protected; -using Xunit; -using SchedulesDirectProvider = Jellyfin.LiveTv.Listings.SchedulesDirect; - -namespace Jellyfin.LiveTv.Tests.Listings; - -public class SchedulesDirectLineupTests -{ - private const string InvalidUserResponse = "{\"response\":\"INVALID_USER\",\"code\":4003,\"message\":\"Invalid user.\",\"serverID\":\"AWS-SD-web.1\"}"; - - private static readonly ListingsProviderInfo _info = new() { Username = "user", Password = "password" }; - - [Fact] - public async Task GetLineups_ValidCredentials_ReturnsLineups() - { - var tokenResponse = await CreateSuccessfulLogin(); - using var provider = CreateProvider(tokenResponse, await GetHeadendsResponse()); - - var lineups = await provider.GetLineups(_info, "USA", "90210"); - - Assert.NotEmpty(lineups); - Assert.Contains(lineups, i => string.Equals(i.Id, "USA-OTA-90210", StringComparison.Ordinal)); - Assert.Contains(lineups, i => string.Equals(i.Name, "Antenna", StringComparison.Ordinal)); - } - - [Fact] - public async Task GetLineups_LoginFails_Throws() - { - using var provider = CreateProvider(CreateFailedLogin(), await GetHeadendsResponse()); - - // An empty lineup list is indistinguishable from "no lineups for this location", so a - // failed login has to surface as an error instead. - await Assert.ThrowsAnyAsync<Exception>(() => provider.GetLineups(_info, "USA", "90210")); - } - - [Fact] - public async Task Validate_LoginFails_Throws() - { - using var provider = CreateProvider(CreateFailedLogin(), await GetHeadendsResponse()); - - await Assert.ThrowsAnyAsync<Exception>(() => provider.Validate(_info, true, false)); - } - - [Fact] - public async Task Validate_AfterAccountError_RecoversWithoutRestart() - { - var login = CreateFailedLogin(); - using var provider = CreateProvider(login, await GetHeadendsResponse()); - - await Assert.ThrowsAnyAsync<Exception>(() => provider.GetLineups(_info, "USA", "90210")); - - // The account error disables Schedules Direct; saving the provider again is the user - // correcting their credentials, and that has to recover without a server restart. - login.Status = HttpStatusCode.OK; - login.Body = await GetTokenResponse(); - - await provider.Validate(_info, true, false); - - Assert.NotEmpty(await provider.GetLineups(_info, "USA", "90210")); - } - - private static async Task<Response> CreateSuccessfulLogin() - => new() { Status = HttpStatusCode.OK, Body = await GetTokenResponse() }; - - private static Response CreateFailedLogin() - => new() { Status = HttpStatusCode.BadRequest, Body = InvalidUserResponse }; - - private static Task<string> GetTokenResponse() - => File.ReadAllTextAsync("Test Data/SchedulesDirect/token_live_response.json", TestContext.Current.CancellationToken); - - private static Task<string> GetHeadendsResponse() - => File.ReadAllTextAsync("Test Data/SchedulesDirect/headends_response.json", TestContext.Current.CancellationToken); - - private static SchedulesDirectProvider CreateProvider(Response login, string headendsResponse) - { - var messageHandler = new Mock<HttpMessageHandler>(); - messageHandler.Protected() - .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) - .Returns<HttpRequestMessage, CancellationToken>((m, _) => - { - var path = m.RequestUri!.AbsolutePath; - if (path.EndsWith("/token", StringComparison.Ordinal)) - { - return Task.FromResult(new HttpResponseMessage(login.Status) - { - Content = new StringContent(login.Body) - }); - } - - if (path.EndsWith("/headends", StringComparison.Ordinal)) - { - return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) - { - Content = new StringContent(headendsResponse) - }); - } - - return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound)); - }); - - var httpClientFactory = new Mock<IHttpClientFactory>(); - httpClientFactory.Setup(x => x.CreateClient(It.IsAny<string>())) - .Returns(() => new HttpClient(messageHandler.Object)); - - var appPaths = new Mock<IApplicationPaths>(); - appPaths.SetupGet(x => x.CachePath).Returns(Path.GetTempPath()); - - return new SchedulesDirectProvider( - NullLogger<SchedulesDirectProvider>.Instance, - httpClientFactory.Object, - appPaths.Object); - } - - private sealed class Response - { - public HttpStatusCode Status { get; set; } - - public string Body { get; set; } = string.Empty; - } -} diff --git a/tests/Jellyfin.LiveTv.Tests/Listings/SchedulesDirectTests.cs b/tests/Jellyfin.LiveTv.Tests/Listings/SchedulesDirectTests.cs new file mode 100644 index 0000000000..51d855cf8a --- /dev/null +++ b/tests/Jellyfin.LiveTv.Tests/Listings/SchedulesDirectTests.cs @@ -0,0 +1,915 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.LiveTv; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Moq.Protected; +using Xunit; +using SchedulesDirectProvider = Jellyfin.LiveTv.Listings.SchedulesDirect; + +namespace Jellyfin.LiveTv.Tests.Listings; + +public class SchedulesDirectTests : IDisposable +{ + private const string InvalidUserResponse = "{\"response\":\"INVALID_USER\",\"code\":4003,\"message\":\"Invalid user.\",\"serverID\":\"AWS-SD-web.1\"}"; + private const string ImageUrl = "https://json.schedulesdirect.org/20141201/image/assets/p1_b.jpg?token=abc"; + + private static readonly ListingsProviderInfo _info = new() { Username = "user", Password = "password" }; + + private readonly Mock<ILibraryManager> _libraryManager = new(); + + // The daily limit files live under CachePath, so every provider needs its own directory or + // one test leaves a limit behind for the next. + private readonly string _cachePath = Path.Combine(Path.GetTempPath(), "jf-sd-" + Guid.NewGuid().ToString("N")); + + [Fact] + public async Task GetLineups_ValidCredentials_ReturnsLineups() + { + var tokenResponse = await CreateSuccessfulLogin(); + using var provider = CreateProvider(tokenResponse, await GetHeadendsResponse()); + + var lineups = await provider.GetLineups(_info, "USA", "90210"); + + Assert.NotEmpty(lineups); + Assert.Contains(lineups, i => string.Equals(i.Id, "USA-OTA-90210", StringComparison.Ordinal)); + Assert.Contains(lineups, i => string.Equals(i.Name, "Antenna", StringComparison.Ordinal)); + } + + [Fact] + public async Task GetLineups_LoginFails_Throws() + { + using var provider = CreateProvider(CreateFailedLogin(), await GetHeadendsResponse()); + + // An empty lineup list is indistinguishable from "no lineups for this location", so a + // failed login has to surface as an error instead. + await Assert.ThrowsAnyAsync<Exception>(() => provider.GetLineups(_info, "USA", "90210")); + } + + [Fact] + public async Task Validate_LoginFails_Throws() + { + using var provider = CreateProvider(CreateFailedLogin(), await GetHeadendsResponse()); + + await Assert.ThrowsAnyAsync<Exception>(() => provider.Validate(_info, true, false)); + } + + [Fact] + public async Task Validate_AfterAccountError_RecoversWithoutRestart() + { + var login = CreateFailedLogin(); + using var provider = CreateProvider(login, await GetHeadendsResponse()); + + await Assert.ThrowsAnyAsync<Exception>(() => provider.GetLineups(_info, "USA", "90210")); + + // The account error disables Schedules Direct; saving the provider again is the user + // correcting their credentials, and that has to recover without a server restart. + login.Status = HttpStatusCode.OK; + login.Body = await GetTokenResponse(); + + await provider.Validate(_info, true, false); + + Assert.NotEmpty(await provider.GetLineups(_info, "USA", "90210")); + } + + [Fact] + public async Task GetLineups_TokenRejectedWithHttp200_DisablesService() + { + // The account lockout this guards against arrived as HTTP 200 carrying code 4005. + var login = new Response + { + Status = HttpStatusCode.OK, + Body = "{\"response\":\"JSON_ACCOUNT_ACCESS_DISABLED\",\"code\":4005,\"serverID\":\"20141201.web\",\"message\":\"Access to account via JSON has been disabled.\"}" + }; + using var provider = CreateProvider(login, await GetHeadendsResponse()); + + await Assert.ThrowsAnyAsync<Exception>(() => provider.GetLineups(_info, "USA", "90210")); + + // The account error disables Schedules Direct: a retry must not reach the network again. + login.Body = await GetTokenResponse(); + await Assert.ThrowsAnyAsync<Exception>(() => provider.GetLineups(_info, "USA", "90210")); + } + + [Theory] + [InlineData(5002, "MAX_IMAGE_DOWNLOADS")] + [InlineData(5003, "MAX_IMAGE_DOWNLOADS_TRIAL")] + public async Task ReportImageDownloadFailure_ImageLimitCode_BlocksOnFirstReport(int code, string response) + { + using var provider = CreateProvider(await CreateSuccessfulLogin(), await GetHeadendsResponse()); + + var action = provider.ReportImageDownloadFailure(ImageUrl, HttpStatusCode.NotFound, ErrorBody(code, response)); + + Assert.Equal(ImageDownloadFailureAction.None, action); + Assert.False(provider.CanDownloadImage(ImageUrl)); + } + + [Fact] + public async Task ReportImageDownloadFailure_ImageNotFound_DropsUrlWithoutBlockingTheDay() + { + using var provider = CreateProvider(await CreateSuccessfulLogin(), await GetHeadendsResponse()); + + var action = provider.ReportImageDownloadFailure(ImageUrl, HttpStatusCode.NotFound, ErrorBody(5000, "IMAGE_NOT_FOUND")); + + // The spec requires that url is never requested again, but the day is not blocked and + // every other image stays downloadable. + Assert.Equal(ImageDownloadFailureAction.RemoveImage, action); + Assert.False(provider.CanDownloadImage(ImageUrl)); + Assert.True(provider.CanDownloadImage("https://json.schedulesdirect.org/20141201/image/assets/p2_b.jpg?token=abc")); + } + + [Fact] + public async Task ReportImageDownloadFailure_InvalidUriLimit_BlocksAndDropsUrl() + { + using var provider = CreateProvider(await CreateSuccessfulLogin(), await GetHeadendsResponse()); + + var action = provider.ReportImageDownloadFailure(ImageUrl, HttpStatusCode.NotFound, ErrorBody(5004, "MAX_IMAGE_INVALID_URI_ERRORS")); + + Assert.Equal(ImageDownloadFailureAction.RemoveImage, action); + Assert.False(provider.CanDownloadImage(ImageUrl)); + } + + [Theory] + [InlineData(1004, "TOKEN_MISSING")] + [InlineData(4006, "TOKEN_EXPIRED")] + public async Task ReportImageDownloadFailure_TokenCode_DoesNotBlockTheDay(int code, string response) + { + using var provider = CreateProvider(await CreateSuccessfulLogin(), await GetHeadendsResponse()); + + var action = provider.ReportImageDownloadFailure(ImageUrl, HttpStatusCode.Forbidden, ErrorBody(code, response)); + + Assert.Equal(ImageDownloadFailureAction.RemoveImage, action); + Assert.True(provider.CanDownloadImage(ImageUrl)); + } + + [Fact] + public async Task ReportImageDownloadFailure_UnreadableBody_FallsBackToFailureStreak() + { + using var provider = CreateProvider(await CreateSuccessfulLogin(), await GetHeadendsResponse()); + + for (var i = 0; i < 9; i++) + { + provider.ReportImageDownloadFailure(ImageUrl, HttpStatusCode.Forbidden, "<html>gateway error</html>"); + Assert.True(provider.CanDownloadImage(ImageUrl)); + } + + provider.ReportImageDownloadFailure(ImageUrl, HttpStatusCode.Forbidden, "<html>gateway error</html>"); + + Assert.False(provider.CanDownloadImage(ImageUrl)); + } + + [Fact] + public async Task ReportImageDownloadSuccess_ResetsUnexplainedFailureStreak() + { + using var provider = CreateProvider(await CreateSuccessfulLogin(), await GetHeadendsResponse()); + + for (var i = 0; i < 9; i++) + { + provider.ReportImageDownloadFailure(ImageUrl, HttpStatusCode.Forbidden, null); + } + + provider.ReportImageDownloadSuccess(ImageUrl); + provider.ReportImageDownloadFailure(ImageUrl, HttpStatusCode.Forbidden, null); + + Assert.True(provider.CanDownloadImage(ImageUrl)); + } + + [Fact] + public async Task ReportImageDownloadFailure_ForeignUrl_IsIgnored() + { + using var provider = CreateProvider(await CreateSuccessfulLogin(), await GetHeadendsResponse()); + + var action = provider.ReportImageDownloadFailure("https://example.com/image.jpg", HttpStatusCode.NotFound, ErrorBody(5002, "MAX_IMAGE_DOWNLOADS")); + + Assert.Equal(ImageDownloadFailureAction.None, action); + Assert.True(provider.CanDownloadImage(ImageUrl)); + Assert.True(provider.CanDownloadImage("https://example.com/image.jpg")); + } + + [Fact] + public async Task ConvertImageToLocal_Blocked_DoesNotDownload() + { + using var provider = CreateProvider(await CreateSuccessfulLogin(), await GetHeadendsResponse()); + provider.ReportImageDownloadFailure(ImageUrl, HttpStatusCode.NotFound, ErrorBody(5002, "MAX_IMAGE_DOWNLOADS")); + + var image = await provider.ConvertImageToLocal(new LiveTvProgram(), new ItemImageInfo { Path = ImageUrl, Type = ImageType.Primary }, 0); + + Assert.Null(image); + _libraryManager.Verify( + l => l.ConvertImageToLocal(It.IsAny<BaseItem>(), It.IsAny<ItemImageInfo>(), It.IsAny<int>(), It.IsAny<bool>()), + Times.Never); + } + + [Fact] + public async Task ConvertImageToLocal_ImageNotFound_StopsOfferingTheUri() + { + using var provider = CreateProvider(await CreateSuccessfulLogin(), await GetHeadendsResponse()); + + // LibraryManager wraps the rejection, which is the only place the SD error body survives. + _libraryManager.Setup(l => l.ConvertImageToLocal(It.IsAny<BaseItem>(), It.IsAny<ItemImageInfo>(), 0, true)) + .ThrowsAsync(new InvalidOperationException( + "test", + new HttpResponseBodyException("test", HttpStatusCode.NotFound, ErrorBody(5000, "IMAGE_NOT_FOUND")))); + + await Assert.ThrowsAsync<InvalidOperationException>( + () => provider.ConvertImageToLocal(new LiveTvProgram(), new ItemImageInfo { Path = ImageUrl, Type = ImageType.Primary }, 0)); + + Assert.False(provider.CanDownloadImage(ImageUrl)); + } + + [Fact] + public async Task GetProgramsAsync_UnchangedMd5_ServesSecondRefreshFromCache() + { + var server = new FakeServer(); + using var provider = CreateProvider(server); + + var first = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + Assert.NotEmpty(first); + + var schedulesAfterFirst = server.Counts["/schedules"]; + var programsAfterFirst = server.Counts.GetValueOrDefault("/programs"); + Assert.True(schedulesAfterFirst > 0); + Assert.True(programsAfterFirst > 0); + + var second = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + + // The md5 is unchanged, so only the hash check should have gone to the server. + Assert.Equal(first.Count(), second.Count()); + Assert.Equal(schedulesAfterFirst, server.Counts["/schedules"]); + Assert.Equal(programsAfterFirst, server.Counts.GetValueOrDefault("/programs")); + Assert.Equal(2, server.Counts["/schedules/md5"]); + } + + [Fact] + public async Task GetProgramsAsync_ChangedMd5_DownloadsTheScheduleAgain() + { + var server = new FakeServer(); + using var provider = CreateProvider(server); + + await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + var afterFirst = server.Counts["/schedules"]; + + server.Md5Salt = "changed"; + await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + + Assert.True(server.Counts["/schedules"] > afterFirst); + } + + [Fact] + public async Task GetProgramsAsync_SystemOffline_ThrowsInsteadOfReportingNoPrograms() + { + var server = new FakeServer { SystemStatus = "Offline" }; + using var provider = CreateProvider(server); + + // An empty list means "this channel has no programs", and the guide refresh acts on that + // by deleting the ones it already has. A failure has to surface as one. + await Assert.ThrowsAnyAsync<Exception>( + () => provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken)); + + Assert.Equal(0, server.Counts.GetValueOrDefault("/schedules")); + } + + [Fact] + public async Task GetProgramsAsync_OfflineCodeWithHttp200_ThrowsInsteadOfReportingNoPrograms() + { + // A 200 carrying an error code used to deserialize into an empty status that read as online. + var server = new FakeServer { StatusCode = 3000 }; + using var provider = CreateProvider(server); + + await Assert.ThrowsAnyAsync<Exception>( + () => provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken)); + + Assert.Equal(0, server.Counts.GetValueOrDefault("/schedules")); + } + + [Fact] + public async Task GetProgramsAsync_ImageLimitHit_StillReturnsPrograms() + { + // The image limit must not be mistaken for a fetch failure: the listings are still good, + // only the artwork is unavailable. + var server = new FakeServer { HasImageArtwork = true }; + using var provider = CreateProvider(server); + + provider.ReportImageDownloadFailure(ImageUrl, HttpStatusCode.NotFound, ErrorBody(5002, "MAX_IMAGE_DOWNLOADS")); + Assert.False(provider.CanDownloadImage(ImageUrl)); + + var programs = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + + Assert.NotEmpty(programs); + Assert.All(programs, p => Assert.Null(p.ImageUrl)); + Assert.Equal(0, server.Counts.GetValueOrDefault("/metadata/programs")); + } + + [Fact] + public async Task GetProgramsAsync_Md5SaysDateIsOutOfRange_DoesNotRequestTheSchedule() + { + // 7020 is what the hash check exists to catch: asking /schedules for the day anyway just + // earns the same error, which is why the spec points at the md5 endpoint for the range. + var server = new FakeServer { Md5ErrorCode = 7020 }; + using var provider = CreateProvider(server); + + var programs = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + + Assert.Empty(programs); + Assert.Equal(1, server.Counts["/schedules/md5"]); + Assert.Equal(0, server.Counts.GetValueOrDefault("/schedules")); + } + + [Fact] + public async Task GetProgramsAsync_ScheduleQueued_HonoursRetryTime() + { + // The queued response is a bare object rather than the usual array, and it carries the + // earliest time the schedule may be asked for again. + var server = new FakeServer { ScheduleRetryTime = DateTime.UtcNow.AddMinutes(10) }; + using var provider = CreateProvider(server); + + // A queued schedule is a failure, not an empty channel: reporting no programs would have + // the guide refresh delete the ones this channel already has. + await Assert.ThrowsAnyAsync<Exception>( + () => provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken)); + var afterFirst = server.Counts["/schedules"]; + + await Assert.ThrowsAnyAsync<Exception>( + () => provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken)); + + Assert.Equal(afterFirst, server.Counts["/schedules"]); + } + + [Fact] + public async Task GetProgramsAsync_ScheduleQueuedRetryTimePassed_AsksAgain() + { + var server = new FakeServer { ScheduleRetryTime = DateTime.UtcNow.AddSeconds(-1) }; + using var provider = CreateProvider(server); + + await Assert.ThrowsAnyAsync<Exception>( + () => provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken)); + var afterFirst = server.Counts["/schedules"]; + + await Assert.ThrowsAnyAsync<Exception>( + () => provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken)); + + Assert.True(server.Counts["/schedules"] > afterFirst); + } + + [Fact] + public async Task GetProgramsAsync_CacheHit_StillRefreshesArtwork() + { + // Artwork uris are ephemeral and their changes are not reflected in the schedule md5, so + // the spec forbids storing them; the index has to be requested again on a cache hit. + var server = new FakeServer { HasImageArtwork = true }; + using var provider = CreateProvider(server); + + var first = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + Assert.All(first, p => Assert.Contains("p1_b.jpg", p.ImageUrl, StringComparison.Ordinal)); + + var metadataAfterFirst = server.Counts["/metadata/programs"]; + + var second = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + + Assert.Equal(1, server.Counts["/schedules"]); + Assert.True(server.Counts["/metadata/programs"] > metadataAfterFirst); + Assert.All(second, p => Assert.Contains("p1_b.jpg", p.ImageUrl, StringComparison.Ordinal)); + } + + [Fact] + public async Task GetProgramsAsync_AfterImageNotFound_StopsOfferingTheUri() + { + var server = new FakeServer { HasImageArtwork = true }; + using var provider = CreateProvider(server); + + var first = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + var imageUrl = first.First().ImageUrl; + Assert.NotNull(imageUrl); + + Assert.Equal( + ImageDownloadFailureAction.RemoveImage, + provider.ReportImageDownloadFailure(imageUrl, HttpStatusCode.NotFound, ErrorBody(5000, "IMAGE_NOT_FOUND"))); + + // Handing the same dead uri back every refresh is what walks an account into + // MAX_IMAGE_INVALID_URI_ERRORS, so it must not survive the rejection. + var second = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + + Assert.All(second, p => Assert.Null(p.ImageUrl)); + } + + [Fact] + public async Task GetProgramsAsync_OneDayQueuedNextToCachedDays_ServesThePreviousCopy() + { + var server = new FakeServer(); + using var provider = CreateProvider(server); + + var first = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + + // One day changed and is now queued; the others still match the cache. Leaving the queued + // day out would have the guide refresh delete its programs. + server.ChangedDate = server.RequestedDates[0]; + server.ScheduleRetryTime = DateTime.UtcNow.AddMinutes(10); + var second = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + + Assert.Equal(2, server.Counts["/schedules"]); + Assert.Equal(first.Select(p => p.Id).Order(), second.Select(p => p.Id).Order()); + } + + [Fact] + public async Task GetProgramsAsync_ProgramQueued_DoesNotCacheTheIncompleteDay() + { + var server = new FakeServer { ProgramErrorCode = 6001 }; + using var provider = CreateProvider(server); + + // With no previous copy to stand in, a queued program fails the channel rather than + // dropping its airings, which the guide refresh would delete. + await Assert.ThrowsAnyAsync<Exception>( + () => provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken)); + + // The program finishing generation need not change the day's md5, so the day must be + // downloaded again rather than served from the cache without it. + server.ProgramErrorCode = 0; + var second = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + + Assert.NotEmpty(second); + Assert.Equal(2, server.Counts["/programs"]); + } + + [Theory] + [InlineData(null)] + [InlineData("EP000000020001")] + public async Task GetProgramsAsync_ProgramQueuedAfterGoodRefresh_KeepsItsAirings(string? queuedProgramId) + { + var server = new FakeServer { SecondProgram = true }; + using var provider = CreateProvider(server); + + var first = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + Assert.Contains(first, p => p.Id!.Contains("EP000000020001", StringComparison.Ordinal)); + + // The day changed and one (or every) program on it is still being generated. + server.Md5Salt = "changed"; + server.ProgramErrorCode = 6001; + server.QueuedProgramId = queuedProgramId; + var second = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + + Assert.Equal(first.Select(p => p.Id).Order(), second.Select(p => p.Id).Order()); + } + + [Theory] + [InlineData(HttpStatusCode.OK, 3000, "SERVICE_OFFLINE")] + [InlineData(HttpStatusCode.Forbidden, 4009, "TOO_MANY_LOGINS")] + public async Task GetProgramsAsync_StopCodeOnMd5_DoesNotRequestSchedules(HttpStatusCode status, int code, string response) + { + var server = new FakeServer { Md5RejectionBody = ErrorBody(code, response), Md5RejectionStatus = status }; + using var provider = CreateProvider(server); + + await Assert.ThrowsAnyAsync<Exception>( + () => provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken)); + + Assert.Equal(0, server.Counts.GetValueOrDefault("/schedules")); + } + + [Theory] + [InlineData(1004, "TOKEN_MISSING")] + [InlineData(1010, "INVALID_TOKEN")] + public async Task GetProgramsAsync_TokenRejected_LogsInAgain(int code, string response) + { + var server = new FakeServer { Md5RejectionBody = ErrorBody(code, response) }; + using var provider = CreateProvider(server); + + var programs = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + + Assert.NotEmpty(programs); + Assert.Equal(2, server.Counts["/token"]); + } + + [Fact] + public async Task GetProgramsAsync_ServiceOffline_DoesNotLogInAgainDuringTheOfflineHour() + { + var server = new FakeServer { StatusCode = 3000 }; + using var provider = CreateProvider(server); + + for (var i = 0; i < 3; i++) + { + await Assert.ThrowsAnyAsync<Exception>( + () => provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken)); + } + + // MAX_LOGIN_ATTEMPTS counts logins, so each channel of a refresh must not log in again. + Assert.Equal(1, server.Counts["/token"]); + } + + [Fact] + public async Task GetProgramsAsync_AfterImageNotFoundAndRestart_StopsOfferingTheUri() + { + var server = new FakeServer { HasImageArtwork = true }; + + using (var provider = CreateProvider(server)) + { + var first = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + provider.ReportImageDownloadFailure(first.First().ImageUrl!, HttpStatusCode.NotFound, ErrorBody(5000, "IMAGE_NOT_FOUND")); + } + + // A second provider over the same cache directory stands in for a restart. + using (var provider = CreateProvider(server)) + { + var second = await provider.GetProgramsAsync(_info, "20454", DateTime.UtcNow, DateTime.UtcNow.AddDays(1), TestContext.Current.CancellationToken); + Assert.All(second, p => Assert.Null(p.ImageUrl)); + } + } + + [Theory] + [InlineData(HttpStatusCode.Forbidden, 4009, "TOO_MANY_LOGINS")] + [InlineData(HttpStatusCode.OK, 4009, "TOO_MANY_LOGINS")] + [InlineData(HttpStatusCode.Forbidden, 4010, "TOO_MANY_UNIQUE_IPS")] + public async Task GetLineups_AccountLimitReached_StopsLoggingIn(HttpStatusCode status, int code, string response) + { + var login = new Response + { + Status = status, + Body = ErrorBody(code, response) + }; + using var provider = CreateProvider(login, await GetHeadendsResponse()); + + await Assert.ThrowsAnyAsync<Exception>(() => provider.GetLineups(_info, "USA", "90210")); + + // These codes count logins, so continuing to ask for a token is what earned them: a + // retry must not go back to /token even once the credentials would work. + login.Status = HttpStatusCode.OK; + login.Body = await GetTokenResponse(); + await Assert.ThrowsAnyAsync<Exception>(() => provider.GetLineups(_info, "USA", "90210")); + } + + [Fact] + public async Task GetChannels_SystemOffline_ThrowsInsteadOfReportingNoChannels() + { + var server = new FakeServer { SystemStatus = "Offline" }; + using var provider = CreateProvider(server); + + // No channels means no channel is mapped, which the guide refresh reads as "no programs". + await Assert.ThrowsAnyAsync<Exception>( + () => provider.GetChannels(new ListingsProviderInfo { Username = "user", Password = "password", ListingsId = "USA-OTA-90210" }, TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task GetChannels_LoginBackedOff_ThrowsInsteadOfReportingNoChannels() + { + var login = new Response { Status = HttpStatusCode.Forbidden, Body = ErrorBody(4009, "TOO_MANY_LOGINS") }; + using var provider = CreateProvider(login, await GetHeadendsResponse()); + var info = new ListingsProviderInfo { Username = "user", Password = "password", ListingsId = "USA-OTA-90210" }; + + await Assert.ThrowsAnyAsync<Exception>(() => provider.GetChannels(info, TestContext.Current.CancellationToken)); + + // The second call never reaches /token, so this is the null-token path. + await Assert.ThrowsAnyAsync<Exception>(() => provider.GetChannels(info, TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task GetChannels_UnchangedModifiedDate_ServesTheLineupFromCache() + { + var server = new FakeServer(); + using var provider = CreateProvider(server); + var info = new ListingsProviderInfo { Username = "user", Password = "password", ListingsId = "USA-OTA-90210" }; + + var first = await provider.GetChannels(info, TestContext.Current.CancellationToken); + Assert.NotEmpty(first); + Assert.Equal(1, server.Counts["/lineups/USA-OTA-90210"]); + + var second = await provider.GetChannels(info, TestContext.Current.CancellationToken); + + Assert.Equal(first.Count, second.Count); + Assert.Equal(1, server.Counts["/lineups/USA-OTA-90210"]); + } + + [Fact] + public async Task GetChannels_NewerModifiedDate_DownloadsTheLineupAgain() + { + var server = new FakeServer(); + var info = new ListingsProviderInfo { Username = "user", Password = "password", ListingsId = "USA-OTA-90210" }; + + using (var provider = CreateProvider(server)) + { + await provider.GetChannels(info, TestContext.Current.CancellationToken); + } + + server.LineupModified = server.LineupModified.AddDays(1); + + // A second provider over the same cache directory stands in for a restart, which is also + // what makes the status re-read rather than coming from its short-lived cache. + using (var provider = CreateProvider(server)) + { + await provider.GetChannels(info, TestContext.Current.CancellationToken); + } + + Assert.Equal(2, server.Counts["/lineups/USA-OTA-90210"]); + } + + [Fact] + public async Task Validate_LineupCannotBeAdded_Throws() + { + var server = new FakeServer { LineupPutStatus = HttpStatusCode.BadRequest }; + using var provider = CreateProvider(server); + + // Silently reporting success leaves the user with a provider that has no lineup. + await Assert.ThrowsAnyAsync<Exception>( + () => provider.Validate(new ListingsProviderInfo { Username = "user", Password = "password", ListingsId = "USA-OTA-90210" }, true, true)); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + if (disposing && Directory.Exists(_cachePath)) + { + Directory.Delete(_cachePath, true); + } + } + + // Schedules Direct answers an exhausted image quota with HTTP 200 and a body like this, which + // ProviderManager surfaces as a synthetic 404 because it is not an image content type. + private static string ErrorBody(int code, string response) + => string.Format( + CultureInfo.InvariantCulture, + "{{\"response\":\"{0}\",\"code\":{1},\"serverID\":\"20141201.debug\",\"message\":\"test\",\"datetime\":\"2026-09-14T00:00:00Z\"}}", + response, + code); + + private static async Task<Response> CreateSuccessfulLogin() + => new() { Status = HttpStatusCode.OK, Body = await GetTokenResponse() }; + + private static Response CreateFailedLogin() + => new() { Status = HttpStatusCode.BadRequest, Body = InvalidUserResponse }; + + private static Task<string> GetTokenResponse() + => File.ReadAllTextAsync("Test Data/SchedulesDirect/token_live_response.json", TestContext.Current.CancellationToken); + + private static Task<string> GetHeadendsResponse() + => File.ReadAllTextAsync("Test Data/SchedulesDirect/headends_response.json", TestContext.Current.CancellationToken); + + private SchedulesDirectProvider CreateProvider(Response login, string headendsResponse) + { + var messageHandler = new Mock<HttpMessageHandler>(); + messageHandler.Protected() + .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) + .Returns<HttpRequestMessage, CancellationToken>((m, _) => + { + var path = m.RequestUri!.AbsolutePath; + if (path.EndsWith("/token", StringComparison.Ordinal)) + { + return Task.FromResult(new HttpResponseMessage(login.Status) + { + Content = new StringContent(login.Body) + }); + } + + if (path.EndsWith("/headends", StringComparison.Ordinal)) + { + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(headendsResponse) + }); + } + + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound)); + }); + + var httpClientFactory = new Mock<IHttpClientFactory>(); + httpClientFactory.Setup(x => x.CreateClient(It.IsAny<string>())) + .Returns(() => new HttpClient(messageHandler.Object)); + + var appPaths = new Mock<IApplicationPaths>(); + appPaths.SetupGet(x => x.CachePath).Returns(_cachePath); + + return new SchedulesDirectProvider( + NullLogger<SchedulesDirectProvider>.Instance, + httpClientFactory.Object, + appPaths.Object, + _libraryManager.Object); + } + + private SchedulesDirectProvider CreateProvider(FakeServer server) + { + var messageHandler = new Mock<HttpMessageHandler>(); + messageHandler.Protected() + .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) + .Returns<HttpRequestMessage, CancellationToken>((m, ct) => server.Respond(m, ct)); + + var httpClientFactory = new Mock<IHttpClientFactory>(); + httpClientFactory.Setup(x => x.CreateClient(It.IsAny<string>())) + .Returns(() => new HttpClient(messageHandler.Object)); + + var appPaths = new Mock<IApplicationPaths>(); + appPaths.SetupGet(x => x.CachePath).Returns(_cachePath); + + return new SchedulesDirectProvider( + NullLogger<SchedulesDirectProvider>.Instance, + httpClientFactory.Object, + appPaths.Object, + _libraryManager.Object); + } + + /// <summary> + /// A minimal stand-in for the Schedules Direct API that counts what was asked of it. + /// </summary> + private sealed class FakeServer + { + public Dictionary<string, int> Counts { get; } = new(StringComparer.Ordinal); + + public string SystemStatus { get; set; } = "Online"; + + public int StatusCode { get; set; } + + public string Md5Salt { get; set; } = "base"; + + public HttpStatusCode LineupPutStatus { get; set; } = HttpStatusCode.OK; + + /// <summary> + /// Gets or sets a per-day error code for the hash endpoint, as SCHEDULE_RANGE_EXCEEDED is + /// reported. Zero means every day is available. + /// </summary> + public int Md5ErrorCode { get; set; } + + /// <summary> + /// Gets or sets the retryTime of a SCHEDULE_QUEUED response, which the spec documents as a + /// bare object rather than the usual array. + /// </summary> + public DateTime? ScheduleRetryTime { get; set; } + + public bool HasImageArtwork { get; set; } + + /// <summary> + /// Gets or sets a date whose schedule md5 differs from the one first reported. + /// </summary> + public string? ChangedDate { get; set; } + + public List<string> RequestedDates { get; private set; } = []; + + /// <summary> + /// Gets or sets a per-program error code for the programs endpoint, such as PROGRAMID_QUEUED. + /// </summary> + public int ProgramErrorCode { get; set; } + + /// <summary> + /// Gets or sets a body the hash endpoint rejects the next request's token with, as HTTP 403. + /// </summary> + public string? Md5RejectionBody { get; set; } + + public HttpStatusCode Md5RejectionStatus { get; set; } = HttpStatusCode.Forbidden; + + /// <summary> + /// Gets or sets a value indicating whether each day airs a second program. + /// </summary> + public bool SecondProgram { get; set; } + + /// <summary> + /// Gets or sets the only program <see cref="ProgramErrorCode"/> applies to; null means all of them. + /// </summary> + public string? QueuedProgramId { get; set; } + + public string ImageUri { get; set; } = "assets/p1_b.jpg"; + + public DateTime LineupModified { get; set; } = new(2026, 9, 14, 0, 0, 0, DateTimeKind.Utc); + + public async Task<HttpResponseMessage> Respond(HttpRequestMessage message, CancellationToken cancellationToken) + { + var path = message.RequestUri!.AbsolutePath.Replace("/20141201", string.Empty, StringComparison.Ordinal).TrimEnd('/'); + Counts[path] = Counts.GetValueOrDefault(path) + 1; + + string body; + switch (path) + { + case "/token": + body = "{\"code\":0,\"message\":\"OK\",\"serverID\":\"test\",\"token\":\"f3fca79989cafe7dead71beefedc812b\"}"; + break; + + case "/status": + body = "{\"code\":" + StatusCode.ToString(CultureInfo.InvariantCulture) + ",\"account\":{\"maxLineups\":4},\"lineups\":[{\"lineup\":\"USA-OTA-90210\",\"modified\":\"" + + LineupModified.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture) + + "\"}],\"systemStatus\":[{\"status\":\"" + SystemStatus + "\",\"message\":\"test\"}]}"; + break; + + case "/schedules/md5": + if (Md5RejectionBody is not null) + { + var rejection = Md5RejectionBody; + Md5RejectionBody = null; + return new HttpResponseMessage(Md5RejectionStatus) { Content = new StringContent(rejection) }; + } + + RequestedDates = await ReadDates(message, cancellationToken).ConfigureAwait(false); + body = BuildMd5Response(RequestedDates); + break; + + case "/schedules": + body = BuildSchedulesResponse(await ReadDates(message, cancellationToken).ConfigureAwait(false)); + break; + + case "/programs": + var ids = JsonSerializer.Deserialize<List<string>>(await message.Content!.ReadAsStringAsync(cancellationToken).ConfigureAwait(false))!; + body = "[" + string.Join(',', ids.Select(BuildProgramEntry)) + "]"; + break; + + case "/metadata/programs": + body = HasImageArtwork + ? "[{\"programID\":\"EP000000010001\",\"data\":[{\"width\":\"120\",\"height\":\"180\",\"uri\":\"" + + ImageUri + "\",\"aspect\":\"2x3\",\"category\":\"Iconic\",\"text\":\"yes\",\"tier\":\"Series\"}]}]" + : "[]"; + break; + + case "/lineups/USA-OTA-90210": + if (message.Method == HttpMethod.Get) + { + body = "{\"map\":[{\"stationID\":\"20454\",\"channel\":\"5\"}],\"stations\":[{\"stationID\":\"20454\",\"name\":\"Test\",\"callsign\":\"TST\"}]}"; + break; + } + + return new HttpResponseMessage(LineupPutStatus) + { + Content = new StringContent(LineupPutStatus == HttpStatusCode.OK + ? "{\"code\":0,\"message\":\"OK\"}" + : "{\"response\":\"MAX_LINEUPS\",\"code\":4101,\"message\":\"Exceeded number of lineups.\"}") + }; + + case "/lineups": + body = "{\"code\":0,\"lineups\":[]}"; + break; + + default: + return new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("{}") }; + } + + return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(body) }; + } + + private static async Task<List<string>> ReadDates(HttpRequestMessage message, CancellationToken cancellationToken) + { + var requestBody = await message.Content!.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + using var doc = JsonDocument.Parse(requestBody); + + var dates = new List<string>(); + foreach (var station in doc.RootElement.EnumerateArray()) + { + foreach (var date in station.GetProperty("date").EnumerateArray()) + { + dates.Add(date.GetString()!); + } + } + + return dates; + } + + private string BuildMd5Response(List<string> dates) + { + var days = dates.ConvertAll(d => Md5ErrorCode == 0 + ? "\"" + d + "\":{\"code\":0,\"message\":\"OK\",\"lastModified\":\"2026-09-14T00:00:00Z\",\"md5\":\"" + GetMd5(d) + "\"}" + : "\"" + d + "\":{\"code\":" + Md5ErrorCode.ToString(CultureInfo.InvariantCulture) + ",\"message\":\"Date requested not within range.\"}"); + + return "{\"20454\":{" + string.Join(',', days) + "}}"; + } + + private string GetMd5(string date) + => (string.Equals(date, ChangedDate, StringComparison.Ordinal) ? "changed" : Md5Salt) + date; + + private string BuildProgramEntry(string id) + => ProgramErrorCode != 0 && (QueuedProgramId is null || string.Equals(id, QueuedProgramId, StringComparison.Ordinal)) + ? "{\"programID\":\"" + id + "\",\"code\":" + ProgramErrorCode.ToString(CultureInfo.InvariantCulture) + ",\"message\":\"test\"}" + : "{\"programID\":\"" + id + "\",\"titles\":[{\"title120\":\"Test\"}],\"hasImageArtwork\":" + + (HasImageArtwork ? "true" : "false") + "}"; + + private string BuildSchedulesResponse(List<string> dates) + { + if (ScheduleRetryTime is { } retryTime) + { + return "{\"response\":\"SCHEDULE_QUEUED\",\"code\":7100,\"serverID\":\"test\",\"message\":\"Queued.\",\"stationID\":\"20454\",\"retryTime\":\"" + + retryTime.ToString("yyyy-MM-ddTHH:mm:ssZ", CultureInfo.InvariantCulture) + "\"}"; + } + + var days = dates.ConvertAll(d => + "{\"stationID\":\"20454\",\"programs\":[{\"programID\":\"EP000000010001\",\"airDateTime\":\"" + d + + "T12:00:00Z\",\"duration\":1800,\"md5\":\"x\"}" + + (SecondProgram ? ",{\"programID\":\"EP000000020001\",\"airDateTime\":\"" + d + "T14:00:00Z\",\"duration\":1800,\"md5\":\"y\"}" : string.Empty) + + "],\"metadata\":{\"modified\":\"2026-09-14T00:00:00Z\",\"md5\":\"" + + GetMd5(d) + "\",\"startDate\":\"" + d + "\"}}"); + + return "[" + string.Join(',', days) + "]"; + } + } + + private sealed class Response + { + public HttpStatusCode Status { get; set; } + + public string Body { get; set; } = string.Empty; + } +} diff --git a/tests/Jellyfin.LiveTv.Tests/Recordings/RecordingsMetadataManagerTests.cs b/tests/Jellyfin.LiveTv.Tests/Recordings/RecordingsMetadataManagerTests.cs index 14ce470fb4..193f794f1d 100644 --- a/tests/Jellyfin.LiveTv.Tests/Recordings/RecordingsMetadataManagerTests.cs +++ b/tests/Jellyfin.LiveTv.Tests/Recordings/RecordingsMetadataManagerTests.cs @@ -10,6 +10,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.LiveTv; using Microsoft.Extensions.Logging.Abstractions; using Moq; @@ -19,6 +20,8 @@ namespace Jellyfin.LiveTv.Tests.Recordings; public sealed class RecordingsMetadataManagerTests { + private const string ImageUrl = "https://json.schedulesdirect.org/20141201/image/assets/p1_b.jpg?token=abc"; + private readonly string _tempDir = Path.Combine(Path.GetTempPath(), "jellyfin-test-" + Guid.NewGuid()); @@ -43,7 +46,8 @@ public sealed class RecordingsMetadataManagerTests var manager = new RecordingsMetadataManager( NullLogger<RecordingsMetadataManager>.Instance, config.Object, - libraryManager.Object); + libraryManager.Object, + Mock.Of<ISchedulesDirectService>()); var timer = new TimerInfo { Name = "Test Recording", ProgramId = null }; @@ -61,4 +65,47 @@ public sealed class RecordingsMetadataManagerTests Assert.InRange(parsed, beforeUtc, afterUtc); } + + [Fact] + public async Task SaveRecordingMetadata_RemoteImage_GoesThroughSchedulesDirect() + { + // Schedules Direct counts every image request, so a recording must not fetch one behind its back. + var (manager, libraryManager, schedulesDirect, recordingPath) = CreateImageManager(); + + await manager.SaveRecordingMetadata(new TimerInfo { Name = "Test Recording", ProgramId = "p1" }, recordingPath, null); + + schedulesDirect.Verify(s => s.ConvertImageToLocal(It.IsAny<BaseItem>(), It.Is<ItemImageInfo>(i => i.Path == ImageUrl), 0), Times.Once); + libraryManager.Verify( + l => l.ConvertImageToLocal(It.IsAny<BaseItem>(), It.IsAny<ItemImageInfo>(), It.IsAny<int>(), It.IsAny<bool>()), + Times.Never); + } + + private (RecordingsMetadataManager Manager, Mock<ILibraryManager> LibraryManager, Mock<ISchedulesDirectService> SchedulesDirect, string RecordingPath) CreateImageManager() + { + Directory.CreateDirectory(_tempDir); + var recordingPath = Path.Combine(_tempDir, "test-recording.ts"); + + var config = new Mock<IConfigurationManager>(); + config.Setup(c => c.GetConfiguration("livetv")) + .Returns(new LiveTvOptions { SaveRecordingNFO = false, SaveRecordingImages = true }); + + var program = new LiveTvProgram + { + Name = "Test", + ImageInfos = [new ItemImageInfo { Path = ImageUrl, Type = ImageType.Primary }] + }; + var libraryManager = new Mock<ILibraryManager>(); + libraryManager + .Setup(l => l.GetItemList(It.IsAny<InternalItemsQuery>())) + .Returns([program]); + + var schedulesDirect = new Mock<ISchedulesDirectService>(); + var manager = new RecordingsMetadataManager( + NullLogger<RecordingsMetadataManager>.Instance, + config.Object, + libraryManager.Object, + schedulesDirect.Object); + + return (manager, libraryManager, schedulesDirect, recordingPath); + } } diff --git a/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs index cf9930abe1..e68abf6947 100644 --- a/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs +++ b/tests/Jellyfin.MediaEncoding.Tests/Probing/ProbeResultNormalizerTests.cs @@ -291,6 +291,19 @@ namespace Jellyfin.MediaEncoding.Tests.Probing } [Fact] + public void GetMediaInfo_ContainerCreationTime_KeptOutOfPremiereDate() + { + var bytes = File.ReadAllBytes("Test Data/Probing/video_progressive_no_field_order.json"); + + var internalMediaInfoResult = JsonSerializer.Deserialize<InternalMediaInfoResult>(bytes, _jsonOptions); + MediaInfo res = _probeResultNormalizer.GetMediaInfo(internalMediaInfoResult, VideoType.VideoFile, false, "Test Data/Probing/video_progressive_no_field_order.mp4", MediaProtocol.File); + + Assert.Equal(new DateTime(2020, 1, 20, 13, 56, 34, DateTimeKind.Utc), res.ContainerCreationDate); + Assert.Null(res.PremiereDate); + Assert.Null(res.ProductionYear); + } + + [Fact] public void GetMediaInfo_ProgressiveVideoNoFieldOrder_Success() { var bytes = File.ReadAllBytes("Test Data/Probing/video_progressive_no_field_order.json"); diff --git a/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SubtitleCacheMetadataTests.cs b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SubtitleCacheMetadataTests.cs new file mode 100644 index 0000000000..f34a07da43 --- /dev/null +++ b/tests/Jellyfin.MediaEncoding.Tests/Subtitles/SubtitleCacheMetadataTests.cs @@ -0,0 +1,128 @@ +using System; +using System.Globalization; +using System.IO; +using AutoFixture; +using AutoFixture.AutoMoq; +using MediaBrowser.MediaEncoding.Subtitles; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.IO; +using Moq; +using Xunit; + +namespace Jellyfin.MediaEncoding.Subtitles.Tests; + +public sealed class SubtitleCacheMetadataTests : IDisposable +{ + private readonly string _directory = Directory.CreateTempSubdirectory("jellyfin-subtitle-metadata-").FullName; + private readonly SubtitleEncoder _encoder; + private readonly string _cachePath; + private readonly string _sourcePath; + + public SubtitleCacheMetadataTests() + { + _cachePath = Path.Combine(_directory, "3.srt"); + _sourcePath = Path.Combine(_directory, "movie.mkv"); + File.WriteAllText(_cachePath, "cached subtitle"); + File.WriteAllText(_sourcePath, "source"); + var fixture = new Fixture().Customize(new AutoMoqCustomization { ConfigureMembers = true }); + fixture.Freeze<Mock<IFileSystem>>().Setup(x => x.GetFileInfo(It.IsAny<string>())).Returns((string path) => + { + var info = new FileInfo(path); + return new FileSystemMetadata + { + Exists = info.Exists, + Length = info.Exists ? info.Length : 0, + LastWriteTimeUtc = info.LastWriteTimeUtc + }; + }); + _encoder = fixture.Create<SubtitleEncoder>(); + } + + [Fact] + public void Cache_LogicalIndexReassignedToDifferentTrack_IsRejected() + { + var source = CreateSource(); + var french = source.MediaStreams[3]; + _encoder.WriteCacheMeta(_cachePath, source, french); + + AddSidecar(source); + var english = source.MediaStreams[3]; + Assert.Equal(3, english.Index); + Assert.False(_encoder.IsCachedSubtitleFresh(_cachePath, source, english)); + Assert.True(_encoder.IsCachedSubtitleFresh(_cachePath, source, french)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Cache_SourcePathChangesWithSameRevision_IsRejected(bool remote) + { + var source = CreateSource(); + if (remote) + { + source.Path = "https://example.invalid/a.mkv"; + } + + var subtitle = source.MediaStreams[3]; + _encoder.WriteCacheMeta(_cachePath, source, subtitle); + Assert.True(_encoder.IsCachedSubtitleFresh(_cachePath, source, subtitle)); + var replacement = Path.Combine(_directory, "other.mkv"); + File.Copy(_sourcePath, replacement); + File.SetLastWriteTimeUtc(replacement, File.GetLastWriteTimeUtc(_sourcePath)); + source.Path = remote ? "https://example.invalid/b.mkv" : replacement; + Assert.False(_encoder.IsCachedSubtitleFresh(_cachePath, source, subtitle)); + } + + [Fact] + public void Cache_SourceRevisionChanges_IsRejected() + { + var source = CreateSource(); + var subtitle = source.MediaStreams[3]; + _encoder.WriteCacheMeta(_cachePath, source, subtitle); + File.AppendAllText(_sourcePath, "replacement"); + Assert.False(_encoder.IsCachedSubtitleFresh(_cachePath, source, subtitle)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Cache_LegacyOrMissingMetadata_IsRejected(bool legacy) + { + var source = CreateSource(); + if (legacy) + { + var info = new FileInfo(_sourcePath); + File.WriteAllText(_cachePath + ".meta", string.Create(CultureInfo.InvariantCulture, $"{info.Length}:{info.LastWriteTimeUtc.Ticks}")); + } + + Assert.False(_encoder.IsCachedSubtitleFresh(_cachePath, source, source.MediaStreams[3])); + } + + private MediaSourceInfo CreateSource() => new() + { + Path = _sourcePath, + MediaStreams = + [ + new() { Index = 0, Type = MediaStreamType.Video }, + new() { Index = 1, Type = MediaStreamType.Audio }, + new() { Index = 2, Type = MediaStreamType.Subtitle, Language = "eng" }, + new() { Index = 3, Type = MediaStreamType.Subtitle, Language = "fra" } + ] + }; + + private static void AddSidecar(MediaSourceInfo source) + { + source.MediaStreams = [new MediaStream { IsExternal = true, Type = MediaStreamType.Subtitle, Path = "sidecar.srt" }, .. source.MediaStreams]; + for (var i = 0; i < source.MediaStreams.Count; i++) + { + source.MediaStreams[i].Index = i; + } + } + + public void Dispose() + { + _encoder.Dispose(); + Directory.Delete(_directory, true); + } +} diff --git a/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs b/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs index f5a023686c..f5d40e3fc6 100644 --- a/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs +++ b/tests/Jellyfin.Model.Tests/Dlna/StreamBuilderTests.cs @@ -372,6 +372,39 @@ namespace Jellyfin.Model.Tests } [Theory] + // Chrome + [InlineData("Chrome", "mp4-h264-ac3-aac-aac-srt-2600k", new TranscodeReason[] { 0, TranscodeReason.AudioCodecNotSupported, TranscodeReason.SecondaryAudioNotSupported, TranscodeReason.SecondaryAudioNotSupported, 0 })] + [InlineData("Chrome", "mp4-h264-dts-srt-2600k", new TranscodeReason[] { 0, TranscodeReason.AudioCodecNotSupported, 0 })] + [InlineData("Chrome", "mkv-vp9-aac-srt-2600k", new TranscodeReason[] { TranscodeReason.ContainerNotSupported, TranscodeReason.ContainerNotSupported, 0 })] + // Firefox + [InlineData("Firefox", "mp4-h264-ac3-aac-aac-srt-2600k", new TranscodeReason[] { 0, TranscodeReason.AudioCodecNotSupported, TranscodeReason.SecondaryAudioNotSupported, TranscodeReason.SecondaryAudioNotSupported, 0 })] + [InlineData("Firefox", "mp4-h264-dts-srt-2600k", new TranscodeReason[] { 0, TranscodeReason.AudioCodecNotSupported, 0 })] + [InlineData("Firefox", "mkv-vp9-aac-srt-2600k", new TranscodeReason[] { TranscodeReason.ContainerNotSupported, TranscodeReason.ContainerNotSupported, 0 })] + // Tizen3-stereo + [InlineData("Tizen3-stereo", "mp4-h264-ac3-aac-aac-srt-2600k", new TranscodeReason[] { 0, 0, TranscodeReason.SecondaryAudioNotSupported, TranscodeReason.SecondaryAudioNotSupported, 0 })] + [InlineData("Tizen3-stereo", "mp4-h264-dts-srt-2600k", new TranscodeReason[] { 0, 0, 0 })] + [InlineData("Tizen3-stereo", "mkv-vp9-aac-srt-2600k", new TranscodeReason[] { 0, 0, 0 })] + // Tizen4-4K-5.1 + [InlineData("Tizen4-4K-5.1", "mp4-h264-ac3-aac-aac-srt-2600k", new TranscodeReason[] { 0, 0, TranscodeReason.SecondaryAudioNotSupported, TranscodeReason.SecondaryAudioNotSupported, 0 })] + [InlineData("Tizen4-4K-5.1", "mp4-h264-dts-srt-2600k", new TranscodeReason[] { 0, TranscodeReason.AudioCodecNotSupported, 0 })] + [InlineData("Tizen4-4K-5.1", "mkv-vp9-aac-srt-2600k", new TranscodeReason[] { 0, 0, 0 })] + public async Task CheckCompatibility(string deviceName, string mediaSourceName, TranscodeReason[] directPlayErrors) + { + var options = await GetMediaOptions(deviceName, mediaSourceName); + + var builder = GetStreamBuilder(); + + var streamInfo = builder.GetOptimalVideoStream(options); + Assert.NotNull(streamInfo); + + var mediaSource = options.MediaSources.First(source => source.Id == streamInfo.MediaSourceId); + Assert.NotNull(mediaSource); + + Assert.Equal(directPlayErrors.Length, mediaSource.MediaStreams.Count); + Assert.All(mediaSource.MediaStreams, (stream, i) => Assert.Equal(stream.DirectPlayErrors, directPlayErrors[i])); + } + + [Theory] [InlineData("pgssub", null)] [InlineData("vobsub", "mks")] public async Task BuildVideoItemWithSecondaryAudioAndExternalGraphicalSubtitleKeepsVideoCopy(string subtitleCodec, string? subtitleContainer) diff --git a/tests/Jellyfin.Naming.Tests/ExternalFiles/ExternalPathParserTests.cs b/tests/Jellyfin.Naming.Tests/ExternalFiles/ExternalPathParserTests.cs index 0b8b1f644b..e06ae02e2a 100644 --- a/tests/Jellyfin.Naming.Tests/ExternalFiles/ExternalPathParserTests.cs +++ b/tests/Jellyfin.Naming.Tests/ExternalFiles/ExternalPathParserTests.cs @@ -118,4 +118,23 @@ public class ExternalPathParserTests Assert.Equal(isForced, actual.IsForced); Assert.Equal(isHearingImpaired, actual.IsHearingImpaired); } + + [Theory] + // LocalizationManager lists ze before the zho code it shares with Chinese. + [InlineData("ze", "Chinese (Bilingual)", new[] { "ze", "zho", "chi" }, "zho")] + // A hyphen in the display name does not make a culture a variant. + [InlineData("el", "Greek, Modern (1453-)", new[] { "ell", "gre" }, "ell")] + [InlineData("pt-br", "pt-br", new[] { "pt-br", "por" }, "pt-br")] + public void ParseFile_Culture_StoresItsLanguageCode(string tag, string name, string[] codes, string expected) + { + var localizationManager = new Mock<ILocalizationManager>(); + localizationManager.Setup(lm => lm.FindLanguageInfo(tag)) + .Returns(new CultureDto(name, name, tag, codes)); + var parser = new ExternalPathParser(new NamingOptions(), localizationManager.Object, DlnaProfileType.Subtitle); + + var actual = parser.ParseFile("My.Video." + tag + ".srt", "." + tag); + + Assert.NotNull(actual); + Assert.Equal(expected, actual!.Language); + } } diff --git a/tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs b/tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs index d3b82cefcd..da2e9c53d8 100644 --- a/tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs +++ b/tests/Jellyfin.Providers.Tests/Manager/ProviderManagerTests.cs @@ -2,10 +2,13 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; +using System.Net; using System.Net.Http; using System.Runtime.CompilerServices; +using System.Text; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Net; using MediaBrowser.Controller; using MediaBrowser.Controller.BaseItemManager; using MediaBrowser.Controller.Configuration; @@ -17,12 +20,14 @@ using MediaBrowser.Controller.MediaSegments; using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Subtitles; using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; using MediaBrowser.Model.IO; using MediaBrowser.Providers.Manager; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; +using Moq.Protected; using Xunit; // Allow Moq to see internal class @@ -488,6 +493,36 @@ namespace Jellyfin.Providers.Tests.Manager Assert.Equal(ItemCount - 1, processed.Count); } + [Theory] + [InlineData(HttpStatusCode.OK, "application/json", HttpStatusCode.NotFound)] + [InlineData(HttpStatusCode.Forbidden, "application/json", HttpStatusCode.Forbidden)] + public async Task SaveImage_ProviderRefusesWithBody_KeepsTheBody(HttpStatusCode status, string contentType, HttpStatusCode expectedStatus) + { + // Schedules Direct reports an exhausted image quota as HTTP 200 with a JSON body, and + // only the code in that body tells the guide refresh to stop requesting images. + const string Body = "{\"response\":\"MAX_IMAGE_DOWNLOADS\",\"code\":5002}"; + + var messageHandler = new Mock<HttpMessageHandler>(); + messageHandler.Protected() + .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()) + .ReturnsAsync(() => new HttpResponseMessage(status) + { + Content = new StringContent(Body, Encoding.UTF8, contentType) + }); + + var httpClientFactory = new Mock<IHttpClientFactory>(); + httpClientFactory.Setup(x => x.CreateClient(It.IsAny<string>())) + .Returns(() => new HttpClient(messageHandler.Object)); + + using var providerManager = GetProviderManager(httpClientFactory: httpClientFactory.Object); + + var ex = await Assert.ThrowsAsync<HttpResponseBodyException>( + () => providerManager.SaveImage(new Movie(), "https://json.schedulesdirect.org/20141201/image/a.jpg", ImageType.Primary, null, CancellationToken.None)); + + Assert.Equal(expectedStatus, ex.StatusCode); + Assert.Equal(Body, ex.ResponseBody); + } + private static void GetMetadataProviders_CanRefreshMetadata_Tester( string providerType, bool expected, @@ -666,7 +701,8 @@ namespace Jellyfin.Providers.Tests.Manager ServerConfiguration? serverConfiguration = null, LibraryOptions? libraryOptions = null, IBaseItemManager? baseItemManager = null, - ILibraryManager? libraryManager = null) + ILibraryManager? libraryManager = null, + IHttpClientFactory? httpClientFactory = null) { var serverConfigurationManager = new Mock<IServerConfigurationManager>(MockBehavior.Strict); serverConfigurationManager.Setup(i => i.Configuration) @@ -683,7 +719,7 @@ namespace Jellyfin.Providers.Tests.Manager } var providerManager = new ProviderManager( - Mock.Of<IHttpClientFactory>(), + httpClientFactory ?? Mock.Of<IHttpClientFactory>(), Mock.Of<ISubtitleManager>(), serverConfigurationManager.Object, Mock.Of<ILibraryMonitor>(), diff --git a/tests/Jellyfin.Providers.Tests/MediaInfo/FFProbeVideoInfoTests.cs b/tests/Jellyfin.Providers.Tests/MediaInfo/FFProbeVideoInfoTests.cs index 59d3f42edf..c4f25f3cb0 100644 --- a/tests/Jellyfin.Providers.Tests/MediaInfo/FFProbeVideoInfoTests.cs +++ b/tests/Jellyfin.Providers.Tests/MediaInfo/FFProbeVideoInfoTests.cs @@ -123,6 +123,141 @@ public class FFProbeVideoInfoTests Assert.Null(video.PremiereDate); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FetchEmbeddedInfo_NoYear_AppliesContainerCreationDate(bool replaceAllMetadata) + { + var video = new Video(); + + _fFProbeVideoInfo.FetchEmbeddedInfo(video, CreateMediaInfoWithCreationDate(), CreateRefreshOptions(replaceAllMetadata), new LibraryOptions()); + + Assert.Equal(new DateTime(2025, 10, 24, 19, 38, 17, DateTimeKind.Utc), video.PremiereDate); + Assert.Equal(2025, video.ProductionYear); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FetchEmbeddedInfo_KnownYear_IgnoresContainerCreationDate(bool replaceAllMetadata) + { + var video = new Video + { + ProductionYear = 2007 + }; + + _fFProbeVideoInfo.FetchEmbeddedInfo(video, CreateMediaInfoWithCreationDate(), CreateRefreshOptions(replaceAllMetadata), new LibraryOptions()); + + Assert.Equal(2007, video.ProductionYear); + Assert.Null(video.PremiereDate); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FetchEmbeddedInfo_MatchingYear_AppliesContainerCreationDate(bool replaceAllMetadata) + { + var video = new Video + { + ProductionYear = 2025 + }; + + _fFProbeVideoInfo.FetchEmbeddedInfo(video, CreateMediaInfoWithCreationDate(), CreateRefreshOptions(replaceAllMetadata), new LibraryOptions()); + + Assert.Equal(2025, video.ProductionYear); + Assert.Equal(new DateTime(2025, 10, 24, 19, 38, 17, DateTimeKind.Utc), video.PremiereDate); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FetchEmbeddedInfo_KnownYear_StillAppliesTaggedPremiereDate(bool replaceAllMetadata) + { + var video = new Video + { + ProductionYear = 2007 + }; + + _fFProbeVideoInfo.FetchEmbeddedInfo(video, CreateMediaInfoWithDates(), CreateRefreshOptions(replaceAllMetadata), new LibraryOptions()); + + Assert.Equal(new DateTime(2016, 5, 4, 0, 0, 0, DateTimeKind.Utc), video.PremiereDate); + } + + [Fact] + public void FetchEmbeddedInfo_KnownYear_ReplacingAppliesTaggedProductionYear() + { + var video = new Video + { + ProductionYear = 2007 + }; + + _fFProbeVideoInfo.FetchEmbeddedInfo(video, CreateMediaInfoWithDates(), CreateRefreshOptions(true), new LibraryOptions()); + + Assert.Equal(2016, video.ProductionYear); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FetchEmbeddedInfo_TaggedDateAndSameYearCreationDate_PrefersTaggedDate(bool replaceAllMetadata) + { + var video = new Video(); + var mediaInfo = new MediaBrowser.Model.MediaInfo.MediaInfo + { + ProductionYear = 2025, + PremiereDate = new DateTime(2025, 5, 4, 0, 0, 0, DateTimeKind.Utc), + ContainerCreationDate = new DateTime(2025, 10, 24, 19, 38, 17, DateTimeKind.Utc) + }; + + _fFProbeVideoInfo.FetchEmbeddedInfo(video, mediaInfo, CreateRefreshOptions(replaceAllMetadata), new LibraryOptions()); + + Assert.Equal(new DateTime(2025, 5, 4, 0, 0, 0, DateTimeKind.Utc), video.PremiereDate); + } + + [Fact] + public void FetchEmbeddedInfo_ExistingPremiereDate_KeepsItOverCreationDate() + { + var video = new Video + { + ProductionYear = 2025, + PremiereDate = new DateTime(2025, 3, 1, 0, 0, 0, DateTimeKind.Utc) + }; + + _fFProbeVideoInfo.FetchEmbeddedInfo(video, CreateMediaInfoWithCreationDate(), CreateRefreshOptions(false), new LibraryOptions()); + + Assert.Equal(new DateTime(2025, 3, 1, 0, 0, 0, DateTimeKind.Utc), video.PremiereDate); + } + + [Fact] + public void FetchEmbeddedInfo_ExistingPremiereDate_ReplacingUsesCreationDate() + { + var video = new Video + { + ProductionYear = 2025, + PremiereDate = new DateTime(2025, 3, 1, 0, 0, 0, DateTimeKind.Utc) + }; + + _fFProbeVideoInfo.FetchEmbeddedInfo(video, CreateMediaInfoWithCreationDate(), CreateRefreshOptions(true), new LibraryOptions()); + + Assert.Equal(new DateTime(2025, 10, 24, 19, 38, 17, DateTimeKind.Utc), video.PremiereDate); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void FetchEmbeddedInfo_ExtraWithCreationDate_StaysWithoutDates(bool replaceAllMetadata) + { + var video = new Video + { + ExtraType = ExtraType.Trailer + }; + + _fFProbeVideoInfo.FetchEmbeddedInfo(video, CreateMediaInfoWithCreationDate(), CreateRefreshOptions(replaceAllMetadata), new LibraryOptions()); + + Assert.Null(video.ProductionYear); + Assert.Null(video.PremiereDate); + } + private static MediaBrowser.Model.MediaInfo.MediaInfo CreateMediaInfoWithDates() => new() { @@ -130,6 +265,12 @@ public class FFProbeVideoInfoTests PremiereDate = new DateTime(2016, 5, 4, 0, 0, 0, DateTimeKind.Utc) }; + private static MediaBrowser.Model.MediaInfo.MediaInfo CreateMediaInfoWithCreationDate() + => new() + { + ContainerCreationDate = new DateTime(2025, 10, 24, 19, 38, 17, DateTimeKind.Utc) + }; + private static MetadataRefreshOptions CreateRefreshOptions(bool replaceAllMetadata) => new(Mock.Of<IDirectoryService>()) { diff --git a/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs b/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs index 6e36c08064..5c976d0592 100644 --- a/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs +++ b/tests/Jellyfin.Providers.Tests/Tmdb/TmdbUtilsTests.cs @@ -22,6 +22,17 @@ namespace Jellyfin.Providers.Tests.Tmdb } [Theory] + [InlineData("es-419", null, "es,null,en")] + [InlineData("es-419", "MX", "es-MX,null,en")] + [InlineData("pt-BR", null, "pt-BR,null,en")] + [InlineData("en", null, "en,null")] + [InlineData("", null, "null,en")] + public static void GetImageLanguagesParam_Valid_Success(string language, string? countryCode, string expected) + { + Assert.Equal(expected, TmdbUtils.GetImageLanguagesParam(language, countryCode)); + } + + [Theory] [InlineData(null, null)] [InlineData("", "")] public static void NormalizeLanguage_Invalid_Equal(string? input, string? expected) @@ -36,6 +47,11 @@ namespace Jellyfin.Providers.Tests.Tmdb [InlineData("en", "GB", "en-US", "en-GB")] [InlineData("en", "US", "en-US", "en-US")] [InlineData("en", null, "en-US", "en-US")] + // Regions TMDb does not have match the images it files under the countries they cover. + [InlineData("es", "MX", "es-419", "es-419")] + [InlineData("es", "AR", "es-419", "es-419")] + [InlineData("es", "ES", "es-419", "es-ES")] + [InlineData("de", "DE", "de-CH", "de-CH")] // TMDb files nearly every image under a region, which must not stop a plain request matching. [InlineData("en", "US", "en", "en")] [InlineData("pt", "PT", "pt", "pt")] diff --git a/tests/Jellyfin.Server.Implementations.Tests/Item/BaseItemRepositoryAncestorFilterTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Item/BaseItemRepositoryAncestorFilterTests.cs new file mode 100644 index 0000000000..d1f19b643f --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Item/BaseItemRepositoryAncestorFilterTests.cs @@ -0,0 +1,174 @@ +using System; +using System.Linq; +using Emby.Server.Implementations.Data; +using Jellyfin.Data.Enums; +using Jellyfin.Database.Implementations; +using Jellyfin.Database.Implementations.Entities; +using Jellyfin.Database.Implementations.Enums; +using Jellyfin.Server.Implementations.Item; +using MediaBrowser.Controller.Entities; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.Item; + +/// <summary> +/// Covers <see cref="InternalItemsQuery.AncestorIds"/>, the filter every recursive query under a parent runs on. +/// </summary> +public sealed class BaseItemRepositoryAncestorFilterTests : SqliteDbTestFixture +{ + private const string FolderType = "MediaBrowser.Controller.Entities.Folder"; + private const string SeriesType = "MediaBrowser.Controller.Entities.TV.Series"; + private const string SeasonType = "MediaBrowser.Controller.Entities.TV.Season"; + private const string EpisodeType = "MediaBrowser.Controller.Entities.TV.Episode"; + + private const string SeasonKey = "series-key-001"; + + private readonly QueryPlanRecorder _recorder; + private readonly BaseItemRepository _repository; + + private readonly Guid _library = Guid.NewGuid(); + private readonly Guid _series = Guid.NewGuid(); + private readonly Guid _season = Guid.NewGuid(); + private readonly Guid _episode = Guid.NewGuid(); + private readonly Guid _otherSeries = Guid.NewGuid(); + private readonly Guid _otherEpisode = Guid.NewGuid(); + private readonly Guid _emptyFolder = Guid.NewGuid(); + + public BaseItemRepositoryAncestorFilterTests() + : this(new QueryPlanRecorder()) + { + } + + private BaseItemRepositoryAncestorFilterTests(QueryPlanRecorder recorder) + : base(recorder) + { + _recorder = recorder; + using (var context = CreateDbContext()) + { + Seed(context); + } + + _repository = CreateBaseItemRepository(new ItemTypeLookup()); + } + + [Fact] + public void AncestorIds_SingleAncestor_ReturnsOnlyItsDescendants() + { + var ids = _repository.GetItemIdsList(new InternalItemsQuery { AncestorIds = [_series] }); + + Assert.Equal(new[] { _season, _episode }.Order(), ids.Order()); + } + + [Fact] + public void AncestorIds_OverlappingAncestors_ReturnsUnionWithoutDuplicates() + { + var ids = _repository.GetItemIdsList(new InternalItemsQuery + { + AncestorIds = [_library, _series, _otherSeries], + IncludeItemTypes = [BaseItemKind.Episode] + }); + + Assert.Equal(new[] { _episode, _otherEpisode }.Order(), ids.Order()); + } + + [Fact] + public void AncestorIds_ParentWithoutDescendants_ReturnsNothing() + { + var ids = _repository.GetItemIdsList(new InternalItemsQuery { AncestorIds = [_emptyFolder] }); + + Assert.Empty(ids); + } + + [Fact] + public void AncestorWithPresentationUniqueKey_ReturnsDescendantsOfTheKeyedFolder() + { + var ids = _repository.GetItemIdsList(new InternalItemsQuery + { + AncestorWithPresentationUniqueKey = SeasonKey, + IncludeItemTypes = [BaseItemKind.Episode] + }); + + Assert.Equal([_episode], ids); + } + + [Fact] + public void AncestorIds_SeeksDescendantsByParent() + { + _recorder.Commands.Clear(); + + _repository.GetItemList(new InternalItemsQuery + { + AncestorIds = [_emptyFolder], + OrderBy = [(ItemSortBy.IsFolder, SortOrder.Ascending), (ItemSortBy.SortName, SortOrder.Ascending)], + Limit = 1 + }); + + var query = Assert.Single(_recorder.Commands, c => c.Sql.Contains("\"AncestorIds\"", StringComparison.Ordinal)); + AssertDrivenByDescendants(Explain(query)); + } + + [Fact] + public void AncestorWithPresentationUniqueKey_SeeksDescendantsByParent() + { + _recorder.Commands.Clear(); + + _repository.GetItemList(new InternalItemsQuery + { + AncestorWithPresentationUniqueKey = SeasonKey, + OrderBy = [(ItemSortBy.IsFolder, SortOrder.Ascending), (ItemSortBy.SortName, SortOrder.Ascending)], + Limit = 1 + }); + + var query = Assert.Single(_recorder.Commands, c => c.Sql.Contains("\"AncestorIds\"", StringComparison.Ordinal)); + AssertDrivenByDescendants(Explain(query)); + } + + // The issue's plan scanned BaseItems and probed AncestorIds per row; the fix looks BaseItems up by the descendant ids. + private static void AssertDrivenByDescendants(string[] plan) + { + Assert.Contains(plan, line => line.Contains("COVERING INDEX IX_AncestorIds_ParentItemId_ItemId (ParentItemId=?)", StringComparison.Ordinal)); + Assert.Contains(plan, line => line.StartsWith("SEARCH b USING INDEX sqlite_autoindex_BaseItems_1 (Id=?)", StringComparison.Ordinal)); + Assert.DoesNotContain(plan, line => line.StartsWith("SCAN b ", StringComparison.Ordinal) || line == "SCAN b"); + } + + private void Seed(JellyfinDbContext context) + { + context.BaseItems.Add(new BaseItemEntity { Id = _library, Type = FolderType, Name = "Shows", IsFolder = true }); + context.BaseItems.Add(new BaseItemEntity { Id = _series, Type = SeriesType, Name = "Series", IsFolder = true }); + context.BaseItems.Add(new BaseItemEntity { Id = _season, Type = SeasonType, Name = "Season 1", IsFolder = true, PresentationUniqueKey = SeasonKey }); + context.BaseItems.Add(new BaseItemEntity { Id = _episode, Type = EpisodeType, Name = "Episode 1" }); + context.BaseItems.Add(new BaseItemEntity { Id = _otherSeries, Type = SeriesType, Name = "Other series", IsFolder = true }); + context.BaseItems.Add(new BaseItemEntity { Id = _otherEpisode, Type = EpisodeType, Name = "Other episode" }); + context.BaseItems.Add(new BaseItemEntity { Id = _emptyFolder, Type = FolderType, Name = "Empty", IsFolder = true }); + + // AncestorIds is a closure: production writes one row per ancestor, not just the parent. + AddAncestors(context, _series, _library); + AddAncestors(context, _season, _series, _library); + AddAncestors(context, _episode, _season, _series, _library); + AddAncestors(context, _otherSeries, _library); + AddAncestors(context, _otherEpisode, _otherSeries, _library); + AddAncestors(context, _emptyFolder, _library); + + context.SaveChanges(); + } + + private static void AddAncestors(JellyfinDbContext context, Guid itemId, params Guid[] ancestorIds) + { + foreach (var ancestorId in ancestorIds) + { + context.AncestorIds.Add(new AncestorId + { + ItemId = itemId, + ParentItemId = ancestorId, + Item = null!, + ParentItem = null! + }); + } + } + + private string[] Explain(RecordedCommand query) + { + using var context = CreateDbContext(); + return QueryPlanRecorder.Explain(context, query); + } +} diff --git a/tests/Jellyfin.Server.Implementations.Tests/Item/BaseItemRepositoryStreamFilterTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Item/BaseItemRepositoryStreamFilterTests.cs index 4e8d84850b..002ccb98ea 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Item/BaseItemRepositoryStreamFilterTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Item/BaseItemRepositoryStreamFilterTests.cs @@ -5,6 +5,8 @@ using Jellyfin.Database.Implementations; using Jellyfin.Database.Implementations.Entities; using Jellyfin.Server.Implementations.Item; using MediaBrowser.Controller.Entities; +using MediaBrowser.Model.Globalization; +using Moq; using Xunit; using LinkedChildType = Jellyfin.Database.Implementations.Entities.LinkedChildType; @@ -183,6 +185,22 @@ public sealed class BaseItemRepositoryStreamFilterTests : SqliteDbTestFixture } [Fact] + public void HasNoAudioTrackWithLanguage_VariantExcludesAnItemWithItsBaseCode() + { + // ffprobe tags a fr-CA track as the base code, so a fr-ca setting has to see it. + var localizationManager = new Mock<ILocalizationManager>(); + localizationManager + .Setup(m => m.FindLanguageInfo("fr-ca")) + .Returns(new CultureDto("fr-ca", "French (Canada)", "fr-ca", ["frc"])); + localizationManager + .Setup(m => m.FindLanguageInfo("fr")) + .Returns(new CultureDto("French", "French", "fr", ["fra", "fre"])); + var repository = CreateBaseItemRepository(new ItemTypeLookup(), localizationManager.Object); + + Assert.DoesNotContain(_versionedMovie, repository.GetItemIdsList(new InternalItemsQuery { HasNoAudioTrackWithLanguage = "fr-ca" })); + } + + [Fact] public void HasChapterImages_MatchesAnItemWhoseAlternateVersionCarriesThem() { Assert.Contains(_versionedMovie, _repository.GetItemIdsList(new InternalItemsQuery { HasChapterImages = true })); diff --git a/tests/Jellyfin.Server.Implementations.Tests/Item/ItemPersistenceOwnedRowTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Item/ItemPersistenceOwnedRowTests.cs index fea6ccb7a1..d2eb53c393 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Item/ItemPersistenceOwnedRowTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Item/ItemPersistenceOwnedRowTests.cs @@ -12,6 +12,7 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Controller.Playlists; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using Microsoft.Extensions.Logging.Abstractions; @@ -114,6 +115,61 @@ public sealed class ItemPersistenceOwnedRowTests : SqliteDbTestFixture } [Fact] + public void SaveItems_BatchLargerThanSqliteVariableLimit_Saves() + { + // SQLite caps bound variables at 32766; batch-wide lookups must not bind one per item. + const int Count = 33_000; + var movies = Enumerable.Range(0, Count) + .Select(i => + { + var movie = CreateMovie(Guid.NewGuid()); + movie.Genres = [$"Genre {i}"]; + return movie; + }) + .ToList(); + + _service.SaveItems(movies, CancellationToken.None); + _service.SaveItems(movies, CancellationToken.None); + + using var ctx = CreateDbContext(); + Assert.Equal(Count, ctx.BaseItems.Count(e => e.Type == "MediaBrowser.Controller.Entities.Movies.Movie")); + Assert.Equal(Count, ctx.ItemValuesMap.Count()); + } + + [Fact] + public void SaveItems_PlaylistLinkedByPathBeyondSqliteVariableLimit_Saves() + { + var appHost = new Mock<IServerApplicationHost>(); + appHost.Setup(h => h.ReverseVirtualPath(It.IsAny<string>())).Returns((string p) => p); + var service = new ItemPersistenceService(CreateDbContextFactory(), appHost.Object, NullLogger<ItemPersistenceService>.Instance); + + const int Count = 33_000; + var movies = Enumerable.Range(0, Count) + .Select(i => + { + var movie = CreateMovie(Guid.NewGuid()); + movie.Path = $"/movies/{i}.mkv"; + return movie; + }) + .ToList(); + service.SaveItems(movies, CancellationToken.None); + + // Legacy links carry only a path, so the save resolves every one of them in a single lookup. +#pragma warning disable CS0618 // Type or member is obsolete + var playlist = new Playlist + { + Id = Guid.NewGuid(), + Name = "Everything", + LinkedChildren = movies.Select(m => new LinkedChild { Path = m.Path, Type = MediaBrowser.Controller.Entities.LinkedChildType.Manual }).ToArray() + }; +#pragma warning restore CS0618 + service.SaveItems([playlist], CancellationToken.None); + + using var ctx = CreateDbContext(); + Assert.Equal(Count, ctx.LinkedChildren.Count(e => e.ParentId.Equals(playlist.Id))); + } + + [Fact] public async Task ReattachUserData_DetachedRowsFromDifferentEras_CollapsesToMostRecentPlay() { var movie = CreateMovie(Guid.Parse("dddddddd-dddd-dddd-dddd-dddddddddddd")); diff --git a/tests/Jellyfin.Server.Implementations.Tests/Item/PeopleRepositoryParentFilterTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Item/PeopleRepositoryParentFilterTests.cs new file mode 100644 index 0000000000..074f37e5c6 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Item/PeopleRepositoryParentFilterTests.cs @@ -0,0 +1,131 @@ +using System; +using System.Linq; +using Emby.Server.Implementations.Data; +using Jellyfin.Data.Enums; +using Jellyfin.Database.Implementations; +using Jellyfin.Database.Implementations.Entities; +using Jellyfin.Server.Implementations.Item; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Persistence; +using Moq; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.Item; + +/// <summary> +/// Covers <see cref="InternalPeopleQuery.ParentId"/>, which limits /Persons to the people credited below a folder. +/// </summary> +public sealed class PeopleRepositoryParentFilterTests : SqliteDbTestFixture +{ + private readonly QueryPlanRecorder _recorder; + private readonly PeopleRepository _people; + + private readonly Guid _library = Guid.NewGuid(); + private readonly Guid _series = Guid.NewGuid(); + private readonly Guid _episode = Guid.NewGuid(); + private readonly Guid _secondEpisode = Guid.NewGuid(); + private readonly Guid _otherSeries = Guid.NewGuid(); + private readonly Guid _otherEpisode = Guid.NewGuid(); + private readonly Guid _emptyFolder = Guid.NewGuid(); + + public PeopleRepositoryParentFilterTests() + : this(new QueryPlanRecorder()) + { + } + + private PeopleRepositoryParentFilterTests(QueryPlanRecorder recorder) + : base(recorder) + { + _recorder = recorder; + var lookup = new ItemTypeLookup(); + using (var context = CreateDbContext()) + { + var folder = lookup.BaseItemKindNames[BaseItemKind.Folder]; + var series = lookup.BaseItemKindNames[BaseItemKind.Series]; + var episode = lookup.BaseItemKindNames[BaseItemKind.Episode]; + context.BaseItems.Add(new BaseItemEntity { Id = _library, Type = folder, Name = "Shows", IsFolder = true }); + context.BaseItems.Add(new BaseItemEntity { Id = _series, Type = series, Name = "Series", IsFolder = true }); + context.BaseItems.Add(new BaseItemEntity { Id = _episode, Type = episode, Name = "Episode 1" }); + context.BaseItems.Add(new BaseItemEntity { Id = _secondEpisode, Type = episode, Name = "Episode 2" }); + context.BaseItems.Add(new BaseItemEntity { Id = _otherSeries, Type = series, Name = "Other series", IsFolder = true }); + context.BaseItems.Add(new BaseItemEntity { Id = _otherEpisode, Type = episode, Name = "Other episode" }); + context.BaseItems.Add(new BaseItemEntity { Id = _emptyFolder, Type = folder, Name = "Empty", IsFolder = true }); + + AddAncestors(context, _series, _library); + AddAncestors(context, _episode, _series, _library); + AddAncestors(context, _secondEpisode, _series, _library); + AddAncestors(context, _otherSeries, _library); + AddAncestors(context, _otherEpisode, _otherSeries, _library); + AddAncestors(context, _emptyFolder, _library); + context.SaveChanges(); + } + + _people = new PeopleRepository(CreateDbContextFactory(), lookup, Mock.Of<IItemQueryHelpers>()); + _people.UpdatePeople(_episode, [Actor("Lead"), Actor("Guest")]); + _people.UpdatePeople(_secondEpisode, [Actor("Lead")]); + _people.UpdatePeople(_otherEpisode, [Actor("Stranger")]); + } + + [Fact] + public void ParentId_ReturnsEachPersonCreditedBelowTheParentOnce() + { + var result = _people.GetPeople(new InternalPeopleQuery([], []) { ParentId = _series }); + + Assert.Equal(["Guest", "Lead"], result.Items.Select(p => p.Name).Distinct().Order()); + Assert.Equal(2, result.TotalRecordCount); + } + + [Fact] + public void ParentId_SpanningSeveralFolders_ReturnsTheirUnion() + { + var result = _people.GetPeople(new InternalPeopleQuery([], []) { ParentId = _library }); + + Assert.Equal(["Guest", "Lead", "Stranger"], result.Items.Select(p => p.Name).Distinct().Order()); + Assert.Equal(3, result.TotalRecordCount); + } + + [Fact] + public void ParentId_WithoutCreditsBelowIt_ReturnsNobody() + { + var result = _people.GetPeople(new InternalPeopleQuery([], []) { ParentId = _emptyFolder }); + + Assert.Empty(result.Items); + Assert.Equal(0, result.TotalRecordCount); + } + + [Fact] + public void ParentId_SeeksCreditsByDescendant() + { + _recorder.Commands.Clear(); + + _people.GetPeople(new InternalPeopleQuery([], []) { ParentId = _series, Limit = 1 }); + + var query = Assert.Single(_recorder.Commands, c => c.Sql.Contains("\"AncestorIds\"", StringComparison.Ordinal) && c.Sql.Contains("ORDER BY", StringComparison.Ordinal)); + var plan = Explain(query); + Assert.Contains(plan, line => line.Contains("COVERING INDEX IX_AncestorIds_ParentItemId_ItemId (ParentItemId=?)", StringComparison.Ordinal)); + Assert.Contains(plan, line => line.StartsWith("SEARCH p USING INDEX sqlite_autoindex_Peoples_1 (Id=?)", StringComparison.Ordinal)); + Assert.DoesNotContain(plan, line => line.StartsWith("SCAN p ", StringComparison.Ordinal) || line == "SCAN p"); + } + + private static PersonInfo Actor(string name) => new() { Name = name, Type = PersonKind.Actor }; + + private static void AddAncestors(JellyfinDbContext context, Guid itemId, params Guid[] ancestorIds) + { + foreach (var ancestorId in ancestorIds) + { + context.AncestorIds.Add(new AncestorId + { + ItemId = itemId, + ParentItemId = ancestorId, + Item = null!, + ParentItem = null! + }); + } + } + + private string[] Explain(RecordedCommand query) + { + using var context = CreateDbContext(); + return QueryPlanRecorder.Explain(context, query); + } +} diff --git a/tests/Jellyfin.Server.Implementations.Tests/Item/QueryPlanRecorder.cs b/tests/Jellyfin.Server.Implementations.Tests/Item/QueryPlanRecorder.cs new file mode 100644 index 0000000000..a356932a78 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Item/QueryPlanRecorder.cs @@ -0,0 +1,72 @@ +using System.Collections.Generic; +using System.Data.Common; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Jellyfin.Database.Implementations; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Diagnostics; + +namespace Jellyfin.Server.Implementations.Tests.Item; + +/// <summary> +/// Records the reader commands EF Core sends, so a test can ask SQLite how it would run one. +/// </summary> +internal sealed class QueryPlanRecorder : DbCommandInterceptor +{ + /// <summary> + /// Gets the recorded commands, oldest first. + /// </summary> + public List<RecordedCommand> Commands { get; } = []; + + /// <summary> + /// Returns the <c>EXPLAIN QUERY PLAN</c> detail lines for a recorded command. + /// </summary> + /// <param name="context">A context on the database the command ran against.</param> + /// <param name="query">The recorded command.</param> + /// <returns>One entry per plan line.</returns> + public static string[] Explain(JellyfinDbContext context, RecordedCommand query) + { + using var command = context.Database.GetDbConnection().CreateCommand(); +#pragma warning disable CA2100 // query.Sql is generated by EF Core; query values remain bound parameters. + command.CommandText = "EXPLAIN QUERY PLAN " + query.Sql; +#pragma warning restore CA2100 + foreach (var value in query.Parameters) + { + var parameter = command.CreateParameter(); + parameter.ParameterName = value.Name; + parameter.Value = value.Value; + command.Parameters.Add(parameter); + } + + using var reader = command.ExecuteReader(); + var plan = new List<string>(); + while (reader.Read()) + { + plan.Add(reader.GetString(3)); + } + + return plan.ToArray(); + } + + /// <inheritdoc /> + public override InterceptionResult<DbDataReader> ReaderExecuting(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result) + { + Record(command); + return result; + } + + /// <inheritdoc /> + public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result, CancellationToken cancellationToken = default) + { + Record(command); + return ValueTask.FromResult(result); + } + + private void Record(DbCommand command) + { + Commands.Add(new RecordedCommand( + command.CommandText, + command.Parameters.Cast<DbParameter>().Select(p => (p.ParameterName, p.Value)).ToArray())); + } +} diff --git a/tests/Jellyfin.Server.Implementations.Tests/Item/RecordedCommand.cs b/tests/Jellyfin.Server.Implementations.Tests/Item/RecordedCommand.cs new file mode 100644 index 0000000000..e7e7314350 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Item/RecordedCommand.cs @@ -0,0 +1,8 @@ +namespace Jellyfin.Server.Implementations.Tests.Item; + +/// <summary> +/// A command captured by <see cref="QueryPlanRecorder"/>. +/// </summary> +/// <param name="Sql">The command text.</param> +/// <param name="Parameters">The bound parameters.</param> +internal sealed record RecordedCommand(string Sql, (string Name, object? Value)[] Parameters); diff --git a/tests/Jellyfin.Server.Implementations.Tests/Item/SqliteDbTestFixture.cs b/tests/Jellyfin.Server.Implementations.Tests/Item/SqliteDbTestFixture.cs index 6da176b4f1..6ab0d8e9ad 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Item/SqliteDbTestFixture.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Item/SqliteDbTestFixture.cs @@ -9,6 +9,7 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Controller; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Globalization; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Diagnostics; @@ -67,7 +68,7 @@ public abstract class SqliteDbTestFixture : IDisposable return factory.Object; } - protected BaseItemRepository CreateBaseItemRepository(ItemTypeLookup itemTypeLookup) + protected BaseItemRepository CreateBaseItemRepository(ItemTypeLookup itemTypeLookup, ILocalizationManager? localizationManager = null) { var serverConfigurationManager = new Mock<IServerConfigurationManager>(); serverConfigurationManager.Setup(c => c.Configuration).Returns(new ServerConfiguration()); @@ -77,6 +78,7 @@ public abstract class SqliteDbTestFixture : IDisposable new Mock<IServerApplicationHost>().Object, itemTypeLookup, serverConfigurationManager.Object, + localizationManager ?? Mock.Of<ILocalizationManager>(), NullLogger<BaseItemRepository>.Instance); } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/DotIgnoreIgnoreRuleTest.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/DotIgnoreIgnoreRuleTest.cs index 03c0b4af39..94de2f7b23 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Library/DotIgnoreIgnoreRuleTest.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/DotIgnoreIgnoreRuleTest.cs @@ -470,4 +470,105 @@ public class DotIgnoreIgnoreRuleTest Directory.Delete(tempDir, true); } } + + [Fact] + public void LibraryRoot_IgnoreFileAboveRoot_IsNotConsulted() + { + var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + var libraryRoot = Path.Combine(tempDir, "Movies"); + var movieDir = Path.Combine(libraryRoot, "Movie (2020)"); + Directory.CreateDirectory(movieDir); + + try + { + File.WriteAllText(Path.Combine(tempDir, ".ignore"), string.Empty); + + var rule = new DotIgnoreIgnoreRule(); + var fileInfo = new FileSystemMetadata + { + FullName = Path.Combine(movieDir, "Movie (2020).mkv"), + IsDirectory = false + }; + + // Without library roots the walk reaches the filesystem root + Assert.True(rule.ShouldIgnore(fileInfo, null)); + + rule.SetLibraryRootsProvider(() => [libraryRoot + Path.DirectorySeparatorChar]); + Assert.False(rule.ShouldIgnore(fileInfo, null)); + + // A .ignore in the library root itself still applies + File.WriteAllText(Path.Combine(libraryRoot, ".ignore"), "*.mkv"); + rule.ClearDirectoryCache(); + Assert.True(rule.ShouldIgnore(fileInfo, null)); + } + finally + { + Directory.Delete(tempDir, true); + } + } + + [Fact] + public void LibraryRoot_NestedRoots_StopAtOutermost() + { + var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + var outerRoot = Path.Combine(tempDir, "Media"); + var innerRoot = Path.Combine(outerRoot, "Movies"); + Directory.CreateDirectory(innerRoot); + + try + { + File.WriteAllText(Path.Combine(outerRoot, ".ignore"), "*.mkv"); + + var rule = new DotIgnoreIgnoreRule(); + rule.SetLibraryRootsProvider(() => [innerRoot, outerRoot]); + var fileInfo = new FileSystemMetadata + { + FullName = Path.Combine(innerRoot, "Movie.mkv"), + IsDirectory = false + }; + + Assert.True(rule.ShouldIgnore(fileInfo, null)); + } + finally + { + Directory.Delete(tempDir, true); + } + } + + [Fact] + public void LibraryRoot_PathOutsideLibraries_WalksToFilesystemRoot() + { + var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + var libraryRoot = Path.Combine(tempDir, "Movies"); + var otherDir = Path.Combine(tempDir, "Other", "Sub"); + Directory.CreateDirectory(libraryRoot); + Directory.CreateDirectory(otherDir); + + try + { + File.WriteAllText(Path.Combine(tempDir, ".ignore"), string.Empty); + + var rule = new DotIgnoreIgnoreRule(); + rule.SetLibraryRootsProvider(() => [libraryRoot]); + + // A sibling whose name only shares the root's prefix is not inside the library + var fileInfo = new FileSystemMetadata + { + FullName = Path.Combine(tempDir, "MoviesExtra", "Movie.mkv"), + IsDirectory = false + }; + Assert.True(rule.ShouldIgnore(fileInfo, null)); + + fileInfo = new FileSystemMetadata + { + FullName = Path.Combine(otherDir, "Movie.mkv"), + IsDirectory = false + }; + Assert.True(rule.ShouldIgnore(fileInfo, null)); + } + finally + { + Directory.Delete(tempDir, true); + } + } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/LibraryManager/LibraryRootIgnoreTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/LibraryManager/LibraryRootIgnoreTests.cs new file mode 100644 index 0000000000..f37aadbe8d --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/LibraryManager/LibraryRootIgnoreTests.cs @@ -0,0 +1,93 @@ +using System; +using System.IO; +using AutoFixture; +using AutoFixture.AutoMoq; +using Emby.Naming.Common; +using Emby.Server.Implementations.IO; +using Emby.Server.Implementations.Library; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Sorting; +using MediaBrowser.Model.IO; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Server.Implementations.Tests.Library.LibraryManager; + +public sealed class LibraryRootIgnoreTests : IDisposable +{ + private readonly string _tempDir; + private readonly string _userViewsPath; + private readonly string _libraryRoot; + private readonly FileSystemMetadata _movieFile; + + public LibraryRootIgnoreTests() + { + _tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + _userViewsPath = Path.Combine(_tempDir, "root", "default"); + _libraryRoot = Path.Combine(_tempDir, "media", "Movies"); + var movieDir = Path.Combine(_libraryRoot, "Movie (2020)"); + Directory.CreateDirectory(movieDir); + + // Ignores everything below it, but sits above the library root + File.WriteAllText(Path.Combine(_tempDir, ".ignore"), string.Empty); + + _movieFile = new FileSystemMetadata + { + FullName = Path.Combine(movieDir, "Movie (2020).mkv"), + IsDirectory = false + }; + } + + public void Dispose() + { + Directory.Delete(_tempDir, true); + } + + [Fact] + public void IgnoreFile_IgnoreFileAboveMblinkLibraryRoot_IsNotConsulted() + { + var libraryDir = Path.Combine(_userViewsPath, "Movies"); + Directory.CreateDirectory(libraryDir); + File.WriteAllText(Path.Combine(libraryDir, "Movies.mblink"), _libraryRoot); + + Assert.False(CreateLibraryManager().IgnoreFile(_movieFile, null)); + } + + [Fact] + public void IgnoreFile_UserViewsPathMissing_WalksToFilesystemRoot() + { + // Before root/default exists there are no library roots, so the .ignore above still applies + Assert.False(Directory.Exists(_userViewsPath)); + Assert.True(CreateLibraryManager().IgnoreFile(_movieFile, null)); + } + + private Emby.Server.Implementations.Library.LibraryManager CreateLibraryManager() + { + var fixture = new Fixture().Customize(new AutoMoqCustomization()); + fixture.Register(() => new NamingOptions()); + var configMock = fixture.Freeze<Mock<IServerConfigurationManager>>(); + configMock.Setup(c => c.ApplicationPaths.ProgramDataPath).Returns(_tempDir); + configMock.Setup(c => c.ApplicationPaths.DefaultUserViewsPath).Returns(_userViewsPath); + fixture.Freeze<Mock<IServerApplicationHost>>() + .Setup(h => h.ExpandVirtualPath(It.IsAny<string>())) + .Returns<string>(path => path); + fixture.Inject<IFileSystem>(new ManagedFileSystem( + NullLogger<ManagedFileSystem>.Instance, + configMock.Object.ApplicationPaths, + [new MbLinkShortcutHandler()])); + + // The same instance LibraryManager hands the roots to must be the one evaluating the rules + var dotIgnoreRule = new DotIgnoreIgnoreRule(); + fixture.Inject(dotIgnoreRule); + + return fixture.Build<Emby.Server.Implementations.Library.LibraryManager>().Do(s => s.AddParts( + [dotIgnoreRule], + [], + [], + Array.Empty<IBaseItemComparer>(), + [])) + .Create(); + } +} diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/LibraryManagerConvertImageTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/LibraryManagerConvertImageTests.cs new file mode 100644 index 0000000000..d374847e54 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/LibraryManagerConvertImageTests.cs @@ -0,0 +1,50 @@ +using System; +using System.Net; +using System.Threading; +using System.Threading.Tasks; +using AutoFixture; +using AutoFixture.AutoMoq; +using Emby.Naming.Common; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.Movies; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; +using Moq; +using Xunit; +using ServerLibraryManager = Emby.Server.Implementations.Library.LibraryManager; + +namespace Jellyfin.Server.Implementations.Tests.Library; + +public class LibraryManagerConvertImageTests +{ + [Theory] + [InlineData(HttpStatusCode.NotFound)] + [InlineData(HttpStatusCode.Forbidden)] + public async Task ConvertImageToLocal_RejectedDownload_KeepsTheResponseAsInnerException(HttpStatusCode status) + { + // The Live TV guide reads the provider's error body off the inner exception to stop + // requesting images from an account that is refusing them. + const string Body = "{\"response\":\"MAX_IMAGE_DOWNLOADS\",\"code\":5002}"; + var rejection = new HttpResponseBodyException("test", status, Body); + + var fixture = new Fixture().Customize(new AutoMoqCustomization()); + fixture.Register(() => new NamingOptions()); + var configuration = fixture.Freeze<Mock<IServerConfigurationManager>>(); + configuration.Setup(c => c.Configuration).Returns(new ServerConfiguration()); + configuration.Setup(c => c.ApplicationPaths.ProgramDataPath).Returns("/data"); + var providerManager = fixture.Freeze<Mock<IProviderManager>>(); + providerManager.Setup(p => p.SaveImage(It.IsAny<BaseItem>(), It.IsAny<string>(), It.IsAny<ImageType>(), It.IsAny<int?>(), It.IsAny<CancellationToken>())) + .ThrowsAsync(rejection); + var manager = fixture.Create<ServerLibraryManager>(); + + var item = new Movie { Id = Guid.NewGuid(), Name = "Test" }; + var image = new ItemImageInfo { Path = "https://example.com/image.jpg", Type = ImageType.Primary }; + + var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => manager.ConvertImageToLocal(item, image, 0, removeOnFailure: false)); + + Assert.Same(rejection, ex.InnerException); + } +} diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/MediaSourceManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/MediaSourceManagerTests.cs index 131cb23fa4..187d44559e 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Library/MediaSourceManagerTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/MediaSourceManagerTests.cs @@ -151,6 +151,31 @@ namespace Jellyfin.Server.Implementations.Tests.Library Assert.Equal(expectedIndex, mediaInfo.DefaultAudioStreamIndex); } + [Fact] + public void SetDefaultAudioStreamIndex_VariantPreference_MatchesBaseCodeTrack() + { + _mockLocalizationManager + .Setup(m => m.FindLanguageInfo("pt-br")) + .Returns(new CultureDto("pt-br", "Portuguese (Brazil)", "pt-br", ["pt-br", "por"])); + + var mediaInfo = new MediaSourceInfo + { + MediaStreams = new MediaStream[] + { + new() { Index = 0, Type = MediaStreamType.Video, IsDefault = true }, + new() { Index = 1, Type = MediaStreamType.Audio, Language = "eng", IsDefault = true }, + new() { Index = 2, Type = MediaStreamType.Audio, Language = "por", IsDefault = false } + } + }; + + _user.AudioLanguagePreference = "pt-br"; + _user.PlayDefaultAudioTrack = false; + + _mediaSourceManager.SetDefaultAudioAndSubtitleStreamIndices(_item, mediaInfo, _user); + + Assert.Equal(2, mediaInfo.DefaultAudioStreamIndex); + } + [Theory] // A remembered full track must not survive a switch to "only forced" (it falls through to // the forced track here); a remembered forced track and "off" still must. diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/MediaStreamSelectorTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/MediaStreamSelectorTests.cs index 07feae587b..3fc474816b 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Library/MediaStreamSelectorTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/MediaStreamSelectorTests.cs @@ -1,5 +1,6 @@ using System; using Emby.Server.Implementations.Library; +using Jellyfin.Database.Implementations.Enums; using MediaBrowser.Model.Entities; using Xunit; @@ -115,4 +116,18 @@ public class MediaStreamSelectorTests Assert.Equal(expectedScore, MediaStreamSelector.GetStreamScore(stream, languagePref)); } + + [Fact] + public void GetDefaultSubtitleStreamIndex_VariantPreference_PrefersVariantTrackOverBaseCodeTrack() + { + var streams = new MediaStream[] + { + new() { Index = 0, Type = MediaStreamType.Video }, + new() { Index = 1, Type = MediaStreamType.Audio, Language = "eng", IsDefault = true }, + new() { Index = 2, Type = MediaStreamType.Subtitle, Language = "por", IsExternal = true }, + new() { Index = 3, Type = MediaStreamType.Subtitle, Language = "pt-br", IsExternal = true } + }; + + Assert.Equal(3, MediaStreamSelector.GetDefaultSubtitleStreamIndex(streams, ["pt-br", "por"], SubtitlePlaybackMode.Always, "eng")); + } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/QueryFiltersTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/QueryFiltersTests.cs new file mode 100644 index 0000000000..72a20d7f98 --- /dev/null +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/QueryFiltersTests.cs @@ -0,0 +1,534 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Security.Claims; +using AutoFixture; +using AutoFixture.AutoMoq; +using Emby.Naming.Common; +using Emby.Server.Implementations.Data; +using Jellyfin.Api.Constants; +using Jellyfin.Api.Controllers; +using Jellyfin.Data; +using Jellyfin.Database.Implementations.Entities; +using Jellyfin.Database.Implementations.Enums; +using Jellyfin.Server.Implementations.Tests.Item; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Persistence; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Globalization; +using MediaBrowser.Model.Library; +using MediaBrowser.Model.Querying; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Moq; +using Xunit; +using BaseItemKind = Jellyfin.Data.Enums.BaseItemKind; +using ServerLibraryManager = Emby.Server.Implementations.Library.LibraryManager; + +namespace Jellyfin.Server.Implementations.Tests.Library; + +public sealed class QueryFiltersTests : SqliteDbTestFixture +{ + private readonly DirectoryInfo _rootDirectory; + private readonly ItemTypeLookup _itemTypeLookup = new(); + private readonly Mock<IUserViewManager> _userViewManager = new(); + private readonly User _user = new("restricted", "auth", "reset") + { + MaxParentalRatingScore = 50 + }; + + private readonly Guid _firstLibraryId = Guid.NewGuid(); + private readonly Guid _secondLibraryId = Guid.NewGuid(); + private readonly Guid _inaccessibleLibraryId = Guid.NewGuid(); + private readonly Folder _folder = new() { Id = Guid.NewGuid() }; + private readonly AggregateFolder _aggregateRoot = new() { Id = Guid.NewGuid() }; + private readonly CollectionFolder _collection; + private readonly UserView _view; + private readonly UserRootFolder _userRoot; + private readonly FilterController _controller; + + public QueryFiltersTests() + { + _rootDirectory = Directory.CreateTempSubdirectory("jellyfin-query-filters-"); + _user.SetPreference(PreferenceKind.BlockedTags, ["blocked"]); + + var fixture = new Fixture().Customize(new AutoMoqCustomization()); + fixture.Register(() => new NamingOptions()); + fixture.Inject<IItemRepository>(CreateBaseItemRepository(_itemTypeLookup)); + fixture.Inject(new Lazy<IUserViewManager>(() => _userViewManager.Object)); + var configuration = fixture.Freeze<Mock<IServerConfigurationManager>>(); + configuration.Setup(c => c.Configuration).Returns(new ServerConfiguration()); + configuration.Setup(c => c.ApplicationPaths.ProgramDataPath).Returns(_rootDirectory.FullName); + configuration.Setup(c => c.ApplicationPaths.DefaultUserViewsPath).Returns(_rootDirectory.FullName); + + var libraryManager = fixture.Create<ServerLibraryManager>(); + _userRoot = new UserRootFolder + { + Id = libraryManager.GetNewItemId(_rootDirectory.FullName, typeof(UserRootFolder)), + Path = _rootDirectory.FullName + }; + _collection = new CollectionFolder + { + Id = Guid.NewGuid(), + PhysicalFolderIds = [_firstLibraryId] + }; + _view = new UserView + { + Id = Guid.NewGuid(), + DisplayParentId = _collection.Id + }; + var secondCollection = new CollectionFolder + { + Id = Guid.NewGuid(), + PhysicalFolderIds = [_secondLibraryId] + }; + libraryManager.RegisterItem(_userRoot); + libraryManager.RegisterItem(_aggregateRoot); + libraryManager.RegisterItem(_collection); + libraryManager.RegisterItem(_view); + libraryManager.RegisterItem(_folder); + + _userViewManager.Setup(m => m.GetUserViews(It.Is<UserViewQuery>(q => q.User == _user && q.IncludeHidden))) + .Returns([_collection, secondCollection]); + var userManager = fixture.Freeze<Mock<IUserManager>>(); + userManager.Setup(m => m.GetUserById(_user.Id)).Returns(_user); + _controller = new FilterController(libraryManager, userManager.Object, Mock.Of<ILocalizationManager>()) + { + ControllerContext = new ControllerContext + { + HttpContext = new DefaultHttpContext + { + User = new ClaimsPrincipal(new ClaimsIdentity( + [new Claim(InternalClaimTypes.UserId, _user.Id.ToString("N"))])) + } + } + }; + + using var context = CreateDbContext(); + foreach (var id in new[] { _firstLibraryId, _secondLibraryId, _inaccessibleLibraryId, _folder.Id, _userRoot.Id, _aggregateRoot.Id }) + { + context.BaseItems.Add(new BaseItemEntity + { + Id = id, + Type = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Folder], + IsFolder = true + }); + } + + context.SaveChanges(); + + SeedItems(BaseItemKind.Movie, 0, "PG", "G", "PG-13"); + SeedItems(BaseItemKind.Series, 1, "TV-PG", "TV-G", "TV-14"); + } + + [Theory] + [InlineData(BaseItemKind.Movie, null)] + [InlineData(BaseItemKind.Series, null)] + [InlineData(BaseItemKind.Movie, "library")] + [InlineData(BaseItemKind.Series, "library")] + [InlineData(BaseItemKind.Movie, "view")] + [InlineData(BaseItemKind.Series, "view")] + [InlineData(BaseItemKind.Movie, "folder")] + [InlineData(BaseItemKind.Series, "folder")] + [InlineData(BaseItemKind.Movie, "userRoot")] + [InlineData(BaseItemKind.Series, "userRoot")] + [InlineData(BaseItemKind.Movie, "aggregateRoot")] + [InlineData(BaseItemKind.Series, "aggregateRoot")] + public void GetQueryFiltersLegacy_ReturnsAccessibleYearsAndRatings(BaseItemKind itemType, string? parent) + { + // A missing userId uses the authenticated user's access restrictions. + var result = _controller.GetQueryFiltersLegacy(null, GetParentId(parent), [itemType], []); + var filters = Assert.IsType<QueryFiltersLegacy>(result.Value); + + AssertYearsAndRatings(itemType, parent, filters.Years, filters.OfficialRatings); + } + + [Theory] + [InlineData(BaseItemKind.Movie)] + [InlineData(BaseItemKind.Series)] + public void GetQueryFiltersLegacy_NoAccessibleLibraries_ReturnsEmptyFilters(BaseItemKind itemType) + { + _userViewManager.Setup(m => m.GetUserViews(It.IsAny<UserViewQuery>())).Returns([]); + + var result = _controller.GetQueryFiltersLegacy(null, null, [itemType], []); + var filters = Assert.IsType<QueryFiltersLegacy>(result.Value); + + Assert.Empty(filters.Years); + Assert.Empty(filters.OfficialRatings); + Assert.Empty(filters.Tags); + Assert.Empty(filters.Genres); + } + + [Theory] + [InlineData(BaseItemKind.Movie, null, true)] + [InlineData(BaseItemKind.Series, null, true)] + [InlineData(BaseItemKind.Movie, null, false)] + [InlineData(BaseItemKind.Series, null, false)] + [InlineData(BaseItemKind.Movie, "library", true)] + [InlineData(BaseItemKind.Series, "library", true)] + [InlineData(BaseItemKind.Movie, "library", false)] + [InlineData(BaseItemKind.Series, "library", false)] + [InlineData(BaseItemKind.Movie, "view", true)] + [InlineData(BaseItemKind.Series, "view", true)] + [InlineData(BaseItemKind.Movie, "view", false)] + [InlineData(BaseItemKind.Series, "view", false)] + [InlineData(BaseItemKind.Movie, "folder", true)] + [InlineData(BaseItemKind.Series, "folder", true)] + [InlineData(BaseItemKind.Movie, "folder", false)] + [InlineData(BaseItemKind.Series, "folder", false)] + [InlineData(BaseItemKind.Movie, "userRoot", true)] + [InlineData(BaseItemKind.Series, "userRoot", true)] + [InlineData(BaseItemKind.Movie, "aggregateRoot", true)] + [InlineData(BaseItemKind.Series, "aggregateRoot", true)] + public void GetQueryFilters_ReturnsAccessibleYearsAndRatings(BaseItemKind itemType, string? parent, bool recursive) + { + var filters = GetFilters(itemType, GetParentId(parent), recursive); + + AssertYearsAndRatings(itemType, parent, filters.Years, filters.OfficialRatings); + } + + [Theory] + [InlineData(BaseItemKind.Movie, true)] + [InlineData(BaseItemKind.Series, true)] + [InlineData(BaseItemKind.Movie, false)] + [InlineData(BaseItemKind.Series, false)] + public void GetQueryFilters_Recursive_ControlsWhetherDescendantsContribute(BaseItemKind itemType, bool recursive) + { + using var context = CreateDbContext(); + var nestedFolder = new BaseItemEntity + { + Id = Guid.NewGuid(), + Type = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Folder], + IsFolder = true, + ParentId = _folder.Id, + TopParentId = _firstLibraryId + }; + context.BaseItems.Add(nestedFolder); + context.SaveChanges(); + var descendantId = AddItem(itemType, _firstLibraryId, nestedFolder.Id, 2019, "Descendant"); + context.AncestorIds.Add(new AncestorId + { + ItemId = descendantId, + Item = context.BaseItems.Find(descendantId)!, + ParentItemId = _folder.Id, + ParentItem = context.BaseItems.Find(_folder.Id)! + }); + context.SaveChanges(); + + var filters = GetFilters(itemType, _folder.Id, recursive); + var firstYear = itemType == BaseItemKind.Movie ? 2001 : 2002; + var firstRating = itemType == BaseItemKind.Movie ? "PG" : "TV-PG"; + + Assert.Equal(recursive ? [firstYear, 2019] : new[] { firstYear }, filters.Years); + Assert.Equal(recursive ? ["Descendant", firstRating] : new[] { firstRating }, filters.OfficialRatings); + } + + [Theory] + [InlineData(BaseItemKind.Movie, false)] + [InlineData(BaseItemKind.Series, false)] + [InlineData(BaseItemKind.Movie, true)] + [InlineData(BaseItemKind.Series, true)] + public void GetQueryFilters_MissingMetadata_DoesNotExcludeTheOtherField(BaseItemKind itemType, bool withParent) + { + using (var context = CreateDbContext()) + { + foreach (var item in context.BaseItems) + { + item.ProductionYear = null; + item.OfficialRating = null; + } + + context.SaveChanges(); + } + + AddItem(itemType, _firstLibraryId, _folder.Id, null, "PG"); + AddItem(itemType, _firstLibraryId, _folder.Id, 2019, null); + AddItem(itemType, _firstLibraryId, _folder.Id, 2019, string.Empty); + AddItem(itemType, _firstLibraryId, _folder.Id, -1, "PG"); + + var filters = GetFilters(itemType, withParent ? _collection.Id : null); + + Assert.Equal([2019], filters.Years); + Assert.Equal(["PG"], filters.OfficialRatings); + } + + [Theory] + [InlineData(BaseItemKind.Movie, false)] + [InlineData(BaseItemKind.Series, false)] + [InlineData(BaseItemKind.Movie, true)] + [InlineData(BaseItemKind.Series, true)] + public void GetQueryFilters_AllowedTags_OnlyIncludesAllowedItems(BaseItemKind itemType, bool withParent) + { + _user.SetPreference(PreferenceKind.AllowedTags, ["allowed"]); + var allowedId = AddItem(itemType, _firstLibraryId, _folder.Id, 2017, "Allowed"); + AddItemValue(allowedId, ItemValueType.Tags, "allowed"); + var blockedId = AddItem(itemType, _firstLibraryId, _folder.Id, 2018, "Blocked", blockedTag: true); + AddItemValue(blockedId, ItemValueType.Tags, "allowed"); + + var filters = GetFilters(itemType, withParent ? _collection.Id : null); + + Assert.Equal([2017], filters.Years); + Assert.Equal(["Allowed"], filters.OfficialRatings); + Assert.Equal(["allowed"], filters.Tags); + } + + [Theory] + [InlineData(BaseItemKind.Movie)] + [InlineData(BaseItemKind.Series)] + public void GetQueryFilters_NoAccessibleLibraries_ReturnsEmptyFilters(BaseItemKind itemType) + { + _userViewManager.Setup(m => m.GetUserViews(It.IsAny<UserViewQuery>())).Returns([]); + + var filters = GetFilters(itemType); + + Assert.Empty(filters.Years); + Assert.Empty(filters.OfficialRatings); + Assert.Empty(filters.Genres); + Assert.Empty(filters.Tags); + Assert.Empty(filters.AudioLanguages); + Assert.Empty(filters.SubtitleLanguages); + } + + [Theory] + [InlineData(BaseItemKind.Movie, false)] + [InlineData(BaseItemKind.Series, false)] + [InlineData(BaseItemKind.Movie, true)] + [InlineData(BaseItemKind.Series, true)] + public void GetQueryFilters_IsMovie_UsesTheSameFilterForMetadata(BaseItemKind itemType, bool withParent) + { + var result = _controller.GetQueryFilters( + userId: null, + parentId: withParent ? _collection.Id : null, + includeItemTypes: [itemType], + isAiring: null, + isMovie: itemType != BaseItemKind.Movie, + isSports: null, + isKids: null, + isNews: null, + isSeries: null, + recursive: null); + var filters = Assert.IsType<QueryFilters>(result.Value); + + Assert.Empty(filters.Years); + Assert.Empty(filters.OfficialRatings); + } + + [Theory] + [InlineData(BaseItemKind.Movie, false)] + [InlineData(BaseItemKind.Series, false)] + [InlineData(BaseItemKind.Movie, true)] + [InlineData(BaseItemKind.Series, true)] + public void GetQueryFilters_PreservesGenresTagsAndLanguages(BaseItemKind itemType, bool withParent) + { + var isMovie = itemType == BaseItemKind.Movie; + var visibleId = AddItem(itemType, _firstLibraryId, _folder.Id, isMovie ? 2001 : 2002, isMovie ? "PG" : "TV-PG"); + AddItemValue(visibleId, ItemValueType.Tags, "visible"); + AddItemValue(visibleId, ItemValueType.Genre, "Drama"); + var hiddenId = AddItem(itemType, _inaccessibleLibraryId, _inaccessibleLibraryId, 2099, "Hidden"); + AddItemValue(hiddenId, ItemValueType.Tags, "hidden"); + AddItemValue(hiddenId, ItemValueType.Genre, "Horror"); + + // Languages come from episodes; years and ratings come from the series. + if (!isMovie) + { + visibleId = AddItem(BaseItemKind.Episode, _firstLibraryId, visibleId, 2088, "Episode rating"); + hiddenId = AddItem(BaseItemKind.Episode, _inaccessibleLibraryId, hiddenId, 2089, "Hidden episode rating"); + } + + AddLanguages(visibleId, "eng", "spa"); + AddLanguages(hiddenId, "ger", "fre"); + using (var context = CreateDbContext()) + { + foreach (var name in new[] { "Drama", "Horror" }) + { + var id = Guid.NewGuid(); + context.BaseItems.Add(new BaseItemEntity + { + Id = id, + Type = _itemTypeLookup.BaseItemKindNames[BaseItemKind.Genre], + Name = name, + CleanName = name.ToLowerInvariant(), + PresentationUniqueKey = id.ToString("N") + }); + } + + context.SaveChanges(); + } + + var filters = GetFilters(itemType, withParent ? _collection.Id : null); + + Assert.Equal(["Drama"], filters.Genres.Select(g => g.Name)); + Assert.NotEqual(Guid.Empty, Assert.Single(filters.Genres).Id); + Assert.Equal(["visible"], filters.Tags); + var audioLanguage = Assert.Single(filters.AudioLanguages); + Assert.Equal("eng", audioLanguage.Value); + Assert.Equal("eng", audioLanguage.Name); + var subtitleLanguage = Assert.Single(filters.SubtitleLanguages); + Assert.Equal("spa", subtitleLanguage.Value); + Assert.Equal("spa", subtitleLanguage.Name); + AssertYearsAndRatings(itemType, withParent ? "library" : null, filters.Years, filters.OfficialRatings); + } + + protected override void Dispose(bool disposing) + { + base.Dispose(disposing); + if (disposing) + { + _rootDirectory.Delete(true); + } + } + + private QueryFilters GetFilters(BaseItemKind itemType, Guid? parentId = null, bool? recursive = null) + { + var result = _controller.GetQueryFilters( + userId: null, + parentId: parentId, + includeItemTypes: [itemType], + isAiring: null, + isMovie: null, + isSports: null, + isKids: null, + isNews: null, + isSeries: null, + recursive: recursive); + return Assert.IsType<QueryFilters>(result.Value); + } + + private Guid? GetParentId(string? parent) + { + return parent switch + { + null => null, + "library" => _collection.Id, + "view" => _view.Id, + "folder" => _folder.Id, + "userRoot" => _userRoot.Id, + "aggregateRoot" => _aggregateRoot.Id, + _ => throw new ArgumentOutOfRangeException(nameof(parent)) + }; + } + + private static void AssertYearsAndRatings(BaseItemKind itemType, string? parent, IReadOnlyList<int> years, IReadOnlyList<string> officialRatings) + { + var offset = itemType == BaseItemKind.Movie ? 0 : 1; + int[] expectedYears = parent switch + { + "folder" => [2001 + offset], + "library" or "view" => [2001 + offset, 2005 + offset], + _ => [2001 + offset, 2005 + offset, 2011 + offset] + }; + string[] ratings = itemType == BaseItemKind.Movie ? ["PG", "G", "PG-13"] : ["TV-PG", "TV-G", "TV-14"]; + + Assert.Equal(expectedYears, years); + Assert.Equal(ratings.Take(expectedYears.Length).Order(StringComparer.Ordinal), officialRatings); + } + + private void SeedItems(BaseItemKind kind, int yearOffset, string firstRating, string siblingRating, string secondRating) + { + // Unsorted, duplicate, and missing values exercise metadata aggregation. + AddItem(kind, _secondLibraryId, _secondLibraryId, 2011 + yearOffset, secondRating); + AddItem(kind, _firstLibraryId, _firstLibraryId, 2005 + yearOffset, siblingRating); + AddItem(kind, _firstLibraryId, _folder.Id, 2001 + yearOffset, firstRating); + AddItem(kind, _firstLibraryId, _folder.Id, 2001 + yearOffset, firstRating); + AddItem(kind, _firstLibraryId, _folder.Id, null, null); + AddItem(kind, _firstLibraryId, _folder.Id, 0, string.Empty); + + // Distinct metadata reveals any restricted items in the response. + AddItem(kind, _inaccessibleLibraryId, _inaccessibleLibraryId, 1991 + yearOffset, "Inaccessible library"); + AddItem(kind, _firstLibraryId, _folder.Id, 2021 + yearOffset, "Above parental limit", parentalRating: 100); + AddItem(kind, _firstLibraryId, _folder.Id, 2031 + yearOffset, "Blocked tag", blockedTag: true); + } + + private Guid AddItem(BaseItemKind kind, Guid libraryId, Guid parentId, int? year, string? rating, int parentalRating = 10, bool blockedTag = false) + { + using var context = CreateDbContext(); + var item = new BaseItemEntity + { + Id = Guid.NewGuid(), + Type = _itemTypeLookup.BaseItemKindNames[kind], + MediaType = "Video", + IsFolder = kind == BaseItemKind.Series, + IsMovie = kind == BaseItemKind.Movie, + IsVirtualItem = false, + TopParentId = libraryId, + ParentId = parentId, + ProductionYear = year, + OfficialRating = rating, + InheritedParentalRatingValue = parentalRating + }; + context.BaseItems.Add(item); + + // Virtual roots and collection views are not stored ancestors. + foreach (var ancestorId in new[] { libraryId, parentId }.Distinct()) + { + context.AncestorIds.Add(new AncestorId + { + ItemId = item.Id, + Item = item, + ParentItemId = ancestorId, + ParentItem = context.BaseItems.Find(ancestorId)! + }); + } + + context.SaveChanges(); + if (blockedTag) + { + AddItemValue(item.Id, ItemValueType.Tags, "blocked"); + } + + return item.Id; + } + + private void AddItemValue(Guid itemId, ItemValueType type, string value) + { + using var context = CreateDbContext(); + var itemValue = context.ItemValues.SingleOrDefault(t => t.Type == type && t.Value == value); + if (itemValue is null) + { + itemValue = new ItemValue + { + ItemValueId = Guid.NewGuid(), + Type = type, + Value = value, + CleanValue = value.ToLowerInvariant() + }; + context.ItemValues.Add(itemValue); + } + + context.ItemValuesMap.Add(new ItemValueMap + { + ItemId = itemId, + ItemValueId = itemValue.ItemValueId, + Item = context.BaseItems.Find(itemId)!, + ItemValue = itemValue + }); + context.SaveChanges(); + } + + private void AddLanguages(Guid itemId, string audioLanguage, string subtitleLanguage) + { + using var context = CreateDbContext(); + var item = context.BaseItems.Find(itemId)!; + context.MediaStreamInfos.AddRange( + new MediaStreamInfo + { + ItemId = itemId, + Item = item, + StreamIndex = 0, + StreamType = MediaStreamTypeEntity.Audio, + Language = audioLanguage + }, + new MediaStreamInfo + { + ItemId = itemId, + Item = item, + StreamIndex = 1, + StreamType = MediaStreamTypeEntity.Subtitle, + Language = subtitleLanguage + }); + context.SaveChanges(); + } +} diff --git a/tests/Jellyfin.Server.Implementations.Tests/Library/SqlSearchProviderTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Library/SqlSearchProviderTests.cs index 89ca037256..eefde9bed6 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Library/SqlSearchProviderTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Library/SqlSearchProviderTests.cs @@ -32,12 +32,24 @@ public sealed class SqlSearchProviderTests : SqliteDbTestFixture private static readonly Guid _primaryId = Guid.Parse("cccccccc-cccc-cccc-cccc-cccccccccccc"); private static readonly Guid _versionId = Guid.Parse("dddddddd-dddd-dddd-dddd-dddddddddddd"); + // A movie nested one folder below the library, so only its AncestorIds rows reach the library. + private static readonly Guid _franchiseFolderId = Guid.Parse("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee"); + private static readonly Guid _nestedMovieId = Guid.Parse("ffffffff-ffff-ffff-ffff-ffffffffffff"); + + private readonly QueryPlanRecorder _recorder; private readonly SqlSearchProvider _provider; private readonly Mock<ILibraryManager> _libraryManager = new(); private readonly User _user = new("test", "auth-provider", "reset-provider"); public SqlSearchProviderTests() + : this(new QueryPlanRecorder()) { + } + + private SqlSearchProviderTests(QueryPlanRecorder recorder) + : base(recorder) + { + _recorder = recorder; var itemTypeLookup = new ItemTypeLookup(); var movieTypeName = itemTypeLookup.BaseItemKindNames[BaseItemKind.Movie]!; var folderTypeName = itemTypeLookup.BaseItemKindNames[BaseItemKind.Folder]!; @@ -49,6 +61,15 @@ public sealed class SqlSearchProviderTests : SqliteDbTestFixture context.BaseItems.Add(CreateLibrary(_movie4KLibraryId, folderTypeName, "Movies-4K", "/movies-4k")); context.BaseItems.Add(CreateMovie(_primaryId, movieTypeName, _movie4KLibraryId, null)); context.BaseItems.Add(CreateMovie(_versionId, movieTypeName, _movieLibraryId, _primaryId)); + context.BaseItems.Add(CreateLibrary(_franchiseFolderId, folderTypeName, "Franchise", "/movies/franchise")); + var nestedMovie = CreateMovie(_nestedMovieId, movieTypeName, _movieLibraryId, null); + nestedMovie.Name = "Moana"; + nestedMovie.CleanName = "moana"; + nestedMovie.SortName = "Moana"; + nestedMovie.ParentId = _franchiseFolderId; + context.BaseItems.Add(nestedMovie); + context.AncestorIds.Add(new AncestorId { ItemId = _nestedMovieId, ParentItemId = _franchiseFolderId, Item = null!, ParentItem = null! }); + context.AncestorIds.Add(new AncestorId { ItemId = _nestedMovieId, ParentItemId = _movieLibraryId, Item = null!, ParentItem = null! }); context.SaveChanges(); } @@ -88,6 +109,31 @@ public sealed class SqlSearchProviderTests : SqliteDbTestFixture Assert.Equal([_primaryId], hits); } + [Fact] + public async Task SearchAsync_WithParent_FindsItemsNestedBelowIt() + { + RestrictUserTo(_movieLibraryId); + + Assert.Equal([_nestedMovieId], await SearchAsync("moana", _movieLibraryId).ConfigureAwait(true)); + Assert.Equal([_nestedMovieId], await SearchAsync("moana", _franchiseFolderId).ConfigureAwait(true)); + Assert.Empty(await SearchAsync("moana", _movie4KLibraryId).ConfigureAwait(true)); + } + + [Fact] + public async Task SearchAsync_WithParent_SeeksDescendantsByParent() + { + RestrictUserTo(_movieLibraryId); + _recorder.Commands.Clear(); + + await SearchAsync("moana", _franchiseFolderId).ConfigureAwait(true); + + var query = Assert.Single(_recorder.Commands, c => c.Sql.Contains("\"AncestorIds\"", StringComparison.Ordinal)); + // The ParentId alternative keeps BaseItems as the driver; the descendants become a list built once, not a per-row probe. + var plan = Explain(query); + Assert.Contains(plan, line => line.Contains("COVERING INDEX IX_AncestorIds_ParentItemId_ItemId (ParentItemId=?)", StringComparison.Ordinal)); + Assert.DoesNotContain(plan, line => line.Contains("sqlite_autoindex_AncestorIds_1", StringComparison.Ordinal)); + } + private void RestrictUserTo(params Guid[] libraryIds) { _libraryManager @@ -95,10 +141,10 @@ public sealed class SqlSearchProviderTests : SqliteDbTestFixture .Callback<InternalItemsQuery, User>((query, _) => query.TopParentIds = libraryIds); } - private async Task<List<Guid>> SearchAsync() + private async Task<List<Guid>> SearchAsync(string searchTerm = "coco", Guid? parentId = null) { var results = await _provider.SearchAsync( - new SearchProviderQuery { SearchTerm = "coco", UserId = _user.Id, Limit = 10 }, + new SearchProviderQuery { SearchTerm = searchTerm, UserId = _user.Id, ParentId = parentId, Limit = 10 }, CancellationToken.None).ConfigureAwait(false); return results.Select(r => r.ItemId).ToList(); @@ -131,4 +177,10 @@ public sealed class SqlSearchProviderTests : SqliteDbTestFixture PresentationUniqueKey = (primaryVersionId ?? id).ToString("N"), PrimaryVersionId = primaryVersionId }; + + private string[] Explain(RecordedCommand query) + { + using var context = CreateDbContext(); + return QueryPlanRecorder.Explain(context, query); + } } diff --git a/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs b/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs index 4e57f32b57..ecf8e9b0f2 100644 --- a/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs +++ b/tests/Jellyfin.Server.Implementations.Tests/Localization/LocalizationManagerTests.cs @@ -6,6 +6,7 @@ using BitFaster.Caching; using Emby.Server.Implementations.Localization; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Globalization; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Moq; @@ -102,6 +103,80 @@ namespace Jellyfin.Server.Implementations.Tests.Localization } [Theory] + // Region qualified variants must stay distinguishable by ThreeLetterISOLanguageName, + // which is what clients use as the value of their language pickers. + [InlineData("pt", "por", "Portuguese")] + [InlineData("pt-br", "pt-br", "Portuguese (Brazil)")] + [InlineData("pob", "pt-br", "Portuguese (Brazil)")] + [InlineData("pt-pt", "pt-pt", "Portuguese (Portugal)")] + [InlineData("pop", "pt-pt", "Portuguese (Portugal)")] + [InlineData("es", "spa", "Spanish; Castilian")] + [InlineData("spa", "spa", "Spanish; Castilian")] + [InlineData("es-419", "es-419", "Spanish; Latin")] + [InlineData("es-mx", "es-419", "Spanish; Latin")] + [InlineData("zh", "zho", "Chinese")] + [InlineData("ze", "ze", "Chinese (Bilingual)")] + [InlineData("zh-cn", "zh-cn", "Chinese (Simplified)")] + [InlineData("zh-tw", "zh-tw", "Chinese (Traditional)")] + public async Task FindLanguageInfo_RegionalVariant_KeepsDistinctCode(string identifier, string expectedCode, string expectedDisplayName) + { + var localizationManager = Setup(new ServerConfiguration + { + UICulture = "en-US" + }); + await localizationManager.LoadAll(); + + var culture = localizationManager.FindLanguageInfo(identifier); + Assert.NotNull(culture); + Assert.Equal(expectedCode, culture.ThreeLetterISOLanguageName); + Assert.Equal(expectedDisplayName, culture.DisplayName); + } + + [Theory] + // Stream tags carry either the variant's own tag (movie.pt-br.srt) or the base code ffprobe reports. + [InlineData("pt-br", new[] { "pt-br", "por" })] + [InlineData("por", new[] { "por" })] + [InlineData("ger", new[] { "deu", "ger" })] + [InlineData("zh-tw", new[] { "zh-tw", "zho", "chi" })] + [InlineData("fr-ca", new[] { "fr-ca", "frc", "fra", "fre" })] + // Streams scanned before 12.0 keep their legacy code until the item is refreshed. + [InlineData("pob", new[] { "pt-br", "por", "pob" })] + // A display name with a hyphen does not make a culture a variant. + [InlineData("ell", new[] { "ell", "gre" })] + [InlineData("UND", new[] { "und" })] + [InlineData("xyz", new[] { "xyz" })] + public async Task GetMediaStreamLanguageCodes_Variant_IncludesBaseCode(string identifier, string[] expected) + { + var localizationManager = Setup(new ServerConfiguration + { + UICulture = "en-US" + }); + await localizationManager.LoadAll(); + + Assert.Equal(expected, localizationManager.GetMediaStreamLanguageCodes(identifier)); + } + + [Fact] + public async Task GetCultures_RegionalVariants_HaveUniqueThreeLetterCodes() + { + var localizationManager = Setup(new ServerConfiguration + { + UICulture = "en-US" + }); + await localizationManager.LoadAll(); + + // Mirrors what LocalizationController serves and what clients use as picker values. + var duplicates = localizationManager.GetCultures() + .DistinctBy(c => c.DisplayName, StringComparer.OrdinalIgnoreCase) + .GroupBy(c => c.ThreeLetterISOLanguageName, StringComparer.OrdinalIgnoreCase) + .Where(g => g.Count() > 1) + .Select(g => $"{g.Key}: {string.Join(", ", g.Select(c => c.DisplayName))}") + .ToList(); + + Assert.Empty(duplicates); + } + + [Theory] [InlineData("mul", "Multiple languages")] [InlineData("und", "Undetermined")] [InlineData("mis", "Uncoded languages")] diff --git a/tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs new file mode 100644 index 0000000000..94672d5c7b --- /dev/null +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/ConfigurationControllerTests.cs @@ -0,0 +1,248 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Mime; +using System.Reflection; +using System.Security.Claims; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading.Tasks; +using Jellyfin.Extensions.Json; +using Jellyfin.Server.Extensions; +using MediaBrowser.Common.Api; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.LiveTv; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Moq; +using Xunit; + +namespace Jellyfin.Server.Integration.Tests.Controllers; + +public sealed class ConfigurationControllerTests : IDisposable +{ + 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, "{}"); + } + + [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) + { + await AssertMatchesLegacyDeserialization(key, json); + } + + [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) + { + 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 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))); + } + + [Fact] + public async Task UpdateConfiguration_CamelCaseProperties_AreApplied() + { + await PostConfiguration("encoding", """{"h264Crf":18,"enableHardwareEncoding":false}"""); + + var configuration = Assert.IsType<EncodingOptions>(_configurations["encoding"]); + Assert.Equal(18, configuration.H264Crf); + Assert.False(configuration.EnableHardwareEncoding); + Assert.Equal(new EncodingOptions().H265Crf, configuration.H265Crf); + + 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); + 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); + } + + [Theory] + [InlineData("encoding", "null")] + [InlineData("encoding", """{"H264Crf":null}""")] + [InlineData("network", """{"InternalHttpPort":"invalid"}""")] + [InlineData("network", """{"BaseUrl":null}""")] + [InlineData("network", """{"LocalNetworkSubnets":null}""")] + [InlineData("network", """{"LocalNetworkAddresses":null}""")] + [InlineData("network", """{"KnownProxies":null}""")] + [InlineData("network", """{"VirtualInterfaceNames":null}""")] + [InlineData("network", """{"PublishedServerUriBySubnet":null}""")] + [InlineData("network", """{"RemoteIPFilter":null}""")] + [InlineData("livetv", """{"TunerHosts":null}""")] + [InlineData("livetv", """{"ListingProviders":null}""")] + [InlineData("livetv", """{"MediaLocationsCreated":null}""")] + [InlineData("livetv", """{"RecordingPostProcessorArguments":null}""")] + [InlineData("xbmcmetadata", """{"ReleaseDateFormat":null}""")] + [InlineData("", """{"ServerName":null}""")] + public async Task UpdateConfiguration_InvalidRequest_DoesNotSave(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); + + 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) + { + 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) + { + using var content = new StringContent(json, Encoding.UTF8, MediaTypeNames.Application.Json); + 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.Integration.Tests/Controllers/FilterControllerTests.cs b/tests/Jellyfin.Server.Integration.Tests/Controllers/FilterControllerTests.cs new file mode 100644 index 0000000000..0e174fb597 --- /dev/null +++ b/tests/Jellyfin.Server.Integration.Tests/Controllers/FilterControllerTests.cs @@ -0,0 +1,35 @@ +using System.Net.Http.Json; +using System.Text.Json; +using System.Threading.Tasks; +using Xunit; + +namespace Jellyfin.Server.Integration.Tests.Controllers; + +public sealed class FilterControllerTests : IClassFixture<JellyfinApplicationFactory> +{ + private readonly JellyfinApplicationFactory _factory; + private static string? _accessToken; + + public FilterControllerTests(JellyfinApplicationFactory factory) + { + _factory = factory; + } + + [Theory] + [InlineData("Movie")] + [InlineData("Series")] + public async Task GetQueryFilters_EmptyLibrary_SerializesEmptyArrays(string itemType) + { + using var client = _factory.CreateClient(); + client.DefaultRequestHeaders.AddAuthHeader(_accessToken ??= await AuthHelper.CompleteStartupAsync(client)); + + var filters = await client.GetFromJsonAsync<JsonElement>($"/Items/Filters2?includeItemTypes={itemType}", TestContext.Current.CancellationToken); + + foreach (var field in new[] { "Years", "OfficialRatings", "Genres", "Tags", "AudioLanguages", "SubtitleLanguages" }) + { + var values = filters.GetProperty(field); + Assert.Equal(JsonValueKind.Array, values.ValueKind); + Assert.Equal(0, values.GetArrayLength()); + } + } +} diff --git a/tests/Jellyfin.Server.Integration.Tests/DotIgnoreLibraryRootTests.cs b/tests/Jellyfin.Server.Integration.Tests/DotIgnoreLibraryRootTests.cs new file mode 100644 index 0000000000..2fd598e6b2 --- /dev/null +++ b/tests/Jellyfin.Server.Integration.Tests/DotIgnoreLibraryRootTests.cs @@ -0,0 +1,55 @@ +using System; +using System.IO; +using Emby.Server.Implementations.Library; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.IO; +using Microsoft.Extensions.DependencyInjection; +using Xunit; + +namespace Jellyfin.Server.Integration.Tests; + +public sealed class DotIgnoreLibraryRootTests : IClassFixture<JellyfinApplicationFactory> +{ + private readonly JellyfinApplicationFactory _factory; + + public DotIgnoreLibraryRootTests(JellyfinApplicationFactory factory) + { + _factory = factory; + } + + [Fact] + public void IgnoreFile_IgnoreFileAboveLibraryRoot_IsNotConsulted() + { + _ = _factory.CreateClient(); + + var tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + var libraryRoot = Path.Combine(tempDir, "Movies"); + var movieDir = Path.Combine(libraryRoot, "Movie (2020)"); + Directory.CreateDirectory(movieDir); + var libraryDir = Path.Combine(_factory.Services.GetRequiredService<IServerApplicationPaths>().DefaultUserViewsPath, "dotignore-root-test"); + Directory.CreateDirectory(libraryDir); + + try + { + File.WriteAllText(Path.Combine(tempDir, ".ignore"), string.Empty); + File.WriteAllText(Path.Combine(libraryDir, "Movies.mblink"), libraryRoot); + + // The rule the resolver evaluates must be the singleton LibraryManager hands the roots to + _factory.Services.GetRequiredService<DotIgnoreIgnoreRule>().ClearDirectoryCache(); + var fileInfo = new FileSystemMetadata + { + FullName = Path.Combine(movieDir, "Movie (2020).mkv"), + IsDirectory = false + }; + + Assert.False(_factory.Services.GetRequiredService<ILibraryManager>().IgnoreFile(fileInfo, new Folder { Path = movieDir })); + } + finally + { + Directory.Delete(libraryDir, true); + Directory.Delete(tempDir, true); + } + } +} diff --git a/tests/Jellyfin.Server.Tests/Migrations/FixLibrarySubtitleDownloadLanguagesTests.cs b/tests/Jellyfin.Server.Tests/Migrations/FixLibrarySubtitleDownloadLanguagesTests.cs new file mode 100644 index 0000000000..e9b8e2f9ff --- /dev/null +++ b/tests/Jellyfin.Server.Tests/Migrations/FixLibrarySubtitleDownloadLanguagesTests.cs @@ -0,0 +1,85 @@ +using System; +using System.Threading.Tasks; +using Emby.Server.Implementations.Localization; +using Jellyfin.Server.Migrations.Routines; +using Jellyfin.Server.ServerSetupApp; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Serialization; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Server.Tests.Migrations; + +public sealed class FixLibrarySubtitleDownloadLanguagesTests : IDisposable +{ + private readonly IXmlSerializer _originalXmlSerializer = CollectionFolder.XmlSerializer; + + [Theory] + // 12.0 stored every variant as its base code, the metadata language tells which one was picked. + [InlineData("por", "pt-br", "en", "pt-br")] + [InlineData("por", "pt-pt", "en", "pt-pt")] + [InlineData("por", null, "pt-br", "pt-br")] + [InlineData("por", "en", "pt-br", "por")] + [InlineData("por", "pt", "en", "por")] + [InlineData("spa", "es-419", "en", "es-419")] + [InlineData("spa", "es", "en", "spa")] + [InlineData("chi", "zh-tw", "en", "zh-tw")] + // Explicit values are never overridden by the metadata language. + [InlineData("pt", "pt-br", "en", "por")] + [InlineData("pob", "pt-pt", "en", "pt-br")] + [InlineData("pt-pt", "pt-br", "en", "pt-pt")] + [InlineData("ger", "de", "en", "deu")] + [InlineData("xyz", "pt-br", "en", "xyz")] + // 10.10 stored por, pop and pob separately, a variant next to por means por was meant generically. + [InlineData("por,pob", "pt-br", "en", "por,pt-br")] + [InlineData("por,pop", "pt-br", "en", "por,pt-pt")] + [InlineData("por,pop", "pt-pt", "en", "por,pt-pt")] + [InlineData("por,pob", "en", "en", "por,pt-br")] + [InlineData("ger,pob", "pt-br", "en", "deu,pt-br")] + [InlineData("por,xyz", "pt-br", "en", "pt-br,xyz")] + public async Task PerformAsync_InfersRegionalVariantFromMetadataLanguage(string stored, string? libraryLanguage, string serverLanguage, string expected) + { + var configurationManager = new Mock<IServerConfigurationManager>(); + configurationManager.SetupGet(x => x.Configuration).Returns(new ServerConfiguration + { + UICulture = "en-US", + PreferredMetadataLanguage = serverLanguage + }); + var localizationManager = new LocalizationManager(configurationManager.Object, NullLogger<LocalizationManager>.Instance); + await localizationManager.LoadAll(); + + var folderId = Guid.NewGuid(); + var options = new LibraryOptions + { + PreferredMetadataLanguage = libraryLanguage, + SubtitleDownloadLanguages = stored.Split(',') + }; + var libraryManager = new Mock<ILibraryManager>(); + libraryManager.Setup(x => x.GetVirtualFolders(false)).Returns( + [ + new VirtualFolderInfo { Name = "Movies", ItemId = folderId.ToString(), LibraryOptions = options } + ]); + libraryManager.Setup(x => x.GetItemById<CollectionFolder>(folderId)).Returns(new CollectionFolder { Path = "/config/root/movies" }); + CollectionFolder.XmlSerializer = Mock.Of<IXmlSerializer>(); + + var migration = new FixLibrarySubtitleDownloadLanguages( + localizationManager, + configurationManager.Object, + new StartupLogger<FixLibrarySubtitleDownloadLanguages>(NullLogger<FixLibrarySubtitleDownloadLanguages>.Instance), + libraryManager.Object, + NullLogger<FixLibrarySubtitleDownloadLanguages>.Instance); + await migration.PerformAsync(TestContext.Current.CancellationToken); + + Assert.Equal(expected.Split(','), options.SubtitleDownloadLanguages); + } + + public void Dispose() + { + CollectionFolder.XmlSerializer = _originalXmlSerializer; + } +} diff --git a/tests/Jellyfin.Server.Tests/Migrations/FixNullEncoderPresetTests.cs b/tests/Jellyfin.Server.Tests/Migrations/FixNullEncoderPresetTests.cs index b41ecbb8ed..baa7909929 100644 --- a/tests/Jellyfin.Server.Tests/Migrations/FixNullEncoderPresetTests.cs +++ b/tests/Jellyfin.Server.Tests/Migrations/FixNullEncoderPresetTests.cs @@ -102,7 +102,7 @@ public sealed class FixNullEncoderPresetTests : IDisposable _configurationDirectory); var migration = new MigrateEncodingOptions(applicationPaths, NullLoggerFactory.Instance); - migration.Perform(); + await migration.PerformAsync(TestContext.Current.CancellationToken); var serializer = new XmlSerializer(typeof(EncodingOptions)); using var reader = XmlReader.Create(_encodingConfigurationPath); diff --git a/tests/Jellyfin.Server.Tests/Migrations/MigrateLinkedChildrenStaleItemsTests.cs b/tests/Jellyfin.Server.Tests/Migrations/MigrateLinkedChildrenStaleItemsTests.cs index 92fc1dca97..03d39c0ee7 100644 --- a/tests/Jellyfin.Server.Tests/Migrations/MigrateLinkedChildrenStaleItemsTests.cs +++ b/tests/Jellyfin.Server.Tests/Migrations/MigrateLinkedChildrenStaleItemsTests.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; +using System.Threading.Tasks; using Jellyfin.Database.Implementations; using Jellyfin.Database.Implementations.Entities; using Jellyfin.Database.Implementations.Locking; @@ -54,18 +55,18 @@ public sealed class MigrateLinkedChildrenStaleItemsTests : IDisposable private string LibraryDefinitionRoot => Path.Combine(_root, "root", "default"); [Fact] - public void Perform_NoLibraryLocationsResolved_KeepsEverything() + public async Task Perform_NoLibraryLocationsResolved_KeepsEverything() { var itemId = Guid.Parse("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"); SeedItem(itemId, SeedMediaFile("kept.flac")); - var deleted = Perform(libraryLocations: []); + var deleted = await PerformAsync(libraryLocations: []); Assert.Empty(deleted); } [Fact] - public void Perform_ItemOutsideEveryLocation_IsRemoved() + public async Task Perform_ItemOutsideEveryLocation_IsRemoved() { var itemId = Guid.Parse("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"); @@ -74,36 +75,36 @@ public sealed class MigrateLinkedChildrenStaleItemsTests : IDisposable SeedMediaFile("anchor.flac"); SeedItem(itemId, Path.Combine(_root, "removed-media", "gone.flac")); - var deleted = Perform(libraryLocations: [Path.Combine(_root, "media")]); + var deleted = await PerformAsync(libraryLocations: [Path.Combine(_root, "media")]); Assert.Equal([itemId], deleted); } [Fact] - public void Perform_ItemInsideLocationWithMissingFile_IsRemoved() + public async Task Perform_ItemInsideLocationWithMissingFile_IsRemoved() { var itemId = Guid.Parse("cccccccc-cccc-cccc-cccc-cccccccccccc"); SeedMediaFile("anchor.flac"); SeedItem(itemId, Path.Combine(_root, "media", "deleted.flac")); - var deleted = Perform(libraryLocations: [Path.Combine(_root, "media")]); + var deleted = await PerformAsync(libraryLocations: [Path.Combine(_root, "media")]); Assert.Equal([itemId], deleted); } [Fact] - public void Perform_ItemInsideLocationWithFilePresent_IsKept() + public async Task Perform_ItemInsideLocationWithFilePresent_IsKept() { var itemId = Guid.Parse("dddddddd-dddd-dddd-dddd-dddddddddddd"); SeedItem(itemId, SeedMediaFile("present.flac")); - var deleted = Perform(libraryLocations: [Path.Combine(_root, "media")]); + var deleted = await PerformAsync(libraryLocations: [Path.Combine(_root, "media")]); Assert.Empty(deleted); } [Fact] - public void Perform_LibraryDefinitionMissing_KeepsItsItems() + public async Task Perform_LibraryDefinitionMissing_KeepsItsItems() { var libraryId = Guid.Parse("11111111-1111-1111-1111-111111111111"); var itemId = Guid.Parse("22222222-2222-2222-2222-222222222222"); @@ -114,13 +115,13 @@ public sealed class MigrateLinkedChildrenStaleItemsTests : IDisposable SeedMediaFile("anchor.flac"); SeedItem(itemId, Path.Combine(_root, "movies", "kept.mkv"), libraryId); - var deleted = Perform(libraryLocations: [Path.Combine(_root, "media")]); + var deleted = await PerformAsync(libraryLocations: [Path.Combine(_root, "media")]); Assert.Empty(deleted); } [Fact] - public void Perform_PathRemovedFromSurvivingLibrary_IsRemoved() + public async Task Perform_PathRemovedFromSurvivingLibrary_IsRemoved() { var libraryId = Guid.Parse("33333333-3333-3333-3333-333333333333"); var itemId = Guid.Parse("44444444-4444-4444-4444-444444444444"); @@ -131,7 +132,7 @@ public sealed class MigrateLinkedChildrenStaleItemsTests : IDisposable SeedMediaFile("anchor.flac"); SeedItem(itemId, Path.Combine(_root, "removed-media", "gone.flac"), libraryId); - var deleted = Perform(libraryLocations: [Path.Combine(_root, "media")]); + var deleted = await PerformAsync(libraryLocations: [Path.Combine(_root, "media")]); Assert.Equal([itemId], deleted); } @@ -200,7 +201,7 @@ public sealed class MigrateLinkedChildrenStaleItemsTests : IDisposable } } - private IReadOnlyList<Guid> Perform(string[] libraryLocations, string libraryName = "Media") + private async Task<IReadOnlyList<Guid>> PerformAsync(string[] libraryLocations, string libraryName = "Media") { var deleted = new List<Guid>(); @@ -229,13 +230,13 @@ public sealed class MigrateLinkedChildrenStaleItemsTests : IDisposable factory.Setup(f => f.CreateDbContext()).Returns(CreateDbContext); factory.Setup(f => f.CreateDbContextAsync(It.IsAny<CancellationToken>())).ReturnsAsync(CreateDbContext); - new MigrateLinkedChildren( + await new MigrateLinkedChildren( NullLoggerFactory.Instance, factory.Object, libraryManager.Object, appHost.Object, appPaths.Object) - .Perform(); + .PerformAsync(TestContext.Current.CancellationToken); return deleted; } diff --git a/tests/Jellyfin.Server.Tests/Migrations/MigrateRatingLevelsTests.cs b/tests/Jellyfin.Server.Tests/Migrations/MigrateRatingLevelsTests.cs new file mode 100644 index 0000000000..da7c72c98c --- /dev/null +++ b/tests/Jellyfin.Server.Tests/Migrations/MigrateRatingLevelsTests.cs @@ -0,0 +1,311 @@ +using System; +using System.Globalization; +using System.Linq; +using Jellyfin.Database.Implementations; +using Jellyfin.Database.Implementations.Entities; +using Jellyfin.Database.Implementations.Locking; +using Jellyfin.Database.Providers.Sqlite; +using Jellyfin.Server.Migrations.Routines; +using Jellyfin.Server.ServerSetupApp; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Globalization; +using Microsoft.Data.Sqlite; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Logging.Abstractions; +using Moq; +using Xunit; + +namespace Jellyfin.Server.Tests.Migrations; + +/// <summary> +/// Covers the recalculation of the stored parental rating levels, including items that only inherit one. +/// </summary> +public sealed class MigrateRatingLevelsTests : IDisposable +{ + private const string SeriesType = "MediaBrowser.Controller.Entities.TV.Series"; + private const string SeasonType = "MediaBrowser.Controller.Entities.TV.Season"; + private const string EpisodeType = "MediaBrowser.Controller.Entities.TV.Episode"; + private const string FolderType = "MediaBrowser.Controller.Entities.Folder"; + private const string CollectionFolderType = "MediaBrowser.Controller.Entities.CollectionFolder"; + private const string AggregateFolderType = "MediaBrowser.Controller.Entities.AggregateFolder"; + private const string UserRootFolderType = "MediaBrowser.Controller.Entities.UserRootFolder"; + private const string LibraryPath = "/media/shows"; + + private static readonly Guid _libraryId = Guid.Parse("11111111-1111-1111-1111-111111111111"); + private static readonly Guid _seriesId = Guid.Parse("22222222-2222-2222-2222-222222222222"); + private static readonly Guid _seasonId = Guid.Parse("33333333-3333-3333-3333-333333333333"); + private static readonly Guid _episodeId = Guid.Parse("44444444-4444-4444-4444-444444444444"); + private static readonly Guid _rootId = Guid.Parse("55555555-5555-5555-5555-555555555555"); + private static readonly Guid _collectionFolderId = Guid.Parse("66666666-6666-6666-6666-666666666666"); + + private readonly SqliteConnection _connection; + private readonly DbContextOptions<JellyfinDbContext> _dbOptions; + private readonly IApplicationPaths _applicationPaths; + private readonly Mock<ILocalizationManager> _localizationManager; + private readonly Mock<ILibraryManager> _libraryManager; + private readonly Mock<IServerApplicationHost> _appHost; + + public MigrateRatingLevelsTests() + { + _applicationPaths = new Mock<IApplicationPaths>().Object; + + _localizationManager = new Mock<ILocalizationManager>(); + _localizationManager.Setup(m => m.GetRatingScore("TV-14", null)).Returns(new ParentalRatingScore(14, null)); + _localizationManager.Setup(m => m.GetRatingScore("TV-MA", null)).Returns(new ParentalRatingScore(17, 1)); + _localizationManager.Setup(m => m.GetRatingScore("TV-14", "DE")).Returns(new ParentalRatingScore(16, null)); + _localizationManager.Setup(m => m.GetRatingScore("TV-14", "GB")).Returns(new ParentalRatingScore(15, null)); + + _libraryManager = new Mock<ILibraryManager>(); + _libraryManager.Setup(m => m.GetVirtualFolders(false)).Returns([]); + + _appHost = new Mock<IServerApplicationHost>(); + _appHost.Setup(m => m.ReverseVirtualPath(It.IsAny<string>())) + .Returns((string path) => path.Replace("/var/lib/jellyfin/data", "%AppDataPath%", StringComparison.Ordinal)); + + // The connection owns the in-memory database, so it stays open for the whole test. + _connection = new SqliteConnection("Data Source=:memory:"); + _connection.Open(); + + _dbOptions = new DbContextOptionsBuilder<JellyfinDbContext>() + .UseSqlite(_connection) + .Options; + + using var context = CreateDbContext(); + context.Database.EnsureCreated(); + } + + [Fact] + public void Perform_UnratedSeasonAndEpisode_InheritTheSeriesRating() + { + SeedSeries(seriesRating: "TV-MA", seriesCustomRating: null, inherited: null); + + Perform(); + + using var context = CreateDbContext(); + AssertRating(context, _seriesId, 17, 1); + AssertRating(context, _seasonId, 17, 1); + AssertRating(context, _episodeId, 17, 1); + AssertRating(context, _libraryId, null, null); + } + + [Fact] + public void Perform_AlreadyMigrated_KeepsTheInheritedRating() + { + // A second run over a database the first run and a scan already brought up to date. + SeedSeries(seriesRating: "TV-MA", seriesCustomRating: null, inherited: new ParentalRatingScore(17, 1)); + + Perform(); + + using var context = CreateDbContext(); + AssertRating(context, _seasonId, 17, 1); + AssertRating(context, _episodeId, 17, 1); + } + + [Fact] + public void Perform_CustomRatingOnSeries_WinsOverTheOfficialOne() + { + SeedSeries(seriesRating: "TV-14", seriesCustomRating: "TV-MA", inherited: null); + + Perform(); + + using var context = CreateDbContext(); + AssertRating(context, _seriesId, 17, 1); + AssertRating(context, _episodeId, 17, 1); + } + + [Fact] + public void Perform_UnratedSeries_ClearsTheInheritedRating() + { + SeedSeries(seriesRating: null, seriesCustomRating: null, inherited: new ParentalRatingScore(14, null)); + + Perform(); + + using var context = CreateDbContext(); + AssertRating(context, _seriesId, null, null); + AssertRating(context, _episodeId, null, null); + } + + [Fact] + public void Perform_LibraryCountry_ScoresInheritedRatingsInThatCountry() + { + SeedSeries(seriesRating: "TV-14", seriesCustomRating: null, inherited: null); + SeedLibrary(folderCountryCode: null, optionsCountryCode: "DE"); + + Perform(); + + using var context = CreateDbContext(); + AssertRating(context, _seriesId, 16, null); + AssertRating(context, _episodeId, 16, null); + } + + [Fact] + public void Perform_CountryOnTheSeries_WinsOverTheLibraryCountry() + { + SeedSeries(seriesRating: "TV-14", seriesCustomRating: null, inherited: null, seriesCountryCode: "GB"); + SeedLibrary(folderCountryCode: "DE", optionsCountryCode: "DE"); + + Perform(); + + using var context = CreateDbContext(); + AssertRating(context, _seriesId, 15, null); + AssertRating(context, _seasonId, 15, null); + } + + [Fact] + public void Perform_LibraryUnderTheDataPath_ScoresInheritedRatingsInThatCountry() + { + SeedSeries(seriesRating: "TV-14", seriesCustomRating: null, inherited: null); + SeedLibrary(folderCountryCode: null, optionsCountryCode: "DE", location: "/var/lib/jellyfin/data/shows"); + using (var context = CreateDbContext()) + { + context.BaseItems.Where(e => e.Id.Equals(_libraryId)).ExecuteUpdate(f => f.SetProperty(e => e.Path, "%AppDataPath%/shows")); + } + + Perform(); + + using var assertContext = CreateDbContext(); + AssertRating(assertContext, _seriesId, 16, null); + AssertRating(assertContext, _episodeId, 16, null); + } + + [Fact] + public void Perform_RatedCollectionFolder_UsesItsOwnLibraryCountryCode() + { + var userRootId = Guid.Parse("77777777-7777-7777-7777-777777777777"); + using (var context = CreateDbContext()) + { + context.BaseItems.Add(new BaseItemEntity { Id = _rootId, Type = AggregateFolderType, Name = "root" }); + context.BaseItems.Add(new BaseItemEntity { Id = userRootId, Type = UserRootFolderType, Name = "default", Path = "/config/root/default" }); + context.BaseItems.Add(new BaseItemEntity + { + Id = _collectionFolderId, + Type = CollectionFolderType, + Name = "Shows", + Path = "/config/root/default/Shows", + ParentId = userRootId, + CustomRating = "TV-14" + }); + context.SaveChanges(); + } + + _libraryManager.Setup(m => m.GetVirtualFolders(false)).Returns( + [ + new VirtualFolderInfo + { + Name = "Shows", + ItemId = _collectionFolderId.ToString("N", CultureInfo.InvariantCulture), + Locations = [LibraryPath], + LibraryOptions = new LibraryOptions { MetadataCountryCode = "DE" } + } + ]); + + Perform(); + + using var assertContext = CreateDbContext(); + AssertRating(assertContext, _collectionFolderId, 16, null); + } + + public void Dispose() + { + _connection.Dispose(); + } + + private static void AssertRating(JellyfinDbContext context, Guid id, int? score, int? subScore) + { + var item = context.BaseItems.AsNoTracking().First(e => e.Id.Equals(id)); + Assert.Equal(score, item.InheritedParentalRatingValue); + Assert.Equal(subScore, item.InheritedParentalRatingSubValue); + } + + private void Perform() + { + 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(); + } + + private JellyfinDbContext CreateDbContext() => new( + _dbOptions, + NullLogger<JellyfinDbContext>.Instance, + new SqliteDatabaseProvider(_applicationPaths, NullLogger<SqliteDatabaseProvider>.Instance), + new NoLockBehavior(NullLogger<NoLockBehavior>.Instance)); + + private void SeedLibrary(string? folderCountryCode, string? optionsCountryCode, string location = LibraryPath) + { + using (var context = CreateDbContext()) + { + context.BaseItems.Add(new BaseItemEntity { Id = _rootId, Type = AggregateFolderType, Name = "root" }); + context.BaseItems.Add(new BaseItemEntity + { + Id = _collectionFolderId, + Type = CollectionFolderType, + Name = "Shows", + Path = "/config/root/default/Shows", + PreferredMetadataCountryCode = folderCountryCode + }); + context.SaveChanges(); + context.BaseItems.Where(e => e.Id.Equals(_libraryId)).ExecuteUpdate(f => f.SetProperty(e => e.ParentId, _rootId)); + } + + _libraryManager.Setup(m => m.GetVirtualFolders(false)).Returns( + [ + new VirtualFolderInfo + { + Name = "Shows", + ItemId = _collectionFolderId.ToString("N", CultureInfo.InvariantCulture), + Locations = [location], + LibraryOptions = new LibraryOptions { MetadataCountryCode = optionsCountryCode } + } + ]); + } + + private void SeedSeries(string? seriesRating, string? seriesCustomRating, ParentalRatingScore? inherited, string? seriesCountryCode = null) + { + using var context = CreateDbContext(); + + context.BaseItems.Add(new BaseItemEntity { Id = _libraryId, Type = FolderType, Name = "Shows", Path = LibraryPath }); + context.BaseItems.Add(new BaseItemEntity + { + Id = _seriesId, + Type = SeriesType, + Name = "Series", + ParentId = _libraryId, + OfficialRating = seriesRating, + CustomRating = seriesCustomRating, + PreferredMetadataCountryCode = seriesCountryCode, + InheritedParentalRatingValue = inherited?.Score, + InheritedParentalRatingSubValue = inherited?.SubScore + }); + context.BaseItems.Add(new BaseItemEntity + { + Id = _seasonId, + Type = SeasonType, + Name = "Season 1", + ParentId = _seriesId, + SeriesId = _seriesId, + InheritedParentalRatingValue = inherited?.Score, + InheritedParentalRatingSubValue = inherited?.SubScore + }); + + // The episode's display parent is its season, not the folder it was found in. + context.BaseItems.Add(new BaseItemEntity + { + Id = _episodeId, + Type = EpisodeType, + Name = "Episode 1", + ParentId = _libraryId, + SeasonId = _seasonId, + SeriesId = _seriesId, + OfficialRating = string.Empty, + InheritedParentalRatingValue = inherited?.Score, + InheritedParentalRatingSubValue = inherited?.SubScore + }); + + context.SaveChanges(); + } +} |
